Files
rosetta/src/Rosetta/codecs/audio/Pcm/init.luau
T

263 lines
7.8 KiB
Luau

--!strict
--!optimize 2
-- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Convert = require("@rosetta/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,
tags: Types.Tags,
read: (self: Source, n: number, out: buffer?) -> (buffer, number),
err: Err.Err?,
}
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
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
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
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
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
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
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
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
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
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
function Pcm.fromInt(v: number, bits: number): number
return v / 2 ^ (bits - 1)
end
return Pcm