merge ws/cm-core: comments to specs only in core / containers / host / ops / api / Types / compat; STYLE comment policy

This commit is contained in:
4DBug committed 2026-11-01 01:33:57 -06:00
commit 5e2fe5ab6e
49 files changed
+156 -1095

No files matched your search

+12 -41
View File
@@ -1,21 +1,9 @@
-- 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.
-- compat/luajit.lua: the Luau standard library pieces rosetta uses, for LuaJIT 2.1 (plain and LÖVE), with Luau
-- semantics (tests/compat.luau). tools/build.py copies it to build/_modules/luajit/rosetta/_compat.lua and prepends
-- `local __compat = require("rosetta._compat") ...` to every built module's first line; tools/bundle.py inlines it at
-- the top of build/rosetta.lua. Nothing is installed globally; table / math / string additions only fill gaps.
-- buffer = { p = uint8_t*, n = length } with a private metatable (typeof / type say "buffer"); LuaJIT-only
-- buffer.toffi(b) / buffer.fromffi(ptr, n).
local ffi = require("ffi")
local bit = require("bit")
local floor = math.floor
@@ -25,17 +13,13 @@ 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).
-- The inline `if r < 0 then r = r + 2^32 end` sign fix runs ~45% faster than `r % 2^32` (inflate).
-- Divergence: bit.tobit rounds a fractional operand where Luau truncates (the library never passes fractions).
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
@@ -186,7 +170,6 @@ do
M.bit32 = B
end
-- ---------------------------------------------------------------------------------------------------- buffer
do
ffi.cdef([[
void *memmove(void *dst, const void *src, size_t n);
@@ -208,9 +191,8 @@ do
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.
-- big buffers are calloc'd so they don't count against the 2 GB GC heap of non-GC64 builds (LÖVE); a full
-- collection runs every 512 MB of them since the GC doesn't see those bytes
local BIG = 262144
local external = 0
@@ -380,7 +362,6 @@ do
end
end
-- LuaJIT-only extensions
function Buf.toffi(b) return b.p end
function Buf.fromffi(ptr, n)
local b = create(n)
@@ -390,7 +371,6 @@ do
M.buffer = Buf
end
-- ---------------------------------------------------------------------------------------------------- typeof / type
do
local BUF = M.BUFFER_MT
function M.type(v)
@@ -404,7 +384,6 @@ do
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
@@ -430,7 +409,6 @@ function M.__iter(t, s, c)
return next, t, nil
end
-- ---------------------------------------------------------------------------------------------------- table
do
local okn, tnew = pcall(require, "table.new")
local okc, tclear = pcall(require, "table.clear")
@@ -475,11 +453,9 @@ do
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).
-- math.min / math.max are branch-free in a trace; an if / elseif clamp spawned side traces 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
@@ -507,7 +483,6 @@ do
end
end
-- ---------------------------------------------------------------------------------------------------- string
string.split = string.split or function(s, sep)
sep = sep or ","
local out = {}
@@ -527,7 +502,6 @@ string.split = string.split or function(s, sep)
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]*" }
@@ -546,7 +520,6 @@ do
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
@@ -593,7 +566,6 @@ do
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
@@ -644,7 +616,6 @@ do
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
+24
View File
@@ -77,6 +77,30 @@ The first comment line starts with the module path (`core/Bytes:`, `image/png:`,
the root). A format's `init.luau` header says what is supported and what is not, and where it came from (spec, port,
absorbed repo).
### Comments
Comments carry specifications, not documentation. Usage lives in `docs/API.md` and `docs/guide`, and the code says what
it does. Keep:
- the file header, 1-3 lines (above);
- spec citations: section numbers, field and bit layouts, magic values, where a table comes from;
- one-line notes where the code deliberately matches a reference tool's quirk or follows a non-obvious spec rule;
- units and layouts on type fields (`pts: number, -- seconds`, `data: buffer, -- u16 LE per cell`);
- licence / provenance lines and the `--!` directives.
Remove signature and docstring comments, comments that restate the code, narrative and history ("we tried X"),
usage examples, and divider banners other than the CONTRACT section markers.
```luau
-- keep
-- CRC-32/MPEG-2 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor): a section including its CRC sums to 0
break -- no end-of-archive blocks: accepted, as GNU tar does (with a warning)
-- LuaJIT keeps t[0] in the array part, so check it
-- remove
-- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil
-- UTF-8 of a code point
-- ---------------------------------------------------------------------------------------------- helpers
```
`python3 -I tools/comment_diff.py <base>` checks that a comment-only change leaves every file's token stream unchanged.
### Section order (CONTRACT)
Section markers are `-- ` + 96 dashes + ` <name>`; in a format's `init.luau` they appear in this order (requires and
contract are mandatory, the rest as needed):
+6 -80
View File
@@ -1,20 +1,13 @@
--!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.
-- Types: the standard value types each category decodes to and encodes from, plus small constructors. Every
-- top-level value has a `kind` ("image", "audio", "scene", ...). Shared enums are plain strings; buffers are tightly
-- packed, rows top to bottom, channels interleaved.
local Err = require("@rosetta/core/Err")
local Types = {}
export 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).
export type PixelFormat = "rgba8" | "rgba16" | "rgbaf32" | "rgb8" | "gray8" | "gray16" | "graya8" | "alpha8" | "yuv420p"
@@ -65,7 +58,6 @@ export type Image = {
}
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
@@ -86,16 +78,13 @@ function Image.new(width: number, height: number, format: PixelFormat?): Image
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
export 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)
export type Decoder = {
sampleRate: number,
channels: number,
@@ -103,13 +92,12 @@ export type Decoder = {
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: interleaved f32, frames read (0 at the end); out 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)
export type Audio = {
kind: "audio",
sampleRate: number,
@@ -134,7 +122,6 @@ function Audio.new(sampleRate: number, channels: number, frames: number): Audio
end
Types.Audio = Audio
-- ------------------------------------------------------------------------------------------------ Music (trackers, MIDI)
export type Module = {
kind: "music",
title: string,
@@ -163,12 +150,6 @@ function Midi.new(division: number?): Midi
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.
export type Track = {
@@ -211,11 +192,9 @@ export type Demuxer = {
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: 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
}
@@ -253,23 +232,10 @@ export type VideoCodecDecoder = {
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`.
export type Accessor = {
data: buffer, -- tightly packed, little endian
type: "f32" | "f64" | "u8" | "u16" | "u32" | "i8" | "i16" | "i32" | "unorm8" | "unorm16" | "snorm8" | "snorm16",
@@ -377,7 +343,6 @@ export type VoxelBlocks = {
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
@@ -389,7 +354,6 @@ function Voxels.new(sx: number, sy: number, sz: number, palette: { { number } }?
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
@@ -430,7 +394,6 @@ function Scene.new(): Scene
meta = {},
}
end
-- the byte size of one component of an accessor type
local COMPONENT_SIZE: { [string]: number } = {
f32 = 4,
f64 = 8,
@@ -446,7 +409,6 @@ local COMPONENT_SIZE: { [string]: number } = {
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 }
@@ -463,7 +425,6 @@ function Scene.material(name: string?): Material
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 } }
@@ -473,8 +434,6 @@ function Scene.fromPrimitive(prim: Primitive, name: string?): Scene
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]
@@ -537,7 +496,6 @@ function Scene.reader(acc: Accessor): ((i: number, c: number) -> number)?
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 }
@@ -553,7 +511,6 @@ function Scene.mul(a: { number }, b: { number }): { number }
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
@@ -583,8 +540,6 @@ function Scene.nodeMatrix(node: Node): { number }
}
end
export 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 {}
@@ -628,7 +583,6 @@ function Scene.flatten(scene: Scene): { Placed }
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)
@@ -641,7 +595,6 @@ export type Cad = {
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ Font
export type Font = {
kind: "font",
info: { family: string?, style: string?, fullName: string?, [string]: any },
@@ -678,7 +631,6 @@ export type BitmapStrike = {
map: { [number]: number }?, -- extra code point -> glyph index (0-based) mappings (several code points on one glyph)
}
-- ------------------------------------------------------------------------------------------------ Archive
export type ArchiveEntry = { name: string, size: number, compressedSize: number?, method: string?, mtime: number?, dir: boolean }
export type Archive = {
kind: "archive",
@@ -690,7 +642,6 @@ export type Archive = {
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()
@@ -701,12 +652,8 @@ 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
@@ -715,11 +662,9 @@ function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any }
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
@@ -727,7 +672,6 @@ function Types.set(o: { [any]: any }, k: any, v: any)
end
o[k] = v
end
-- keyLess(a, b): a total order for table keys (by type name, then value; numbers before strings)
local function keyLess(a: any, b: any): boolean
local ta, tb = type(a), type(b)
if ta ~= tb then
@@ -740,8 +684,6 @@ local function keyLess(a: any, b: any): boolean
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
@@ -759,8 +701,6 @@ function Types.isArray(t: { [any]: any }, emptyIsMap: boolean?): boolean
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 = {}, {}
@@ -859,7 +799,6 @@ 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
@@ -872,11 +811,9 @@ function DateLib.new(f: { [string]: any }): Date
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
@@ -897,8 +834,7 @@ function DateLib.valid(d: Date): boolean
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
-- parse: RFC 3339 / ISO 8601 date-times and the TOML partial forms; lower-case t / z accepted
function DateLib.parse(s: string): Date?
local d: any = {}
local rest: string = s
@@ -954,13 +890,11 @@ function DateLib.parse(s: string): Date?
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)
@@ -1000,7 +934,6 @@ export type XmlNode = {
[string]: any,
}
-- ------------------------------------------------------------------------------------------------ Vector
export type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any }
export type VectorPath = {
d: { { op: string, [number]: number } }, -- absolute M / L / C / Q / Z commands
@@ -1033,7 +966,6 @@ function Vector.new(width: number, height: number): Vector
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`).
@@ -1051,17 +983,14 @@ 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
@@ -1087,7 +1016,6 @@ function TileMap.new(width: number, height: number, tileWidth: number, tileHeigh
end
Types.TileMap = TileMap
-- ------------------------------------------------------------------------------------------------ Subtitles
export type Cue = { start: number, stop: number, text: string, style: string?, id: string?, [string]: any } -- seconds
export type Subtitles = { kind: "subtitles", cues: { Cue }, styles: { [string]: any }, meta: { [string]: any } }
local Subtitles = {}
@@ -1096,7 +1024,6 @@ function Subtitles.new(): Subtitles
end
Types.Subtitles = Subtitles
-- ------------------------------------------------------------------------------------------------ Playlist
-- the playlist-luau shape
export type PlaylistEntry = {
url: string,
@@ -1119,7 +1046,6 @@ export type Playlist = {
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ the format contract
-- what every format folder's init.luau returns (checked by tools/lint.sh CONTRACT; see docs/STYLE.md)
export type Caps = { decode: boolean, encode: boolean, [string]: any }
export type Format = {
+4 -30
View File
@@ -1,14 +1,6 @@
--!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()
--
-- containers/Archive: the in-memory Archive value (Types.Archive) archive formats return. Entries hold their data or
-- a lazy loader; write() calls the encoder the format attached, and any Archive can be encoded by any archive writer.
-- 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 = require("@rosetta/core/Err")
@@ -34,7 +26,6 @@ export 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
@@ -53,7 +44,6 @@ function Methods.list(self: any): { Types.ArchiveEntry }
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
@@ -75,7 +65,6 @@ function Methods.read(self: any, name: string): (buffer?, Err.Err?)
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 {}
@@ -90,7 +79,6 @@ function Methods.add(self: any, name: string, data: buffer | string, opts: any?)
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
@@ -99,7 +87,6 @@ function Methods.write(self: any, opts: any?): (buffer?, Err.Err?)
return enc(self, opts)
end
-- new(format, encode?) -> an empty Archive
function Archive.new(format: string, encode: Encoder?): any
return setmetatable({
kind = "archive",
@@ -111,7 +98,6 @@ function Archive.new(format: string, encode: Encoder?): any
}, 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
@@ -125,8 +111,6 @@ function Archive.put(a: any, e: Entry)
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
@@ -153,7 +137,6 @@ function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () ->
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)
@@ -162,8 +145,6 @@ function Archive.slice(buf: buffer, at: number, n: number): () -> (buffer?, Err.
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
@@ -184,8 +165,6 @@ function Archive.collect(value: any): ({ { entry: Types.ArchiveEntry, data: buff
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
@@ -208,8 +187,6 @@ function Archive.files(value: any, name: string?): ({ { name: string, data: buff
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
@@ -240,8 +217,7 @@ function Archive.streamData(value: any): (buffer?, Err.Err?)
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
-- MS-DOS date / time: stamp = date * 65536 + time (LHA / ARJ / ZIP); local time without a zone, read as UTC
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)
@@ -252,7 +228,7 @@ function Archive.fromDos(stamp: number): number?
return Types.Date.daysFromCivil(y, m, d) * 86400 + secs
end
-- toDos(unix?) -> date * 65536 + time (clamped to 1980-01-01 .. 2107-12-31)
-- MS-DOS dates cover 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
@@ -267,8 +243,6 @@ function Archive.toDos(t: number?): number
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
+5 -23
View File
@@ -1,18 +1,7 @@
--!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 })
-- containers/AudioWrap: a video container's audio track as a stream an audio format reads (a format never requires
-- another). New in rosetta. PCM / WAVEFORMATEX -> WAV, adpcm_swf -> f32 WAV, mp1-3 / ac3 -> frames back to back,
-- flac -> fLaC + metadata blocks, opus / vorbis -> Ogg, aac -> ADTS. E-AC-3 is UNSUPPORTED.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
@@ -58,7 +47,6 @@ local function concat(packets: { Types.Packet }, prefix: buffer?): buffer
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 },
@@ -159,7 +147,6 @@ local function swfWav(track: Types.Track, packets: { Types.Packet }): (buffer?,
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)
@@ -315,7 +302,6 @@ local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean }
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
@@ -353,10 +339,8 @@ local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Er
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)
-- trim: a container's codec delay (Matroska CodecDelay, an MP4 edit's media time for MP2 / MP3 / AAC, as ffmpeg)
-- and end padding
function AudioWrap.trim(dec: any, skip: number, length: number?): any
if skip <= 0 and length == nil then
return dec
@@ -412,8 +396,6 @@ function AudioWrap.trim(dec: any, skip: number, length: number?): any
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")
+5 -25
View File
@@ -1,16 +1,7 @@
--!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)
--
-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + OpenDML 1.02), read and written. New in rosetta. The chunk
-- index comes from the OpenDML super index (indx -> ix##), else idx1 (movi-relative or absolute, detected), else a
-- scan of the movi lists. Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an odml / dmlh header.
-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning).
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
@@ -48,8 +39,6 @@ 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)
@@ -193,7 +182,6 @@ local function readIndex(b: buffer, d: number, n: number, s: Stream, limit: numb
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)
@@ -342,7 +330,6 @@ function Avi.read(b: buffer, base: number, limit: number): (File?, Err.Err?)
return file, nil
end
-- ------------------------------------------------------------------------------------------------ writing
export type WStream = {
type: string, -- "vids" | "auds"
handler: string, -- fccHandler (4 chars)
@@ -364,7 +351,6 @@ export type WOptions = {
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)
@@ -397,7 +383,6 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer
local riffSize = w:tell()
w:u32le(0)
w:string("AVI ")
-- hdrl
w:string("LIST")
local hdrlSize = w:tell()
w:u32le(0)
@@ -475,7 +460,6 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer
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"
@@ -486,7 +470,6 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer
w:string("ISFT")
w:u32le(#sw)
w:string(sw)
-- movi
w:string("LIST")
local moviSize = w:tell()
w:u32le(0)
@@ -508,7 +491,6 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer
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
@@ -521,7 +503,6 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer
return w:finish()
end
-- ------------------------------------------------------------------------------------------------ BITMAPINFO
export type BitmapInfo = {
width: number,
height: number, -- signed: > 0 = bottom-up rows
@@ -531,9 +512,8 @@ export type BitmapInfo = {
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.
-- BITMAPINFOHEADER: the palette is the last (2^bits) * 4 bytes after the header (B, G, R, x; a trailing "BottomUp"
-- tag skipped), as the VfW codecs store it
function Avi.bitmapInfo(f: buffer): BitmapInfo?
local n = buffer.len(f)
if n < 40 then
+3 -12
View File
@@ -1,14 +1,7 @@
--!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")
--
-- containers/Chunks: the generic walker for chunked files (an id and a size per chunk, body, optional trailer and
-- padding): RIFF / RIFX / RF64, IFF / AIFF / AIFC, PNG (size first, CRC trailer), CAF (64-bit sizes). New in rosetta
-- (the RIFF leniency comes from containers/Riff, absorbed from wav-luau).
-- 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
@@ -65,7 +58,6 @@ local function u32(b: buffer, o: number, be: boolean): number
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
@@ -129,7 +121,6 @@ function Chunks.walk(b: buffer, p: number, limit: number, layout: Layout?): { Ch
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
+4 -18
View File
@@ -1,16 +1,7 @@
--!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" })
--
-- containers/Cpio: cpio, read and written, from cpio(5) (libarchive, GNU cpio) and POSIX.1-1988 (odc). Reads newc
-- (070701), crc (070702, byte sums verified), odc (070707), old binary in both byte orders; writes newc / crc / odc
-- padded to opts.block (512, as GNU cpio). A hard link group's data sits on its last link (as GNU cpio and bsdtar).
-- Never throws: bad data returns nil, Err.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
@@ -62,7 +53,6 @@ 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
@@ -99,7 +89,7 @@ local function num(b: buffer, o: number, n: number, base: number): number?
return tonumber(s, base)
end
-- checksum(buf, offset, n) -> the crc format's sum of the data bytes (mod 2^32)
-- the crc format's checksum: the sum of the data bytes mod 2^32
function Cpio.checksum(b: buffer, o: number, n: number): number
local s = 0
local i = o
@@ -116,7 +106,6 @@ function Cpio.checksum(b: buffer, o: number, n: number): number
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
@@ -179,7 +168,6 @@ local function header(b: buffer, p: number, e: number, fmt: string): (any, Err.E
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)))
@@ -278,7 +266,6 @@ function Cpio.read(b: buffer, offset: number?, length: number?, opts: ReadOption
return out, { format = fmt }
end
-- ------------------------------------------------------------------------------------------------ writing
export type WriteEntry = {
name: string,
data: buffer?, -- file data (a symlink: its target, else taken from link)
@@ -316,7 +303,6 @@ local function oct(v: number, w: number): string?
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
+1 -24
View File
@@ -1,15 +1,6 @@
--!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)
-- New in rosetta. Packets are offset + length into the source buffer (or own bytes); per-track cursors are independent.
local Types = require("@rosetta/Types")
local Demux = {}
@@ -42,7 +33,6 @@ export type Demux = typeof(setmetatable(
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",
@@ -68,7 +58,6 @@ function Demux.new(format: string, tracks: { Types.Track }, src: buffer, meta: {
}, 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
@@ -81,13 +70,11 @@ function D.add(self: Demux, track: number, pts: number, dts: number?, duration:
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
@@ -97,8 +84,6 @@ function D.setExtra(self: Demux, key: string, value: any)
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
@@ -158,7 +143,6 @@ function D.finish(self: Demux)
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
@@ -190,7 +174,6 @@ function D._packet(self: Demux, i: number): Types.Packet
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
@@ -213,14 +196,12 @@ function D.read(self: Demux, track: number?): Types.Packet?
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
@@ -234,7 +215,6 @@ function D.get(self: Demux, track: number, k: number): Types.Packet?
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]
@@ -244,7 +224,6 @@ function D.info(self: Demux, track: number, k: number): (number?, number?, numbe
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
@@ -256,7 +235,6 @@ function D.rewind(self: Demux, track: number?)
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
@@ -279,7 +257,6 @@ function D.seek(self: Demux, seconds: number)
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
-24
View File
@@ -4,11 +4,6 @@
-- 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 = require("@rosetta/core/Bytes")
@@ -18,7 +13,6 @@ 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
@@ -51,7 +45,6 @@ function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?)
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
@@ -63,7 +56,6 @@ function Ebml.svint(buf: buffer, pos: number, limit: number): (number?, number?)
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
@@ -80,7 +72,6 @@ function Ebml.id(buf: buffer, pos: number, limit: number): (number?, number?)
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
@@ -93,8 +84,6 @@ function Ebml.header(buf: buffer, pos: number, limit: number): (number?, number?
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)
@@ -114,7 +103,6 @@ function Ebml.children(buf: buffer, off: number, limit: number): () -> (number?,
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
@@ -156,18 +144,15 @@ function Ebml.binary(buf: buffer, off: number, len: number): buffer
return b
end
-- ------------------------------------------------------------------------------------------------ writing
local W = {}
W.__index = W
export 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)
@@ -180,7 +165,6 @@ local function writeId(w: Bytes.Writer, id: number)
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
@@ -200,7 +184,6 @@ local function writeSize(w: Bytes.Writer, size: number, n: number?)
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)
@@ -211,7 +194,6 @@ 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()
@@ -221,7 +203,6 @@ function W.open(self: Writer, id: number): number
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
@@ -232,7 +213,6 @@ function W.close(self: Writer, at: number)
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)
@@ -289,7 +269,6 @@ function W.string(self: Writer, id: number, s: string)
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)
@@ -298,7 +277,6 @@ function W.binary(self: Writer, id: number, b: buffer, off: number?, len: number
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
@@ -306,13 +284,11 @@ 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
+3 -24
View File
@@ -1,15 +1,7 @@
--!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
--
-- containers/Fat: FAT12 / FAT16 / FAT32 over a byte range (BPB, chains, VFAT long names checksum-validated against
-- their 8.3 entry, NT lower-case flags; an MBR's first FAT partition) and a FAT12 floppy writer. New code, from
-- Microsoft's fatgen103 and the VFAT long-name layout.
-- 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 = require("@rosetta/containers/Archive")
@@ -48,7 +40,6 @@ export type Entry = {
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"
@@ -154,7 +145,6 @@ function Fat.open(b: buffer, off: number, len: number, opts: OpenOptions?): (Vol
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
@@ -180,7 +170,6 @@ local function nextCluster(v: Volume, c: number): number
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
@@ -204,7 +193,6 @@ 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
@@ -233,7 +221,6 @@ local function readChain(v: Volume, first: number, size: number?): (buffer?, str
return out, nil
end
-- ------------------------------------------------------------------------------------------------ directories
local function latin1(s: string): string
if not string.find(s, "[\128-\255]") then
return s
@@ -259,7 +246,6 @@ local function ucs2(b: buffer, o: number, n: number, out: { number })
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
@@ -349,7 +335,6 @@ local function parseDir(d: buffer, prefix: string, out: { Entry }): { Entry }
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
@@ -403,7 +388,6 @@ function Fat.list(v: Volume, maxEntries: number?): ({ Entry }?, string?)
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
@@ -414,7 +398,6 @@ function Fat.read(v: Volume, e: Entry): (buffer?, string?)
return readChain(v, e.cluster, e.size)
end
-- ------------------------------------------------------------------------------------------------ write
export type WriteFile = { name: string, data: buffer?, dir: boolean?, mtime: number? }
export type WriteOptions = {
size: number?, -- 360 / 720 / 1200 / 1440 / 2880 KB (default 1440)
@@ -439,7 +422,6 @@ 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
@@ -491,7 +473,6 @@ local function shortName(name: string, used: { [string]: boolean }): (string, nu
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?)
@@ -556,7 +537,6 @@ local function dirEntries(n: Node, parentCluster: number, isRoot: boolean, label
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]
@@ -681,7 +661,6 @@ function Fat.write(files: { WriteFile }, opts: WriteOptions?): (buffer?, string?
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)
+4 -26
View File
@@ -1,18 +1,8 @@
--!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)
-- containers/Iso9660: ISO 9660 (ECMA-119) images, read; from ECMA-119, SUSP / RRIP 1.12, Joliet and El Torito 1.0, no
-- code ported. Name sets: Rock Ridge, else Joliet (%/@, %/C, %/E), else plain (";1" and a trailing "." dropped);
-- multi-extent files joined, CL / RE / PL relocations resolved, El Torito catalog in info.boot. Not supported: zisofs
-- (read returns the stored bytes), interleaved files (Err.UNSUPPORTED), UDF, writing.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Text = require("@rosetta/codecs/text/Text")
@@ -45,7 +35,6 @@ export type ReadOptions = {
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
@@ -78,10 +67,8 @@ local function longDate(b: buffer, o: number): number?
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
@@ -116,7 +103,6 @@ local function suspEntries(b: buffer, base: number, limit: number, o: number, e:
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
@@ -189,7 +175,6 @@ local function rockRidge(b: buffer, base: number, limit: number, o: number, e: n
return rr
end
-- ------------------------------------------------------------------------------------------------ directories
type Record = {
name: string,
dir: boolean,
@@ -202,7 +187,6 @@ type Record = {
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)
@@ -258,7 +242,6 @@ local function records(b: buffer, base: number, limit: number, at: number, size:
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
@@ -281,7 +264,6 @@ local function rockRidgeSkip(b: buffer, base: number, limit: number, lba: number
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
@@ -309,8 +291,6 @@ local function boot(b: buffer, base: number, limit: number, vd: number, bs: numb
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)))
@@ -498,7 +478,6 @@ function Iso9660.read(b: buffer, offset: number?, length: number?, opts: ReadOpt
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)
@@ -516,7 +495,6 @@ function Iso9660.extract(b: buffer, e: Entry, limit: number?): (buffer?, Err.Err
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"
-7
View File
@@ -42,7 +42,6 @@ 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)
@@ -79,8 +78,6 @@ function Box.header(b: buffer, p: number, limit: number): (Box?, Err.Err?)
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 } = {}
@@ -133,7 +130,6 @@ function Box.list(b: buffer, p: number, limit: number, parentType: string?, dept
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
@@ -146,7 +142,6 @@ function Box.child(box: Box?, typ: string): Box?
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
@@ -159,7 +154,6 @@ function Box.childrenOf(box: Box?, typ: string): { Box }
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
@@ -181,7 +175,6 @@ function Box.path(root: any, path: string): Box?
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
+3 -22
View File
@@ -1,10 +1,7 @@
--!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.
-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8),
-- edit lists and fragments (mvex / trex, moof / traf / tfhd / tfdt / trun). The per-sample tables are columnar arrays,
-- offsets absolute in the reader's buffer. Never throws.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Box = require("@rosetta/containers/IsoBmff/Box")
@@ -20,8 +17,6 @@ local Demux = {}
export 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
export type Track = {
id: number,
kind: "video" | "audio" | "subtitle" | "data",
@@ -47,7 +42,6 @@ export type Track = {
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 },
@@ -110,7 +104,6 @@ local function descLen(r: Bytes.Reader): number
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
@@ -150,7 +143,6 @@ function Demux.esds(b: buffer, box: Box.Box): (number?, buffer?, number?)
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)
@@ -253,7 +245,6 @@ local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track)
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")
@@ -321,7 +312,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
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")
@@ -330,7 +320,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
end
t.sampleEntries = entries
end
-- edit list
local elst = Box.path(trak, "edts/elst")
if elst then
local r = reader(b, elst)
@@ -373,7 +362,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
end
end
end
-- sample sizes
local maxSamples = o.maxSamples or 2 ^ 25
local sizes = t.sizes
local count = 0
@@ -432,7 +420,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
end
end
end
-- decode times
local dts, durs = t.dts, t.durations
local stts = Box.child(stbl, "stts")
if stts and count > 0 then
@@ -466,7 +453,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
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)
@@ -493,7 +479,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
t.cts = cts
end
end
-- sync samples
local stss = Box.child(stbl, "stss")
if stss then
local r = reader(b, stss)
@@ -507,7 +492,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
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 } = {}
@@ -614,12 +598,10 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
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
@@ -751,7 +733,6 @@ export type Movie = {
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
+1 -10
View File
@@ -32,7 +32,6 @@ local function uint(r: Bytes.Reader, size: number): number
return 0
end
-- ------------------------------------------------------------------------------------------------ HEIF items
export type Property = { type: string, box: Box.Box, [string]: any }
export type Item = {
id: number,
@@ -103,7 +102,6 @@ local function property(b: buffer, box: Box.Box): Property
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")
@@ -253,8 +251,6 @@ function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?)
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
@@ -296,7 +292,6 @@ function Meta.itemData(b: buffer, base: number, limit: number, items: Items, id:
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",
@@ -330,7 +325,6 @@ local GENRES = {
export 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 } = {}
@@ -396,7 +390,6 @@ function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture
return tags, pics
end
-- ------------------------------------------------------------------------------------------------ ilst writer
local function box(w: Bytes.Writer, typ: string, body: (Bytes.Writer) -> ())
local start = w:tell()
w:u32be(0)
@@ -426,8 +419,6 @@ local function num(s: string?): number
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 = {}
@@ -506,7 +497,7 @@ function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: {
end)
end
-- writeUdta(w, tags, pictures?): udta / meta (hdlr mdir) / ilst
-- udta / meta (hdlr mdir) / ilst
function Meta.writeUdta(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?)
box(w, "udta", function()
box(w, "meta", function()
+3 -8
View File
@@ -1,9 +1,7 @@
--!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.
-- containers/IsoBmff/Mux: writes a progressive ISO BMFF / MP4 / M4A file (ISO/IEC 14496-12): ftyp, moov first ("fast
-- start"), the samples interleaved in chunks in one mdat, udta / meta / ilst tags; co64 past 4 GB. Audio and video
-- sample entries with their configuration box, plus raw child boxes. Never throws: bad specs return nil, Err.ARG.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Meta = require("@rosetta/containers/IsoBmff/Meta")
@@ -154,7 +152,6 @@ 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
@@ -381,7 +378,6 @@ local function moov(w: Bytes.Writer, spec: MuxSpec, prep: { Prepared }, co64: bo
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 = { ... } }")
@@ -476,7 +472,6 @@ function Mux.mux(spec: MuxSpec): (buffer?, Err.Err?)
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")
@@ -5,10 +5,6 @@
-- 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
@@ -71,8 +67,7 @@ local function defaultTable(bits: number): buffer
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.
-- 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
+1 -21
View File
@@ -2,15 +2,6 @@
-- 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),
@@ -40,8 +31,6 @@ local TOP: { [string]: boolean } = {
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
@@ -60,18 +49,15 @@ function IsoBmff.sniff(r: Bytes.Reader): string?
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
@@ -80,12 +66,10 @@ function IsoBmff.items(r: Bytes.Reader, movie: Movie): (Items?, Err.Err?)
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
@@ -96,8 +80,6 @@ function IsoBmff.sample(r: Bytes.Reader, t: Track, i: number): buffer?
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
@@ -137,7 +119,6 @@ function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?)
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
@@ -154,7 +135,7 @@ function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?)
return packet(best, i)
end
end
-- seek(seconds): every track to its last sync sample at or before the time
-- 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
@@ -180,7 +161,6 @@ function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?)
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
-11
View File
@@ -4,11 +4,6 @@
-- 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 = require("@rosetta/core/Err")
local Archive = require("@rosetta/containers/Archive")
@@ -56,7 +51,6 @@ 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
@@ -69,7 +63,6 @@ function MacFile.name(s: string): string
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
@@ -88,8 +81,6 @@ local function four(s: any): string
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,
@@ -112,8 +103,6 @@ function MacFile.put(a: any, f: Info, noData: boolean?)
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
-9
View File
@@ -7,7 +7,6 @@ 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
@@ -40,7 +39,6 @@ export type Picture = {
}
export 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
@@ -64,7 +62,6 @@ function MpegEs.info(b: buffer, off: number, limit: number): Info?
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
@@ -79,8 +76,6 @@ function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, num
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
@@ -100,9 +95,6 @@ function MpegEs.pictureStructure(b: buffer, p: number, limit: number): number
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
@@ -151,7 +143,6 @@ function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture }
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
+1 -7
View File
@@ -4,12 +4,7 @@
-- 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.
-- Never throws: malformed packets are skipped (ps.errors). Private stream 1 sub-streams are keyed 0xBD00 + their id.
local Err = require("@rosetta/core/Err")
local MpegEs = require("@rosetta/containers/MpegEs")
@@ -44,7 +39,6 @@ local function ts(b: buffer, p: number): number
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 } = {}
+2 -27
View File
@@ -1,16 +1,8 @@
--!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.
-- author; no third-party code); changed: the unit queue keeps an explicit tail (#q on a table with holes at its front
-- loses units under LuaJIT's border rule). Never throws: bad input is skipped and counted in `stats`.
local Crc32 = require("@rosetta/core/Crc32")
local MpegTs = {}
@@ -172,7 +164,6 @@ function MpegTs.new(): Demuxer
return self
end
-- PSI ---------------------------------------------------------------------------------------------------------
local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?)
local info = CODECS[streamType]
@@ -259,7 +250,6 @@ local function sectionBytes(self: Demuxer, pid: number, s: SectionState, src: bu
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
@@ -304,7 +294,6 @@ local function sectionPayload(self: Demuxer, pid: number, pusi: boolean, b: buff
sectionBytes(self, pid, s, b, pos, stop)
end
-- PES ---------------------------------------------------------------------------------------------------------
local function completePes(self: Demuxer, pid: number, st: PesState)
st.active = false
@@ -516,7 +505,6 @@ local function pesPayload(
end
end
-- packets -----------------------------------------------------------------------------------------------------
local function packet(self: Demuxer, b: buffer, pk: number)
local stats = self.stats
@@ -572,7 +560,6 @@ local function packet(self: Demuxer, b: buffer, pk: number)
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
@@ -592,8 +579,6 @@ local function packet(self: Demuxer, b: buffer, pk: number)
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: Demuxer, data: buffer | string, offset: number?, len: number?): boolean
local src: buffer
if type(data) == "string" then
@@ -612,7 +597,6 @@ function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len
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)
@@ -678,7 +662,6 @@ function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len
return true
end
-- The next completed unit (any PID), or nil.
function Demuxer.pull(self: Demuxer): Unit?
local q = self._queue
local h = self._qhead
@@ -697,8 +680,6 @@ function Demuxer.pull(self: Demuxer): Unit?
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: Demuxer)
local pids = {}
for pid, st in self._pes do
@@ -713,7 +694,6 @@ function Demuxer.flush(self: Demuxer)
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: Demuxer)
self._pendLen = 0
for _, st in self._pes do
@@ -732,7 +712,6 @@ function Demuxer.reset(self: Demuxer)
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: Demuxer, kind: string): Stream?
for _, s in self.streams do
if s.kind == kind then
@@ -744,9 +723,6 @@ end
export 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.
function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed
local d = MpegTs.new()
d:push(data)
@@ -796,7 +772,6 @@ function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed
}
end
-- Concatenates the data of a list of units (e.g. a segment's audio access units, for Mp3.open).
function MpegTs.concat(units: { Unit }): buffer
local n = 0
for _, u in units do
-15
View File
@@ -6,14 +6,6 @@
-- 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 = require("@rosetta/core/Err")
local Page = require("@rosetta/containers/Ogg/Page")
@@ -35,7 +27,6 @@ export type PacketOptions = {
eos: boolean?, -- this is the stream's last packet (default false: finish() writes an empty eos page if needed)
}
-- new(opts?) -> Mux
function Mux.new(opts: Options?): any
local size = opts and opts.pageSize or 4096
if type(size) ~= "number" or size < 1 then
@@ -50,7 +41,6 @@ function Mux.new(opts: Options?): any
}, Mux)
end
-- stream(serial?) -> Stream (serials must be unique in the file)
function Mux.stream(self: any, serial: number?): any
local sr = serial or self.nextSerial
self.nextSerial = math.max(self.nextSerial, sr + 1)
@@ -80,7 +70,6 @@ local function crc(b: buffer, n: number): number
return c
end
-- close the page being built (also when empty, for eos)
function Stream._flush(self: any, eos: boolean)
local nseg = #self.lacing
local n = 27 + nseg + self.dataLen
@@ -121,8 +110,6 @@ function Stream._flush(self: any, eos: boolean)
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: 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)
@@ -179,14 +166,12 @@ function Stream.packet(self: any, data: any, granule: number, opts: PacketOption
return true, nil
end
-- flush(): close the current page now (if it holds anything)
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)
function Mux.finish(self: any): buffer
for _, s in self.streams do
if not s.ended then
+4 -12
View File
@@ -1,10 +1,9 @@
--!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.
--
-- containers/Ogg/Page: Ogg pages (RFC 3533): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the crc field read as
-- zero), header parsing and the capture-pattern resync. Absorbed from ogg-luau be9f604 (same author, no third-party
-- code). Never 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
@@ -32,7 +31,6 @@ export type Info = {
local CRC = Crc32.MSB_TABLE
Page.CRC_TABLE = CRC
-- CRC of bytes [from, to) (caller guarantees bounds), continuing from crc
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])
@@ -40,7 +38,7 @@ local function crcRange(b: buffer, from: number, to: number, crc: number): numbe
return crc
end
-- CRC-32 of a byte range, the Ogg way (the crc field is not zeroed: use for arbitrary data)
-- the Ogg CRC-32 of arbitrary data (the crc field is not zeroed)
function Page.crc32(b: buffer, offset: number?, len: number?): number
local o = offset or 0
local n = len or (buffer.len(b) - o)
@@ -50,8 +48,6 @@ function Page.crc32(b: buffer, offset: number?, len: number?): number
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: buffer, pos: number, verify: boolean?): (Info?, string?)
local size = buffer.len(b)
if pos < 0 or pos + 27 > size then
@@ -102,8 +98,6 @@ function Page.parse(b: buffer, pos: number, verify: boolean?): (Info?, string?)
}, 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: buffer, pos: number, limit: number?, verify: boolean?): Info?
local size = buffer.len(b)
local lim = math.min(limit or size, size - 27 + 1)
@@ -122,7 +116,6 @@ function Page.find(b: buffer, pos: number, limit: number?, verify: boolean?): In
return nil
end
-- The last valid page starting at an offset in [floor, pos] (searching backwards).
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)
@@ -141,7 +134,6 @@ function Page.findBack(b: buffer, pos: number, floor: number?, verify: boolean?)
return nil
end
-- The identification of a codec from a stream's first packet (the bos page's packet)
function Page.codec(b: buffer, off: number, len: number): string
local function is(s: string, at: number): boolean
if at + #s > len then
+4 -37
View File
@@ -1,24 +1,9 @@
--!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
-- containers/Ogg: the Ogg container (RFC 3533): a demuxer (absorbed from ogg-luau be9f604, same author, no third-party
-- code) and the muxer (Ogg/Mux, new). Packets are reassembled across pages per serial; seeking bisects byte offsets
-- to the page holding a granule. Never throws.
local Err = require("@rosetta/core/Err")
local Page = require("@rosetta/containers/Ogg/Page")
local Mux = require("@rosetta/containers/Ogg/Mux")
@@ -51,7 +36,6 @@ export type Stream = {
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
@@ -76,7 +60,6 @@ local function newReader(d: any, serial: number, start: number): any
}, Reader)
end
-- Load the next page of this serial; false at the end of the data
function Reader._nextPage(self: any): boolean
local b, d = self.buf, self.demux
while true do
@@ -129,7 +112,6 @@ function Reader._nextPage(self: any): boolean
end
end
-- The next packet, or nil at the end of the stream
function Reader.nextPacket(self: any): Packet?
if self.ended then
return nil
@@ -207,7 +189,6 @@ function Reader.nextPacket(self: any): Packet?
end
end
-- Back to the start of the stream (the identification packet comes next)
function Reader.rewind(self: any)
self.pagePos = self.start
self.page = nil
@@ -218,7 +199,6 @@ function Reader.rewind(self: any)
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: any, p: PageInfo)
self:rewind()
self.pagePos = p.offset
@@ -237,10 +217,7 @@ function Reader._at(self: any, p: PageInfo)
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).
-- seekGranule: after the last page with granule <= g (bisection, then a short scan); before every granule rewinds (-1)
function Reader.seekGranule(self: any, g: number): (number?, Err.Err?)
local b, d = self.buf, self.demux
local serial = self.serial
@@ -286,13 +263,9 @@ function Reader.seekGranule(self: any, g: number): (number?, Err.Err?)
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: any, opts: { verify: boolean?, scanAll: boolean? }?): (any, Err.Err?)
local buf: buffer
if type(src) == "buffer" then
@@ -359,7 +332,6 @@ function Ogg.open(src: any, opts: { verify: boolean?, scanAll: boolean? }?): (an
return d, nil
end
-- Scan backwards from the end for each stream's last granule
function Demux._scanLast(self: any)
if self._lastDone then
return
@@ -382,7 +354,6 @@ function Demux._scanLast(self: any)
end
end
-- Every logical stream: { serial, codec, firstPacket, bosOffset, lastGranule }
function Demux.streams(self: any): { Stream }
self:_scanLast()
return self._streams
@@ -393,7 +364,6 @@ function Demux.stream(self: any, serial: number): Stream?
return self._bySerial[serial]
end
-- The serial of the first stream of a codec, or nil
function Demux.find(self: any, codec: string): number?
for _, s in self._streams do
if s.codec == codec then
@@ -403,7 +373,6 @@ function Demux.find(self: any, codec: string): number?
return nil
end
-- The packet cursor of a stream (one per serial, shared by nextPacket / seekGranule below), or nil, Err
function Demux.reader(self: any, serial: number): (any, Err.Err?)
local r = self._readers[serial]
if r then
@@ -438,7 +407,6 @@ function Demux.rewind(self: any, serial: number)
end
end
-- for p in demux:packets(serial) do ... end (continues from the stream's current position)
function Demux.packets(self: any, serial: number): () -> Packet?
local r = self:reader(serial)
return function()
@@ -446,7 +414,6 @@ function Demux.packets(self: any, serial: number): () -> Packet?
end
end
-- Copy a packet's bytes into a fresh buffer of its own
function Ogg.copy(p: Packet): buffer
local c = buffer.create(p.size)
buffer.copy(c, 0, p.data, p.offset, p.size)
-28
View File
@@ -2,18 +2,6 @@
-- 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
@@ -52,13 +40,11 @@ export type ReadOptions = {
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
@@ -68,8 +54,6 @@ function Riff.sniff(r: any): string?
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,
@@ -89,7 +73,6 @@ local function walk(b: buffer, p: number, limit: number, be: boolean, opts: Read
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
@@ -147,7 +130,6 @@ function Riff.read(src: any, opts: ReadOptions?): (File?, Err.Err?)
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
@@ -157,7 +139,6 @@ function Riff.find(f: File, id: string, from: number?): (Chunk?, number?)
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
@@ -165,7 +146,6 @@ function Riff.listType(f: File, c: Chunk): string?
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 {}
@@ -173,12 +153,10 @@ function Riff.list(f: File, c: Chunk, opts: ReadOptions?): { Chunk }
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)
@@ -189,7 +167,6 @@ function Riff.u32(f: File, o: number): number
return u32(f.buf, o, f.bigEndian)
end
-- ------------------------------------------------------------------------------------------------ write
local Writer = {}
Writer.__index = Writer
@@ -200,7 +177,6 @@ export type WriteOptions = {
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),
@@ -212,8 +188,6 @@ function Riff.writer(form: string, opts: WriteOptions?): 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
@@ -231,7 +205,6 @@ function Writer.chunk(self: any, id: string, body: any, offset: number?, length:
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))
@@ -253,7 +226,6 @@ function Writer.list(self: any, listType: string, items: { { any } })
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
+3 -17
View File
@@ -1,16 +1,7 @@
--!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)
--
-- containers/Tar: tar (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written; from POSIX pax(1) (IEEE Std
-- 1003.1-2017) and the GNU tar manual. Reads v7 / ustar / GNU / pax headers ('x' / 'g', 'L' / 'K', base-256, signed
-- checksums); writes ustar + pax, or GNU 'L' / 'K'. Not supported: sparse files, multi-volume (listed as "S" / "M").
-- Never throws: bad data returns nil, Err.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
@@ -78,7 +69,6 @@ local function checksum(b: buffer, o: number): (number, number)
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
@@ -117,7 +107,6 @@ end
export 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)))
@@ -261,7 +250,6 @@ function Tar.read(b: buffer, offset: number?, length: number?, opts: ReadOptions
return out, nil
end
-- ------------------------------------------------------------------------------------------------ writing
export type WriteEntry = {
name: string,
data: buffer?,
@@ -305,7 +293,6 @@ local function paxRecord(key: string, value: string): string
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)
@@ -340,7 +327,6 @@ local function split(path: string): (string?, string?)
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))
+7 -35
View File
@@ -1,23 +1,9 @@
--!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.
-- containers/Zip: ZIP (PKWARE APPNOTE 6.3), read and written. The reader is absorbed from zip-luau 121d4b0 (same
-- author, no third-party code): EOCD search, ZIP64, prefix shifts (self-extractor stubs), stored / deflated entries,
-- data descriptors. The writer is new: stored / deflated, UTF-8 names, DOS times, raw entry copies, ZIP64 when needed.
-- Never throws: corrupt archives and bad arguments return nil, Err.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Bytes = require("@rosetta/core/Bytes")
@@ -50,7 +36,6 @@ export type Entry = {
cdExtraLen: number,
}
-- ------------------------------------------------------------------------------------------------ read
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
local SIG_LOCAL, SIG_CD, SIG_EOCD = 0x04034b50, 0x02014b50, 0x06054b50
@@ -85,7 +70,6 @@ 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)
@@ -253,8 +237,6 @@ local function parse(b: buffer): (any, Err.Err?)
}, 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
@@ -279,14 +261,11 @@ function Zip.open(src: any): (any, Err.Err?)
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.
-- lookup: exact, then case-insensitive, then by basename (never __MACOSX/ or ._ files); "\\" and "/" are the same
function Archive.find(self: any, name: string): Entry?
local n = normalize(name)
local e = self._exact[n]
@@ -327,8 +306,8 @@ local function extract(b: buffer, e: Entry, dataStart: number): (buffer?, any)
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)
-- data offset candidates: the local header's 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 = {}
@@ -345,7 +324,6 @@ function Zip._starts(b: buffer, e: Entry): { number }
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
@@ -390,7 +368,6 @@ function Archive.read(self: any, entry: Entry | string, verify: boolean?): (buff
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
@@ -399,7 +376,6 @@ function Archive.readString(self: any, entry: Entry | string, verify: boolean?):
return buffer.tostring(out), nil
end
-- ------------------------------------------------------------------------------------------------ write
local Writer = {}
Writer.__index = Writer
@@ -416,7 +392,6 @@ export type FinishOptions = {
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
@@ -463,7 +438,6 @@ 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")
@@ -513,7 +487,6 @@ function Writer.add(self: any, name: string, data: any, opts: AddOptions?): (boo
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
@@ -544,7 +517,6 @@ function Writer.addRaw(self: any, e: Entry, archive: any, newName: string?): (bo
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
+1 -7
View File
@@ -2,19 +2,14 @@
--!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: 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.
-- zlib NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32
local stop = math.min(e, i + 5552)
while i < stop do
a += readu8(buf, i)
@@ -27,7 +22,6 @@ local function adler32(buf: buffer, off: number, len: number, adler: number?): n
return b * 65536 + a
end
-- clamp (offset, length) to the buffer
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)
+2 -12
View File
@@ -4,12 +4,6 @@
-- 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 = {}
export type EncodeOptions = {
@@ -37,7 +31,6 @@ 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: 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)
@@ -45,7 +38,7 @@ function Base64.encode(data: buffer | string, opts: EncodeOptions?, offset: numb
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 wrap = if opts and opts.wrap and opts.wrap >= 4 then opts.wrap // 4 else 0
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)
@@ -92,7 +85,6 @@ function Base64.encode(data: buffer | string, opts: EncodeOptions?, offset: numb
return buffer.tostring(out)
end
-- decode(s) -> buffer | nil, message
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)
@@ -129,8 +121,7 @@ function Base64.decode(s: string | buffer): (buffer?, string?)
return res, nil
end
-- decodeDataUri(uri) -> buffer, mime | nil, message: "data:[<mime>][;params][;base64],<data>" (percent-encoded data
-- when not base64)
-- RFC 2397: data:[<mime>][;params][;base64],<data> (percent-encoded data when not base64)
function Base64.decodeDataUri(uri: string): (buffer?, string?)
if string.sub(uri, 1, 5) ~= "data:" then
return nil, "not a data: URI"
@@ -159,7 +150,6 @@ function Base64.decodeDataUri(uri: string): (buffer?, string?)
return buffer.fromstring(decoded), mime
end
-- dataUri(buf, mime?) -> "data:<mime>;base64,..."
function Base64.dataUri(buf: buffer | string, mime: string?): string
return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf)
end
+1 -20
View File
@@ -2,25 +2,14 @@
--!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 = require("@rosetta/core/Err")
local Bytes = require("@rosetta/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
@@ -29,7 +18,6 @@ end
local Bits = {}
Bits.POW = POW
-- ------------------------------------------------------------------------------------------------ readers
export type BitReader = {
buf: buffer,
pos: number, -- next byte to load
@@ -108,14 +96,12 @@ function Lsb.skip(self: any, n: number)
end
Lsb.read(self, n)
end
-- align(): drop the bits up to the next byte boundary
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
function Lsb.bytePos(self: any): number
return self.pos - floor(self.cnt / 8)
end
@@ -196,7 +182,6 @@ local function reader(meta: any, buf: buffer, offset: number?, length: number?):
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
function Bits.lsbReader(buf: buffer, offset: number?, length: number?): BitReader
return reader(Lsb, buf, offset, length)
end
@@ -204,7 +189,6 @@ function Bits.msbReader(buf: buffer, offset: number?, length: number?): BitReade
return reader(Msb, buf, offset, length)
end
-- ------------------------------------------------------------------------------------------------ writers
export type BitWriter = {
out: Bytes.Writer, -- the bytes so far (whole bytes only)
acc: number,
@@ -234,7 +218,6 @@ function LsbW.write(self: any, v: number, n: number)
end
self.acc, self.cnt = acc, cnt
end
-- align(): pad with zero bits to a byte boundary
function LsbW.align(self: any)
if self.cnt > 0 then
self.out:u8(self.acc)
@@ -278,8 +261,7 @@ function MsbW.finish(self: any): buffer
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).
-- w = { buf, pos, acc, cnt }: no growth (the caller keeps buf large enough); acc holds cnt < 8 bits
export type RawWriter = { buf: buffer, pos: number, acc: number, cnt: number }
function Bits.msbPut(w: RawWriter, v: number, n: number)
if n == 0 then
@@ -299,7 +281,6 @@ function Bits.msbPut(w: RawWriter, v: number, n: number)
w.acc, w.cnt, w.pos = acc, cnt, p
end
-- lsbWriter(capacity?) / msbWriter(capacity?) -> BitWriter
function Bits.lsbWriter(capacity: number?): BitWriter
return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) :: any
end
+1 -43
View File
@@ -2,19 +2,8 @@
--!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
-- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads.
local Err = require("@rosetta/core/Err")
local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32
@@ -28,7 +17,6 @@ local scratch = bcreate(8) -- reinterpret casts for big-endian floats
local Bytes = {}
-- ------------------------------------------------------------------------------------------------ Reader
local Reader = {}
Reader.__index = Reader
@@ -43,7 +31,6 @@ export type Reader = typeof(setmetatable(
Reader
))
-- reader(buf, offset?, length?) -> Reader over buf[offset, offset + length), clamped to the buffer
function Bytes.reader(buf: buffer, offset: number?, length: number?): Reader
local n = blen(buf)
local o = math.clamp(offset or 0, 0, n)
@@ -51,7 +38,6 @@ function Bytes.reader(buf: buffer, offset: number?, length: number?): Reader
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(...)`
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)
@@ -59,7 +45,6 @@ function Reader.fail(self: Reader, code: string, message: string): (nil, Err.Err
return nil, self.err :: Err.Err
end
-- need(n) -> true when n more bytes are available; otherwise records TRUNCATED and moves to the end
function Reader.need(self: Reader, n: number): boolean
if self.pos + n <= self.limit and n >= 0 then
return true
@@ -84,7 +69,6 @@ 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
function Reader.seek(self: Reader, offset: number): boolean
if offset < 0 or self.base + offset > self.limit then
self.pos = self.limit
@@ -105,7 +89,6 @@ function Reader.skip(self: Reader, n: number): boolean
return false
end
-- align(n): skip to the next multiple of n (relative to the reader's start)
function Reader.align(self: Reader, n: number): boolean
local r = (self.pos - self.base) % n
if r == 0 then
@@ -114,7 +97,6 @@ function Reader.align(self: Reader, n: number): boolean
return self:skip(n - r)
end
-- integers
function Reader.u8(self: Reader): number
local p = self.pos
if p + 1 > self.limit then
@@ -213,7 +195,6 @@ 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)
function Reader.u64le(self: Reader): number
local lo = self:u32le()
return lo + self:u32le() * TWO32
@@ -231,7 +212,6 @@ function Reader.i64be(self: Reader): number
return hi * TWO32 + self:u32be()
end
-- floats
local function half(h: number): number
local s = if h >= 32768 then -1 else 1
local e = bit32.band(bit32.rshift(h, 10), 31)
@@ -282,7 +262,6 @@ function Reader.f64be(self: Reader): number
return readf64(scratch, 0)
end
-- strings
function Reader.string(self: Reader, n: number): string
local p = self.pos
if n < 0 or p + n > self.limit then
@@ -293,14 +272,12 @@ function Reader.string(self: Reader, n: number): string
return readstring(self.buf, p, n)
end
-- fixed(n): an n-byte field, cut at the first NUL
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
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
@@ -318,7 +295,6 @@ function Reader.cstring(self: Reader, max: number?): string
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: Reader, s: string): boolean
local p, n = self.pos, #s
if p + n > self.limit or readstring(self.buf, p, n) ~= s then
@@ -328,7 +304,6 @@ function Reader.match(self: Reader, s: string): boolean
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: Reader, n: number, at: number?): string
local p = self.pos + (at or 0)
if p < self.base or p >= self.limit then
@@ -337,7 +312,6 @@ function Reader.peek(self: Reader, n: number, at: number?): string
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: Reader, at: number?): number
local p = self.pos + (at or 0)
if p < self.base or p >= self.limit then
@@ -346,7 +320,6 @@ function Reader.peekU8(self: Reader, at: number?): number
return readu8(self.buf, p)
end
-- bytes(n) -> a new buffer with a copy of the next n bytes
function Reader.bytes(self: Reader, n: number): buffer
local p = self.pos
if n < 0 or p + n > self.limit then
@@ -359,8 +332,6 @@ function Reader.bytes(self: Reader, n: number): buffer
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: Reader, n: number): Reader
local p = self.pos
local l = math.max(0, math.min(n, self.limit - p))
@@ -372,15 +343,12 @@ function Reader.slice(self: Reader, n: number): Reader
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
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
@@ -392,12 +360,10 @@ export type Writer = typeof(setmetatable(
Writer
))
-- writer(capacity?) -> Writer
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)
function Writer.reserve(self: Writer, n: number): number
local p = self.pos
local cap = blen(self.buf)
@@ -493,12 +459,10 @@ function Writer.string(self: Writer, s: string)
writestring(self.buf, p, s)
self.pos = p + n
end
-- cstring(s): s and a NUL
function Writer.cstring(self: Writer, s: string)
self:string(s)
self:u8(0)
end
-- bytes(b, offset?, length?): copy a buffer range
function Writer.bytes(self: Writer, b: buffer, offset: number?, length: number?)
local o = offset or 0
local n = length or (blen(b) - o)
@@ -512,7 +476,6 @@ function Writer.fill(self: Writer, v: number, n: number)
self.pos = p + n
end
-- patch fields written earlier (lengths, CRCs) at an absolute offset < pos
function Writer.setU32le(self: Writer, at: number, v: number)
writeu32(self.buf, at, v)
end
@@ -526,7 +489,6 @@ 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)
function Writer.finish(self: Writer): buffer
local b = bcreate(self.pos)
bcopy(b, 0, self.buf, 0, self.pos)
@@ -536,8 +498,6 @@ 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: any): buffer?
if type(v) == "string" then
return buffer.fromstring(v)
@@ -545,8 +505,6 @@ function Bytes.toBuffer(v: any): buffer?
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)
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
+3 -5
View File
@@ -1,10 +1,8 @@
--!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.
-- core/Crc16: the 16-bit CRCs old archive formats use, table driven. New code. ccitt: CRC-16/XMODEM (0x1021, MSB first,
-- init 0, no final XOR; BinHex 4.0, MacBinary II / III). arc: CRC-16/ARC (0x8005 reflected = 0xA001, init 0; LHA, Zoo,
-- ARC). Never throws: the range is clamped.
local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift
local readu8 = buffer.readu8
+3 -14
View File
@@ -1,14 +1,7 @@
--!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)
-- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; no third-party code). Never throws.
local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift
local readu8, readu32 = buffer.readu8, buffer.readu32
@@ -43,8 +36,6 @@ for n = 0, 255 do
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: buffer, off: number, len: number, crc: number?): number
local c = bxor(crc or 0, 0xFFFFFFFF)
local i, e = off, off + len
@@ -77,7 +68,6 @@ local function crc32(buf: buffer, off: number, len: number, crc: number?): numbe
return bxor(c, 0xFFFFFFFF)
end
-- clamp (offset, length) to the buffer
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)
@@ -95,10 +85,10 @@ 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
-- MSB-first CRC-32 (polynomial 0x04C11DB7, not reflected, raw register, no inversions): Ogg pages (init 0),
-- MPEG-2 PSI sections and bzip2 blocks (init 0xFFFFFFFF)
local MSB = table.create(256, 0)
for n = 0, 255 do
local c = lshift(n, 24)
@@ -109,7 +99,6 @@ for n = 0, 255 do
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: buffer, off: number, len: number, init: number?): number
local c = init or 0
for i = off, off + len - 1 do
-14
View File
@@ -2,9 +2,6 @@
-- 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
@@ -33,24 +30,16 @@ Meta.__tostring = function(e: Err): string
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 "<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: any, offset: number?, kind: string?): Err
if Err.is(message) then
return message
@@ -74,13 +63,10 @@ function Err.from(message: any, offset: number?, kind: string?): Err
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))
-8
View File
@@ -1,9 +1,6 @@
--!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.
@@ -17,12 +14,10 @@ export type HostLike = {
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)
@@ -50,7 +45,6 @@ function Input.resolve(src: any, opts: any?, host: HostLike?): (buffer?, Err.Err
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
@@ -59,8 +53,6 @@ function Input.extension(name: string?): string?
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
-7
View File
@@ -3,11 +3,6 @@
--!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 = {}
@@ -145,7 +140,6 @@ function Md5.new(): State
}
end
-- hex(digest) -> 32 lower-case hex digits
function Md5.hex(d: string): string
local out = table.create(#d)
for i = 1, #d do
@@ -154,7 +148,6 @@ function Md5.hex(d: string): string
return table.concat(out)
end
-- of(buf, offset?, length?) -> hex digest
function Md5.of(buf: buffer, offset: number?, length: number?): string
local h = Md5.new()
h:update(buf, offset, length)
-9
View File
@@ -1,27 +1,18 @@
--!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 = {}
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
+1 -9
View File
@@ -1,9 +1,6 @@
--!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)
-- paths outside them. ImageData is rgba8; SoundData is 16-bit.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
@@ -42,7 +39,6 @@ function Host.readFile(path: string): (buffer?, Err.Err?)
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
@@ -73,7 +69,6 @@ function Host.exists(path: string): boolean
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))
@@ -90,7 +85,6 @@ function Host.toImageData(img: any): (any, Err.Err?)
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")
@@ -105,11 +99,9 @@ function Host.fromImageData(id: any): Types.Image
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)
+3 -35
View File
@@ -1,11 +1,6 @@
--!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).
-- standard types to EditableImage / EditableMesh.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
@@ -25,7 +20,6 @@ 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))
@@ -42,24 +36,8 @@ function Host.toEditableImage(img: any): (any, Err.Err?)
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.
-- EditableMesh limits (measured in Studio): ~20k triangles and 60k vertices each, 8 growable per client.
-- Roblox is y-up, right-handed, counter-clockwise front faces, as glTF; EditableMesh colours are sRGB, COLOR_0 linear.
export type MeshPage = {
first: number, -- the first triangle (0-based) of the primitive in this page
@@ -97,7 +75,6 @@ export type MeshOptions = {
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
@@ -125,8 +102,6 @@ local function checkPrim(prim: any): (number, Err.Err?)
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
@@ -195,8 +170,6 @@ local function toSrgb(c: number): number
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
@@ -239,7 +212,6 @@ function Host.pageData(prim: any, page: MeshPage, opts: MeshOptions?): (PageData
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
@@ -274,9 +246,6 @@ function Host.pageData(prim: any, page: MeshPage, opts: MeshOptions?): (PageData
}, 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
@@ -331,7 +300,6 @@ function Host.toEditableMesh(prim: any, page: MeshPage?, opts: MeshOptions?): (a
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
+1 -8
View File
@@ -1,11 +1,6 @@
--!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 = require("@rosetta/core/Err")
export type Host = {
@@ -39,9 +34,7 @@ elseif name == "luajit" then
else
host = require("@rosetta/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.
-- LuaJIT: the big decoders outgrow the default 1000 traces / 8 MB of mcode; _G.ROSETTA_NO_JIT_TUNE = true skips this.
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
+13 -97
View File
@@ -1,20 +1,7 @@
--!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)).
-- Formats are found through the generated Registry: by content (each format's sniff), then by extension. Never throws
-- on bad data or bad arguments: every function returns nil, Err.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
@@ -32,12 +19,11 @@ 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.Rbx = Rbx
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",
@@ -56,7 +42,6 @@ local KIND_CATEGORY: { [string]: string } = {
playlist = "playlist",
}
-- ------------------------------------------------------------------------------------------------ registry access
local loaded: { [string]: any } = {}
local function module(entry: Registry.Entry): (any, Err.Err?)
@@ -76,7 +61,6 @@ 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
@@ -92,7 +76,6 @@ local function find(key: string, category: string?): Registry.Entry?
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)
@@ -132,9 +115,7 @@ local function detect(buf: buffer, name: string?, category: string?, format: str
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)
-- music that renders (MOD, S3M, XM, IT, MIDI) is also audio: an audio lookup falls back to it (rendered = true)
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
@@ -159,7 +140,6 @@ local function tag(value: any, formatName: string)
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
@@ -183,7 +163,7 @@ local function drain(dec: any): any
return a
end
-- siblings(path) -> resolve(uri): reads files relative to path's directory (no absolute paths, no "..", no URLs)
-- siblings resolve relative to path's directory only (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?
@@ -203,13 +183,10 @@ local function siblings(path: string): (uri: string) -> buffer?
end
end
-- ------------------------------------------------------------------------------------------------ API
export 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
@@ -230,7 +207,7 @@ local function pageLoader(value: any, name: string?, o: Options)
src = (dir :: string) .. file
end
if type(src) == "table" then
return src -- already an Image
return src
end
if src == nil then
return nil, Err.new(Err.IO, "no data for page " .. file)
@@ -239,11 +216,8 @@ local function pageLoader(value: any, name: string?, o: Options)
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.
-- a single-stream archive (meta.stream) holding another archive or a .pcf / .psf(u) / .bdf font loads as that, with
-- meta.compression = the outer format; package archives load as meta.payload (meta.container / meta.outer)
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
@@ -292,18 +266,8 @@ local function unwrap(value: any, formatName: string, o: Options): any
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.
-- api hooks (a format never requires another format): opts.decodeImage / encodeImage, opts.plugins, opts.decodeModule,
-- opts.openAudio (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / FLAC / AC-3 as they are)
local function openAudio(demuxer: any, track: any): (any, Err.Err?)
local buf, fmt, err = AudioWrap.wrap(demuxer, track)
if not buf then
@@ -345,7 +309,6 @@ local function withHooks(o: Options): Options
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
@@ -353,7 +316,6 @@ local function withHooks(o: Options): Options
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)
@@ -373,7 +335,6 @@ function F.load(src: any, opts: Options?): (any, Err.Err?)
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
@@ -405,7 +366,6 @@ function F.load(src: any, opts: Options?): (any, Err.Err?)
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)
@@ -448,10 +408,6 @@ 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")
@@ -510,9 +466,6 @@ local function videoToImage(v: any, o: Options): (any, Err.Err?)
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
@@ -523,8 +476,7 @@ local function renderMusic(value: any, o: Options): (any, Err.Err?)
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)
-- AHX / HVL render through the Module's own 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
@@ -542,7 +494,6 @@ local function renderMusic(value: any, o: Options): (any, Err.Err?)
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
@@ -602,17 +553,12 @@ function encodeTextures(scene: any): Err.Err?
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
@@ -621,7 +567,7 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [s
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
o.files = {}
end
if entry.category == "video" and type(value) == "table" and value.kind == "image" then
local v, verr = F.video.fromImage(value)
@@ -638,7 +584,7 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [s
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
local dec, rerr = renderMusic(value, o)
if not dec then
return nil, rerr
end
@@ -679,7 +625,6 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [s
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
@@ -688,7 +633,6 @@ function F.saveString(value: any, opts: Options?): (string?, Err.Err?)
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)
@@ -701,7 +645,6 @@ function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?, {
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)
@@ -725,7 +668,6 @@ end
export 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
@@ -736,7 +678,6 @@ function F.formats(category: string?): { FormatInfo }
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
@@ -745,8 +686,6 @@ function F.format(name: string): (any, Err.Err?)
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
@@ -771,9 +710,6 @@ for category in Types.CATEGORIES do
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)
@@ -795,16 +731,12 @@ for _, fn in { "toBodies", "fromBodies", "tessellate" } do
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")
@@ -830,18 +762,11 @@ F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?)
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
@@ -867,15 +792,6 @@ F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: E
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
+3 -38
View File
@@ -1,18 +1,6 @@
--!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
--
-- ops/AudioOps: editing on the standard Audio: collect, gain, normalize, mix, remix, resample (codecs/audio/Resample),
-- trim, concat, fades, peak / RMS. New code.
-- 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
@@ -28,7 +16,6 @@ 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"
@@ -45,7 +32,6 @@ 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 {})
@@ -53,9 +39,6 @@ local function like(a: Types.Audio, channels: number, frames: number, rate: numb
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
@@ -68,8 +51,6 @@ function AudioOps.toAudio(v: any, opts: { maxFrames: number? }?): (Types.Audio?,
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")
@@ -86,7 +67,6 @@ function AudioOps.gain(a: Types.Audio, factor: number): (Types.Audio?, Err.Err?)
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")
@@ -94,7 +74,6 @@ function AudioOps.gainDb(a: Types.Audio, db: number): (Types.Audio?, Err.Err?)
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")
@@ -118,7 +97,6 @@ function AudioOps.peak(a: Types.Audio): (number?, { number } | Err.Err)
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")
@@ -142,7 +120,6 @@ function AudioOps.rms(a: Types.Audio): (number?, { number } | Err.Err)
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
@@ -155,7 +132,6 @@ function AudioOps.normalize(a: Types.Audio, target: number?): (Types.Audio?, Err
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")
@@ -186,7 +162,6 @@ function AudioOps.fade(a: Types.Audio, inSec: number?, outSec: number?): (Types.
return out, nil
end
-- ------------------------------------------------------------------------------------------------ channels
-- the WAVE-order speakers of 1 .. 8 channel layouts (as FFmpeg's default layouts)
local LAYOUT: { { string } } = {
{ "C" },
@@ -205,7 +180,7 @@ local TO_STEREO: { [string]: { number } } = {
SR = { 0, H }, BC = { 0.5, 0.5 },
}
-- matrix(from, to) -> m[o][i]: output channel o = sum m[o][i] * input i
-- 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
@@ -296,7 +271,6 @@ local function matrix(from: number, to: number): { { number } }
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")
@@ -338,7 +312,6 @@ function AudioOps.remix(a: Types.Audio, channels: number, m: { { number } }?): (
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")
@@ -350,7 +323,6 @@ function AudioOps.downmix(a: Types.Audio, channels: number?): (Types.Audio?, Err
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")
@@ -361,8 +333,6 @@ function AudioOps.upmix(a: Types.Audio, channels: number): (Types.Audio?, Err.Er
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")
@@ -377,7 +347,6 @@ function AudioOps.resample(a: Types.Audio, rate: number, opts: Resample.Options?
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")
@@ -393,7 +362,6 @@ function AudioOps.trim(a: Types.Audio, start: number, stop: number?): (Types.Aud
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")
@@ -427,7 +395,6 @@ local function conform(list: { Types.Audio }, what: string): ({ Types.Audio }?,
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
@@ -448,8 +415,6 @@ function AudioOps.concat(list: { Types.Audio }): (Types.Audio?, Err.Err?)
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
+7 -19
View File
@@ -1,12 +1,9 @@
--!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.
-- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps; callers validate, so indexes are in range by construction.
-- Sample kinds: 1 = u8, 2 = u16, 4 = f32 (little endian). Resampling follows Pillow's Resample.c (separable, 22-bit
-- fixed point for 8-bit) and Geometry.c (affine through pixel centres); 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
@@ -36,7 +33,6 @@ local function wr(b: buffer, o: number, kind: number, v: number)
end
end
-- ------------------------------------------------------------------------------------------------ convert
-- depth: 8 -> 0..255, 16 -> 0..65535, 0 -> float 0..1
local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 }
@@ -55,7 +51,6 @@ local function depthConv(v: number, from: number, to: number): number
end
return v / 65535
end
-- float
if v ~= v then
v = 0
end
@@ -201,8 +196,6 @@ function K.yuvToRgba(src: buffer, w: number, h: number, dst: buffer)
local _ = ch
end
-- ------------------------------------------------------------------------------------------------ geometry
-- flip(src, dst, w, h, bpp, horizontal)
function K.flip(src: buffer, dst: buffer, w: number, h: number, bpp: number, horizontal: boolean)
local stride = w * bpp
if not horizontal then
@@ -219,7 +212,7 @@ function K.flip(src: buffer, dst: buffer, w: number, h: number, bpp: number, hor
end
end
-- rotate90(src, dst, w, h, bpp, turns): counter-clockwise quarter turns 1..3
-- counter-clockwise quarter turns 1..3
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
@@ -241,7 +234,6 @@ function K.rotate90(src: buffer, dst: buffer, w: number, h: number, bpp: number,
end
end
-- ------------------------------------------------------------------------------------------------ resample
local function bilinearF(x: number): number
if x < 0 then
x = -x
@@ -303,7 +295,6 @@ function K.coeffs(inSize: number, outSize: number, filter: string): Coeffs
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: 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
@@ -383,8 +374,8 @@ function K.nearest(src: buffer, w: number, h: number, bpp: number, dst: buffer,
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)
-- affine: dst pixel centres through m = { a, b, c, d, e, f } (xin = a x + b y + c), bilinear with clamped
-- neighbours; centres outside the source -> zeros (Pillow)
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
@@ -421,8 +412,7 @@ function K.affine(src: buffer, w: number, h: number, ch: number, kind: number, d
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
-- Pillow's alpha_composite of src onto dst, in place
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
@@ -475,14 +465,12 @@ function K.overFloat(dst: buffer, dw: number, src: buffer, sw: number, sx: numbe
end
end
-- copyRect: rows of a rectangle (bpp bytes per pixel)
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
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
+3 -50
View File
@@ -1,15 +1,6 @@
--!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
--
-- ops/ImageOps: editing on the standard Image: conversion, crop, resize, flips, rotation, compositing, pixel access,
-- animation helpers. New code; the resampling and compositing follow Pillow's C sources.
-- 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
@@ -25,7 +16,6 @@ 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
@@ -42,7 +32,6 @@ local function bytesOf(fmt: string, w: number, h: number): number?
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")
@@ -69,7 +58,6 @@ local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?)
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
@@ -79,8 +67,6 @@ local function like(img: Image, w: number, h: number, fmt: string?): Image
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
@@ -96,7 +82,6 @@ function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?)
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
@@ -108,8 +93,6 @@ function ImageOps.copy(img: Image): (Image?, Err.Err?)
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
@@ -158,10 +141,8 @@ local function viaRgba(img: Image, f: (Image) -> (Image?, Err.Err?)): (Image?, E
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
@@ -183,7 +164,6 @@ function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number):
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
@@ -199,7 +179,6 @@ function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?)
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
@@ -222,7 +201,6 @@ end
export 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
@@ -275,9 +253,6 @@ function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts
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
@@ -337,14 +312,10 @@ function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?,
end)
end
-- ------------------------------------------------------------------------------------------------ compositing
local RGBA: { [string]: boolean } = { rgba8 = true, rgba16 = true, rgbaf32 = true }
export 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
@@ -365,7 +336,6 @@ function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitO
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)
@@ -403,7 +373,6 @@ function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitO
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
@@ -426,7 +395,6 @@ local function premul(img: Image, un: boolean): (Image?, Err.Err?)
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
@@ -434,11 +402,8 @@ 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
@@ -478,8 +443,6 @@ function ImageOps.getPixel(img: Image, x: number, y: number): (any, any, number?
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
@@ -546,7 +509,6 @@ function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: numbe
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
@@ -570,8 +532,6 @@ function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?):
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
@@ -579,7 +539,6 @@ function ImageOps.frameCount(img: Image): number
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
@@ -591,10 +550,7 @@ function ImageOps.durations(img: Image): { number }
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 }.
-- coalesce: dispose "none" keeps the canvas, "background" clears the frame's rectangle, "previous" restores it
function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?)
local ok, e = check(img)
if not ok then
@@ -650,9 +606,6 @@ function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?)
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")
-10
View File
@@ -2,13 +2,6 @@
-- 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 = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
@@ -22,7 +15,6 @@ export type FlattenOptions = {
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")
@@ -54,7 +46,6 @@ function LayerOps.flatten(layered: Types.Layered, opts: FlattenOptions?): (Types
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
@@ -78,7 +69,6 @@ function LayerOps.flattenFrames(layered: Types.Layered, opts: FlattenOptions?):
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?)
+1 -3
View File
@@ -19,7 +19,7 @@ export type Out = {
quads: number,
}
-- run(data, sx, sy, sz, ox, oy, oz, scale) -> Out: vertex position = (cell corner + (ox, oy, oz)) * scale
-- vertex position = (cell corner + (ox, oy, oz)) * scale
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)
@@ -89,7 +89,6 @@ function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number
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: buffer, per: number): buffer
@@ -104,7 +103,6 @@ function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number
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
+7 -60
View File
@@ -1,16 +1,7 @@
--!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
-- ops/MeshOps: editing meshes in the standard Scene type: triangulate, transform, normals (area weighted or flat),
-- tangents (Lengyel 2001), weld, bounds, merge into world space, unit / up-axis changes, greedy voxel meshing. Inputs
-- may use any accessor type; outputs are f32 attributes and u32 indices. Never throws.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Greedy = require("@rosetta/ops/MeshOps/Greedy")
@@ -25,8 +16,6 @@ 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
@@ -47,7 +36,6 @@ function MeshOps.f32(acc: Accessor): Accessor?
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
@@ -114,7 +102,6 @@ local function checkPrim(prim: any): Err.Err?
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
@@ -206,9 +193,7 @@ local function u32(list: { number }): Accessor
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.
-- strips and fans unroll with glTF's alternating strip winding
function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Primitive?, Err.Err?)
local err = checkPrim(prim)
if err then
@@ -294,7 +279,6 @@ function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Prim
}, 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
@@ -317,8 +301,7 @@ local function normalMatrix(m: { number }): { number }
}
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.
-- a mirroring matrix (negative determinant) reverses the winding so faces stay front-facing
function MeshOps.transform(prim: Primitive, m: { number }): (Primitive?, Err.Err?)
local err = checkPrim(prim)
if err then
@@ -423,10 +406,6 @@ function MeshOps.transform(prim: Primitive, m: { number }): (Primitive?, Err.Err
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
@@ -482,8 +461,7 @@ function MeshOps.computeNormals(prim: Primitive, opts: { flat: boolean? }?): (Pr
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>.
-- TANGENT: f32 vec4, xyz orthogonal to the normal, w = +-1 handedness
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
@@ -565,7 +543,6 @@ function MeshOps.computeTangents(prim: Primitive, opts: { texCoord: number? }?):
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)
@@ -577,7 +554,6 @@ local function gather(acc: Accessor, ib: buffer, n: number): Accessor
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 = {}
@@ -598,10 +574,6 @@ function MeshOps.unweld(prim: Primitive): Primitive
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
@@ -680,9 +652,6 @@ function MeshOps.weld(prim: Primitive, opts: { epsilon: number?, positionsOnly:
}, 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 }
@@ -736,7 +705,6 @@ function MeshOps.bounds(x: any): ({ number }?, { number }?)
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
@@ -748,11 +716,6 @@ local function defaultFor(name: string, k: number): number
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
@@ -765,7 +728,6 @@ function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string?
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
@@ -861,7 +823,6 @@ function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string?
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
@@ -877,9 +838,6 @@ local function scaleAccessor(acc: Accessor?, f: number): Accessor?
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")
@@ -956,7 +914,6 @@ function MeshOps.scale(scene: Scene, f: number): (Scene?, Err.Err?)
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")
@@ -965,8 +922,6 @@ function MeshOps.setUnit(scene: Scene, metresPerUnit: number): (Scene?, Err.Err?
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\"")
@@ -984,17 +939,12 @@ function MeshOps.setUp(scene: Scene, up: string): (Scene?, Err.Err?)
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).
-- pivot "center": MagicaVoxel's placement (cell x spans x - floor(sx / 2) ..)
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")
@@ -1051,9 +1001,6 @@ function MeshOps.voxelsToPrimitive(v: Types.Voxels, opts: { pivot: string?, scal
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")
+5 -28
View File
@@ -1,16 +1,6 @@
--!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
--
-- ops/MusicOps: building and editing tracker Modules over codecs/audio/Tracker without touching the engine's internal
-- layout (5-byte cells, f32 samples, tuning fields). New code.
-- 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
@@ -35,7 +25,6 @@ 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
export 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)
@@ -44,7 +33,6 @@ export type NewOptions = {
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"
@@ -73,9 +61,6 @@ function MusicOps.new(opts: NewOptions?): (any, Err.Err?)
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")
@@ -95,8 +80,6 @@ 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
@@ -148,7 +131,6 @@ local function patternAt(m: any, pattern: any, row: any, channel: any): (any, Er
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
@@ -175,7 +157,6 @@ function MusicOps.setCell(m: any, pattern: number, row: number, channel: number,
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
@@ -185,7 +166,6 @@ function MusicOps.getCell(m: any, pattern: number, row: number, channel: number)
return { note = note, instrument = ins, volume = vol, effect = fx, param = param }, nil
end
-- ------------------------------------------------------------------------------------------------ samples
export type SampleSpec = {
name: string?,
audio: any?, -- an Audio (1 or 2 channels): the sample data and, unless rate is given, its rate
@@ -203,9 +183,8 @@ export type SampleSpec = {
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).
-- tuning: c5speed for S3M / IT; relativeNote + finetune (1/128 semitone from 8363 Hz) for MOD / XM (MOD stores
-- only the finetune, -1..+7/8 semitone)
function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?)
if not isModule(m) then
return bad("addSample: needs a tracker Module")
@@ -283,7 +262,6 @@ function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?)
return #m.samples, nil
end
-- ------------------------------------------------------------------------------------------------ instruments
export type InstrumentSpec = {
name: string?,
sample: number?, -- the sample every note plays (1-based)
@@ -293,8 +271,7 @@ export type InstrumentSpec = {
-- 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).
-- instruments: XM and IT 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")