ws-audio2: codecs/audio/Qoa and audio/qoa (QOA read / write, port of qoa.h, MIT)

Decode bit-exact with ffmpeg and qoa.h; encode byte-for-byte qoa.h's qoa_encode (fixtures compile the committed
qoa.h reference with nix gcc).
This commit is contained in:
4DBug committed 2026-10-31 14:26:33 -05:00
1 parent 5dfaaf7524
commit f765763537
9 files changed
+1468

No files matched your search

+12
View File
@@ -278,6 +278,18 @@ local list: { Entry } = {
return require("@formats/audio/opus")
end,
},
{
name = "qoa",
category = "audio",
path = "audio/qoa",
extensions = { "qoa" },
mime = { "audio/qoa" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" },
caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 },
load = function()
return require("@formats/audio/qoa")
end,
},
{
name = "vag",
category = "audio",
+185
View File
@@ -0,0 +1,185 @@
--!strict
-- audio/qoa: QOA, "Quite OK Audio" (.qoa), over codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). New in
-- formats-luau. Decode / open: static files and streaming files (total 0 in the header), 1-255 channels (WAVE order
-- for 1-8, as the spec lays them out), any rate up to 16777215 Hz, frame-accurate seeking (every frame carries its
-- own predictor state), a truncated file decodes its whole frames. Encode (Audio or Decoder, streamed frame by frame):
-- byte-for-byte what qoa.h's qoa_encode writes, 1-8 channels (qoa.h's limit). Not supported: frames whose channel
-- count or rate change mid-stream (Err.UNSUPPORTED).
--
-- local dec = Qoa.open(Bytes.reader(buf)) -- Types.Decoder
-- local file = Qoa.encode(audio)
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/audio/Pcm")
local Stream = require("@formats/codecs/audio/Stream")
local Codec = require("@formats/codecs/audio/Qoa")
-- ------------------------------------------------------------------------------------------------ contract
local Qoa = {
name = "qoa",
category = "audio",
extensions = { "qoa" },
mime = { "audio/qoa" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" },
caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this many sample frames (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Qoa.sniff(r: Bytes.Reader): number
return if r:peek(4) == "qoaf" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Qoa.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Qoa.open(r)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
return Pcm.drain(d, { format = "qoa", streaming = d.streaming }, limit)
end
-- ------------------------------------------------------------------------------------------------ encode
function Qoa.encode(value: any, _opts: any?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local ch, rate = src.channels, src.sampleRate
if ch > 8 then
return nil, Err.new(Err.ARG, "QOA (qoa.h) holds at most 8 channels")
end
if rate ~= math.floor(rate) or rate < 1 or rate > 0xFFFFFF then
return nil, Err.new(Err.ARG, "the sample rate must be an integer in 1 .. 16777215")
end
local FL = Codec.FRAME_LEN
local w = Bytes.writer(8 + (if src.frames > 0 then Codec.frameSize(ch, (src.frames + 19) // 20) + 24 * ch * (src.frames // FL + 1) else 65536))
w:string("qoaf")
w:u32be(0)
local lms = Codec.newLms(ch)
local fb = buffer.create(FL * ch * 4)
local tmp: buffer? = nil
local total = 0
while true do
-- one frame: 5120 sample frames (the last may be shorter), as qoa.h cuts them
local have = 0
while have < FL do
local b, n = src:read(FL - have, tmp)
if n <= 0 then
break
end
tmp = b
buffer.copy(fb, have * ch * 4, b, 0, n * ch * 4)
have += n
end
if have == 0 then
break
end
local at = w:reserve(Codec.frameSize(ch, (have + 19) // 20))
w.pos = at + Codec.encodeFrame(fb, 0, have, ch, rate, lms, w.buf, at)
total += have
if have < FL then
break
end
end
if src.err then
return nil, src.err
end
if total == 0 then
return nil, Err.new(Err.ARG, "QOA needs at least one sample")
end
if total >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "too many samples for QOA")
end
local out = w:finish()
buffer.writeu32(out, 4, bit32.byteswap(total))
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
function Qoa.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?)
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local h = r:sub(0)
if h:string(4) ~= "qoaf" then
return nil, Err.new(Err.CORRUPT, "not a QOA file")
end
local declared = h:u32be()
if h.err then
return nil, h.err
end
local buf = r.buf
-- the frame index: offsets, first frames
local offs, starts = {}, {}
local p, total = r.base + 8, 0
local ch, rate = 0, 0
while p < r.limit do
local info, msg = Codec.frameInfo(buf, p, r.limit - p)
if not info then
if #offs == 0 then
return nil, Err.from(msg, p - r.base)
end
break -- a cut or damaged tail: keep the whole frames
end
if #offs == 0 then
ch, rate = info.channels, info.rate
elseif info.channels ~= ch or info.rate ~= rate then
return nil, Err.new(Err.UNSUPPORTED, "the channel count or rate changes mid-stream", p - r.base)
end
table.insert(offs, p)
table.insert(starts, total)
total += info.samples
p += info.size
if declared > 0 and total >= declared then
break
end
end
if #offs == 0 then
return nil, Err.new(Err.TRUNCATED, "no frames")
end
local frames = if declared > 0 then math.min(declared, total) else total
local pcm = buffer.create(Codec.FRAME_LEN * ch * 4)
local dec: any = {
sampleRate = rate,
channels = ch,
frames = frames,
duration = frames / rate,
bitrate = math.floor((p - r.base) * 8 / math.max(frames / rate, 1e-9)),
tags = {},
streaming = declared == 0,
}
local limit = r.limit
return Stream.packets(dec, {
count = #offs,
start = function(i: number): number
return if i > #offs then total else starts[i]
end,
decode = function(i: number): (number?, Err.Err?)
local n, msg = Codec.decodeFrame(buf, offs[i], limit - offs[i], pcm, 0)
if not n then
return nil, Err.from(msg, offs[i] - r.base)
end
return n, nil
end,
pcm = function(): buffer
return pcm
end,
reset = function() end,
stop = frames,
})
end
return Qoa
+297
View File
@@ -0,0 +1,297 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale
-- factor and 20 3-bit residuals over a 4-tap sign-sign LMS predictor. Ported from qoa.h (phoboslab/qoa, Dominic
-- Szablewski, MIT: licenses/qoa-LICENSE.txt): the tables, the predictor, the decoder and the encoder's brute-force
-- scale factor search, so encoding is byte-for-byte qoa.h's (including its 32-bit wrap in the reciprocal division).
-- The 64-bit slices are handled as two 32-bit halves.
--
-- local info = Qoa.frameInfo(buf, p, avail) -- { channels, rate, samples, size } | nil, message
-- local n, msg = Qoa.decodeFrame(buf, p, avail, dst, d) -- one frame -> interleaved f32 at float index d
-- local size = Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) -- n frames of f32 at frame xf -> bytes at out[p]
-- local lms = Qoa.newLms(ch) -- the encoder state (history 0, weights 0, 0, -1, 2)
--
-- Never throws: decodeFrame checks the frame against avail before reading; encodeFrame needs Qoa.frameSize bytes.
local readu8, readu32, readf32, writef32, writeu32 = buffer.readu8, buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32
local readi32, writei32 = buffer.readi32, buffer.writei32
local band, rshift, bor, lshift, byteswap = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.byteswap
local floor = math.floor
local Qoa = {}
Qoa.SLICE_LEN = 20
Qoa.SLICES_PER_FRAME = 256
Qoa.FRAME_LEN = 256 * 20
Qoa.MAX_CHANNELS = 255
local QUANT = { 7, 7, 7, 5, 5, 3, 3, 1, 0, 0, 2, 2, 4, 4, 6, 6, 6 } -- residual -8 .. 8 -> code
local RECIP = { 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32 }
-- DEQ[sf * 8 + q + 1]
local DEQ = {
1, -1, 3, -3, 5, -5, 7, -7,
5, -5, 18, -18, 32, -32, 49, -49,
16, -16, 53, -53, 95, -95, 147, -147,
34, -34, 113, -113, 203, -203, 315, -315,
63, -63, 210, -210, 378, -378, 588, -588,
104, -104, 345, -345, 621, -621, 966, -966,
158, -158, 528, -528, 950, -950, 1477, -1477,
228, -228, 760, -760, 1368, -1368, 2128, -2128,
316, -316, 1053, -1053, 1895, -1895, 2947, -2947,
422, -422, 1405, -1405, 2529, -2529, 3934, -3934,
548, -548, 1828, -1828, 3290, -3290, 5117, -5117,
696, -696, 2320, -2320, 4176, -4176, 6496, -6496,
868, -868, 2893, -2893, 5207, -5207, 8099, -8099,
1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933,
1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005,
1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336,
}
local function be32(b: buffer, p: number): number
return byteswap(readu32(b, p))
end
local function s16(v: number): number
return if v >= 32768 then v - 65536 else v
end
-- frameSize(channels, slices) -> bytes
function Qoa.frameSize(ch: number, slices: number): number
return 8 + 16 * ch + 8 * slices * ch
end
export type FrameInfo = { channels: number, rate: number, samples: number, size: number }
-- frameInfo(buf, p, avail) -> the frame header's facts, checked against avail and the slice count | nil, message
function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?)
if avail < 8 then
return nil, "truncated frame header"
end
local hi, lo = be32(b, p), be32(b, p + 4)
local ch = rshift(hi, 24)
local rate = band(hi, 0xFFFFFF)
local samples = rshift(lo, 16)
local size = band(lo, 0xFFFF)
if ch == 0 or rate == 0 or samples == 0 then
return nil, "bad frame header"
end
local slices = (samples + 19) // 20
local head = 8 + 16 * ch
if slices > 256 or size < head or slices * ch > (size - head) // 8 then
return nil, "bad frame size"
end
if size > avail then
return nil, "truncated frame"
end
return { channels = ch, rate = rate, samples = samples, size = size }, nil
end
-- decodeFrame(buf, p, avail, dst, d) -> samples per channel, frame bytes | nil, message: one frame (its own LMS state
-- in the header) as interleaved f32 into dst from float index d (dst holds samples * channels floats there)
function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: number): (number?, number | string)
local info, msg = Qoa.frameInfo(b, p, avail)
if not info then
return nil, msg :: string
end
local ch, samples = info.channels, info.samples
for c = 0, ch - 1 do
local lp = p + 8 + c * 16
local hA, hB, hC, hD = be32(b, lp), be32(b, lp + 4), be32(b, lp + 8), be32(b, lp + 12)
local h0, h1, h2, h3 = s16(rshift(hA, 16)), s16(band(hA, 0xFFFF)), s16(rshift(hB, 16)), s16(band(hB, 0xFFFF))
local w0, w1, w2, w3 = s16(rshift(hC, 16)), s16(band(hC, 0xFFFF)), s16(rshift(hD, 16)), s16(band(hD, 0xFFFF))
local sp = p + 8 + 16 * ch + c * 8
local o = (d + c) * 4
local os = ch * 4
local s0 = 0
while s0 < samples do
local hi, lo = be32(b, sp), be32(b, sp + 4)
local base = rshift(hi, 28) * 8 + 1
local n = math.min(20, samples - s0)
for k = 0, n - 1 do
local q
if k < 9 then
q = band(rshift(hi, 25 - 3 * k), 7)
elseif k == 9 then
q = band(hi, 1) * 4 + rshift(lo, 30)
else
q = band(rshift(lo, 57 - 3 * k), 7)
end
local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192
local dq = DEQ[base + q]
local r = pred + dq
if r > 32767 then
r = 32767
elseif r < -32768 then
r = -32768
end
writef32(dst, o, r / 32768)
o += os
local delta = dq // 16
w0 += if h0 < 0 then -delta else delta
w1 += if h1 < 0 then -delta else delta
w2 += if h2 < 0 then -delta else delta
w3 += if h3 < 0 then -delta else delta
h0, h1, h2, h3 = h1, h2, h3, r
end
s0 += 20
sp += 8 * ch
end
end
return samples, info.size
end
-- ------------------------------------------------------------------------------------------------ encoder
-- newLms(ch) -> the encoder's LMS state: 8 i32 per channel (history 0..3, weights 0..3), weights 0, 0, -1, 2 (<< 13)
function Qoa.newLms(ch: number): buffer
local st = buffer.create(32 * ch)
for c = 0, ch - 1 do
writei32(st, c * 32 + 24, -8192)
writei32(st, c * 32 + 28, 16384)
end
return st
end
-- the nearest s16 to x * 32768 (NaN -> 0)
local function toS16(x: number): number
local v = floor(x * 32768 + 0.5)
if v ~= v then
return 0
elseif v > 32767 then
return 32767
elseif v < -32768 then
return -32768
end
return v
end
-- qoa.h's qoa_div: a rounding division by the scale factor through its .16 reciprocal (in 32-bit int arithmetic, which
-- wraps for big residuals at scale factor 0), rounding away from zero
local function qdiv(v: number, sf: number): number
local x = v * RECIP[sf + 1] + 32768
if x >= 2147483648 or x < -2147483648 then
x = (x + 2147483648) % 4294967296 - 2147483648
end
local n = x // 65536
local sv = if v > 0 then 1 elseif v < 0 then -1 else 0
local sn = if n > 0 then 1 elseif n < 0 then -1 else 0
return n + sv - sn
end
-- encodeFrame(x, xf, n, ch, rate, lms, out, p) -> bytes written: frames xf .. xf + n - 1 (n <= 5120) of interleaved f32 x
-- as one QOA frame at out[p] (Qoa.frameSize(ch, ceil(n / 20)) bytes); lms carries the encoder state between frames
function Qoa.encodeFrame(x: buffer, xf: number, n: number, ch: number, rate: number, lms: buffer, out: buffer, p: number): number
local slices = (n + 19) // 20
local size = Qoa.frameSize(ch, slices)
writeu32(out, p, byteswap(bor(lshift(ch, 24), rate)))
writeu32(out, p + 4, byteswap(bor(lshift(n, 16), size)))
for c = 0, ch - 1 do
local so = c * 32
-- the history and weights as big-endian i16 x 4
for i = 0, 3 do
local hv = band(readi32(lms, so + i * 4), 0xFFFF)
local wv = band(readi32(lms, so + 16 + i * 4), 0xFFFF)
buffer.writeu8(out, p + 8 + c * 16 + i * 2, rshift(hv, 8))
buffer.writeu8(out, p + 8 + c * 16 + i * 2 + 1, band(hv, 255))
buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2, rshift(wv, 8))
buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2 + 1, band(wv, 255))
end
end
local xs = table.create(20, 0)
local codes = table.create(20, 0)
local best = table.create(20, 0)
local prevSf = table.create(ch, 0)
local sp = p + 8 + 16 * ch
for s = 0, slices - 1 do
local len = math.min(20, n - s * 20)
for c = 0, ch - 1 do
for k = 1, len do
xs[k] = toS16(readf32(x, ((xf + s * 20 + k - 1) * ch + c) * 4))
end
local so = c * 32
local H0, H1, H2, H3 = readi32(lms, so), readi32(lms, so + 4), readi32(lms, so + 8), readi32(lms, so + 12)
local W0, W1, W2, W3 = readi32(lms, so + 16), readi32(lms, so + 20), readi32(lms, so + 24), readi32(lms, so + 28)
local bestRank, bestSf = math.huge, 0
local b0, b1, b2, b3, bw0, bw1, bw2, bw3 = H0, H1, H2, H3, W0, W1, W2, W3
for sfi = 0, 15 do
local sf = (sfi + prevSf[c + 1]) % 16
local h0, h1, h2, h3, w0, w1, w2, w3 = H0, H1, H2, H3, W0, W1, W2, W3
local rank = 0
local base = sf * 8 + 1
for k = 1, len do
local v = xs[k]
local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192
local res = v - pred
local sc = qdiv(res, sf)
if sc > 8 then
sc = 8
elseif sc < -8 then
sc = -8
end
local q = QUANT[sc + 9]
local dq = DEQ[base + q]
local r = pred + dq
if r > 32767 then
r = 32767
elseif r < -32768 then
r = -32768
end
local sq = w0 * w0 + w1 * w1 + w2 * w2 + w3 * w3
if sq >= 2147483648 then -- C int arithmetic
sq = (sq + 2147483648) % 4294967296 - 2147483648
end
local pen = sq // 262144 - 0x8ff
if pen < 0 then
pen = 0
end
local e = v - r
rank += e * e + pen * pen
if rank > bestRank then
break
end
local delta = dq // 16
w0 += if h0 < 0 then -delta else delta
w1 += if h1 < 0 then -delta else delta
w2 += if h2 < 0 then -delta else delta
w3 += if h3 < 0 then -delta else delta
h0, h1, h2, h3 = h1, h2, h3, r
codes[k] = q
end
if rank < bestRank then
bestRank, bestSf = rank, sf
b0, b1, b2, b3, bw0, bw1, bw2, bw3 = h0, h1, h2, h3, w0, w1, w2, w3
for k = 1, len do
best[k] = codes[k]
end
end
end
prevSf[c + 1] = bestSf
writei32(lms, so, b0)
writei32(lms, so + 4, b1)
writei32(lms, so + 8, b2)
writei32(lms, so + 12, b3)
writei32(lms, so + 16, bw0)
writei32(lms, so + 20, bw1)
writei32(lms, so + 24, bw2)
writei32(lms, so + 28, bw3)
-- the slice: sf in the top 4 bits, then the codes, unused codes 0
local hi, lo = bestSf * 268435456, 0
for k = 0, 19 do
local q = if k < len then best[k + 1] else 0
if k < 9 then
hi += q * 2 ^ (25 - 3 * k)
elseif k == 9 then
hi += rshift(q, 2)
lo += band(q, 3) * 1073741824
else
lo += q * 2 ^ (57 - 3 * k)
end
end
writeu32(out, sp, byteswap(hi))
writeu32(out, sp + 4, byteswap(lo))
sp += 8
end
end
return size
end
return Qoa