Files
rosetta/src/Formats/audio/opus/Decoder.luau
T

467 lines
13 KiB
Luau

--!strict
--!native
--!optimize 2
-- 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/audio/opus/RangeDecoder")
local Packet = require("@formats/audio/opus/Packet")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
local Decoder = {}
local MODE_SILK, MODE_HYBRID, MODE_CELT = Packet.MODE_SILK_ONLY, Packet.MODE_HYBRID, Packet.MODE_CELT_ONLY
local BW_NB, BW_MB, BW_WB, BW_SWB = Packet.BW_NB, Packet.BW_MB, Packet.BW_WB, Packet.BW_SWB
local F20, F10, F5, F2_5 = 960, 480, 240, 120
local min, max = math.min, math.max
local readu8 = buffer.readu8
local WINDOW = Celt.window
local TRANS = table.create(F5 * 2, 0)
local REDUND = table.create(F5 * 2, 0)
local SILKTMP = table.create(F10 * 2, 0)
local SILENCE = buffer.create(2)
buffer.writeu8(SILENCE, 0, 0xFF)
buffer.writeu8(SILENCE, 1, 0xFF)
local EMPTY_EC = RD.new(buffer.create(0), 0, 0)
local OFFS = table.create(48, 0)
local SIZES = table.create(48, 0)
export type State = {
channels: number,
celt: any,
silk: any,
ctrl: any,
stream_channels: number,
frame_size: number,
mode: number,
bandwidth: number,
prev_mode: number,
prev_redundancy: boolean,
last_packet_duration: number,
rangeFinal: number,
}
function Decoder.new(channels: number): State
return {
channels = channels,
celt = Celt.new(channels),
silk = Silk.new(channels),
ctrl = {
nChannelsAPI = channels,
nChannelsInternal = channels,
API_sampleRate = 48000,
internalSampleRate = 16000,
payloadSize_ms = 20,
},
stream_channels = channels,
frame_size = 120,
mode = 0,
bandwidth = 0,
prev_mode = 0,
prev_redundancy = false,
last_packet_duration = 0,
rangeFinal = 0,
}
end
function Decoder.reset(st: State)
Celt.reset(st.celt)
Silk.reset(st.silk)
st.stream_channels = st.channels
st.frame_size = 120
st.mode = 0
st.bandwidth = 0
st.prev_mode = 0
st.prev_redundancy = false
st.last_packet_duration = 0
st.rangeFinal = 0
end
-- out = w^2 * in2 + (1 - w^2) * in1 over `overlap` samples per channel
local function smoothFade(in1: { number }, b1: number, in2: { number }, b2: number, out: { number }, bo: number, overlap: number, ch: number)
for c = 0, ch - 1 do
for i = 0, overlap - 1 do
local w = WINDOW[i + 1]
w *= w
local k = i * ch + c
out[bo + k] = w * in2[b2 + k] + (1 - w) * in1[b1 + k]
end
end
end
local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number
local ch = st.channels
local celt = st.celt
if frameSize < F2_5 then
return -2
end
frameSize = min(frameSize, 2880)
local data = buf
if len <= 1 then
data = nil
frameSize = min(frameSize, st.frame_size)
end
local audiosize, mode, bandwidth
local dec = EMPTY_EC
if data then
audiosize = st.frame_size
mode = st.mode
bandwidth = st.bandwidth
dec = RD.new(data, off, len)
else
audiosize = frameSize
mode = if st.prev_redundancy then MODE_CELT else st.prev_mode
bandwidth = 0
if mode == 0 then
for i = 0, audiosize * ch - 1 do
pcm[pbase + i] = 0
end
return audiosize
end
if audiosize > F20 then
repeat
local ret = decodeFrame(st, nil, 0, 0, pcm, pbase, min(audiosize, F20))
if ret < 0 then
return ret
end
pbase += ret * ch
audiosize -= ret
until audiosize <= 0
return frameSize
elseif audiosize < F20 then
if audiosize > F10 then
audiosize = F10
elseif mode ~= MODE_SILK and audiosize > F5 and audiosize < F10 then
audiosize = F5
end
end
end
local celtAccum = mode ~= MODE_CELT
local transition = false
if data and st.prev_mode > 0
and ((mode == MODE_CELT and st.prev_mode ~= MODE_CELT and not st.prev_redundancy)
or (mode ~= MODE_CELT and st.prev_mode == MODE_CELT)) then
transition = true
end
if transition and mode == MODE_CELT then
decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize))
end
if audiosize > frameSize then
return -1
end
frameSize = audiosize
-- SILK
if mode ~= MODE_CELT then
local tooSmall = frameSize < F10
local sarr, sbase = pcm, pbase
if tooSmall then
sarr, sbase = SILKTMP, 1
end
if st.prev_mode == MODE_CELT then
Silk.reset(st.silk)
end
local ctrl = st.ctrl
ctrl.payloadSize_ms = max(10, 1000 * audiosize // 48000)
if data then
ctrl.nChannelsInternal = st.stream_channels
if mode == MODE_SILK then
ctrl.internalSampleRate = if bandwidth == BW_NB then 8000 elseif bandwidth == BW_MB then 12000 else 16000
else
ctrl.internalSampleRate = 16000
end
end
local lost = if data == nil then 1 else 0
local decoded = 0
repeat
local ret, n = Silk.decode(st.silk, ctrl, lost, decoded == 0, dec, sarr, sbase + decoded * ch)
if ret ~= 0 or n <= 0 then
if lost ~= 0 or n <= 0 then
n = frameSize - decoded
for i = 0, n * ch - 1 do
sarr[sbase + decoded * ch + i] = 0
end
else
return -3
end
end
decoded += n
until decoded >= frameSize
if tooSmall then
for i = 0, frameSize * ch - 1 do
pcm[pbase + i] = SILKTMP[i + 1]
end
end
end
local startBand = 0
local redundancy, celtToSilk = false, false
local redundancyBytes = 0
if mode ~= MODE_CELT and data and RD.tell(dec) + 17 + (if mode == MODE_HYBRID then 20 else 0) <= 8 * len then
if mode == MODE_HYBRID then
redundancy = RD.bitLogp(dec, 12)
else
redundancy = true
end
if redundancy then
celtToSilk = RD.bitLogp(dec, 1)
redundancyBytes = if mode == MODE_HYBRID then RD.uint(dec, 256) + 2 else len - bit32.rshift(RD.tell(dec) + 7, 3)
len -= redundancyBytes
if len * 8 < RD.tell(dec) then
len = 0
redundancyBytes = 0
redundancy = false
end
dec.storage -= redundancyBytes
end
end
if mode ~= MODE_CELT then
startBand = 17
end
if redundancy then
transition = false
end
if transition and mode ~= MODE_CELT then
decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize))
end
if bandwidth ~= 0 then
celt["end"] = if bandwidth == BW_NB then 13 elseif bandwidth == BW_MB or bandwidth == BW_WB then 17 elseif bandwidth == BW_SWB then 19 else 21
end
celt.stream_channels = st.stream_channels
local redundantRng = 0
if redundancy and celtToSilk then
celt.start = 0
Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false)
redundantRng = celt.rng
end
celt.start = startBand
local celtRet = 0
if mode ~= MODE_SILK then
local celtFrameSize = min(F20, frameSize)
if mode ~= st.prev_mode and st.prev_mode > 0 and not st.prev_redundancy then
Celt.reset(celt)
end
celtRet = Celt.decode(celt, data, off, len, pcm, pbase, celtFrameSize, if data then dec else nil, celtAccum)
st.rangeFinal = celt.rng
else
if st.prev_mode == MODE_HYBRID and not (redundancy and celtToSilk and st.prev_redundancy) then
celt.start = 0
Celt.decode(celt, SILENCE, 0, 2, pcm, pbase, F2_5, nil, celtAccum)
end
st.rangeFinal = if data then dec.rng else 0
end
if redundancy and not celtToSilk then
Celt.reset(celt)
celt.start = 0
Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false)
redundantRng = celt.rng
local b = pbase + ch * (frameSize - F2_5)
smoothFade(pcm, b, REDUND, 1 + ch * F2_5, pcm, b, F2_5, ch)
end
if redundancy and celtToSilk and (st.prev_mode ~= MODE_SILK or st.prev_redundancy) then
for i = 0, F2_5 * ch - 1 do
pcm[pbase + i] = REDUND[1 + i]
end
smoothFade(REDUND, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch)
end
if transition then
if audiosize >= F5 then
for i = 0, ch * F2_5 - 1 do
pcm[pbase + i] = TRANS[1 + i]
end
smoothFade(TRANS, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch)
else
smoothFade(TRANS, 1, pcm, pbase, pcm, pbase, F2_5, ch)
end
end
if len <= 1 then
st.rangeFinal = 0
else
st.rangeFinal = bit32.bxor(st.rangeFinal, redundantRng)
end
st.prev_mode = mode
st.prev_redundancy = redundancy and not celtToSilk
if celtRet < 0 then
return celtRet
end
return audiosize
end
-- opus_decode_native: decodes one packet (buf == nil or len == 0: conceal frameSize samples). pcm[pbase + i * ch + c].
-- Returns the samples per channel (or < 0 on error) and the packet's size (self-delimited packets).
function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, selfDelimited: boolean?): (number, number)
local ch = st.channels
if buf == nil or len == 0 then
if frameSize % 120 ~= 0 then
return -1, 0
end
local count = 0
repeat
local ret = decodeFrame(st, nil, 0, 0, pcm, pbase + count * ch, frameSize - count)
if ret <= 0 then
return if ret < 0 then ret else -3, 0
end
count += ret
until count >= frameSize
st.last_packet_duration = count
return count, 0
end
local b = buf :: buffer
local toc = readu8(b, off)
local packetMode = Packet.mode(toc)
local packetBandwidth = Packet.bandwidth(toc)
local packetFrameSize = Packet.samplesPerFrame(toc, 48000)
local packetChannels = Packet.channels(toc)
local count, _, packetOffset = Packet.parse(b, off, len, OFFS, SIZES, selfDelimited)
if count < 0 then
return -4, 0
end
if count * packetFrameSize > frameSize then
return -2, 0
end
st.mode = packetMode
st.bandwidth = packetBandwidth
st.frame_size = packetFrameSize
st.stream_channels = packetChannels
local nb = 0
for i = 1, count do
local ret = decodeFrame(st, b, OFFS[i], SIZES[i], pcm, pbase + nb * ch, frameSize - nb)
if ret < 0 then
return ret, 0
end
nb += ret
end
st.last_packet_duration = nb
return nb, packetOffset
end
-- ---------------------------------------------------------------------------------------------------------------
-- multistream (channel mapping families 0 / 1 / 255)
export type MS = {
channels: number,
streams: number,
coupled: number,
mapping: { number },
decoders: { State },
tmp: { number },
}
function Decoder.newMultistream(channels: number, streams: number, coupled: number, mapping: { number }): MS
local decs = {}
for s = 0, streams - 1 do
decs[s + 1] = Decoder.new(if s < coupled then 2 else 1)
end
return {
channels = channels,
streams = streams,
coupled = coupled,
mapping = mapping,
decoders = decs,
tmp = table.create(5760 * 2, 0),
}
end
function Decoder.resetMultistream(ms: MS)
for _, d in ms.decoders do
Decoder.reset(d)
end
end
-- copies channel `sc` of src (stride sstride) into every output channel mapped to stream channel index `id`
local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride: number, pcm: { number }, pbase: number, n: number)
local nch = ms.channels
for c = 0, nch - 1 do
if ms.mapping[c + 1] == id then
local o = pbase + c
local s = 1 + sc
for _ = 1, n do
pcm[o] = src[s]
o += nch
s += sstride
end
end
end
end
-- opus_multistream_decode_native (float). Returns the samples per channel, or < 0 on error.
function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number
local doPlc = buf == nil or len == 0
frameSize = min(frameSize, 5760)
if not doPlc and len < 2 * ms.streams - 1 then
return -4
end
local tmp = ms.tmp
for s = 0, ms.streams - 1 do
local d = ms.decoders[s + 1]
if not doPlc and len <= 0 then
return -3
end
local ret, packetOffset = Decoder.decode(d, if doPlc then nil else buf, off, if doPlc then 0 else len, tmp, 1, frameSize, s ~= ms.streams - 1)
if not doPlc then
off += packetOffset
len -= packetOffset
end
if ret <= 0 then
return if ret < 0 then ret else -3
end
frameSize = ret
if s < ms.coupled then
copyOut(ms, s * 2, tmp, 0, 2, pcm, pbase, frameSize)
copyOut(ms, s * 2 + 1, tmp, 1, 2, pcm, pbase, frameSize)
else
copyOut(ms, s + ms.coupled, tmp, 0, 1, pcm, pbase, frameSize)
end
end
local nch = ms.channels
for c = 0, nch - 1 do
if ms.mapping[c + 1] == 255 then
local o = pbase + c
for _ = 1, frameSize do
pcm[o] = 0
o += nch
end
end
end
return frameSize
end
-- writes src[base + 1 .. base + count] * gain to out as f32 from byte offset o
function Decoder.writeF32(src: { number }, base: number, count: number, gain: number, out: buffer, o: number)
local writef32 = buffer.writef32
if gain == 1 then
for i = base + 1, base + count do
writef32(out, o, src[i])
o += 4
end
else
for i = base + 1, base + count do
writef32(out, o, src[i] * gain)
o += 4
end
end
end
-- Stereo downmix of n frames of srcCh-channel audio (src[base + 1 ..], interleaved): matrix[c * 2 + 1 / + 2] are the
-- left / right weights of channel c. Writes f32 to out from byte offset o.
function Decoder.writeDownmix(src: { number }, base: number, n: number, srcCh: number, matrix: { number }, gain: number, out: buffer, o: number)
local writef32 = buffer.writef32
local p = base
for _ = 1, n do
local l, r = 0, 0
for c = 0, srcCh - 1 do
local v = src[p + c + 1]
l += v * matrix[c * 2 + 1]
r += v * matrix[c * 2 + 2]
end
writef32(out, o, l * gain)
writef32(out, o + 4, r * gain)
o += 8
p += srcCh
end
end
return Decoder