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:
4DBug committed 2026-10-31 12:25:03 -05:00
1 parent 763f4a7c04
commit 51b08575c4
283 files changed
+1877 -1660

No files matched your search

+22 -76
View File
@@ -1,6 +1,6 @@
--!strict
-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams
-- write. Supports: reading AAC-LC through codecs/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected
-- write. Supports: reading AAC-LC through codecs/audio/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected
-- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by
-- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM.
@@ -8,8 +8,9 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Aac = require("@formats/codecs/Aac")
local Pcm = require("@formats/codecs/audio/Pcm")
local Stream = require("@formats/codecs/audio/Stream")
local Aac = require("@formats/codecs/audio/Aac")
-- ------------------------------------------------------------------------------------------------ contract
local AacFormat = {
@@ -17,7 +18,7 @@ local AacFormat = {
category = "audio",
extensions = { "aac", "adts" },
mime = { "audio/aac", "audio/aacp", "audio/x-aac" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Pcm", "codecs/audio/Stream" },
caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true },
}
@@ -168,11 +169,6 @@ function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?,
local id3 = id3Size(r.buf, r.base, r.limit)
local tags = if id3 > 0 then id3Tags(r.buf, r.base, id3) else {}
local buf = r.buf
local nextFrame = 1
local pendPos, pendN = 0, 0
local drop = 0
local pos = 0
local failed: Err.Err? = nil
local out: any = {
sampleRate = sr,
channels = channels,
@@ -181,74 +177,24 @@ function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?,
bitrate = if total > 0 then math.floor(bytes * 8 * sr / total) else 0,
tags = tags,
codec = "aac",
error = nil,
}
local function fill(): boolean
while true do
if nextFrame > nframes then
return false
end
local i = nextFrame
nextFrame += 1
local n, e = d:decode(buf, offs[i], sizes[i])
if not n then
failed = e
out.error = e
return false
end
if drop >= n then
drop -= n
else
pendPos, pendN = drop, n
drop = 0
return true
end
end
end
function out.read(_self: any, n: number, ob: buffer?): (buffer, number)
local want = math.max(0, math.floor(n))
local need = want * channels * 4
local res = if ob and buffer.len(ob) >= need then ob else buffer.create(need)
local got = 0
local writef32 = buffer.writef32
while got < want do
if pendPos >= pendN then
if failed or not fill() then
break
end
end
local take = math.min(want - got, pendN - pendPos)
local src = d.pcm
local q = got * channels * 4
local s = pendPos * channels
for k = 1, take * channels do
writef32(res, q, src[s + k])
q += 4
end
pendPos += take
got += take
end
pos += got
return res, got
end
function out.seek(_self: any, seconds: number)
local target = math.clamp(math.floor(seconds * sr + 0.5), 0, total)
local f = target // 1024 -- frame holding the target (0-based)
local start = math.max(0, f - 1) -- one frame of pre-roll for the overlap
d:reset()
nextFrame = start + 1
drop = target - start * 1024
pendPos, pendN = 0, 0
failed = nil
pos = target
end
function out.position(_self: any): number
return pos / sr
end
if nframes > 0 and not fill() and failed then
return nil, failed
end
return out, nil
-- 1024 frames per ADTS frame; one frame of pre-roll for the overlap when seeking
return Stream.packets(out, {
count = nframes,
start = function(i: number): number
return (i - 1) * 1024
end,
decode = function(i: number): (number?, Err.Err?)
return d:decode(buf, offs[i], sizes[i])
end,
pcm = function(): { number }
return d.pcm
end,
reset = function()
d:reset()
end,
preroll = 1,
})
end
function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
+9 -9
View File
@@ -10,7 +10,8 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Chunks = require("@formats/containers/Chunks")
local Pcm = require("@formats/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Aiff = {
@@ -18,7 +19,7 @@ local Aiff = {
category = "audio",
extensions = { "aiff", "aif", "aifc", "afc" },
mime = { "audio/aiff", "audio/x-aiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
}
@@ -159,12 +160,12 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
local ssnd: number? = nil
local ssndLen = 0
local tags: Types.Tags = {}
local p = base + 12
while p + 8 <= formEnd do
local id = buffer.readstring(b, p, 4)
local len = bit32.byteswap(buffer.readu32(b, p + 4))
local d = p + 8
local avail = math.min(len, limit - d)
-- (walked to the end of the data: a FORM size that undercounts still reads the last chunk's body)
for _, c in Chunks.walk(b, base + 12, limit, Chunks.IFF) do
local id, len, d, avail, p = c.id, c.declared, c.offset, c.avail, c.start
if p + 8 > formEnd then
break
end
if id == "COMM" then
if avail < 18 or (aifc and avail < 22) then
return nil, Err.new(Err.TRUNCATED, "COMM chunk too short", p)
@@ -219,7 +220,6 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
if len > formEnd - d then
break
end
p = d + len + len % 2
end
if not comm or not info then
return nil, Err.new(Err.CORRUPT, "no COMM chunk", base)
+2 -2
View File
@@ -9,7 +9,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Au = {
@@ -17,7 +17,7 @@ local Au = {
category = "audio",
extensions = { "au", "snd" },
mime = { "audio/basic", "audio/x-au" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
}
+27 -109
View File
@@ -1,6 +1,6 @@
--!strict
-- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear
-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/Alac), AAC-LC (codecs/Aac,
-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/audio/Alac), AAC-LC (codecs/audio/Aac,
-- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown
-- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 /
-- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED).
@@ -9,9 +9,11 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Aac = require("@formats/codecs/Aac")
local Alac = require("@formats/codecs/Alac")
local Chunks = require("@formats/containers/Chunks")
local Pcm = require("@formats/codecs/audio/Pcm")
local Stream = require("@formats/codecs/audio/Stream")
local Aac = require("@formats/codecs/audio/Aac")
local Alac = require("@formats/codecs/audio/Alac")
-- ------------------------------------------------------------------------------------------------ contract
local Caf = {
@@ -19,7 +21,7 @@ local Caf = {
category = "audio",
extensions = { "caf", "caff" },
mime = { "audio/x-caf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true },
}
@@ -146,26 +148,15 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?)
if Caf.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base)
end
r:seek(8)
local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} }
local haveData = false
while r:remaining() >= 12 do
local typ = r:string(4)
local size = r:i64be()
local start = r.pos
if size == -1 and typ == "data" then
size = r.limit - start
end
if size < 0 then
return nil, Err.new(Err.CORRUPT, "bad chunk size", start - 12)
end
local stop = start + size
if stop > r.limit then
if typ ~= "data" then
return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", start - 12)
end
stop = r.limit -- a truncated data chunk: play what is there
-- 64-bit big-endian chunk sizes; the data chunk may say -1 (= to the end) or run past a truncated file
for _, ch in Chunks.walk(r.buf, r.base + 8, r.limit, { bigEndian = true, sizeBytes = 8, openEnded = { data = true } }) do
local typ, start = ch.id, ch.offset
if ch.truncated and typ ~= "data" then
return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", ch.start)
end
local stop = start + ch.avail
local c = Bytes.reader(r.buf, start, stop - start)
if typ == "desc" then
p.desc = {
@@ -226,7 +217,6 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?)
p.tags[INFO_TAGS[string.lower(k)] or string.lower(k)] = v
end
end
r.pos = stop
if typ == "data" and stop >= r.limit then
break
end
@@ -456,12 +446,6 @@ function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
stopAt = math.max(skip, total - p.remainder)
end
local frames = math.max(0, stopAt - skip)
local nextPacket = 1
local decoded = 0
local pendPos, pendN = 0, 0
local dropUntil = skip
local pos = 0
local failed: Err.Err? = nil
local dec: any = {
sampleRate = rate,
channels = ch,
@@ -471,87 +455,21 @@ function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
tags = p.tags,
codec = src.codec,
bitsPerSample = src.bits,
error = nil,
}
local function fill(): boolean
while true do
if nextPacket > src.packetCount or decoded >= stopAt then
return false
end
local i = nextPacket
nextPacket += 1
local start = starts[i]
local n, e = src.decode(i)
if not n then
failed = e
dec.error = e
return false
end
decoded = start + n
local a = math.max(start, dropUntil)
local b = math.min(decoded, stopAt)
if b > a then
pendPos, pendN = a - start, b - start
return true
end
end
end
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
local want = math.max(0, math.floor(n))
local need = want * ch * 4
local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
local got = 0
local writef32 = buffer.writef32
while got < want do
if pendPos >= pendN then
if failed or not fill() then
break
end
end
local take = math.min(want - got, pendN - pendPos)
local q = got * ch * 4
local sidx = pendPos * ch
local pcm = src.pcm
for k = 1, take * ch do
writef32(ob, q, pcm[sidx + k])
q += 4
end
pendPos += take
got += take
end
pos += got
return ob, got
end
function dec.seek(_self: any, seconds: number)
local target = math.clamp(math.floor(seconds * rate + 0.5), 0, frames) + skip
local lo, hi, found = 1, src.packetCount, 1
while lo <= hi do
local mid = (lo + hi) // 2
if starts[mid] <= target then
found = mid
lo = mid + 1
else
hi = mid - 1
end
end
if src.codec == "aac" then
found = math.max(1, found - 1)
end
src.reset()
nextPacket = found
decoded = starts[found]
dropUntil = target
pendPos, pendN = 0, 0
failed = nil
pos = target - skip
end
function dec.position(_self: any): number
return pos / rate
end
if src.packetCount > 0 and frames > 0 and not fill() and failed then
return nil, failed
end
return dec, nil
return Stream.packets(dec, {
count = src.packetCount,
start = function(i: number): number
return starts[i]
end,
decode = src.decode,
pcm = function(): { number }
return src.pcm
end,
reset = src.reset,
skip = skip,
stop = stopAt,
preroll = if src.codec == "aac" then 1 else 0,
})
end
function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
+2 -2
View File
@@ -8,11 +8,11 @@
-- libFLAC's precision table, the order estimated from the prediction error or searched exhaustively at -8), wasted
-- bits; Rice / Rice2 partitions with the partition order and parameters searched per subframe. Frames carry CRC-8 /
-- CRC-16; STREAMINFO carries the sizes, total samples and the MD5 of the PCM; VORBIS_COMMENT from the tags; an optional
-- SEEKTABLE. Streams: input blocks are pulled from a codecs/Pcm Source, so a Decoder is encoded without decoding it
-- SEEKTABLE. Streams: input blocks are pulled from a codecs/audio/Pcm Source, so a Decoder is encoded without decoding it
-- whole. Never throws: bad options are rejected by audio/flac before calling in.
local Bits = require("@formats/core/Bits")
local Md5 = require("@formats/core/Md5")
local VorbisComment = require("@formats/codecs/VorbisComment")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local Frame = require("@formats/audio/flac/Frame")
local Encode = {}
+1 -1
View File
@@ -4,7 +4,7 @@
-- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is
-- left in place); every other block is skipped. Nothing throws: bad data gives nil, err.
-- Absorbed from flac-luau 7083d0d (same author, no third-party code).
local VorbisComment = require("@formats/codecs/VorbisComment")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local readu8, readu32 = buffer.readu8, buffer.readu32
+2 -2
View File
@@ -21,7 +21,7 @@ local Types = require("@formats/Types")
local Ogg = require("@formats/containers/Ogg")
local Stream = require("@formats/audio/flac/Stream")
local Encode = require("@formats/audio/flac/Encode")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Flac = {
@@ -29,7 +29,7 @@ local Flac = {
category = "audio",
extensions = { "flac", "oga" },
mime = { "audio/flac", "audio/x-flac" },
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" },
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/audio/Pcm", "codecs/audio/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
}
+24 -105
View File
@@ -1,6 +1,6 @@
--!strict
-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading
-- AAC-LC (codecs/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/Alac) tracks, gapless
-- AAC-LC (codecs/audio/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/audio/Alac) tracks, gapless
-- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures);
-- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs
-- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files.
@@ -9,10 +9,11 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
local Stream = require("@formats/codecs/audio/Stream")
local IsoBmff = require("@formats/containers/IsoBmff")
local Aac = require("@formats/codecs/Aac")
local Alac = require("@formats/codecs/Alac")
local Aac = require("@formats/codecs/audio/Aac")
local Alac = require("@formats/codecs/audio/Alac")
-- ------------------------------------------------------------------------------------------------ contract
local M4a = {
@@ -20,7 +21,7 @@ local M4a = {
category = "audio",
extensions = { "m4a", "m4b", "m4r" },
mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream" },
caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true },
}
@@ -181,15 +182,6 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
end
local frames = math.max(0, total - skip)
local buf = r.buf
-- streaming state
local nextPacket = 1
local decoded = 0 -- frames produced by the packets decoded so far (before trimming)
local pend, pendPos, pendN = p.pcm, 0, 0 -- the current packet: frames pendPos .. pendN - 1 not yet returned
local dropUntil = skip -- absolute frame index of the first frame to return
local stopAt = total
local pos = 0 -- frames returned
local failed: Err.Err? = nil
local dec: any = {
sampleRate = sr,
channels = channels,
@@ -201,103 +193,30 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
codec = t.codec,
track = t,
movie = movie,
error = nil,
}
local bytes = 0
for i = 1, t.sampleCount do
bytes += t.sizes[i]
end
dec.bitrate = if frames > 0 then math.floor(bytes * 8 * sr / frames) else (t.bitrate or 0)
-- decode the next packet into pend; false at the end / on an error
local function fill(): boolean
while true do
if nextPacket > t.sampleCount or decoded >= stopAt then
return false
end
local i = nextPacket
nextPacket += 1
local start = decoded
local n, e = p.decode(buf, t.offsets[i], t.sizes[i])
if not n then
failed = e
dec.error = e
return false
end
decoded += n
-- the part of this packet inside [dropUntil, stopAt)
local a = math.max(start, dropUntil)
local b = math.min(decoded, stopAt)
if b > a then
pendPos = a - start
pendN = b - start
return true
end
end
end
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
local want = math.max(0, math.floor(n))
local need = want * channels * 4
local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
local got = 0
local writef32 = buffer.writef32
while got < want do
if pendPos >= pendN then
if failed or not fill() then
break
end
end
local take = math.min(want - got, pendN - pendPos)
local src = pend
local o = got * channels * 4
local s = pendPos * channels
for k = 1, take * channels do
writef32(ob, o, src[s + k])
o += 4
end
pendPos += take
got += take
end
pos += got
return ob, got
end
function dec.seek(_self: any, seconds: number)
local target = math.clamp(math.floor(seconds * sr + 0.5), 0, frames) + skip -- absolute frame
-- the last packet starting at or before the target, minus one for the codec's overlap (AAC)
local ticks = target / tickScale
local lo, hi, found = 1, t.sampleCount, 1
while lo <= hi do
local mid = (lo + hi) // 2
if t.dts[mid] <= ticks then
found = mid
lo = mid + 1
else
hi = mid - 1
end
end
local startPacket = if t.codec == "aac" then math.max(1, found - 1) else found
p.reset()
nextPacket = startPacket
decoded = math.floor((t.dts[startPacket] or 0) * tickScale + 0.5)
dropUntil = math.max(target, skip)
pendPos, pendN = 0, 0
failed = nil
pos = target - skip
end
function dec.position(_self: any): number
return pos / sr
end
-- prime: surface a broken first packet as an open error
if t.sampleCount > 0 and frames > 0 then
if not fill() and failed then
return nil, failed
end
end
return dec, nil
-- packet start frames (media ticks -> frames); one AAC packet of pre-roll for the overlap when seeking
return Stream.packets(dec, {
count = t.sampleCount,
start = function(i: number): number
return math.floor((t.dts[i] or (t.dts[t.sampleCount] or 0) + (t.durations[t.sampleCount] or 0)) * tickScale + 0.5)
end,
decode = function(i: number): (number?, Err.Err?)
return p.decode(buf, t.offsets[i], t.sizes[i])
end,
pcm = function(): { number }
return p.pcm
end,
reset = p.reset,
skip = skip,
stop = total,
preroll = if t.codec == "aac" then 1 else 0,
cumulative = true,
})
end
-- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures)
+7 -7
View File
@@ -6,7 +6,7 @@
-- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped).
-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, audio/mp3/Encode3 + Encode2): layer III
-- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from
-- the tags; input at rates the layer cannot hold is resampled (codecs/Resample). Not supported: MPEG-2 multichannel
-- the tags; input at rates the layer cannot hold is resampled (codecs/audio/Resample). Not supported: MPEG-2 multichannel
-- extension, CRC checks, VBR / Xing output.
--
-- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay,
@@ -23,8 +23,8 @@ local Tags = require("@formats/audio/mp3/Tags")
local Stream = require("@formats/audio/mp3/Stream")
local Encode3 = require("@formats/audio/mp3/Encode3")
local Encode2 = require("@formats/audio/mp3/Encode2")
local Pcm = require("@formats/codecs/Pcm")
local Resample = require("@formats/codecs/Resample")
local Pcm = require("@formats/codecs/audio/Pcm")
local Resample = require("@formats/codecs/audio/Resample")
-- ------------------------------------------------------------------------------------------------ contract
local Mp3 = {
@@ -32,7 +32,7 @@ local Mp3 = {
category = "audio",
extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/Pcm", "codecs/Resample" },
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/audio/Pcm", "codecs/audio/Resample" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 },
}
@@ -48,8 +48,8 @@ export type EncodeOptions = {
-- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo"
id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags)
sampleRate: number?, -- output rate (one the layer holds); default the input rate if possible, else the nearest
-- higher one (input at other rates is resampled through codecs/Resample)
resampleQuality: ("low" | "medium" | "high")?, -- codecs/Resample quality (default "medium")
-- higher one (input at other rates is resampled through codecs/audio/Resample)
resampleQuality: ("low" | "medium" | "high")?, -- codecs/audio/Resample quality (default "medium")
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -173,7 +173,7 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
local Enc = if layer == 3 then Encode3 else Encode2
-- the output rate: opts.sampleRate, else the input's when the layer has it, else the nearest rate above it (else
-- the highest); other input rates go through codecs/Resample
-- the highest); other input rates go through codecs/audio/Resample
local rate = o.sampleRate or src.sampleRate
if o.sampleRate and not Enc.RATES[o.sampleRate] then
return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz", layer, tostring(o.sampleRate)))
+1 -1
View File
@@ -7,7 +7,7 @@
--
-- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch
-- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it.
local RD = require("@formats/codecs/RangeCoder/Decoder")
local RD = require("@formats/codecs/entropy/RangeCoder/Decoder")
local Mdct = require("@formats/audio/opus/Mdct")
local T = require("@formats/audio/opus/CeltTables")
+3 -3
View File
@@ -5,11 +5,11 @@
-- bit rate, long MDCTs only (no transient detection), no pitch pre-filter, normal spreading, default allocation trim,
-- mono, or stereo as mid / side per band (the angle, intensity when it has no bits; dual L / R stereo on request). The bitstream side is a port of the libopus 1.6 encoder paths
-- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that
-- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/Mdct.
-- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/audio/Mdct.
-- Never throws.
local RE = require("@formats/codecs/RangeCoder/Encoder")
local RE = require("@formats/codecs/entropy/RangeCoder/Encoder")
local T = require("@formats/audio/opus/CeltTables")
local Mdct = require("@formats/codecs/Mdct")
local Mdct = require("@formats/codecs/audio/Mdct")
local CeltEncoder = {}
+1 -1
View File
@@ -4,7 +4,7 @@
-- audio/opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching
-- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the
-- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays.
local RD = require("@formats/codecs/RangeCoder/Decoder")
local RD = require("@formats/codecs/entropy/RangeCoder/Decoder")
local Packet = require("@formats/audio/opus/Packet")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
+5 -5
View File
@@ -2,14 +2,14 @@
-- audio/opus/Encode: Ogg Opus writing (RFC 7845) around audio/opus/CeltEncoder: CELT-only packets (TOC config 31:
-- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor +
-- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at
-- other rates is resampled to 48 kHz (codecs/Resample); the input is a Types.Audio or a Decoder (codecs/Pcm). New in
-- other rates is resampled to 48 kHz (codecs/audio/Resample); the input is a Types.Audio or a Decoder (codecs/audio/Pcm). New in
-- formats-luau.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Ogg = require("@formats/containers/Ogg")
local Pcm = require("@formats/codecs/Pcm")
local Resample = require("@formats/codecs/Resample")
local VorbisComment = require("@formats/codecs/VorbisComment")
local Pcm = require("@formats/codecs/audio/Pcm")
local Resample = require("@formats/codecs/audio/Resample")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local CeltEncoder = require("@formats/audio/opus/CeltEncoder")
local Encode = {}
@@ -42,7 +42,7 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then
return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000")
end
-- the whole input at 48 kHz (codecs/Resample for other rates), then as floats
-- the whole input at 48 kHz (codecs/audio/Resample for other rates), then as floats
if rate ~= 48000 then
local rs, rerr = Resample.source(src, 48000)
if not rs then
+1 -1
View File
@@ -4,7 +4,7 @@
-- audio/opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the
-- kiss_fft stages used by libopus: radix 5, 3, 4 and 2). The 48 kHz mode uses N = 1920 >> shift for
-- shift = 0..3 (FFT sizes 480, 240, 120, 60). Arrays are Luau tables of numbers, 1-based.
-- Why not codecs/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a
-- Why not codecs/audio/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a
-- DCT-IV, of which CELT keeps the middle N / 2, so routing the decoder through it made CELT decoding 2-3x slower
-- (luau: 25 -> 54-76 ms for 3 s of 32 kbps stereo) and changed the output bits (same SNR against opusdec). This
-- fused libopus port (pre-rotation, a kiss_fft with fixed factors, post-rotation, TDAC) stays private.
+1 -1
View File
@@ -14,7 +14,7 @@
--
-- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values
-- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact.
local RD = require("@formats/codecs/RangeCoder/Decoder")
local RD = require("@formats/codecs/entropy/RangeCoder/Decoder")
local T = require("@formats/audio/opus/SilkTables")
local icdf = RD.icdf
+6 -6
View File
@@ -24,9 +24,9 @@ local Types = require("@formats/Types")
local Ogg = require("@formats/containers/Ogg")
local Decoder = require("@formats/audio/opus/Decoder")
local Packet = require("@formats/audio/opus/Packet")
local VorbisComment = require("@formats/codecs/VorbisComment")
local Pcm = require("@formats/codecs/Pcm")
local RangeDecoder = require("@formats/codecs/RangeCoder/Decoder")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local Pcm = require("@formats/codecs/audio/Pcm")
local RangeDecoder = require("@formats/codecs/entropy/RangeCoder/Decoder")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
local Encode = require("@formats/audio/opus/Encode")
@@ -37,7 +37,7 @@ local Opus = {
category = "audio",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/RangeCoder/Decoder", "codecs/RangeCoder/Encoder", "codecs/Pcm", "codecs/Resample", "codecs/VorbisComment" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/entropy/RangeCoder/Decoder", "codecs/entropy/RangeCoder/Encoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 },
}
@@ -126,7 +126,7 @@ local function parseHead(b: buffer, off: number, size: number): (Head?, string?)
return head, nil
end
-- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/VorbisComment: lower-case keys, repeated fields joined
-- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/audio/VorbisComment: lower-case keys, repeated fields joined
-- with "; "), the raw fields
local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }, { VorbisComment.Field })
if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then
@@ -372,7 +372,7 @@ function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?)
vendor = vendor,
tags = tags,
comments = rawTags,
-- mapping family 1 is in Vorbis channel order; the output is WAVE order (codecs/Pcm)
-- mapping family 1 is in Vorbis channel order; the output is WAVE order (codecs/audio/Pcm)
order = if not downmix and head.mappingFamily == 1 and head.channels > 2 then Pcm.WAVE_FROM_VORBIS[head.channels] else nil,
sampleRate = SAMPLE_RATE,
channels = if downmix then 2 else head.channels,
+2 -2
View File
@@ -11,7 +11,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Voc = {
@@ -19,7 +19,7 @@ local Voc = {
category = "audio",
extensions = { "voc" },
mime = { "audio/x-voc" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false },
}
+4 -4
View File
@@ -3,16 +3,16 @@
--!optimize 2
-- audio/vorbis/Encode: a basic but valid Vorbis I encoder in Ogg. New code written from the Vorbis I specification
-- (no libvorbis code). Design: long blocks only (2048 samples; blocksize 0 is declared as 256 but never used), the
-- Vorbis window, the MDCT (codecs/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a
-- Vorbis window, the MDCT (codecs/audio/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a
-- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality-
-- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer
-- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then
-- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian
-- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact
-- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws.
local Mdct = require("@formats/codecs/Mdct")
local Pcm = require("@formats/codecs/Pcm")
local VorbisComment = require("@formats/codecs/VorbisComment")
local Mdct = require("@formats/codecs/audio/Mdct")
local Pcm = require("@formats/codecs/audio/Pcm")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local Ogg = require("@formats/containers/Ogg")
local Tables = require("@formats/audio/vorbis/Tables")
+2 -2
View File
@@ -2,7 +2,7 @@
--!native
--!optimize 2
-- audio/vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1
-- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/Mdct), windowing and overlap-add.
-- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/audio/Mdct), windowing and overlap-add.
-- Floors, residues and coupling are ported from stb_vorbis 1.22 vorbis_decode_packet_rest / decode_residue /
-- do_floor / draw_line (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). The overlap follows libvorbis:
-- each packet after the first returns the n_prev/4 + n_cur/4 samples between the centres of the two windows, so
@@ -16,7 +16,7 @@
local Codebook = require("@formats/audio/vorbis/Codebook")
local Setup = require("@formats/audio/vorbis/Setup")
local Tables = require("@formats/audio/vorbis/Tables")
local Mdct = require("@formats/codecs/Mdct")
local Mdct = require("@formats/codecs/audio/Mdct")
local Packet = {}
+6 -6
View File
@@ -1,6 +1,6 @@
--!strict
-- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau
-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/Mdct,
-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/audio/Mdct,
-- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last
-- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position).
-- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2,
@@ -18,8 +18,8 @@ local Ogg = require("@formats/containers/Ogg")
local Setup = require("@formats/audio/vorbis/Setup")
local Packet = require("@formats/audio/vorbis/Packet")
local Encode = require("@formats/audio/vorbis/Encode")
local Pcm = require("@formats/codecs/Pcm")
local VorbisComment = require("@formats/codecs/VorbisComment")
local Pcm = require("@formats/codecs/audio/Pcm")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
-- ------------------------------------------------------------------------------------------------ contract
local Vorbis = {
@@ -27,7 +27,7 @@ local Vorbis = {
category = "audio",
extensions = { "ogg", "oga" },
mime = { "audio/ogg", "audio/vorbis" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm", "codecs/VorbisComment" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 },
}
@@ -41,7 +41,7 @@ export type EncodeOptions = {
}
-- ------------------------------------------------------------------------------------------------ constants
-- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/Pcm; identity past 8 channels)
-- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/audio/Pcm; identity past 8 channels)
local function waveOrder(ch: number): { number }
local m = Pcm.WAVE_FROM_VORBIS[ch]
if m then
@@ -399,7 +399,7 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
tags = tags,
vendor = vendor,
ident = id,
-- WAVE channel order out (codecs/Pcm): output channel c is Vorbis channel order[c]
-- WAVE channel order out (codecs/audio/Pcm): output channel c is Vorbis channel order[c]
order = waveOrder(id.channels),
source = {
format = "vorbis",
+2 -2
View File
@@ -18,7 +18,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
local Riff = require("@formats/containers/Riff")
local Codecs = require("@formats/audio/wav/Codecs")
@@ -28,7 +28,7 @@ local Wav = {
category = "audio",
extensions = { "wav", "wave", "rf64", "bw64" },
mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
}