ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically): - codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder; codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url; codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err Crc32 Adler32 Base64 Md5 Input Sniff. - LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md). - Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes. C3, generic code out of format folders: - containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first, trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64 through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it. - codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position, priming and end trimming) that aac, caf and m4a each carried (~70 lines each). - codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of its own (the AND mask / alpha rule stay ICO's). - codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model), Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the fixtures' bind shapes). - README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes: FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.
This commit is contained in:
1 parent
763f4a7c04
commit
51b08575c4
283 files changed
+1877
-1660
No files matched your search
@@ -0,0 +1,377 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or
|
||||
-- whole-buffer, any channel count, interleaved f32 (the Types.Audio / Decoder layout). Used by the Opus, MP3 and MP2
|
||||
-- encoders (their input rates are fixed) and ops/AudioOps.resample. New in formats-luau (the textbook polyphase
|
||||
-- filter; the kernel is the one the Opus encoder carried).
|
||||
--
|
||||
-- The filter is a polyphase table: exact phases when to / gcd(from, to) <= 4096 (44100 <-> 48000: 160 phases),
|
||||
-- else 4096 phases with linear interpolation between them. Each phase is normalised to unit DC gain. The cutoff is a
|
||||
-- fraction (opts.cutoff, default 0.97) of the lower Nyquist frequency; quality picks the taps per side at the cutoff:
|
||||
--
|
||||
-- quality zero crossings per side Kaiser beta stop band
|
||||
-- "low" 8 6 ~ -60 dB
|
||||
-- "medium" 16 (default) 8 ~ -80 dB
|
||||
-- "high" 32 10 ~ -100 dB
|
||||
--
|
||||
-- Output frame j sits at input time j * from / to (no delay: the filter is centred, the input is zero outside its
|
||||
-- range); a stream of n input frames gives floor(n * to / from + 0.5) output frames.
|
||||
--
|
||||
-- local out, frames = Resample.buffer(samples, frames, channels, 44100, 48000, { quality = "high" })
|
||||
-- local rs = Resample.new(44100, 48000, 2) -- nil, message for bad rates
|
||||
-- local b, n = rs:process(chunk, chunkFrames) -- the output frames this input completes
|
||||
-- local b2, n2 = rs:flush() -- the rest (the input end padded with zeros)
|
||||
-- local src2 = Resample.source(pcmSource, 48000) -- a codecs/audio/Pcm Source at the new rate
|
||||
--
|
||||
-- Never throws: bad arguments return nil, message (the api turns them into Err.ARG).
|
||||
local Resample = {}
|
||||
|
||||
export type Options = {
|
||||
quality: ("low" | "medium" | "high")?, -- default "medium"
|
||||
cutoff: number?, -- pass band edge as a fraction of the lower Nyquist frequency, 0.5 .. 1 (default 0.97)
|
||||
}
|
||||
|
||||
export type Resampler = {
|
||||
from: number,
|
||||
to: number,
|
||||
channels: number,
|
||||
-- process(src, frames, out?) -> interleaved f32 buffer, output frames (out is reused when big enough)
|
||||
process: (self: Resampler, src: buffer, frames: number, out: buffer?) -> (buffer, number),
|
||||
-- flush(out?) -> the remaining output frames; the resampler is finished afterwards
|
||||
flush: (self: Resampler, out: buffer?) -> (buffer, number),
|
||||
}
|
||||
|
||||
local QUALITY = { low = { 8, 6 }, medium = { 16, 8 }, high = { 32, 10 } }
|
||||
local MAX_EXACT = 4096
|
||||
local INTERP_PHASES = 4096
|
||||
|
||||
local floor, sin, pi, sqrt, max, min = math.floor, math.sin, math.pi, math.sqrt, math.max, math.min
|
||||
local readf32, writef32 = buffer.readf32, buffer.writef32
|
||||
|
||||
local function besselI0(x: number): number
|
||||
local sum, term = 1, 1
|
||||
for k = 1, 80 do
|
||||
term *= (x / (2 * k)) ^ 2
|
||||
sum += term
|
||||
if term < sum * 1e-16 then
|
||||
break
|
||||
end
|
||||
end
|
||||
return sum
|
||||
end
|
||||
|
||||
local function gcd(a: number, b: number): number
|
||||
while b ~= 0 do
|
||||
a, b = b, a % b
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
type Filter = {
|
||||
taps: number, -- per phase
|
||||
half: number, -- taps on the left of the centre (taps = 2 * half)
|
||||
phases: number,
|
||||
exact: boolean,
|
||||
h: { number }, -- phase p, tap k: h[p * taps + k + 1]
|
||||
}
|
||||
|
||||
-- filter(ratio, phases, exact, opts) -> the polyphase table. Phase p is the kernel for an output at fraction
|
||||
-- p / phases past an input sample; tap k multiplies input (floor(t) - half + 1 + k).
|
||||
local function makeFilter(ratio: number, phases: number, exact: boolean, zc: number, beta: number, cut: number): Filter
|
||||
local cutoff = cut * min(1, ratio)
|
||||
local width = zc / cutoff -- in input samples, each side
|
||||
local half = math.ceil(width)
|
||||
local taps = 2 * half
|
||||
local i0b = besselI0(beta)
|
||||
local n = if exact then phases else phases + 1
|
||||
local h = table.create(n * taps, 0)
|
||||
for p = 0, n - 1 do
|
||||
local frac = p / phases
|
||||
local sum = 0
|
||||
local base = p * taps
|
||||
for k = 0, taps - 1 do
|
||||
local d = (k - half + 1) - frac -- input position minus output position
|
||||
local r = d / width
|
||||
local v = 0
|
||||
if r > -1 and r < 1 then
|
||||
local x = d * cutoff
|
||||
local s = if x == 0 then 1 else sin(pi * x) / (pi * x)
|
||||
v = s * besselI0(beta * sqrt(1 - r * r)) / i0b
|
||||
end
|
||||
h[base + k + 1] = v
|
||||
sum += v
|
||||
end
|
||||
if sum ~= 0 then
|
||||
for k = 1, taps do
|
||||
h[base + k] /= sum
|
||||
end
|
||||
end
|
||||
end
|
||||
return { taps = taps, half = half, phases = phases, exact = exact, h = h }
|
||||
end
|
||||
|
||||
-- the stream state: the input history as an interleaved Lua array; hist[1] is frame `base` (absolute)
|
||||
type State = {
|
||||
from: number,
|
||||
to: number,
|
||||
channels: number,
|
||||
f: Filter,
|
||||
step: number, -- M = from / g: the input advance per output frame, in units of 1 / L
|
||||
L: number, -- to / g
|
||||
hist: { number },
|
||||
histFrames: number,
|
||||
base: number, -- the absolute input frame of hist[1]
|
||||
inFrames: number, -- absolute input frames received
|
||||
outPos: number, -- next output frame (absolute)
|
||||
done: boolean,
|
||||
process: any,
|
||||
flush: any,
|
||||
}
|
||||
|
||||
-- run(st, lastInput) -> buffer, frames: every output frame whose taps end at or before lastInput (absolute, exclusive)
|
||||
local function run(st: State, limitOut: number, out: buffer?): (buffer, number)
|
||||
local f = st.f
|
||||
local taps, half, h = f.taps, f.half, f.h
|
||||
local ch = st.channels
|
||||
local hist, base, histFrames = st.hist, st.base, st.histFrames
|
||||
local L, M = st.L, st.step
|
||||
local j0 = st.outPos
|
||||
-- outputs j with floor(j * M / L) - half + taps <= available frames (zero beyond the end after flush)
|
||||
local avail = base + histFrames
|
||||
local jmax = limitOut
|
||||
if not st.done then
|
||||
-- the last tap must be buffered: floor(j * M / L) + half <= avail - 1, i.e. j * M < (avail - half) * L
|
||||
local lim = floor(((avail - half) * L - 1) / M)
|
||||
if lim + 1 < jmax then
|
||||
jmax = lim + 1
|
||||
end
|
||||
end
|
||||
local n = jmax - j0
|
||||
if n <= 0 then
|
||||
return out or buffer.create(0), 0
|
||||
end
|
||||
local bytes = n * ch * 4
|
||||
local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes)
|
||||
local exact = f.exact
|
||||
local phases = f.phases
|
||||
local o = 0
|
||||
for j = j0, jmax - 1 do
|
||||
local num = j * M
|
||||
local ip = num // L -- floor(t)
|
||||
local first = ip - half + 1 -- absolute input frame of tap 0
|
||||
local rel = first - base -- frame index in hist
|
||||
local kLo = if rel < 0 then -rel else 0
|
||||
local kHi = taps - 1
|
||||
if rel + kHi >= histFrames then
|
||||
kHi = histFrames - 1 - rel
|
||||
end
|
||||
if exact then
|
||||
local hb = (num - ip * L) * taps + 1 -- phase * taps + 1
|
||||
for c = 0, ch - 1 do
|
||||
local acc = 0
|
||||
local hi = (rel + kLo) * ch + c + 1
|
||||
for k = kLo, kHi do
|
||||
acc += hist[hi] * h[hb + k]
|
||||
hi += ch
|
||||
end
|
||||
writef32(b, o, acc)
|
||||
o += 4
|
||||
end
|
||||
else
|
||||
local fp = (num - ip * L) / L * phases
|
||||
local p = floor(fp)
|
||||
local a = fp - p
|
||||
local hb = p * taps + 1
|
||||
local hb2 = hb + taps
|
||||
for c = 0, ch - 1 do
|
||||
local acc, acc2 = 0, 0
|
||||
local hi = (rel + kLo) * ch + c + 1
|
||||
for k = kLo, kHi do
|
||||
local x = hist[hi]
|
||||
acc += x * h[hb + k]
|
||||
acc2 += x * h[hb2 + k]
|
||||
hi += ch
|
||||
end
|
||||
writef32(b, o, acc + (acc2 - acc) * a)
|
||||
o += 4
|
||||
end
|
||||
end
|
||||
end
|
||||
st.outPos = jmax
|
||||
-- drop history no future output needs (keep from the next output's first tap)
|
||||
local keepFrom = (jmax * M) // L - half + 1
|
||||
local drop = keepFrom - base
|
||||
if drop > 0 then
|
||||
if drop >= histFrames then
|
||||
st.hist = {}
|
||||
st.histFrames = 0
|
||||
st.base = base + histFrames
|
||||
else
|
||||
local nh: { number } = table.create((histFrames - drop) * ch) :: any
|
||||
table.move(hist, drop * ch + 1, histFrames * ch, 1, nh)
|
||||
st.hist = nh
|
||||
st.histFrames = histFrames - drop
|
||||
st.base = base + drop
|
||||
end
|
||||
end
|
||||
return b, n
|
||||
end
|
||||
|
||||
local function process(self: State, src: buffer, frames: number, out: buffer?): (buffer, number)
|
||||
if self.done or type(src) ~= "buffer" or type(frames) ~= "number" or frames <= 0 then
|
||||
return out or buffer.create(0), 0
|
||||
end
|
||||
local ch = self.channels
|
||||
frames = min(floor(frames), buffer.len(src) // (ch * 4))
|
||||
local hist = self.hist
|
||||
local p = self.histFrames * ch
|
||||
for i = 0, frames * ch - 1 do
|
||||
hist[p + i + 1] = readf32(src, i * 4)
|
||||
end
|
||||
self.histFrames += frames
|
||||
self.inFrames += frames
|
||||
return run(self, math.huge, out)
|
||||
end
|
||||
|
||||
local function flush(self: State, out: buffer?): (buffer, number)
|
||||
if self.done then
|
||||
return out or buffer.create(0), 0
|
||||
end
|
||||
self.done = true
|
||||
local total = floor(self.inFrames * self.to / self.from + 0.5)
|
||||
return run(self, total, out)
|
||||
end
|
||||
|
||||
-- new(from, to, channels, opts?) -> Resampler | nil, message
|
||||
function Resample.new(from: number, to: number, channels: number, opts: Options?): (Resampler?, string?)
|
||||
if type(from) ~= "number" or type(to) ~= "number" or from ~= from or to ~= to or from <= 0 or to <= 0 or from > 2 ^ 24 or to > 2 ^ 24 then
|
||||
return nil, "bad sample rates"
|
||||
end
|
||||
if type(channels) ~= "number" or channels < 1 or channels > 256 or channels ~= floor(channels) then
|
||||
return nil, "bad channel count"
|
||||
end
|
||||
local q: { number }? = QUALITY[(opts and opts.quality) or "medium"]
|
||||
if not q then
|
||||
return nil, "quality must be low, medium or high"
|
||||
end
|
||||
local cut = (opts and opts.cutoff) or 0.97
|
||||
if type(cut) ~= "number" or not (cut >= 0.5 and cut <= 1) then
|
||||
return nil, "cutoff must be 0.5 .. 1"
|
||||
end
|
||||
-- positions are exact integers: output j sits at input j * M / L (non-integer rates: to 1 / 1000 Hz)
|
||||
local scale = if from ~= floor(from) or to ~= floor(to) then 1000 else 1
|
||||
local fi: number = floor(from * scale + 0.5)
|
||||
local ti: number = floor(to * scale + 0.5)
|
||||
local g: number = gcd(fi, ti)
|
||||
local L: number, M: number = ti // g, fi // g
|
||||
local exact = L <= MAX_EXACT
|
||||
local phases = if exact then L else INTERP_PHASES
|
||||
local st: State = {
|
||||
from = from,
|
||||
to = to,
|
||||
channels = channels,
|
||||
-- the same rate: a pass-through (tap 0 is the input frame itself)
|
||||
f = if L == 1 and M == 1 then { taps = 2, half = 1, phases = 1, exact = true, h = { 1, 0 } } else makeFilter(to / from, phases, exact, q[1], q[2], cut),
|
||||
step = M,
|
||||
L = L,
|
||||
hist = {},
|
||||
histFrames = 0,
|
||||
base = 0,
|
||||
inFrames = 0,
|
||||
outPos = 0,
|
||||
done = false,
|
||||
process = process,
|
||||
flush = flush,
|
||||
}
|
||||
return st :: any, nil
|
||||
end
|
||||
|
||||
-- buffer(src, frames, channels, from, to, opts?) -> interleaved f32 buffer, frames | nil, message
|
||||
function Resample.buffer(src: buffer, frames: number, channels: number, from: number, to: number, opts: Options?): (buffer?, number | string)
|
||||
local rs, err = Resample.new(from, to, channels, opts)
|
||||
if not rs then
|
||||
return nil, err :: string
|
||||
end
|
||||
if type(src) ~= "buffer" or type(frames) ~= "number" or frames < 0 or buffer.len(src) < frames * channels * 4 then
|
||||
return nil, "the buffer is shorter than frames * channels * 4"
|
||||
end
|
||||
local total = floor(frames * to / from + 0.5)
|
||||
local out = buffer.create(total * channels * 4)
|
||||
local got = 0
|
||||
local chunk = 65536
|
||||
local tmp: buffer? = nil
|
||||
local pos = 0
|
||||
while pos < frames do
|
||||
local n = min(chunk, frames - pos)
|
||||
local part = buffer.create(n * channels * 4)
|
||||
buffer.copy(part, 0, src, pos * channels * 4, n * channels * 4)
|
||||
local b, m = rs:process(part, n, tmp)
|
||||
tmp = b
|
||||
if m > 0 then
|
||||
buffer.copy(out, got * channels * 4, b, 0, m * channels * 4)
|
||||
got += m
|
||||
end
|
||||
pos += n
|
||||
end
|
||||
local b, m = rs:flush(tmp)
|
||||
if m > 0 then
|
||||
buffer.copy(out, got * channels * 4, b, 0, m * channels * 4)
|
||||
got += m
|
||||
end
|
||||
return out, got
|
||||
end
|
||||
|
||||
-- source(src, to, opts?) -> a pull source ({ sampleRate, channels, frames, tags, read, err }, the codecs/audio/Pcm Source
|
||||
-- shape) reading src (any such source: Pcm.source(audioOrDecoder)) at the rate `to` | nil, message
|
||||
function Resample.source(src: any, to: number, opts: Options?): (any, string?)
|
||||
if type(src) ~= "table" or type(src.read) ~= "function" then
|
||||
return nil, "needs a source"
|
||||
end
|
||||
local rs, err = Resample.new(src.sampleRate, to, src.channels, opts)
|
||||
if not rs then
|
||||
return nil, err
|
||||
end
|
||||
local ch = src.channels
|
||||
local pending = buffer.create(0) -- produced but not yet returned
|
||||
local pendingFrames, pendingPos = 0, 0
|
||||
local ended = false
|
||||
local out = {
|
||||
sampleRate = to,
|
||||
channels = ch,
|
||||
frames = if src.frames > 0 then floor(src.frames * to / src.sampleRate + 0.5) else 0,
|
||||
tags = src.tags,
|
||||
err = nil :: any,
|
||||
}
|
||||
local inTmp: buffer? = nil
|
||||
function out.read(self: any, n: number, dst: buffer?): (buffer, number)
|
||||
n = floor(n)
|
||||
while pendingFrames - pendingPos <= 0 and not ended do
|
||||
local b: buffer, m: number = (src :: any):read(math.max(1024, floor(n * src.sampleRate / to) + 64), inTmp)
|
||||
inTmp = b
|
||||
local r: buffer, k: number
|
||||
if m <= 0 then
|
||||
ended = true
|
||||
self.err = src.err
|
||||
r, k = rs:flush()
|
||||
else
|
||||
r, k = rs:process(b, m)
|
||||
end
|
||||
if k > 0 then
|
||||
pending, pendingFrames, pendingPos = r, k, 0
|
||||
end
|
||||
end
|
||||
local k = min(n, pendingFrames - pendingPos)
|
||||
if k <= 0 then
|
||||
return dst or buffer.create(0), 0
|
||||
end
|
||||
local bytes = k * ch * 4
|
||||
local b = if dst and buffer.len(dst) >= bytes then dst else buffer.create(bytes)
|
||||
buffer.copy(b, 0, pending, pendingPos * ch * 4, bytes)
|
||||
pendingPos += k
|
||||
return b, k
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Resample
|
||||
Reference in new issue
Block a user