Files
rosetta/src/Formats/codecs/audio/Pcm/init.luau
T
4DBug 7cfec05eeb ws-cleanup: Pcm.collect reads a known length in one call into the result (no copy); README links the guide
Measured in an A/B of the touched paths (best of 3-4, one core): LuaJIT wav decode through Pcm.drain was ~10%
slower than the old single read; now within noise.
2026-10-31 13:19:43 -05:00

295 lines
11 KiB
Luau

--!strict
-- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
-- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one
-- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au,
-- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder.
--
-- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else
-- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read
-- local audio = Pcm.collect(src) -- read everything into a Types.Audio
-- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder
-- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio
-- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer
-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/audio/Pcm/Convert)
-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767]
-- local x = Pcm.fromInt(s16, 16) -- s / 32768
--
-- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw.
-- Never throws (a decoder's read that throws is caught and ends the stream).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Convert = require("@formats/codecs/audio/Pcm/Convert")
local Pcm = {}
Pcm.Convert = Convert
-- Channel order. Decoders return WAVE (WAVEFORMATEXTENSIBLE) order: FL FR C LFE BL BR (SL SR) ..., as FLAC, WAV and
-- AAC store it. Vorbis and Opus (mapping family 1) store the Vorbis order (FL C FR ... LFE last); WAVE_FROM_VORBIS[n][i]
-- is the Vorbis-order channel (1-based) that WAVE-order channel i holds, for n = 1 .. 8 channels.
Pcm.WAVE_FROM_VORBIS = {
{ 1 },
{ 1, 2 },
{ 1, 3, 2 }, -- L C R -> L R C
{ 1, 2, 3, 4 }, -- FL FR RL RR
{ 1, 3, 2, 4, 5 }, -- FL C FR RL RR -> FL FR C RL RR
{ 1, 3, 2, 6, 4, 5 }, -- FL C FR RL RR LFE -> FL FR C LFE RL RR
{ 1, 3, 2, 7, 6, 4, 5 }, -- FL C FR SL SR RC LFE -> FL FR C LFE RC SL SR
{ 1, 3, 2, 8, 6, 7, 4, 5 }, -- FL C FR SL SR RL RR LFE -> FL FR C LFE RL RR SL SR
}
export type Source = {
sampleRate: number,
channels: number,
frames: number, -- total frames, 0 = unknown (a streaming decoder without an index)
tags: Types.Tags,
-- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end)
read: (self: Source, n: number, out: buffer?) -> (buffer, number),
err: Err.Err?, -- set when the underlying decoder failed mid-stream
}
local function audioRead(self: any, n: number, out: buffer?): (buffer, number)
local a = self._audio
local ch = a.channels
local left = a.frames - self._pos
if n > left then
n = left
end
if n <= 0 then
return out or buffer.create(0), 0
end
local bytes = n * ch * 4
local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes)
buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes)
self._pos += n
return b, n
end
local function decoderRead(self: any, n: number, out: buffer?): (buffer, number)
if self._done then
return out or buffer.create(0), 0
end
local ok, b, got = pcall(self._dec.read, self._dec, n, out)
if not ok then
self._done = true
self.err = Err.new(Err.CORRUPT, "source decoder failed: " .. tostring(b))
return out or buffer.create(0), 0
end
if type(b) ~= "buffer" or type(got) ~= "number" or got <= 0 then
self._done = true
return out or buffer.create(0), 0
end
local ch = self.channels
if buffer.len(b) < got * ch * 4 then
got = buffer.len(b) // (ch * 4)
end
return b, got
end
-- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read)
function Pcm.source(v: any): (Source?, Err.Err?)
if type(v) ~= "table" then
return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder")
end
local sr, ch = v.sampleRate, v.channels
if type(sr) ~= "number" or sr <= 0 or sr ~= sr or type(ch) ~= "number" or ch < 1 or ch ~= math.floor(ch) then
return nil, Err.new(Err.ARG, "bad sampleRate or channels")
end
if v.kind == "audio" and type(v.samples) == "buffer" then
local frames = v.frames
if type(frames) ~= "number" or frames < 0 or buffer.len(v.samples) < frames * ch * 4 then
return nil, Err.new(Err.ARG, "the Audio's samples buffer is shorter than frames * channels * 4")
end
return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = audioRead, _audio = v, _pos = 0 } :: any, nil
end
if type(v.read) == "function" then
local frames = if type(v.frames) == "number" and v.frames > 0 then v.frames else 0
return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } :: any, nil
end
return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder")
end
-- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames)
function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?)
local ch = src.channels
local cap = math.max(src.frames, 4096)
local data = buffer.create(cap * ch * 4)
local total = 0
local limit = maxFrames or 2 ^ 31
local tmp: buffer? = nil
-- a known length: one read straight into the result (decoders write into a big enough out buffer: no copy)
if src.frames > 0 and src.frames <= limit then
local b, n = src:read(src.frames, data)
if n > 0 then
if b ~= data then
buffer.copy(data, 0, b, 0, math.min(n, cap) * ch * 4)
end
total = math.min(n, cap)
end
end
while true do
local b, n = src:read(16384, tmp)
if n <= 0 then
break
end
tmp = b
if total + n > limit then
return nil, Err.new(Err.LIMIT, string.format("more than %d frames", limit))
end
if total + n > cap then
cap = math.max(cap * 2, total + n)
local nd = buffer.create(cap * ch * 4)
buffer.copy(nd, 0, data, 0, total * ch * 4)
data = nd
end
buffer.copy(data, total * ch * 4, b, 0, n * ch * 4)
total += n
end
if src.err then
return nil, src.err
end
local a = Types.Audio.new(src.sampleRate, ch, 0)
a.frames = total
if buffer.len(data) == total * ch * 4 then
a.samples = data
else
a.samples = buffer.create(total * ch * 4)
buffer.copy(a.samples, 0, data, 0, total * ch * 4)
end
a.tags = table.clone(src.tags)
return a, nil
end
-- drain(dec, source?, maxFrames?) -> Types.Audio | nil, Err: a format's decode() through its open(): every frame of
-- the Decoder (dec.frames is only a hint: short or long streams keep what decodes), dec.tags, meta.source = source
-- (default dec.source). A decoder that recorded a failure in dec.error (an Err) fails the drain.
function Pcm.drain(dec: any, source: { [string]: any }?, maxFrames: number?): (Types.Audio?, Err.Err?)
local src, err = Pcm.source(dec)
if not src then
return nil, err
end
local a, cerr = Pcm.collect(src, maxFrames)
if not a then
return nil, cerr
end
if Err.is(dec.error) then
return nil, dec.error
end
a.tags = dec.tags or {}
a.meta.source = source or dec.source
return a, nil
end
-- ------------------------------------------------------------------------------------------------ decoders
-- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming
-- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf)
function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: number, sampleRate: number, fmt: string, tags: Types.Tags?): (Types.Decoder?, Err.Err?)
local size = Convert.SIZE[fmt]
if not size then
return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt))
end
if channels < 1 or sampleRate <= 0 or frames < 0 or offset < 0 or offset + frames * channels * size > buffer.len(buf) then
return nil, Err.new(Err.ARG, "bad raw PCM layout")
end
local pos = 0
local frameBytes = channels * size
local dec = {
sampleRate = sampleRate,
channels = channels,
frames = frames,
duration = frames / sampleRate,
bitrate = sampleRate * frameBytes * 8,
tags = tags or {},
}
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
n = math.clamp(math.floor(n), 0, frames - pos)
local bytes = n * channels * 4
local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes)
if n > 0 then
Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0)
pos += n
end
return b, n
end
function dec.seek(_self: any, seconds: number)
local f = math.floor(seconds * sampleRate + 0.5)
pos = if f ~= f then 0 else math.clamp(f, 0, frames)
end
function dec.position(_self: any): number
return pos / sampleRate
end
return dec :: any, nil
end
-- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples)
function Pcm.audioDecoder(a: Types.Audio): Types.Decoder
local d = Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) :: any
d.bitrate = a.sampleRate * a.channels * 32
return d
end
-- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples
function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?)
local size = Convert.SIZE[fmt]
if not size then
return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt))
end
local ch = src.channels
local total = 0
local tmp: buffer? = nil
while true do
local b, n = src:read(8192, tmp)
if n <= 0 then
break
end
tmp = b
local at = w:reserve(n * ch * size)
Convert.encode(b, 0, n * ch, fmt, w.buf, at)
w.pos = at + n * ch * size
total += n
end
if src.err then
return nil, src.err
end
return total, nil
end
-- ------------------------------------------------------------------------------------------------ conversions
-- reorder(buf, offset, frames, channels, map): in place, frame by frame, channel i of the result = channel map[i]
-- (1-based) of the input; for converting between channel orders (Pcm.WAVE_FROM_VORBIS)
function Pcm.reorder(buf: buffer, offset: number, frames: number, channels: number, map: { number })
local tmp = table.create(channels, 0)
local readf32, writef32 = buffer.readf32, buffer.writef32
for f = 0, frames - 1 do
local p = offset + f * channels * 4
for c = 1, channels do
tmp[c] = readf32(buf, p + (map[c] - 1) * 4)
end
for c = 1, channels do
writef32(buf, p + (c - 1) * 4, tmp[c])
end
end
end
-- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0)
function Pcm.toInt(x: number, bits: number): number
local s = 2 ^ (bits - 1)
local v = math.floor(x * s + 0.5)
if v ~= v then
return 0
end
if v >= s then
return s - 1
elseif v < -s then
return -s
end
return v
end
-- fromInt(v, bits) -> v / 2^(bits-1)
function Pcm.fromInt(v: number, bits: number): number
return v / 2 ^ (bits - 1)
end
return Pcm