ws-audio2: merge ws/audio2-adpcm (codecs/audio/Adpcm, Qoa; adx, vag, brstm/bcstm/bfstm, raw adpcm, qoa; wav/aiff/caf/xm ADPCM)
This commit is contained in:
commit
703af4cc71
43 files changed
+5121
-197
No files matched your search
@@ -170,13 +170,37 @@ local list: { Entry } = {
|
||||
return require("@formats/audio/ac3")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "adpcm",
|
||||
category = "audio",
|
||||
path = "audio/adpcm",
|
||||
extensions = { "adpcm", "ima" },
|
||||
mime = { "audio/x-adpcm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } },
|
||||
load = function()
|
||||
return require("@formats/audio/adpcm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "adx",
|
||||
category = "audio",
|
||||
path = "audio/adx",
|
||||
extensions = { "adx" },
|
||||
mime = { "audio/x-adx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 },
|
||||
load = function()
|
||||
return require("@formats/audio/adx")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "aiff",
|
||||
category = "audio",
|
||||
path = "audio/aiff",
|
||||
extensions = { "aiff", "aif", "aifc", "afc" },
|
||||
mime = { "audio/aiff", "audio/x-aiff" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
|
||||
load = function()
|
||||
return require("@formats/audio/aiff")
|
||||
@@ -194,13 +218,25 @@ local list: { Entry } = {
|
||||
return require("@formats/audio/au")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "brstm",
|
||||
category = "audio",
|
||||
path = "audio/brstm",
|
||||
extensions = { "brstm", "bcstm", "bfstm" },
|
||||
mime = { "audio/x-brstm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } },
|
||||
load = function()
|
||||
return require("@formats/audio/brstm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "caf",
|
||||
category = "audio",
|
||||
path = "audio/caf",
|
||||
extensions = { "caf", "caff" },
|
||||
mime = { "audio/x-caf" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "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 },
|
||||
load = function()
|
||||
return require("@formats/audio/caf")
|
||||
@@ -266,6 +302,30 @@ 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",
|
||||
path = "audio/vag",
|
||||
extensions = { "vag" },
|
||||
mime = { "audio/x-vag" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 },
|
||||
load = function()
|
||||
return require("@formats/audio/vag")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "voc",
|
||||
category = "audio",
|
||||
@@ -296,7 +356,7 @@ local list: { Entry } = {
|
||||
path = "audio/wav",
|
||||
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/audio/Pcm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
|
||||
load = function()
|
||||
return require("@formats/audio/wav")
|
||||
@@ -968,7 +1028,7 @@ local list: { Entry } = {
|
||||
path = "music/xm",
|
||||
extensions = { "xm" },
|
||||
mime = { "audio/xm", "audio/x-xm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" },
|
||||
caps = { decode = true, encode = true, render = true, channels = { 1, 64 } },
|
||||
load = function()
|
||||
return require("@formats/music/xm")
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
--!strict
|
||||
-- audio/adpcm: headerless ADPCM streams (.adpcm / .ima / .vox-style dumps), over codecs/audio/Adpcm. New in
|
||||
-- formats-luau. A raw stream has no header, so nothing identifies it: sniff is always 0, F.detect only finds it by
|
||||
-- extension, and the layout comes from the options (codec, sampleRate, channels, blockAlign). vgmstream plays such
|
||||
-- files only through a .txth description and ffmpeg not at all (its adpcm_* codecs need a container), so the codecs
|
||||
-- here are the layouts those containers use:
|
||||
-- "ima" IMA nibbles from predictor 0 / step index 0, channels interleaved by nibble, the high nibble first
|
||||
-- (DVI order, as KVAG / adpcm_ima_ssi); lowFirst = true for the other order
|
||||
-- "ima_wav" Microsoft IMA blocks (the WAV / AVI data chunk), blockAlign bytes each (default 1024)
|
||||
-- "ms" Microsoft ADPCM blocks with the 7 standard coefficient pairs (default blockAlign 1024)
|
||||
-- "ima_qt" Apple ima4 packets (34 bytes per channel, 64 frames), as in AIFF-C / CAF / QuickTime
|
||||
-- "psx" Sony PS-ADPCM frames (16 bytes, 28 samples), channels interleaved every `interleave` bytes (default 16)
|
||||
-- Encode: "ima", "ima_wav" and "ms" (from an Audio or a Decoder). Not supported: raw DSP / ADX (their coefficients
|
||||
-- live in a header: see audio/brstm and audio/adx).
|
||||
--
|
||||
-- local a = Adpcm.decode(Bytes.reader(buf), { codec = "ms", sampleRate = 22050, channels = 2, blockAlign = 512 })
|
||||
-- local raw = Adpcm.encode(a, { codec = "ima" })
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
local Decoder = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Raw = {
|
||||
name = "adpcm",
|
||||
category = "audio",
|
||||
extensions = { "adpcm", "ima" },
|
||||
mime = { "audio/x-adpcm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type Codec = "ima" | "ima_wav" | "ms" | "ima_qt" | "psx"
|
||||
export type Options = {
|
||||
codec: Codec?, -- default "ima"
|
||||
sampleRate: number?, -- default 22050 (decode)
|
||||
channels: number?, -- default 1 (decode)
|
||||
blockAlign: number?, -- ima_wav / ms: bytes per block (default 1024 when decoding; 256 * channels when encoding)
|
||||
lowFirst: boolean?, -- ima: the low nibble first
|
||||
interleave: number?, -- psx: bytes per channel before the next channel (default 16)
|
||||
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = true }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Raw.sniff(_r: Bytes.Reader): number
|
||||
return 0 -- no header: found by extension or opts.format only
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Raw.decode(r: Bytes.Reader, opts: Options?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Raw.open(r, opts)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local limit = opts and opts.maxFrames or 2 ^ 28
|
||||
if dec.frames > limit or dec.frames * dec.channels > 2 ^ 28 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", dec.frames))
|
||||
end
|
||||
return Pcm.drain(dec, { format = "adpcm", codec = (dec :: any).codec }, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Raw.encode(value: any, opts: Options?): (buffer?, Err.Err?)
|
||||
local o: Options = opts or {}
|
||||
local codec = o.codec or "ima"
|
||||
if codec ~= "ima" and codec ~= "ima_wav" and codec ~= "ms" then
|
||||
return nil, Err.new(Err.ARG, "encode: codec must be ima, ima_wav or ms")
|
||||
end
|
||||
local src, serr = Pcm.source(value)
|
||||
if not src then
|
||||
return nil, serr
|
||||
end
|
||||
local a, cerr = Pcm.collect(src)
|
||||
if not a then
|
||||
return nil, cerr
|
||||
end
|
||||
local ch, n, x = a.channels, a.frames, a.samples
|
||||
if codec == "ima" then
|
||||
local out = buffer.create((n * ch + 1) // 2)
|
||||
local st = buffer.create(8 * ch)
|
||||
for c = 0, ch - 1 do
|
||||
Adpcm.imaEncode(x, c, ch, n, st, c * 8, out, 0, c, ch, not o.lowFirst)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local ba = o.blockAlign or 256 * ch
|
||||
local spb = Decoder.blockFrames(codec, ba, ch)
|
||||
if type(ba) ~= "number" or ba ~= math.floor(ba) or ba > 65535 or not spb or spb < 2 then
|
||||
return nil, Err.new(Err.ARG, "bad blockAlign " .. tostring(ba))
|
||||
end
|
||||
if codec == "ima_wav" and (ba % (4 * ch) ~= 0) then
|
||||
return nil, Err.new(Err.ARG, "ima_wav: blockAlign must be a multiple of 4 * channels")
|
||||
end
|
||||
local blocks = (n + spb - 1) // spb
|
||||
local out = buffer.create(blocks * ba)
|
||||
local st = buffer.create(8 * ch)
|
||||
for b = 0, blocks - 1 do
|
||||
local f0 = b * spb
|
||||
if codec == "ms" then
|
||||
Adpcm.msEncode(x, f0, n - f0, ch, spb, out, b * ba)
|
||||
else
|
||||
Adpcm.imaWavEncode(x, f0, n - f0, ch, spb, st, out, b * ba)
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
function Raw.open(r: Bytes.Reader, opts: Options?): (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 o: Options = opts or {}
|
||||
local codec = o.codec or "ima"
|
||||
local rate, ch = o.sampleRate or 22050, o.channels or 1
|
||||
if not CODECS[codec] then
|
||||
return nil, Err.new(Err.ARG, "unknown codec " .. tostring(codec))
|
||||
end
|
||||
if type(rate) ~= "number" or rate <= 0 or rate ~= rate or type(ch) ~= "number" or ch < 1 or ch > 255 or ch ~= math.floor(ch) then
|
||||
return nil, Err.new(Err.ARG, "bad sampleRate or channels")
|
||||
end
|
||||
local size = r.limit - r.base
|
||||
local dec: any = { sampleRate = rate, channels = ch, tags = {}, codec = codec, frames = 0, duration = 0 }
|
||||
local d, err
|
||||
if codec == "ima" then
|
||||
d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base, size = size, hi = not o.lowFirst })
|
||||
elseif codec == "psx" then
|
||||
local il = o.interleave or 16
|
||||
if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "interleave must be a multiple of 16")
|
||||
end
|
||||
d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = r.base, size = size, interleave = if ch == 1 then 16 else il })
|
||||
else
|
||||
local ba = o.blockAlign or 1024
|
||||
if type(ba) ~= "number" or ba < 1 or ba ~= math.floor(ba) then
|
||||
return nil, Err.new(Err.ARG, "bad blockAlign")
|
||||
end
|
||||
d, err = Decoder.blocks(dec, { kind = codec :: any, buf = r.buf, offset = r.base, size = size, blockAlign = ba })
|
||||
end
|
||||
if not d then
|
||||
return nil, err
|
||||
end
|
||||
d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0
|
||||
return d, nil
|
||||
end
|
||||
|
||||
return Raw
|
||||
@@ -0,0 +1,237 @@
|
||||
--!strict
|
||||
-- audio/adx: CRI ADX (.adx), the game-audio ADPCM of Sega / CRI Middleware, over codecs/audio/Adpcm. New in
|
||||
-- formats-luau; the header layout and the decoder details follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt),
|
||||
-- whose output it matches bit for bit (the scale + 1 of CRI's decoders, the version 3 rounding; ffmpeg's ADX decoder
|
||||
-- differs slightly on both). Supports: encoding type 3 (the standard predictor from the header's high-pass cutoff),
|
||||
-- versions 3, 4 and 5, 1-8 channels, the initial history of version 4, loop points (dec.loop and
|
||||
-- meta.source.loop = { start, stop } in frames, stop exclusive). Encode (Audio or Decoder): version 4, 1-8 channels,
|
||||
-- loop points from opts.loop. Not supported: encrypted ADX (versions 0x0408 / 0x0409, keys needed), the fixed (2) and
|
||||
-- exponential (4) encoding types, AHX.
|
||||
--
|
||||
-- local dec = Adx.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, version, cutoff)
|
||||
-- local file = Adx.encode(audio, { loop = { start = 44100, stop = 441000 } })
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
local Decoder = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Adx = {
|
||||
name = "adx",
|
||||
category = "audio",
|
||||
extensions = { "adx" },
|
||||
mime = { "audio/x-adx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type Loop = { start: number, stop: number }
|
||||
export type DecodeOptions = {
|
||||
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
loop: Loop?, -- loop points in frames (stop exclusive); default: the source's meta.source.loop / loop, else none
|
||||
cutoff: number?, -- the predictor's high-pass cutoff in Hz (default 500, as CRI's encoders)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local FRAME = 18
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Adx.sniff(r: Bytes.Reader): number
|
||||
if r:peekU8(0) ~= 0x80 or r:peekU8(1) ~= 0 then
|
||||
return 0
|
||||
end
|
||||
local off = r:peekU8(2) * 256 + r:peekU8(3)
|
||||
return if r:peek(6, off - 2) == "(c)CRI" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Adx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Adx.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 = "adx", version = d.version, cutoff = d.cutoff, loop = d.loop }, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Adx.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
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, "ADX holds at most 8 channels")
|
||||
end
|
||||
if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 31 then
|
||||
return nil, Err.new(Err.ARG, "the sample rate must be a positive integer")
|
||||
end
|
||||
local loop = o.loop
|
||||
if loop == nil then
|
||||
local v = value :: any
|
||||
local m = type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.loop
|
||||
loop = if type(m) == "table" then m else (if type(v.loop) == "table" then v.loop else nil)
|
||||
end
|
||||
local a, cerr = Pcm.collect(src)
|
||||
if not a then
|
||||
return nil, cerr
|
||||
end
|
||||
local n = a.frames
|
||||
if loop and (type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop <= loop.start or loop.stop > n) then
|
||||
return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio")
|
||||
end
|
||||
local cutoff = o.cutoff or 500
|
||||
if type(cutoff) ~= "number" or cutoff < 1 or cutoff >= rate / 2 or cutoff > 65535 then
|
||||
return nil, Err.new(Err.ARG, "bad cutoff")
|
||||
end
|
||||
cutoff = math.floor(cutoff)
|
||||
local c1, c2 = Adpcm.adxCoefs(cutoff, rate)
|
||||
local hist = if ch > 1 then 4 * ch else 8
|
||||
local start = 0x18 + hist + (if loop then 0x18 else 0) + 6
|
||||
start = (start + 3) // 4 * 4
|
||||
local nframes = (n + 31) // 32
|
||||
local w = Bytes.writer(start + (nframes + 1) * FRAME * ch)
|
||||
w:u16be(0x8000)
|
||||
w:u16be(start - 4)
|
||||
w:u8(3)
|
||||
w:u8(FRAME)
|
||||
w:u8(4)
|
||||
w:u8(ch)
|
||||
w:u32be(rate)
|
||||
w:u32be(n)
|
||||
w:u16be(cutoff)
|
||||
w:u16be(0x0400)
|
||||
w:u32be(0)
|
||||
w:fill(0, hist)
|
||||
if loop then
|
||||
local bytesAt = function(f: number): number
|
||||
return start + (f // 32) * FRAME * ch
|
||||
end
|
||||
w:u16be(0)
|
||||
w:u16be(1)
|
||||
w:u32be(1)
|
||||
w:u32be(loop.start)
|
||||
w:u32be(bytesAt(loop.start))
|
||||
w:u32be(loop.stop)
|
||||
w:u32be(bytesAt(loop.stop + 31))
|
||||
end
|
||||
w:fill(0, start - 6 - w.pos)
|
||||
w:string("(c)CRI")
|
||||
local at = w:reserve(nframes * FRAME * ch)
|
||||
local st = buffer.create(8 * ch)
|
||||
for c = 0, ch - 1 do
|
||||
Adpcm.adxEncode(a.samples, c, ch, n, c1, c2, st, c * 8, w.buf, at + c * FRAME, FRAME * ch)
|
||||
end
|
||||
w.pos = at + nframes * FRAME * ch
|
||||
-- the end marker: scale 0x8001, then the padding size
|
||||
w:u16be(0x8001)
|
||||
w:u16be(FRAME - 4)
|
||||
w:fill(0, FRAME - 4)
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
function Adx.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
|
||||
if Adx.sniff(r) == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "not an ADX file")
|
||||
end
|
||||
local h = r:sub(0)
|
||||
local copyright = (h:seek(2) and h:u16be()) or 0
|
||||
local start = copyright + 4
|
||||
local enc, fsize, bits, ch = h:u8(), h:u8(), h:u8(), h:u8()
|
||||
local rate, frames, cutoff, version = h:u32be(), h:u32be(), h:u16be(), h:u16be()
|
||||
if h.err then
|
||||
return nil, h.err
|
||||
end
|
||||
if version == 0x0408 or version == 0x0409 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "encrypted ADX (keys needed)")
|
||||
end
|
||||
if enc ~= 3 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "encoding type " .. enc .. (if enc == 0x10 or enc == 0x11 then " (AHX)" else ""))
|
||||
end
|
||||
if fsize ~= FRAME or bits ~= 4 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("frame size %d, %d bits", fsize, bits))
|
||||
end
|
||||
if ch < 1 or ch > 8 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch)
|
||||
end
|
||||
if rate < 1 or rate >= 2 ^ 31 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate)
|
||||
end
|
||||
if version ~= 0x0300 and version ~= 0x0400 and version ~= 0x0500 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%04X", version))
|
||||
end
|
||||
local size = r.limit - r.base - start
|
||||
if size < 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "the header runs past the end")
|
||||
end
|
||||
-- loop points and the initial history (vgmstream's reading of the extra header fields)
|
||||
local hist: { number }? = nil
|
||||
local loopsAt: number? = nil
|
||||
if version == 0x0300 then
|
||||
if start - 6 >= 0x14 + 0x18 then
|
||||
loopsAt = 0x14
|
||||
end
|
||||
elseif version == 0x0400 then
|
||||
local hsize = if ch > 1 then 4 * ch else 8
|
||||
hist = {}
|
||||
for c = 0, ch - 1 do
|
||||
local hh = r:sub(0x18 + c * 4, 4)
|
||||
local h1, h2 = hh:i16be(), hh:i16be()
|
||||
hist[c * 2 + 1], hist[c * 2 + 2] = if hh.err then 0 else h1, if hh.err then 0 else h2
|
||||
end
|
||||
local ainf = 0
|
||||
local ai = r:sub(0x18 + hsize + 4, 8)
|
||||
if ai:string(4) == "AINF" then
|
||||
ainf = ai:u32be()
|
||||
end
|
||||
if start - ainf - 6 >= 0x18 + hsize + 0x18 then
|
||||
loopsAt = 0x18 + hsize
|
||||
end
|
||||
end
|
||||
local loopTable: { start: number, stop: number }? = nil
|
||||
if loopsAt then
|
||||
local l = r:sub(loopsAt + 4, 0x14)
|
||||
local flag, ls, _, le = l:u32be(), l:u32be(), l:u32be(), l:u32be()
|
||||
if not l.err and flag ~= 0 and le > ls then
|
||||
loopTable = { start = ls, stop = le }
|
||||
end
|
||||
end
|
||||
local c1, c2 = Adpcm.adxCoefs(cutoff, rate)
|
||||
local dec: any = { sampleRate = rate, channels = ch, tags = {}, version = version, cutoff = cutoff, loop = loopTable }
|
||||
local d, err = Decoder.interleaved(dec, {
|
||||
kind = "adx",
|
||||
buf = r.buf,
|
||||
offset = r.base + start,
|
||||
size = size,
|
||||
interleave = FRAME,
|
||||
frames = frames,
|
||||
c1 = c1,
|
||||
c2 = c2,
|
||||
v3 = version == 0x0300,
|
||||
hist = hist,
|
||||
})
|
||||
if not d then
|
||||
return nil, err
|
||||
end
|
||||
d.bitrate = rate * FRAME * ch * 8 // 32
|
||||
return d, nil
|
||||
end
|
||||
|
||||
return Adx
|
||||
@@ -3,8 +3,9 @@
|
||||
-- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw
|
||||
-- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated
|
||||
-- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 /
|
||||
-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. Not supported: compressed AIFF-C codecs (ima4, MAC3 /
|
||||
-- MAC6, Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk.
|
||||
-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. AIFF-C ima4 (Apple IMA ADPCM, codecs/audio/Adpcm;
|
||||
-- COMM counts packets of 64 frames) decodes too. Not supported: the other compressed AIFF-C codecs (MAC3 / MAC6,
|
||||
-- Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
@@ -12,6 +13,7 @@ local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Chunks = require("@formats/containers/Chunks")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Aiff = {
|
||||
@@ -19,7 +21,7 @@ local Aiff = {
|
||||
category = "audio",
|
||||
extensions = { "aiff", "aif", "aifc", "afc" },
|
||||
mime = { "audio/aiff", "audio/x-aiff" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
|
||||
}
|
||||
|
||||
@@ -115,6 +117,8 @@ local function sampleFormat(comp: string, bits: number): (string?, string?)
|
||||
return "ulaw", nil
|
||||
elseif comp == "alaw" or comp == "ALAW" then
|
||||
return "alaw", nil
|
||||
elseif comp == "ima4" then
|
||||
return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks
|
||||
end
|
||||
return nil, "compression " .. string.format("%q", comp)
|
||||
end
|
||||
@@ -138,6 +142,7 @@ type Info = {
|
||||
compression: string,
|
||||
aifc: boolean,
|
||||
dataOffset: number, -- absolute in r.buf
|
||||
dataSize: number, -- bytes of sample data present
|
||||
truncated: boolean,
|
||||
tags: Types.Tags,
|
||||
}
|
||||
@@ -194,6 +199,7 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
compression = comp,
|
||||
aifc = aifc,
|
||||
dataOffset = 0,
|
||||
dataSize = 0,
|
||||
truncated = false,
|
||||
tags = tags,
|
||||
}
|
||||
@@ -228,13 +234,19 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
if fi.frames > 0 and not ssnd then
|
||||
return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base)
|
||||
end
|
||||
local frameBytes = fi.channels * Pcm.Convert.SIZE[fi.format]
|
||||
local present = if ssnd then ssndLen // frameBytes else 0
|
||||
local present
|
||||
if fi.format == "ima4" then
|
||||
fi.frames *= 64 -- COMM counts packets
|
||||
present = if ssnd then ssndLen // (34 * fi.channels) * 64 else 0
|
||||
else
|
||||
present = if ssnd then ssndLen // (fi.channels * Pcm.Convert.SIZE[fi.format]) else 0
|
||||
end
|
||||
if present < fi.frames then
|
||||
fi.frames = present
|
||||
fi.truncated = true
|
||||
end
|
||||
fi.dataOffset = ssnd or base
|
||||
fi.dataSize = ssndLen
|
||||
return fi, nil
|
||||
end
|
||||
|
||||
@@ -360,7 +372,16 @@ function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.
|
||||
if info.frames > maxFrames then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames))
|
||||
end
|
||||
local dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags)
|
||||
local dec, derr
|
||||
if info.format == "ima4" then
|
||||
local base = { sampleRate = info.sampleRate, channels = info.channels, tags = info.tags }
|
||||
dec, derr = Adpcm.blocks(base, { kind = "ima_qt", buf = r.buf, offset = info.dataOffset, size = info.dataSize, frames = info.frames })
|
||||
if dec then
|
||||
(dec :: any).bitrate = math.floor(info.sampleRate * 34 * 8 * info.channels / 64)
|
||||
end
|
||||
else
|
||||
dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags)
|
||||
end
|
||||
if not dec then
|
||||
return nil, derr
|
||||
end
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
--!strict
|
||||
-- audio/brstm: Nintendo's streamed audio: BRSTM (Wii, "RSTM", big-endian), BCSTM (3DS, "CSTM", little-endian) and
|
||||
-- BFSTM (Wii U big-endian / Switch little-endian, "FSTM"), over codecs/audio/Adpcm. New in formats-luau; the layouts
|
||||
-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: DSP
|
||||
-- ADPCM (with the header's initial history; seeks into blocks not yet played use the ADPC / SEEK history table), PCM16
|
||||
-- and PCM8, 1-255 channels in block-interleaved layout, the loop start (dec.loop and meta.source.loop = { start, stop }
|
||||
-- in frames, stop exclusive). Read only. Not supported: BCSTM IMA ADPCM, BRSTM version 0.1 (beta), BFSTM regions
|
||||
-- (the whole stream plays), the track table (channels are not grouped).
|
||||
--
|
||||
-- local dec = Brstm.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, container, codec)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 Decoder = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Brstm = {
|
||||
name = "brstm",
|
||||
category = "audio",
|
||||
extensions = { "brstm", "bcstm", "bfstm" },
|
||||
mime = { "audio/x-brstm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local CODECS = { [0] = "pcm8", [1] = "pcm16", [2] = "dsp", [3] = "ima" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Brstm.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
if m ~= "RSTM" and m ~= "CSTM" and m ~= "FSTM" then
|
||||
return 0
|
||||
end
|
||||
local bom = r:peek(2, 4)
|
||||
return if bom == "\254\255" or bom == "\255\254" then 1 else 0
|
||||
end
|
||||
|
||||
-- variant(r) -> "brstm" / "bcstm" / "bfstm": the flavour, for F.detect
|
||||
function Brstm.variant(r: Bytes.Reader): string?
|
||||
local m = r:peek(4)
|
||||
return if m == "RSTM" then "brstm" elseif m == "CSTM" then "bcstm" elseif m == "FSTM" then "bfstm" else nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Brstm.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 = "brstm", container = d.container, codec = d.codec, loop = d.loop }, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- a reader of the whole file in its byte order: u8 / u16 / u32 / i16 / i32 at absolute offsets (relative to the file
|
||||
-- start); a read out of range records the error in .err and returns 0
|
||||
local function view(r: Bytes.Reader, be: boolean)
|
||||
local v = { err = nil :: string? }
|
||||
local size = r.limit - r.base
|
||||
local function at(o: number, n: number): Bytes.Reader?
|
||||
if o < 0 or o + n > size then
|
||||
v.err = "an offset points past the end"
|
||||
return nil
|
||||
end
|
||||
return r:sub(o, n)
|
||||
end
|
||||
function v.u8(o: number): number
|
||||
local s = at(o, 1)
|
||||
return if s then s:u8() else 0
|
||||
end
|
||||
function v.u16(o: number): number
|
||||
local s = at(o, 2)
|
||||
return if s then (if be then s:u16be() else s:u16le()) else 0
|
||||
end
|
||||
function v.i16(o: number): number
|
||||
local s = at(o, 2)
|
||||
return if s then (if be then s:i16be() else s:i16le()) else 0
|
||||
end
|
||||
function v.u32(o: number): number
|
||||
local s = at(o, 4)
|
||||
return if s then (if be then s:u32be() else s:u32le()) else 0
|
||||
end
|
||||
function v.i32(o: number): number
|
||||
local s = at(o, 4)
|
||||
return if s then (if be then s:i32be() else s:i32le()) else 0
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
type Layout = {
|
||||
codec: number,
|
||||
loop: boolean,
|
||||
ch: number,
|
||||
rate: number,
|
||||
loopStart: number,
|
||||
frames: number,
|
||||
blockSize: number,
|
||||
lastPadded: number,
|
||||
data: number, -- the first block (absolute in the file)
|
||||
adp: { number }, -- each channel's DSP info offset (coefficients, then gain, ps, yn1, yn2)
|
||||
hist: number?, -- the per-block history table: (yn1, yn2) per channel per block
|
||||
histEntries: number,
|
||||
}
|
||||
|
||||
local function parseRstm(v: any): (Layout?, string?)
|
||||
if v.u16(0x06) ~= 0x0100 then
|
||||
return nil, string.format("unsupported: BRSTM version %d.%d", v.u8(0x06), v.u8(0x07))
|
||||
end
|
||||
local head = v.u32(0x10)
|
||||
local adpc = v.u32(0x18)
|
||||
if v.u32(head) ~= 0x48454144 then -- "HEAD", read big-endian
|
||||
return nil, "no HEAD chunk"
|
||||
end
|
||||
local base = head + 8
|
||||
local info = base + v.u32(base + 4)
|
||||
local chans = base + v.u32(base + 20)
|
||||
local ch = v.u8(info + 2)
|
||||
local L: Layout = {
|
||||
codec = v.u8(info),
|
||||
loop = v.u8(info + 1) ~= 0,
|
||||
ch = ch,
|
||||
rate = v.u16(info + 4),
|
||||
loopStart = v.u32(info + 8),
|
||||
frames = v.u32(info + 12),
|
||||
data = v.u32(info + 16),
|
||||
blockSize = v.u32(info + 24),
|
||||
lastPadded = v.u32(info + 40),
|
||||
adp = {},
|
||||
hist = nil,
|
||||
histEntries = 0,
|
||||
}
|
||||
for c = 0, ch - 1 do
|
||||
local ci = base + v.u32(chans + 4 + c * 8 + 4)
|
||||
L.adp[c + 1] = base + v.u32(ci + 4)
|
||||
end
|
||||
if adpc > 0 and v.u32(adpc) == 0x41445043 then -- "ADPC"
|
||||
L.hist = adpc + 8
|
||||
L.histEntries = (v.u32(adpc + 4) - 8) // math.max(1, 4 * ch)
|
||||
end
|
||||
return L, nil
|
||||
end
|
||||
|
||||
local function parseFstm(v: any): (Layout?, string?)
|
||||
local info: number, seek: number, data: number = 0, 0, 0
|
||||
local seekSize: number = 0
|
||||
for i = 0, math.min(v.u16(0x10), 16) - 1 do
|
||||
local id, off = v.u16(0x14 + i * 12), v.u32(0x14 + i * 12 + 4)
|
||||
if id == 0x4000 then
|
||||
info = off
|
||||
elseif id == 0x4001 then
|
||||
seek = off
|
||||
seekSize = v.u32(0x14 + i * 12 + 8) :: number
|
||||
elseif id == 0x4002 then
|
||||
data = off
|
||||
end
|
||||
end
|
||||
if info == 0 or data == 0 then
|
||||
return nil, "no INFO or DATA block"
|
||||
end
|
||||
local stream = info + 8 + v.i32(info + 0x0C)
|
||||
local chans = info + 8 + v.i32(info + 0x1C)
|
||||
local ch = v.u8(stream + 2)
|
||||
local dataRef = stream + 0x30
|
||||
local L: Layout = {
|
||||
codec = v.u8(stream),
|
||||
loop = v.u8(stream + 1) ~= 0,
|
||||
ch = ch,
|
||||
rate = v.u32(stream + 4),
|
||||
loopStart = v.u32(stream + 8),
|
||||
frames = v.u32(stream + 12),
|
||||
blockSize = v.u32(stream + 20),
|
||||
lastPadded = v.u32(stream + 36),
|
||||
data = if v.u16(dataRef) == 0x1F00 then data + 8 + v.i32(dataRef + 4) else data + 0x20,
|
||||
adp = {},
|
||||
hist = nil,
|
||||
histEntries = 0,
|
||||
}
|
||||
for c = 0, ch - 1 do
|
||||
local ci = chans + v.i32(chans + 4 + c * 8 + 4)
|
||||
L.adp[c + 1] = ci + v.i32(ci + 4)
|
||||
end
|
||||
if seek > 0 and seekSize > 8 then
|
||||
L.hist = seek + 8
|
||||
L.histEntries = (seekSize - 8) // math.max(1, 4 * ch)
|
||||
end
|
||||
return L, nil
|
||||
end
|
||||
|
||||
function Brstm.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
|
||||
if r.limit - r.base < 0x40 then
|
||||
return nil, Err.new(Err.TRUNCATED, "the header runs past the end")
|
||||
end
|
||||
if Brstm.sniff(r) == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "not a BRSTM / BCSTM / BFSTM file")
|
||||
end
|
||||
local magic = r:peek(4)
|
||||
local be = r:peek(2, 4) == "\254\255"
|
||||
local v = view(r, be)
|
||||
local parsed: Layout?, msg: string?
|
||||
if magic == "RSTM" then
|
||||
if not be then
|
||||
return nil, Err.new(Err.CORRUPT, "a little-endian BRSTM")
|
||||
end
|
||||
parsed, msg = parseRstm(v)
|
||||
else
|
||||
parsed, msg = parseFstm(v)
|
||||
end
|
||||
if v.err then
|
||||
return nil, Err.new(Err.TRUNCATED, v.err)
|
||||
elseif not parsed then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
local L = parsed :: Layout
|
||||
local codec = CODECS[L.codec]
|
||||
if not codec then
|
||||
return nil, Err.new(Err.CORRUPT, "codec " .. L.codec)
|
||||
elseif codec == "ima" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM streams")
|
||||
end
|
||||
local ch = L.ch
|
||||
if ch < 1 or L.rate < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad channel count or sample rate")
|
||||
end
|
||||
local size = r.limit - r.base - L.data
|
||||
if L.data < 0 or size < 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "the data starts past the end")
|
||||
end
|
||||
local kind = if codec == "dsp" then "dsp" elseif codec == "pcm8" then "s8" elseif be then "s16be" else "s16le"
|
||||
local coefs: buffer? = nil
|
||||
local hist: { number }? = nil
|
||||
if codec == "dsp" then
|
||||
coefs = buffer.create(64 * ch)
|
||||
hist = {}
|
||||
for c = 0, ch - 1 do
|
||||
local adp = L.adp[c + 1]
|
||||
for k = 0, 15 do
|
||||
buffer.writei32(coefs :: buffer, c * 64 + k * 4, v.i16(adp + k * 2))
|
||||
end
|
||||
hist[c * 2 + 1], hist[c * 2 + 2] = v.i16(adp + 36), v.i16(adp + 38)
|
||||
end
|
||||
if v.err then
|
||||
return nil, Err.new(Err.TRUNCATED, v.err)
|
||||
end
|
||||
end
|
||||
local histAt, entries = L.hist, L.histEntries
|
||||
local loop = if L.loop and L.loopStart < L.frames then { start = L.loopStart, stop = L.frames } else nil
|
||||
local dec: any = { sampleRate = L.rate, channels = ch, tags = {}, container = magic, codec = codec, loop = loop }
|
||||
local block = L.blockSize
|
||||
if block < 1 or (kind == "dsp" and block % 8 ~= 0) or (kind ~= "s8" and block % 2 ~= 0) then
|
||||
return nil, Err.new(Err.CORRUPT, "bad block size " .. block)
|
||||
end
|
||||
local d, err = Decoder.interleaved(dec, {
|
||||
kind = kind :: any,
|
||||
buf = r.buf,
|
||||
offset = r.base + L.data,
|
||||
size = size,
|
||||
interleave = block,
|
||||
lastInterleave = if L.lastPadded > 0 and L.lastPadded <= block then L.lastPadded else block,
|
||||
frames = L.frames,
|
||||
coefs = coefs,
|
||||
hist = hist,
|
||||
restore = if codec == "dsp" and histAt
|
||||
then function(row: number, st: buffer): boolean
|
||||
if row >= entries then
|
||||
return false
|
||||
end
|
||||
for c = 0, ch - 1 do
|
||||
local p = (histAt :: number) + (row * ch + c) * 4
|
||||
buffer.writei32(st, c * 8, v.i16(p))
|
||||
buffer.writei32(st, c * 8 + 4, v.i16(p + 2))
|
||||
end
|
||||
return v.err == nil
|
||||
end
|
||||
else nil,
|
||||
})
|
||||
if d then
|
||||
d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0
|
||||
end
|
||||
return d, err
|
||||
end
|
||||
|
||||
return Brstm
|
||||
@@ -3,7 +3,8 @@
|
||||
-- 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).
|
||||
-- 24-bit) with info tags. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported:
|
||||
-- other compressed formats (UNSUPPORTED).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
@@ -14,6 +15,7 @@ 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")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Caf = {
|
||||
@@ -21,7 +23,7 @@ local Caf = {
|
||||
category = "audio",
|
||||
extensions = { "caf", "caff" },
|
||||
mime = { "audio/x-caf" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "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 },
|
||||
}
|
||||
|
||||
@@ -333,7 +335,7 @@ local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?)
|
||||
end
|
||||
-- packetised codecs
|
||||
local sizes = p.packets
|
||||
if not sizes then
|
||||
if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none
|
||||
if d.bytesPerPacket > 0 then
|
||||
local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket
|
||||
sizes = table.create(n, d.bytesPerPacket)
|
||||
@@ -425,7 +427,23 @@ function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
|
||||
if not p then
|
||||
return nil, err
|
||||
end
|
||||
local s, serr = source(r, p :: Parsed)
|
||||
local pp = p :: Parsed
|
||||
if pp.desc.format == "ima4" then
|
||||
-- Apple IMA ADPCM: 34-byte packets per channel, 64 frames; the predictor carries across packets
|
||||
local ch = pp.desc.channels
|
||||
local packets = (pp.dataEnd - pp.dataStart) // (34 * ch)
|
||||
local frames = packets * 64
|
||||
if pp.validFrames and pp.validFrames >= 0 then
|
||||
frames = math.min(frames, pp.validFrames)
|
||||
end
|
||||
local dec: any = { sampleRate = pp.desc.rate, channels = ch, tags = pp.tags, codec = "ima4", bitsPerSample = 16 }
|
||||
local d, derr = Adpcm.blocks(dec, { kind = "ima_qt", buf = r.buf, offset = pp.dataStart, size = pp.dataEnd - pp.dataStart, frames = frames })
|
||||
if d then
|
||||
d.bitrate = math.floor(pp.desc.rate * 34 * 8 * ch / 64)
|
||||
end
|
||||
return d, derr
|
||||
end
|
||||
local s, serr = source(r, pp)
|
||||
if not s then
|
||||
return nil, serr
|
||||
end
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,231 @@
|
||||
--!strict
|
||||
-- audio/vag: Sony VAG (PlayStation SPU PS-ADPCM, .vag), and Simon & Schuster / Hyperscan KVAG (IMA ADPCM, the same
|
||||
-- extension), over codecs/audio/Adpcm. New in formats-luau; the header variants and the PS-ADPCM decoding follow
|
||||
-- vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: "VAGp" mono
|
||||
-- (versions 0, 2, 3, 4, 6, 0x20; the name field as tags.title; loop points from the frame flags, as dec.loop and
|
||||
-- meta.source.loop = { start, stop } in frames, stop exclusive), "VAGi" stereo (interleaved blocks), "KVAG" mono /
|
||||
-- stereo IMA. The output starts with the blank frame Sony's tools put first (28 silent samples), as vgmstream plays it.
|
||||
-- Encode (Audio or Decoder): mono to VAGp, stereo to VAGi (2048-byte interleave), loop points from opts.loop (frame
|
||||
-- aligned: 28 samples). Not supported: HEVAG (VAGp versions 0x00020001 / 0x00030000, Vita / PS4), the many game
|
||||
-- specific variants vgmstream knows (pGAV, VAG1 / VAG2, Jak, ...).
|
||||
--
|
||||
-- local dec = Vag.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, variant)
|
||||
-- local file = Vag.encode(audio, { loop = { start = 0, stop = audio.frames } })
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
local Decoder = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Vag = {
|
||||
name = "vag",
|
||||
category = "audio",
|
||||
extensions = { "vag" },
|
||||
mime = { "audio/x-vag" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type Loop = { start: number, stop: number }
|
||||
export type DecodeOptions = {
|
||||
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
loop: Loop?, -- loop points in frames of the input (stop exclusive), rounded out to 28-sample frames; default: the
|
||||
-- source's meta.source.loop, else none
|
||||
name: string?, -- the 16-byte name field (default: tags.title)
|
||||
interleave: number?, -- stereo: bytes per channel block (default 2048, a multiple of 16)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local HEVAG = { [0x00020001] = true, [0x00030000] = true }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Vag.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
return if m == "VAGp" or m == "VAGi" or m == "KVAG" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Vag.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Vag.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 = "vag", variant = d.variant, codec = d.codec, loop = d.loop }, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local src, serr = Pcm.source(value)
|
||||
if not src then
|
||||
return nil, serr
|
||||
end
|
||||
local ch, rate = src.channels, src.sampleRate
|
||||
if ch > 2 then
|
||||
return nil, Err.new(Err.ARG, "VAG holds mono or stereo")
|
||||
end
|
||||
if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 32 then
|
||||
return nil, Err.new(Err.ARG, "the sample rate must be a positive integer")
|
||||
end
|
||||
local il = o.interleave or 2048
|
||||
if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "interleave must be a multiple of 16")
|
||||
end
|
||||
local loop = o.loop
|
||||
local v = value :: any
|
||||
if loop == nil and type(v.meta) == "table" and type(v.meta.source) == "table" and type(v.meta.source.loop) == "table" then
|
||||
loop = v.meta.source.loop
|
||||
end
|
||||
local a, cerr = Pcm.collect(src)
|
||||
if not a then
|
||||
return nil, cerr
|
||||
end
|
||||
local n = a.frames
|
||||
local nf = (n + 27) // 28 -- data frames (after the blank one)
|
||||
local ls, le = -1, -1
|
||||
if loop then
|
||||
if type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop > n then
|
||||
return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio")
|
||||
end
|
||||
ls, le = loop.start // 28, (loop.stop + 27) // 28 - 1
|
||||
if le <= ls then
|
||||
return nil, Err.new(Err.ARG, "the loop must span two 28-sample frames")
|
||||
end
|
||||
end
|
||||
local chBytes = (nf + 1) * 16
|
||||
local stride = if ch == 1 then chBytes else (chBytes + il - 1) // il * il
|
||||
local start = if ch == 1 then 0x30 else 0x800
|
||||
local out = buffer.create(start + stride * ch)
|
||||
local title = o.name or (a.tags and a.tags.title) or ""
|
||||
buffer.writestring(out, 0, if ch == 1 then "VAGp" else "VAGi")
|
||||
buffer.writeu32(out, 4, bit32.byteswap(0x20))
|
||||
if ch == 2 then
|
||||
buffer.writeu32(out, 8, il)
|
||||
end
|
||||
buffer.writeu32(out, 0x0C, bit32.byteswap(if ch == 1 then chBytes else stride))
|
||||
buffer.writeu32(out, 0x10, bit32.byteswap(rate))
|
||||
buffer.writestring(out, 0x20, string.sub(title, 1, 16))
|
||||
local st = buffer.create(8 * ch)
|
||||
local plane = buffer.create(chBytes)
|
||||
for c = 0, ch - 1 do
|
||||
buffer.fill(plane, 0, 0)
|
||||
Adpcm.psxEncode(a.samples, c, ch, n, st, c * 8, plane, 16, 16)
|
||||
for k = 0, nf - 1 do
|
||||
local flag = if k == ls then 6 elseif k == le then 3 elseif k > ls and k < le then 2 else 0
|
||||
if not loop and k == nf - 1 then
|
||||
flag = 1
|
||||
end
|
||||
buffer.writeu8(plane, 16 + k * 16 + 1, flag)
|
||||
end
|
||||
if ch == 1 then
|
||||
buffer.copy(out, start, plane, 0, chBytes)
|
||||
else
|
||||
for b = 0, stride // il - 1 do
|
||||
local take = math.clamp(chBytes - b * il, 0, il)
|
||||
if take > 0 then
|
||||
buffer.copy(out, start + (b * ch + c) * il, plane, b * il, take)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- the loop from the PS-ADPCM frame flags of channel 0 (vgmstream's reading: the first start flag 6, the first end
|
||||
-- flag 3), or nil
|
||||
local function findLoop(buf: buffer, p: number, frames: number, il: number, ch: number): Loop?
|
||||
local ls, le = -1, -1
|
||||
for k = 0, frames - 1 do
|
||||
local off = p + (k * 16) // il * il * ch + (k * 16) % il
|
||||
local flag = bit32.band(buffer.readu8(buf, off + 1), 15)
|
||||
if flag == 6 and ls < 0 then
|
||||
ls = k * 28
|
||||
elseif flag == 3 and le < 0 then
|
||||
le = k * 28 + 28
|
||||
if ls >= 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
return if ls >= 0 and le > ls then { start = ls, stop = le } else nil
|
||||
end
|
||||
|
||||
function Vag.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)
|
||||
local magic = h:string(4)
|
||||
local total = r.limit - r.base
|
||||
if magic == "KVAG" then
|
||||
local size, rate, stereo = h:u32le(), h:u32le(), h:u16le()
|
||||
if h.err then
|
||||
return nil, h.err
|
||||
end
|
||||
if rate < 1 or stereo > 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad KVAG header")
|
||||
end
|
||||
local dec: any = { sampleRate = rate, channels = stereo + 1, tags = {}, variant = "KVAG", codec = "ima" }
|
||||
local d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base + 14, size = math.min(size, total - 14), hi = true })
|
||||
if d then
|
||||
d.bitrate = rate * 4 * (stereo + 1)
|
||||
end
|
||||
return d, err
|
||||
end
|
||||
if magic ~= "VAGp" and magic ~= "VAGi" then
|
||||
return nil, Err.new(Err.CORRUPT, "not a VAG file")
|
||||
end
|
||||
local version, il = h:u32be(), h:u32le()
|
||||
local chSize, rate = h:u32be(), h:u32be()
|
||||
local name = r:sub(0x20, 16):cstring(16)
|
||||
if h.err then
|
||||
return nil, h.err
|
||||
end
|
||||
if HEVAG[version] then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "HEVAG (Vita / PS4 VAG)")
|
||||
end
|
||||
if rate < 1 or rate >= 2 ^ 31 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate)
|
||||
end
|
||||
local ch, start = 1, 0x30
|
||||
if magic == "VAGi" then
|
||||
ch, start = 2, 0x800
|
||||
if il < 16 or il % 16 ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad interleave " .. il)
|
||||
end
|
||||
else
|
||||
il = 16
|
||||
end
|
||||
if total < start then
|
||||
return nil, Err.new(Err.TRUNCATED, "the header runs past the end")
|
||||
end
|
||||
local size = math.min(chSize * ch, total - start)
|
||||
local p = r.base + start
|
||||
local frames = math.min(chSize // 16, (size // (il * ch)) * (il // 16) + math.clamp(size % (il * ch) - (ch - 1) * il, 0, il) // 16)
|
||||
local loop = if magic == "VAGp" then findLoop(r.buf, p, frames, il, ch) else nil -- vgmstream: VAGi never loops
|
||||
local tags = {}
|
||||
if name ~= "" then
|
||||
tags.title = name
|
||||
end
|
||||
local dec: any = { sampleRate = rate, channels = ch, tags = tags, variant = magic, codec = "psx", loop = loop }
|
||||
local d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = p, size = size, interleave = il, frames = frames * 28 })
|
||||
if d then
|
||||
d.bitrate = rate * 16 * 8 * ch // 28
|
||||
end
|
||||
return d, err
|
||||
end
|
||||
|
||||
return Vag
|
||||
@@ -1,7 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers).
|
||||
-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). The
|
||||
-- ADPCM block decoders moved to codecs/audio/Adpcm.
|
||||
-- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau)
|
||||
-- only calls them with ranges it has checked against the source length and the output size.
|
||||
local readu8, readi8, readu16, readi16, readu32, readi32 =
|
||||
@@ -102,160 +103,6 @@ function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: num
|
||||
end
|
||||
end
|
||||
|
||||
local IMA_STEP = buffer.create(89 * 4)
|
||||
do
|
||||
local steps = {
|
||||
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97,
|
||||
107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724,
|
||||
796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026,
|
||||
4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500,
|
||||
20350, 22385, 24623, 27086, 29794, 32767,
|
||||
}
|
||||
for i, s in steps do
|
||||
buffer.writei32(IMA_STEP, (i - 1) * 4, s)
|
||||
end
|
||||
end
|
||||
local IMA_INDEX = buffer.create(16 * 4)
|
||||
do
|
||||
local t = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 }
|
||||
for i, v in t do
|
||||
buffer.writei32(IMA_INDEX, (i - 1) * 4, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- IMA ADPCM (Microsoft / WAV layout), one block at src[off] of blockAlign bytes with `avail` bytes present (a
|
||||
-- truncated last block decodes the whole 8-sample groups it has). Writes interleaved f32 to dst from frame 0 and
|
||||
-- returns the frame count.
|
||||
function Codecs.imaBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer): number
|
||||
if avail < 4 * ch then
|
||||
return 0
|
||||
end
|
||||
-- groups of 8 samples per channel (4 bytes each) after the per-channel headers
|
||||
local groups = (avail - 4 * ch) // (4 * ch)
|
||||
local frames = math.min(spb, 1 + groups * 8)
|
||||
for c = 0, ch - 1 do
|
||||
local pred = readi16(src, off + c * 4)
|
||||
local index = readu8(src, off + c * 4 + 2)
|
||||
if index > 88 then
|
||||
index = 88
|
||||
end
|
||||
writef32(dst, c * 4, pred / 32768)
|
||||
local f = 1
|
||||
local g = 0
|
||||
while f < frames do
|
||||
local p = off + 4 * ch + (g * ch + c) * 4
|
||||
for k = 0, 7 do
|
||||
if f >= frames then
|
||||
break
|
||||
end
|
||||
local b = readu8(src, p + rshift(k, 1))
|
||||
local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4)
|
||||
local step = buffer.readi32(IMA_STEP, index * 4)
|
||||
local diff = rshift(step, 3)
|
||||
if band(nib, 1) ~= 0 then
|
||||
diff += rshift(step, 2)
|
||||
end
|
||||
if band(nib, 2) ~= 0 then
|
||||
diff += rshift(step, 1)
|
||||
end
|
||||
if band(nib, 4) ~= 0 then
|
||||
diff += step
|
||||
end
|
||||
if band(nib, 8) ~= 0 then
|
||||
pred -= diff
|
||||
else
|
||||
pred += diff
|
||||
end
|
||||
if pred > 32767 then
|
||||
pred = 32767
|
||||
elseif pred < -32768 then
|
||||
pred = -32768
|
||||
end
|
||||
index += buffer.readi32(IMA_INDEX, nib * 4)
|
||||
if index < 0 then
|
||||
index = 0
|
||||
elseif index > 88 then
|
||||
index = 88
|
||||
end
|
||||
writef32(dst, (f * ch + c) * 4, pred / 32768)
|
||||
f += 1
|
||||
end
|
||||
g += 1
|
||||
end
|
||||
end
|
||||
return frames
|
||||
end
|
||||
|
||||
local MS_ADAPT = buffer.create(16 * 4)
|
||||
do
|
||||
local t = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 }
|
||||
for i, v in t do
|
||||
buffer.writei32(MS_ADAPT, (i - 1) * 4, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- MS ADPCM, one block. coefs: i32 pairs (coef1, coef2) x ncoef (256 = 1.0). state: 5 * ch i32 scratch.
|
||||
-- Returns the frame count (a truncated last block decodes the whole bytes it has).
|
||||
function Codecs.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer,
|
||||
coefs: buffer, ncoef: number, state: buffer): number
|
||||
local hdr = 7 * ch
|
||||
if avail < hdr or ncoef < 1 then
|
||||
return 0
|
||||
end
|
||||
local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch)
|
||||
-- state per channel: c1, c2, idelta, s1, s2 (5 i32)
|
||||
for c = 0, ch - 1 do
|
||||
local pi = readu8(src, off + c)
|
||||
if pi >= ncoef then
|
||||
pi = ncoef - 1
|
||||
end
|
||||
local idelta = readi16(src, off + ch + c * 2)
|
||||
local s1 = readi16(src, off + 3 * ch + c * 2)
|
||||
local s2 = readi16(src, off + 5 * ch + c * 2)
|
||||
local so = c * 20
|
||||
buffer.writei32(state, so, buffer.readi32(coefs, pi * 8))
|
||||
buffer.writei32(state, so + 4, buffer.readi32(coefs, pi * 8 + 4))
|
||||
buffer.writei32(state, so + 8, idelta)
|
||||
buffer.writei32(state, so + 12, s1)
|
||||
buffer.writei32(state, so + 16, s2)
|
||||
writef32(dst, c * 4, s2 / 32768)
|
||||
if frames > 1 then
|
||||
writef32(dst, (ch + c) * 4, s1 / 32768)
|
||||
end
|
||||
end
|
||||
-- nibbles, high first, channels interleaved per nibble
|
||||
local total = (frames - 2) * ch
|
||||
for k = 0, total - 1 do
|
||||
local b = readu8(src, off + hdr + rshift(k, 1))
|
||||
local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
|
||||
local c = k % ch
|
||||
local so = c * 20
|
||||
local c1, c2 = buffer.readi32(state, so), buffer.readi32(state, so + 4)
|
||||
local idelta = buffer.readi32(state, so + 8)
|
||||
local s1, s2 = buffer.readi32(state, so + 12), buffer.readi32(state, so + 16)
|
||||
local p = s1 * c1 + s2 * c2
|
||||
p = if p >= 0 then p // 256 else -((-p) // 256)
|
||||
local sn = if nib >= 8 then nib - 16 else nib
|
||||
p += sn * idelta
|
||||
if p > 32767 then
|
||||
p = 32767
|
||||
elseif p < -32768 then
|
||||
p = -32768
|
||||
end
|
||||
idelta = (buffer.readi32(MS_ADAPT, nib * 4) * idelta) // 256
|
||||
if idelta < 16 then
|
||||
idelta = 16
|
||||
elseif idelta > 2796202 then -- INT_MAX / 768, as ffmpeg
|
||||
idelta = 2796202
|
||||
end
|
||||
buffer.writei32(state, so + 8, idelta)
|
||||
buffer.writei32(state, so + 12, p)
|
||||
buffer.writei32(state, so + 16, s1)
|
||||
writef32(dst, (2 * ch + k) * 4, p / 32768)
|
||||
end
|
||||
return frames
|
||||
end
|
||||
|
||||
-- copy frames from a block cache into the output: count f32 values
|
||||
function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number)
|
||||
buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4)
|
||||
|
||||
@@ -21,6 +21,7 @@ local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Riff = require("@formats/containers/Riff")
|
||||
local Codecs = require("@formats/audio/wav/Codecs")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Wav = {
|
||||
@@ -28,7 +29,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/audio/Pcm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
|
||||
}
|
||||
|
||||
@@ -488,8 +489,7 @@ function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?)
|
||||
spb = computed
|
||||
end
|
||||
-- coefficients from the fmt extension, else the 7 standard pairs
|
||||
local c1 = { 256, 512, 0, 192, 240, 460, 392 }
|
||||
local c2 = { 0, -256, 0, 64, 0, -208, -232 }
|
||||
local c1, c2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2
|
||||
local ncoef = 7
|
||||
if fmt.avail >= 22 then
|
||||
local k = u16(fmt.body + 20)
|
||||
@@ -592,9 +592,9 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer,
|
||||
local avail = math.min(ba, self.dataOffset + self.dataSize - off)
|
||||
local got
|
||||
if kind == "ima_adpcm" then
|
||||
got = Codecs.imaBlock(self._buf, off, avail, ch, spb, cache)
|
||||
got = Adpcm.imaWav(self._buf, off, avail, ch, spb, cache, 0)
|
||||
else
|
||||
got = Codecs.msBlock(self._buf, off, avail, ch, spb, cache, self._coefs :: buffer, self._ncoef,
|
||||
got = Adpcm.msBlock(self._buf, off, avail, ch, spb, cache, 0, self._coefs :: buffer, self._ncoef,
|
||||
self._state :: buffer)
|
||||
end
|
||||
self._cacheBlock = block
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
--!strict
|
||||
-- codecs/audio/Adpcm/Decoder: the streaming Decoder (Types.Decoder) over an ADPCM stream cut into packets, for the
|
||||
-- formats whose state carries from packet to packet (ADX, VAG, BRSTM, raw IMA): codecs/audio/Stream.packets plus
|
||||
-- exact seeking. The codec state (one buffer the packet decoder advances) is snapshotted at every packet start it
|
||||
-- passes; a seek restores the snapshot, else the format's own state for that packet (BRSTM's ADPC history), else
|
||||
-- decodes forward from the nearest earlier snapshot. New in formats-luau.
|
||||
--
|
||||
-- local dec, err = Decoder.packets(dec, { -- dec: the Decoder table (sampleRate, channels, frames, ...)
|
||||
-- count = n, packetFrames = 4096, -- packets of packetFrames frames (the last may be shorter)
|
||||
-- frames = total, -- output frames
|
||||
-- state = st, -- the codec state buffer decode advances
|
||||
-- decode = function(i, out) return frames end, -- packet i (1-based) as interleaved f32 into out from 0
|
||||
-- restore = function(i) return false end, -- optional: set st for packet i, true if it could
|
||||
-- })
|
||||
--
|
||||
-- The layouts the formats share, each returning the Decoder (dec gets read / seek / position) | nil, Err:
|
||||
-- Decoder.interleaved(dec, spec) psx / adx / dsp frames (or s16 / s8 PCM), channels interleaved every
|
||||
-- spec.interleave bytes (VAG, ADX, BRSTM / BCSTM / BFSTM, raw PS-ADPCM)
|
||||
-- Decoder.nibbles(dec, spec) an IMA nibble stream, channels interleaved by nibble (raw IMA, KVAG)
|
||||
-- Decoder.blocks(dec, spec) self-contained blocks: "ms" / "ima_wav" (blockAlign bytes), "ima_qt" (34 bytes
|
||||
-- per channel), raw or inside AIFF-C / CAF
|
||||
--
|
||||
-- Never throws (decode failures end the stream and land in dec.error, see codecs/audio/Stream).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Stream = require("@formats/codecs/audio/Stream")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
|
||||
local Decoder = {}
|
||||
|
||||
export type Spec = {
|
||||
count: number,
|
||||
packetFrames: number,
|
||||
frames: number,
|
||||
state: buffer,
|
||||
decode: (i: number, out: buffer) -> (number?, Err.Err?),
|
||||
restore: ((i: number) -> boolean)?,
|
||||
}
|
||||
|
||||
function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?)
|
||||
local ch = dec.channels
|
||||
local pf = spec.packetFrames
|
||||
local st = spec.state
|
||||
local out = buffer.create(pf * ch * 4)
|
||||
local decodeP = spec.decode
|
||||
local restore = spec.restore
|
||||
local snaps: { [number]: buffer } = {}
|
||||
local nextPacket = 1
|
||||
local function snap(i: number)
|
||||
if not snaps[i] then
|
||||
local b = buffer.create(buffer.len(st))
|
||||
buffer.copy(b, 0, st)
|
||||
snaps[i] = b
|
||||
end
|
||||
end
|
||||
snap(1)
|
||||
local function decode(i: number): (number?, Err.Err?)
|
||||
if i ~= nextPacket then
|
||||
if snaps[i] then
|
||||
buffer.copy(st, 0, snaps[i])
|
||||
elseif restore and restore(i) then
|
||||
-- the format set the state (BRSTM's seek table)
|
||||
else
|
||||
local j = i - 1
|
||||
while j > 1 and not snaps[j] do
|
||||
j -= 1
|
||||
end
|
||||
buffer.copy(st, 0, snaps[j])
|
||||
for k = j, i - 1 do
|
||||
local n, e = decodeP(k, out)
|
||||
if not n then
|
||||
return nil, e
|
||||
end
|
||||
snap(k + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
local n, e = decodeP(i, out)
|
||||
if n then
|
||||
nextPacket = i + 1
|
||||
snap(i + 1)
|
||||
end
|
||||
return n, e
|
||||
end
|
||||
return Stream.packets(dec, {
|
||||
count = spec.count,
|
||||
start = function(i: number): number
|
||||
return (i - 1) * pf
|
||||
end,
|
||||
decode = decode,
|
||||
pcm = function(): buffer
|
||||
return out
|
||||
end,
|
||||
reset = function() end,
|
||||
stop = spec.frames,
|
||||
})
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ layouts
|
||||
local FRAME: { [string]: number } = { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame
|
||||
local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame
|
||||
|
||||
-- PCM samples of one channel into every ds-th float of dst from float d
|
||||
local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, d: number, ds: number)
|
||||
if kind == "s8" then
|
||||
for k = 0, n - 1 do
|
||||
buffer.writef32(dst, (d + k * ds) * 4, buffer.readi8(src, p + k) / 128)
|
||||
end
|
||||
elseif kind == "s16le" then
|
||||
for k = 0, n - 1 do
|
||||
buffer.writef32(dst, (d + k * ds) * 4, buffer.readi16(src, p + k * 2) / 32768)
|
||||
end
|
||||
else
|
||||
for k = 0, n - 1 do
|
||||
local v = buffer.readu8(src, p + k * 2) * 256 + buffer.readu8(src, p + k * 2 + 1)
|
||||
buffer.writef32(dst, (d + k * ds) * 4, (if v >= 32768 then v - 65536 else v) / 32768)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
export type InterleavedSpec = {
|
||||
kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", -- ADPCM frames, or PCM samples laid out the same way
|
||||
buf: buffer,
|
||||
offset: number, -- the first row
|
||||
size: number, -- data bytes (rows past it are cut; a truncated file decodes its whole frames)
|
||||
interleave: number, -- bytes per channel per row (a multiple of the frame size; mono: any multiple)
|
||||
lastInterleave: number?, -- bytes per channel in the last row (BRSTM's padded last block), default interleave
|
||||
frames: number?, -- frames to output (default: what the data holds)
|
||||
c1: number?, -- adx: the predictor (Adpcm.adxCoefs)
|
||||
c2: number?,
|
||||
v3: boolean?, -- adx: version 3 rounding
|
||||
coefs: buffer?, -- dsp: 16 i32 per channel
|
||||
hist: { number }?, -- initial history, h1 / h2 per channel (default 0)
|
||||
restore: ((row: number, st: buffer) -> boolean)?, -- the exact history at the start of a row (BRSTM ADPC)
|
||||
}
|
||||
|
||||
-- interleaved(dec, spec) -> Decoder | nil, Err
|
||||
function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?)
|
||||
local ch = dec.channels
|
||||
local kind = spec.kind
|
||||
local fsize, spf = FRAME[kind], SPF[kind]
|
||||
local il = spec.interleave
|
||||
local last = spec.lastInterleave or il
|
||||
if not fsize or ch < 1 or il < fsize or il % fsize ~= 0 or last < 0 or last > il then
|
||||
return nil, Err.new(Err.CORRUPT, "bad interleave " .. tostring(il))
|
||||
end
|
||||
local buf, base, size = spec.buf, spec.offset, spec.size
|
||||
local rowBytes = il * ch
|
||||
-- rows: the full ones, then the last (which may be shorter, and may be cut by a truncated file)
|
||||
local rows = math.max(1, math.ceil(size / rowBytes))
|
||||
local function rowFrames(r: number): number -- the frames row r (0-based) holds whole in every channel
|
||||
local width = if r == rows - 1 then last else il
|
||||
-- channel c sits at c * width in the row: the last channel is the one a cut file shortens
|
||||
local per = math.clamp(size - r * rowBytes - (ch - 1) * width, 0, width)
|
||||
return (per // fsize) * spf
|
||||
end
|
||||
local fullFrames = (il // fsize) * spf
|
||||
local total = (rows - 1) * fullFrames + rowFrames(rows - 1)
|
||||
local frames = math.min(spec.frames or total, total)
|
||||
local st = buffer.create(8 * ch)
|
||||
if spec.hist then
|
||||
for c = 0, ch - 1 do
|
||||
buffer.writei32(st, c * 8, spec.hist[c * 2 + 1] or 0)
|
||||
buffer.writei32(st, c * 8 + 4, spec.hist[c * 2 + 2] or 0)
|
||||
end
|
||||
end
|
||||
local rowsPer = if spec.restore then 1 else math.max(1, 4096 // fullFrames)
|
||||
local pf = rowsPer * fullFrames
|
||||
local c1, c2, v3, coefs = spec.c1 or 0, spec.c2 or 0, spec.v3 == true, spec.coefs
|
||||
local restore = spec.restore
|
||||
dec.frames = frames
|
||||
dec.duration = frames / dec.sampleRate
|
||||
return Decoder.packets(dec, {
|
||||
count = math.max(1, math.ceil(frames / pf)),
|
||||
packetFrames = pf,
|
||||
frames = frames,
|
||||
state = st,
|
||||
restore = if restore
|
||||
then function(i: number): boolean
|
||||
return restore(i - 1, st)
|
||||
end
|
||||
else nil,
|
||||
decode = function(i: number, out: buffer): (number?, Err.Err?)
|
||||
local got = 0
|
||||
for r = (i - 1) * rowsPer, math.min(i * rowsPer, rows) - 1 do
|
||||
local n = math.min(rowFrames(r), frames - r * fullFrames)
|
||||
if n <= 0 then
|
||||
break
|
||||
end
|
||||
local nf = math.ceil(n / spf)
|
||||
local width = if r == rows - 1 then last else il
|
||||
for c = 0, ch - 1 do
|
||||
local p = base + r * rowBytes + c * width
|
||||
local d = got * ch + c
|
||||
if kind == "psx" then
|
||||
Adpcm.psx(buf, p, fsize, nf, st, c * 8, out, d, ch)
|
||||
elseif kind == "adx" then
|
||||
Adpcm.adx(buf, p, fsize, nf, c1, c2, v3, st, c * 8, out, d, ch)
|
||||
elseif kind == "dsp" then
|
||||
Adpcm.dsp(buf, p, n, coefs :: buffer, c * 64, st, c * 8, out, d, ch)
|
||||
else
|
||||
pcm(kind, buf, p, n, out, d, ch)
|
||||
end
|
||||
end
|
||||
got += n
|
||||
end
|
||||
return got, nil
|
||||
end,
|
||||
})
|
||||
end
|
||||
|
||||
export type NibbleSpec = {
|
||||
buf: buffer,
|
||||
offset: number,
|
||||
size: number, -- bytes
|
||||
hi: boolean?, -- the high nibble first (DVI / KVAG); default low first
|
||||
frames: number?, -- default: every whole frame of nibbles
|
||||
}
|
||||
|
||||
-- nibbles(dec, spec): an IMA stream starting from predictor 0, step index 0, channel c in nibbles c, c + ch, ...
|
||||
function Decoder.nibbles(dec: any, spec: NibbleSpec): (any, Err.Err?)
|
||||
local ch = dec.channels
|
||||
local buf, base = spec.buf, spec.offset
|
||||
local frames = math.min(spec.frames or math.huge, (spec.size * 2) // ch)
|
||||
local st = buffer.create(8 * ch)
|
||||
local hi = spec.hi == true
|
||||
dec.frames = frames
|
||||
dec.duration = frames / dec.sampleRate
|
||||
return Decoder.packets(dec, {
|
||||
count = math.max(1, math.ceil(frames / 4096)),
|
||||
packetFrames = 4096,
|
||||
frames = frames,
|
||||
state = st,
|
||||
decode = function(i: number, out: buffer): (number?, Err.Err?)
|
||||
local f0 = (i - 1) * 4096
|
||||
local n = math.min(4096, frames - f0)
|
||||
for c = 0, ch - 1 do
|
||||
Adpcm.ima(buf, base, f0 * ch + c, ch, n, hi, st, c * 8, out, c, ch)
|
||||
end
|
||||
return n, nil
|
||||
end,
|
||||
})
|
||||
end
|
||||
|
||||
export type BlockSpec = {
|
||||
kind: "ms" | "ima_wav" | "ima_qt",
|
||||
buf: buffer,
|
||||
offset: number,
|
||||
size: number,
|
||||
blockAlign: number?, -- ms / ima_wav: bytes per block
|
||||
frames: number?, -- default: what the blocks hold
|
||||
coefs: { number }?, -- ms: coefficient pairs, flat (default the 7 standard pairs)
|
||||
}
|
||||
|
||||
-- blockFrames(kind, blockAlign, ch) -> frames per block, or nil when the block cannot hold the headers
|
||||
function Decoder.blockFrames(kind: string, ba: number, ch: number): number?
|
||||
if kind == "ima_qt" then
|
||||
return 64
|
||||
elseif kind == "ms" then
|
||||
return if ba >= 7 * ch then (ba - 7 * ch) * 2 // ch + 2 else nil
|
||||
end
|
||||
return if ba >= 4 * ch then (ba - 4 * ch) * 2 // ch + 1 else nil
|
||||
end
|
||||
|
||||
-- blocks(dec, spec): self-contained ADPCM blocks (no state across blocks); a truncated last block decodes what it has
|
||||
function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?)
|
||||
local ch = dec.channels
|
||||
local kind = spec.kind
|
||||
local ba = if kind == "ima_qt" then 34 * ch else spec.blockAlign or 0
|
||||
local spb = Decoder.blockFrames(kind, ba, ch)
|
||||
if not spb then
|
||||
return nil, Err.new(Err.CORRUPT, "block of " .. ba .. " bytes is too small")
|
||||
end
|
||||
if spb * ch > 2 ^ 20 then
|
||||
return nil, Err.new(Err.LIMIT, "ADPCM block too large")
|
||||
end
|
||||
local buf, base, size = spec.buf, spec.offset, spec.size
|
||||
local full = size // ba
|
||||
local rest = size - full * ba
|
||||
local total = full * spb
|
||||
if kind ~= "ima_qt" and rest > 0 then
|
||||
-- a partial last block: the frames it holds whole
|
||||
if kind == "ms" then
|
||||
total += if rest >= 7 * ch then math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) else 0
|
||||
elseif rest >= 4 * ch then
|
||||
total += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8)
|
||||
end
|
||||
end
|
||||
local frames = math.min(spec.frames or total, total)
|
||||
local ncoef = 7
|
||||
local cf = spec.coefs
|
||||
if cf and #cf >= 2 then
|
||||
ncoef = math.min(256, #cf // 2)
|
||||
end
|
||||
local coefs = buffer.create(ncoef * 8)
|
||||
for k = 0, ncoef - 1 do
|
||||
buffer.writei32(coefs, k * 8, if cf and #cf >= 2 then cf[k * 2 + 1] else Adpcm.MS_COEF1[k + 1])
|
||||
buffer.writei32(coefs, k * 8 + 4, if cf and #cf >= 2 then cf[k * 2 + 2] else Adpcm.MS_COEF2[k + 1])
|
||||
end
|
||||
local scratch = buffer.create(20 * ch)
|
||||
dec.frames = frames
|
||||
dec.duration = frames / dec.sampleRate
|
||||
dec.blockAlign = ba
|
||||
dec.samplesPerBlock = spb
|
||||
return Decoder.packets(dec, {
|
||||
count = math.max(1, math.ceil(frames / spb)),
|
||||
packetFrames = spb,
|
||||
frames = frames,
|
||||
state = scratch,
|
||||
decode = function(i: number, out: buffer): (number?, Err.Err?)
|
||||
local off = base + (i - 1) * ba
|
||||
local avail = math.min(ba, base + size - off)
|
||||
if kind == "ms" then
|
||||
return Adpcm.msBlock(buf, off, avail, ch, spb, out, 0, coefs, ncoef, scratch), nil
|
||||
elseif kind == "ima_wav" then
|
||||
return Adpcm.imaWav(buf, off, avail, ch, spb, out, 0), nil
|
||||
end
|
||||
if avail < ba then
|
||||
return 0, nil
|
||||
end
|
||||
for c = 0, ch - 1 do
|
||||
Adpcm.imaQt(buf, off + c * 34, scratch, c * 8, out, c, ch)
|
||||
end
|
||||
return 64, nil
|
||||
end,
|
||||
})
|
||||
end
|
||||
|
||||
return Decoder
|
||||
@@ -0,0 +1,707 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in formats-luau; the IMA and
|
||||
-- MS block decoders moved here from audio/wav/Codecs (wav-luau, same author). ADX coefficients, PS-ADPCM and Nintendo
|
||||
-- DSP decoding follow vgmstream r2117 (ISC licence, licenses/vgmstream-LICENSE.txt) so the output is bit-exact with it:
|
||||
-- the ADX scale + 1 and the version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024
|
||||
-- rounding. Codec kernels only: the formats (wav, aiff, caf, adx, vag, brstm, adpcm, ...) walk the layouts.
|
||||
--
|
||||
-- Decoders write f32 (sample / 32768) to dst at float index d, every ds floats (interleaving), and keep their running
|
||||
-- state in a caller-owned buffer `st` at byte offset `so` (i32 pairs: IMA pred / step index, the others hist1 / hist2),
|
||||
-- so a decoder can stop between calls and snapshot the state for seeking (codecs/audio/Adpcm/Decoder).
|
||||
--
|
||||
-- Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) -- IMA nibbles: count samples, nibble q0, q0+qs, ...
|
||||
-- Adpcm.imaQt(src, p, st, so, dst, d, ds) -- Apple ima4: one 34-byte packet -> 64 samples
|
||||
-- Adpcm.imaWav(src, off, avail, ch, spb, dst, d) -> frames -- Microsoft IMA block (WAV / AVI)
|
||||
-- Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, st) -> frames -- MS ADPCM block
|
||||
-- Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) -- CRI ADX: 18-byte frames, 32 samples
|
||||
-- Adpcm.adxCoefs(cutoff, rate) -> c1, c2
|
||||
-- Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) -- Sony PS-ADPCM (VAG): 16-byte frames, 28 samples
|
||||
-- Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) -- Nintendo DSP: 8-byte frames, 14 samples
|
||||
-- Adpcm.modplug(src, p, count, dst, d) -- ModPlug ADPCM (XM / MOD samples)
|
||||
-- encoders: imaEncode, imaWavEncode, msEncode, adxEncode, psxEncode, dspEncode (see each)
|
||||
--
|
||||
-- Every function reads only the bytes its arguments describe: the caller checks the ranges (byte counts per call are
|
||||
-- documented on each). Never throws.
|
||||
local readu8, readi16, readu16, readi32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readi32
|
||||
local writef32, readf32, writei32, writeu8, writeu16 = buffer.writef32, buffer.readf32, buffer.writei32, buffer.writeu8, buffer.writeu16
|
||||
local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift
|
||||
local floor = math.floor
|
||||
|
||||
local Adpcm = {}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ IMA
|
||||
local IMA_STEP = {
|
||||
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
|
||||
130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060,
|
||||
1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484,
|
||||
7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767,
|
||||
}
|
||||
local IMA_ADJ = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 }
|
||||
-- IMA_DIFF[index * 8 + (nibble & 7) + 1]: the shift-and-add difference (step/8 + bits of step/4, step/2, step), as
|
||||
-- the IMA reference computes it (not (2n + 1) * step / 8, which rounds differently)
|
||||
local IMA_DIFF = table.create(89 * 8, 0)
|
||||
-- IMA_NEXT[index * 16 + nibble + 1]: the next step index
|
||||
local IMA_NEXT = table.create(89 * 16, 0)
|
||||
for i = 0, 88 do
|
||||
local step = IMA_STEP[i + 1]
|
||||
for n = 0, 7 do
|
||||
local d = rshift(step, 3)
|
||||
if band(n, 1) ~= 0 then
|
||||
d += rshift(step, 2)
|
||||
end
|
||||
if band(n, 2) ~= 0 then
|
||||
d += rshift(step, 1)
|
||||
end
|
||||
if band(n, 4) ~= 0 then
|
||||
d += step
|
||||
end
|
||||
IMA_DIFF[i * 8 + n + 1] = d
|
||||
end
|
||||
for n = 0, 15 do
|
||||
IMA_NEXT[i * 16 + n + 1] = math.clamp(i + IMA_ADJ[n + 1], 0, 88)
|
||||
end
|
||||
end
|
||||
Adpcm.IMA_STEP = IMA_STEP
|
||||
|
||||
-- ima: `count` samples of one channel from a nibble stream at byte p: nibble q0, q0 + qs, q0 + 2 qs, ... (nibble q is
|
||||
-- in byte p + q // 2, the low half first unless hi). State: st[so] predictor, st[so + 4] step index. Reads bytes
|
||||
-- p .. p + (q0 + (count - 1) * qs) // 2.
|
||||
function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number, hi: boolean, st: buffer, so: number,
|
||||
dst: buffer, d: number, ds: number)
|
||||
local pred = readi32(st, so)
|
||||
local index = math.clamp(readi32(st, so + 4), 0, 88)
|
||||
local q = q0
|
||||
local o = d * 4
|
||||
local os = ds * 4
|
||||
for _ = 1, count do
|
||||
local b = readu8(src, p + rshift(q, 1))
|
||||
local nib
|
||||
if (band(q, 1) == 0) == hi then
|
||||
nib = rshift(b, 4)
|
||||
else
|
||||
nib = band(b, 15)
|
||||
end
|
||||
local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1]
|
||||
if nib >= 8 then
|
||||
pred -= diff
|
||||
if pred < -32768 then
|
||||
pred = -32768
|
||||
end
|
||||
else
|
||||
pred += diff
|
||||
if pred > 32767 then
|
||||
pred = 32767
|
||||
end
|
||||
end
|
||||
index = IMA_NEXT[index * 16 + nib + 1]
|
||||
writef32(dst, o, pred / 32768)
|
||||
o += os
|
||||
q += qs
|
||||
end
|
||||
writei32(st, so, pred)
|
||||
writei32(st, so + 4, index)
|
||||
end
|
||||
|
||||
-- imaQt: one Apple ima4 packet (34 bytes at p: a big-endian header, the predictor's top 9 bits and the 7-bit step
|
||||
-- index, then 64 nibbles low first) -> 64 samples. Apple's decoders keep the running full-precision predictor while
|
||||
-- the header agrees with it (the same step index, the predictor within 127): st carries it from packet to packet
|
||||
-- (zeros before the first).
|
||||
function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer, d: number, ds: number)
|
||||
local h = readu8(src, p) * 256 + readu8(src, p + 1)
|
||||
local pred = band(h, 0xFF80)
|
||||
if pred >= 32768 then
|
||||
pred -= 65536
|
||||
end
|
||||
local index = band(h, 0x7F)
|
||||
if index ~= readi32(st, so + 4) or math.abs(pred - readi32(st, so)) > 0x7F then
|
||||
writei32(st, so, pred)
|
||||
writei32(st, so + 4, index)
|
||||
end
|
||||
Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds)
|
||||
end
|
||||
|
||||
-- imaWav: one Microsoft IMA ADPCM block (WAV / AVI) at src[off]: per channel a 4-byte header (s16 predictor = the
|
||||
-- first sample, u8 step index, pad), then groups of 4 bytes (8 nibbles, low first) per channel in turn. avail: the
|
||||
-- bytes present (a truncated last block decodes the whole groups it has). Writes interleaved frames to dst from float
|
||||
-- index d; returns the frame count (<= spb).
|
||||
function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number): number
|
||||
if avail < 4 * ch then
|
||||
return 0
|
||||
end
|
||||
local groups = (avail - 4 * ch) // (4 * ch)
|
||||
local frames = math.min(spb, 1 + groups * 8)
|
||||
local o = d * 4
|
||||
for c = 0, ch - 1 do
|
||||
local pred = readi16(src, off + c * 4)
|
||||
local index = math.min(readu8(src, off + c * 4 + 2), 88)
|
||||
writef32(dst, o + c * 4, pred / 32768)
|
||||
local f = 1
|
||||
local g = 0
|
||||
while f < frames do
|
||||
local p = off + 4 * ch + (g * ch + c) * 4
|
||||
local k = 0
|
||||
while k < 8 and f < frames do
|
||||
local b = readu8(src, p + rshift(k, 1))
|
||||
local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4)
|
||||
local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1]
|
||||
if nib >= 8 then
|
||||
pred -= diff
|
||||
if pred < -32768 then
|
||||
pred = -32768
|
||||
end
|
||||
else
|
||||
pred += diff
|
||||
if pred > 32767 then
|
||||
pred = 32767
|
||||
end
|
||||
end
|
||||
index = IMA_NEXT[index * 16 + nib + 1]
|
||||
writef32(dst, o + (f * ch + c) * 4, pred / 32768)
|
||||
f += 1
|
||||
k += 1
|
||||
end
|
||||
g += 1
|
||||
end
|
||||
end
|
||||
return frames
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ MS ADPCM
|
||||
local MS_ADAPT = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 }
|
||||
Adpcm.MS_COEF1 = { 256, 512, 0, 192, 240, 460, 392 }
|
||||
Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 }
|
||||
|
||||
-- msBlock: one MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for
|
||||
-- every channel in turn), then nibbles high first, channels interleaved per nibble. coefs: i32 pairs (coef1, coef2) x
|
||||
-- ncoef (256 = 1.0). state: 20 * ch bytes of scratch. avail: the bytes present. Writes interleaved frames to dst from
|
||||
-- float index d; returns the frame count (<= spb).
|
||||
function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number,
|
||||
coefs: buffer, ncoef: number, state: buffer): number
|
||||
local hdr = 7 * ch
|
||||
if avail < hdr or ncoef < 1 then
|
||||
return 0
|
||||
end
|
||||
local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch)
|
||||
local o = d * 4
|
||||
for c = 0, ch - 1 do
|
||||
local pi = math.min(readu8(src, off + c), ncoef - 1)
|
||||
local idelta = readi16(src, off + ch + c * 2)
|
||||
local s1 = readi16(src, off + 3 * ch + c * 2)
|
||||
local s2 = readi16(src, off + 5 * ch + c * 2)
|
||||
local so = c * 20
|
||||
writei32(state, so, readi32(coefs, pi * 8))
|
||||
writei32(state, so + 4, readi32(coefs, pi * 8 + 4))
|
||||
writei32(state, so + 8, idelta)
|
||||
writei32(state, so + 12, s1)
|
||||
writei32(state, so + 16, s2)
|
||||
writef32(dst, o + c * 4, s2 / 32768)
|
||||
if frames > 1 then
|
||||
writef32(dst, o + (ch + c) * 4, s1 / 32768)
|
||||
end
|
||||
end
|
||||
local total = (frames - 2) * ch
|
||||
for k = 0, total - 1 do
|
||||
local b = readu8(src, off + hdr + rshift(k, 1))
|
||||
local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
|
||||
local so = (k % ch) * 20
|
||||
local c1, c2 = readi32(state, so), readi32(state, so + 4)
|
||||
local idelta = readi32(state, so + 8)
|
||||
local s1, s2 = readi32(state, so + 12), readi32(state, so + 16)
|
||||
local p = s1 * c1 + s2 * c2
|
||||
p = if p >= 0 then p // 256 else -((-p) // 256)
|
||||
p += (if nib >= 8 then nib - 16 else nib) * idelta
|
||||
if p > 32767 then
|
||||
p = 32767
|
||||
elseif p < -32768 then
|
||||
p = -32768
|
||||
end
|
||||
idelta = (MS_ADAPT[nib + 1] * idelta) // 256
|
||||
if idelta < 16 then
|
||||
idelta = 16
|
||||
elseif idelta > 2796202 then -- INT_MAX / 768
|
||||
idelta = 2796202
|
||||
end
|
||||
writei32(state, so + 8, idelta)
|
||||
writei32(state, so + 12, p)
|
||||
writei32(state, so + 16, s1)
|
||||
writef32(dst, o + (2 * ch + k) * 4, p / 32768)
|
||||
end
|
||||
return frames
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ CRI ADX
|
||||
local F32 = buffer.create(4)
|
||||
local function f32(x: number): number
|
||||
writef32(F32, 0, x)
|
||||
return readf32(F32, 0)
|
||||
end
|
||||
|
||||
-- adxCoefs(cutoff, rate) -> coef1, coef2 (fixed point, 12 fractional bits): the 2-pole high-pass predictor from the
|
||||
-- header's cutoff frequency, in single precision as CRI's decoders (and vgmstream) compute it
|
||||
function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number)
|
||||
if rate <= 0 then
|
||||
return 0, 0
|
||||
end
|
||||
local z = f32(math.cos(f32(2 * math.pi * cutoff / rate)))
|
||||
local a = f32(math.sqrt(2) - z)
|
||||
local b = f32(math.sqrt(2) - 1)
|
||||
local c = f32(f32(a - f32(math.sqrt(f32(f32(a + b) * f32(a - b))))) / b)
|
||||
local c1 = c * 8192
|
||||
local c2 = f32(c * c) * -4096
|
||||
c1 = if c1 >= 0 then floor(c1) else -floor(-c1)
|
||||
c2 = if c2 >= 0 then floor(c2) else -floor(-c2)
|
||||
return c1, c2
|
||||
end
|
||||
|
||||
-- adx: nframes 18-byte frames of one channel (s16 big-endian scale, 32 nibbles high first), pstride bytes apart from
|
||||
-- p. v3: the version 3 rounding (each product shifted on its own). A scale of 0x8001 (CRI's end marker) decodes as
|
||||
-- silence. Reads p .. p + (nframes - 1) * pstride + 17; writes 32 * nframes samples.
|
||||
function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: number, c2: number, v3: boolean,
|
||||
st: buffer, so: number, dst: buffer, d: number, ds: number)
|
||||
local h1, h2 = readi32(st, so), readi32(st, so + 4)
|
||||
local o = d * 4
|
||||
local os = ds * 4
|
||||
for f = 0, nframes - 1 do
|
||||
local fp = p + f * pstride
|
||||
local scale = readu8(src, fp) * 256 + readu8(src, fp + 1)
|
||||
if scale == 0x8001 then
|
||||
scale = 0
|
||||
elseif scale >= 32768 then
|
||||
scale -= 65535 -- the signed value + 1
|
||||
else
|
||||
scale += 1
|
||||
end
|
||||
for k = 0, 31 do
|
||||
local b = readu8(src, fp + 2 + rshift(k, 1))
|
||||
local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
|
||||
if n >= 8 then
|
||||
n -= 16
|
||||
end
|
||||
local s
|
||||
if v3 then
|
||||
s = n * scale + (c1 * h1) // 4096 + (c2 * h2) // 4096
|
||||
else
|
||||
s = n * scale + (c1 * h1 + c2 * h2) // 4096
|
||||
end
|
||||
if s > 32767 then
|
||||
s = 32767
|
||||
elseif s < -32768 then
|
||||
s = -32768
|
||||
end
|
||||
h2 = h1
|
||||
h1 = s
|
||||
writef32(dst, o, s / 32768)
|
||||
o += os
|
||||
end
|
||||
end
|
||||
writei32(st, so, h1)
|
||||
writei32(st, so + 4, h2)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ PS-ADPCM
|
||||
local PSX1 = { 0, 60, 115, 98, 122 }
|
||||
local PSX2 = { 0, 0, -52, -55, -60 }
|
||||
|
||||
-- the filter term (c1 * h1 + c2 * h2) / 64 * 256 truncated, as vgmstream's single-precision float code computes it:
|
||||
-- exact in integers while the products fit a float's 24 bits
|
||||
local function psxPred(f: number, h1: number, h2: number): number
|
||||
local x = PSX1[f] * h1 + PSX2[f] * h2
|
||||
if h1 > -65536 and h1 < 65536 and h2 > -65536 and h2 < 65536 then
|
||||
return 4 * x
|
||||
end
|
||||
local v = f32(f32(f32(PSX1[f] / 64) * h1) + f32(f32(PSX2[f] / 64) * h2)) * 256
|
||||
return if v >= 0 then floor(v) else -floor(-v)
|
||||
end
|
||||
|
||||
-- psx: nframes 16-byte frames of one channel (filter << 4 | shift, flags, 28 nibbles low first), pstride bytes apart
|
||||
-- from p. Filters past 4 decode as 0 and shifts past 12 as 9 (as vgmstream); a frame with flags 7 is silence. The
|
||||
-- history keeps the unclipped value. Reads p .. p + (nframes - 1) * pstride + 15; writes 28 * nframes samples.
|
||||
function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: buffer, so: number, dst: buffer,
|
||||
d: number, ds: number)
|
||||
local h1, h2 = readi32(st, so), readi32(st, so + 4)
|
||||
local o = d * 4
|
||||
local os = ds * 4
|
||||
for f = 0, nframes - 1 do
|
||||
local fp = p + f * pstride
|
||||
local head = readu8(src, fp)
|
||||
local filter = rshift(head, 4)
|
||||
local shift = band(head, 15)
|
||||
if filter > 4 then
|
||||
filter = 0
|
||||
end
|
||||
if shift > 12 then
|
||||
shift = 9
|
||||
end
|
||||
local mul = 2 ^ (20 - shift)
|
||||
local fi = filter + 1
|
||||
local silent = band(readu8(src, fp + 1), 15) == 7
|
||||
for k = 0, 27 do
|
||||
local s = 0
|
||||
if not silent then
|
||||
local b = readu8(src, fp + 2 + rshift(k, 1))
|
||||
local n = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4)
|
||||
if n >= 8 then
|
||||
n -= 16
|
||||
end
|
||||
s = (n * mul + psxPred(fi, h1, h2)) // 256
|
||||
end
|
||||
h2 = h1
|
||||
h1 = s
|
||||
if s > 32767 then
|
||||
s = 32767
|
||||
elseif s < -32768 then
|
||||
s = -32768
|
||||
end
|
||||
writef32(dst, o, s / 32768)
|
||||
o += os
|
||||
end
|
||||
end
|
||||
writei32(st, so, h1)
|
||||
writei32(st, so + 4, h2)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Nintendo DSP
|
||||
-- dsp: count samples of one channel from 8-byte frames at p (predictor << 4 | scale shift, 14 nibbles high first).
|
||||
-- coefs: 16 i32 at byte co (8 pairs, 11 fractional bits); a predictor index past 7 uses pair 7. Reads p ..
|
||||
-- p + ceil(count / 14) * 8 - 1.
|
||||
function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: number, st: buffer, so: number,
|
||||
dst: buffer, d: number, ds: number)
|
||||
local h1, h2 = readi32(st, so), readi32(st, so + 4)
|
||||
local o = d * 4
|
||||
local os = ds * 4
|
||||
local done = 0
|
||||
local fp = p
|
||||
while done < count do
|
||||
local head = readu8(src, fp)
|
||||
local pi = math.min(rshift(head, 4), 7)
|
||||
local scale = 2 ^ band(head, 15) * 2048
|
||||
local c1, c2 = readi32(coefs, co + pi * 8), readi32(coefs, co + pi * 8 + 4)
|
||||
local n14 = math.min(14, count - done)
|
||||
for k = 0, n14 - 1 do
|
||||
local b = readu8(src, fp + 1 + rshift(k, 1))
|
||||
local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
|
||||
if n >= 8 then
|
||||
n -= 16
|
||||
end
|
||||
local s = (n * scale + 1024 + c1 * h1 + c2 * h2) // 2048
|
||||
if s > 32767 then
|
||||
s = 32767
|
||||
elseif s < -32768 then
|
||||
s = -32768
|
||||
end
|
||||
h2 = h1
|
||||
h1 = s
|
||||
writef32(dst, o, s / 32768)
|
||||
o += os
|
||||
end
|
||||
done += n14
|
||||
fp += 8
|
||||
end
|
||||
writei32(st, so, h1)
|
||||
writei32(st, so + 4, h2)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encoders
|
||||
-- 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
|
||||
Adpcm.toS16 = toS16
|
||||
|
||||
-- the IMA nibble for x from (pred, index): the one whose decoded value lands nearest (greedy, all 16 tried)
|
||||
local function imaNibble(x: number, pred: number, index: number): number
|
||||
local base = index * 8 + 1
|
||||
local best, bestErr = 0, math.huge
|
||||
for m = 0, 7 do
|
||||
local diff = IMA_DIFF[base + m]
|
||||
local up = math.min(pred + diff, 32767)
|
||||
local e = math.abs(x - up)
|
||||
if e < bestErr then
|
||||
best, bestErr = m, e
|
||||
end
|
||||
local down = math.max(pred - diff, -32768)
|
||||
e = math.abs(x - down)
|
||||
if e < bestErr then
|
||||
best, bestErr = m + 8, e
|
||||
end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
-- imaEncode: count samples of one channel, f32 at float index xi every xs floats of x, into nibbles q0, q0 + qs, ...
|
||||
-- of out at byte p (the other half of each byte is kept). State as Adpcm.ima. Writes bytes p ..
|
||||
-- p + (q0 + (count - 1) * qs) // 2.
|
||||
function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer,
|
||||
p: number, q0: number, qs: number, hi: boolean)
|
||||
local pred = readi32(st, so)
|
||||
local index = math.clamp(readi32(st, so + 4), 0, 88)
|
||||
local q = q0
|
||||
for i = 0, count - 1 do
|
||||
local v = toS16(readf32(x, (xi + i * xs) * 4))
|
||||
local nib = imaNibble(v, pred, index)
|
||||
local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1]
|
||||
pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767)
|
||||
index = IMA_NEXT[index * 16 + nib + 1]
|
||||
local bp = p + rshift(q, 1)
|
||||
local b = readu8(out, bp)
|
||||
if (band(q, 1) == 0) == hi then
|
||||
b = bor(band(b, 0x0F), lshift(nib, 4))
|
||||
else
|
||||
b = bor(band(b, 0xF0), nib)
|
||||
end
|
||||
writeu8(out, bp, b)
|
||||
q += qs
|
||||
end
|
||||
writei32(st, so, pred)
|
||||
writei32(st, so + 4, index)
|
||||
end
|
||||
|
||||
-- imaWavEncode: one Microsoft IMA block of spb frames (spb = 1 + 8k) from interleaved f32 x at frame xf (frames
|
||||
-- available: n; the rest is padded with the last sample) to out[off] (4 * ch + (spb - 1) / 2 * ch bytes). st: 8 * ch
|
||||
-- bytes carrying the step index from block to block.
|
||||
function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: number, st: buffer, out: buffer, off: number)
|
||||
local groups = (spb - 1) // 8
|
||||
for c = 0, ch - 1 do
|
||||
local so = c * 8
|
||||
local first = if n > 0 then toS16(readf32(x, (xf * ch + c) * 4)) else 0
|
||||
writei32(st, so, first)
|
||||
local index = math.clamp(readi32(st, so + 4), 0, 88)
|
||||
writei32(st, so + 4, index)
|
||||
buffer.writei16(out, off + c * 4, first)
|
||||
writeu8(out, off + c * 4 + 2, index)
|
||||
writeu8(out, off + c * 4 + 3, 0)
|
||||
local pred = first
|
||||
for g = 0, groups - 1 do
|
||||
local gp = off + 4 * ch + (g * ch + c) * 4
|
||||
for k = 0, 7 do
|
||||
local f = 1 + g * 8 + k
|
||||
local v = if f < n then toS16(readf32(x, ((xf + f) * ch + c) * 4)) else pred
|
||||
local nib = imaNibble(v, pred, index)
|
||||
local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1]
|
||||
pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767)
|
||||
index = IMA_NEXT[index * 16 + nib + 1]
|
||||
local bp = gp + rshift(k, 1)
|
||||
if band(k, 1) == 0 then
|
||||
writeu8(out, bp, nib)
|
||||
else
|
||||
writeu8(out, bp, bor(readu8(out, bp), lshift(nib, 4)))
|
||||
end
|
||||
end
|
||||
end
|
||||
writei32(st, so + 4, index)
|
||||
end
|
||||
end
|
||||
|
||||
-- one MS ADPCM channel run for the encoder: the nibbles for samples 2 .. n - 1 with predictor (c1, c2) and the first
|
||||
-- delta; returns the squared error and the nibbles in nibs (when given)
|
||||
local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0: number, nibs: { number }?): number
|
||||
local s1, s2 = xs[2], xs[1]
|
||||
local idelta = delta0
|
||||
local err = 0
|
||||
for i = 3, n do
|
||||
local p = s1 * c1 + s2 * c2
|
||||
p = if p >= 0 then p // 256 else -((-p) // 256)
|
||||
local e = xs[i] - p
|
||||
local nib = if e >= 0 then (e + idelta // 2) // idelta else -((-e + idelta // 2) // idelta)
|
||||
nib = math.clamp(nib, -8, 7)
|
||||
local v = math.clamp(p + nib * idelta, -32768, 32767)
|
||||
err += (xs[i] - v) * (xs[i] - v)
|
||||
if nibs then
|
||||
nibs[i] = band(nib, 15)
|
||||
end
|
||||
idelta = math.clamp((MS_ADAPT[band(nib, 15) + 1] * idelta) // 256, 16, 2796202)
|
||||
s2 = s1
|
||||
s1 = v
|
||||
end
|
||||
return err
|
||||
end
|
||||
|
||||
-- msEncode: one MS ADPCM block of spb frames (standard 7 coefficient pairs) from interleaved f32 x at frame xf
|
||||
-- (frames available: n; the rest is padded with silence) to out[off] (7 * ch + (spb - 2) * ch / 2 bytes). Each channel
|
||||
-- takes the predictor with the least error.
|
||||
function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: number, out: buffer, off: number)
|
||||
local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2
|
||||
local xs = table.create(spb, 0)
|
||||
local nibs = table.create(spb, 0)
|
||||
local all = table.create(spb * ch, 0)
|
||||
for c = 0, ch - 1 do
|
||||
for i = 1, spb do
|
||||
xs[i] = if i <= n then toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) else 0
|
||||
end
|
||||
-- the first delta from the first steps
|
||||
local sum = 0
|
||||
for i = 3, math.min(spb, 10) do
|
||||
sum += math.abs(xs[i] - xs[i - 1])
|
||||
end
|
||||
local delta0 = math.clamp(sum // 16, 16, 32767)
|
||||
local best, bestErr = 1, math.huge
|
||||
for k = 1, 7 do
|
||||
local e = msTrial(xs, spb, C1[k], C2[k], delta0, nil)
|
||||
if e < bestErr then
|
||||
best, bestErr = k, e
|
||||
end
|
||||
end
|
||||
msTrial(xs, spb, C1[best], C2[best], delta0, nibs)
|
||||
writeu8(out, off + c, best - 1)
|
||||
writeu16(out, off + ch + c * 2, delta0)
|
||||
buffer.writei16(out, off + 3 * ch + c * 2, xs[2] or 0)
|
||||
buffer.writei16(out, off + 5 * ch + c * 2, xs[1])
|
||||
for i = 3, spb do
|
||||
all[(i - 3) * ch + c + 1] = nibs[i]
|
||||
end
|
||||
end
|
||||
local total = (spb - 2) * ch
|
||||
for k = 0, total - 1, 2 do
|
||||
writeu8(out, off + 7 * ch + k // 2, all[k + 1] * 16 + (all[k + 2] or 0))
|
||||
end
|
||||
end
|
||||
|
||||
-- one ADX frame for the encoder: the squared error of encoding xs[1..32] with scale from (h1, h2) (v4 rounding), and
|
||||
-- the nibbles in nibs when given; returns the error and the new history
|
||||
local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h1: number, h2: number, nibs: { number }?): (number, number, number)
|
||||
local err = 0
|
||||
for k = 1, 32 do
|
||||
local pred = (c1 * h1 + c2 * h2) // 4096
|
||||
local e = xs[k] - pred
|
||||
local n = if e >= 0 then (e + scale // 2) // scale else -((-e + scale // 2) // scale)
|
||||
n = math.clamp(n, -8, 7)
|
||||
local s = math.clamp(n * scale + pred, -32768, 32767)
|
||||
err += (xs[k] - s) * (xs[k] - s)
|
||||
if nibs then
|
||||
nibs[k] = band(n, 15)
|
||||
end
|
||||
h2 = h1
|
||||
h1 = s
|
||||
end
|
||||
return err, h1, h2
|
||||
end
|
||||
|
||||
-- adxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 32) ADX frames
|
||||
-- (v4 rounding, the scale stored minus one as CRI's decoders add it back) at out[p], pstride bytes apart; the frame
|
||||
-- past count is padded with silence. State as Adpcm.adx.
|
||||
function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: number, c2: number, st: buffer, so: number,
|
||||
out: buffer, p: number, pstride: number)
|
||||
local h1, h2 = readi32(st, so), readi32(st, so + 4)
|
||||
local v = table.create(32, 0)
|
||||
local nibs = table.create(32, 0)
|
||||
for f = 0, (count + 31) // 32 - 1 do
|
||||
local peak = 0
|
||||
local a, b = h1, h2
|
||||
for k = 1, 32 do
|
||||
local i = f * 32 + k - 1
|
||||
local s = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0
|
||||
v[k] = s
|
||||
peak = math.max(peak, math.abs(s - (c1 * a + c2 * b) // 4096))
|
||||
b = a
|
||||
a = s
|
||||
end
|
||||
-- the scale that covers the open-loop residual peak, and a few around it, closed loop
|
||||
local base = math.max(1, (peak + 6) // 7)
|
||||
local best, bestErr = base, math.huge
|
||||
for _, m in { 1, 0.75, 1.25, 0.5, 1.6 } do
|
||||
local sc = math.clamp(floor(base * m + 0.5), 1, 0x7FFF)
|
||||
local e = adxTrial(v, sc, c1, c2, h1, h2, nil)
|
||||
if e < bestErr then
|
||||
best, bestErr = sc, e
|
||||
end
|
||||
end
|
||||
local _, n1, n2 = adxTrial(v, best, c1, c2, h1, h2, nibs)
|
||||
h1, h2 = n1, n2
|
||||
local fp = p + f * pstride
|
||||
writeu8(out, fp, rshift(best - 1, 8))
|
||||
writeu8(out, fp + 1, band(best - 1, 255))
|
||||
for k = 0, 15 do
|
||||
writeu8(out, fp + 2 + k, nibs[k * 2 + 1] * 16 + nibs[k * 2 + 2])
|
||||
end
|
||||
end
|
||||
writei32(st, so, h1)
|
||||
writei32(st, so + 4, h2)
|
||||
end
|
||||
|
||||
-- psxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 28) PS-ADPCM
|
||||
-- frames at out[p], pstride bytes apart, flags byte 0 (the caller sets loop / end flags); every filter and shift is
|
||||
-- tried per frame against Adpcm.psx's decoding, the least squared error wins. State as Adpcm.psx.
|
||||
function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer,
|
||||
p: number, pstride: number)
|
||||
local h1, h2 = readi32(st, so), readi32(st, so + 4)
|
||||
local v = table.create(28, 0)
|
||||
local nibs = table.create(28, 0)
|
||||
for f = 0, (count + 27) // 28 - 1 do
|
||||
for k = 1, 28 do
|
||||
local i = f * 28 + k - 1
|
||||
v[k] = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0
|
||||
end
|
||||
local bestErr, bestHead = math.huge, 0
|
||||
for fi = 1, 5 do
|
||||
for shift = 0, 12 do
|
||||
local mul = 2 ^ (20 - shift)
|
||||
local a, b = h1, h2
|
||||
local err = 0
|
||||
for k = 1, 28 do
|
||||
local pred = psxPred(fi, a, b)
|
||||
local n = floor((v[k] * 256 - pred) / mul + 0.5)
|
||||
n = if n > 7 then 7 elseif n < -8 then -8 else n
|
||||
local s = (n * mul + pred) // 256
|
||||
local c = if s > 32767 then 32767 elseif s < -32768 then -32768 else s
|
||||
err += (v[k] - c) * (v[k] - c)
|
||||
if err >= bestErr then
|
||||
break
|
||||
end
|
||||
b = a
|
||||
a = s
|
||||
end
|
||||
if err < bestErr then
|
||||
bestErr, bestHead = err, (fi - 1) * 16 + shift
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the winner again, for its nibbles and history
|
||||
local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15)
|
||||
local mul = 2 ^ (20 - shift)
|
||||
for k = 1, 28 do
|
||||
local pred = psxPred(fi, h1, h2)
|
||||
local n = math.clamp(floor((v[k] * 256 - pred) / mul + 0.5), -8, 7)
|
||||
nibs[k] = band(n, 15)
|
||||
h2 = h1
|
||||
h1 = (n * mul + pred) // 256
|
||||
end
|
||||
local fp = p + f * pstride
|
||||
writeu8(out, fp, bestHead)
|
||||
writeu8(out, fp + 1, 0)
|
||||
for k = 0, 13 do
|
||||
writeu8(out, fp + 2 + k, nibs[k * 2 + 1] + nibs[k * 2 + 2] * 16)
|
||||
end
|
||||
end
|
||||
writei32(st, so, h1)
|
||||
writei32(st, so + 4, h2)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ ModPlug
|
||||
-- modplug: ModPlug / OpenMPT ADPCM samples (XM / MOD sample data marked 0xAD): a table of 16 signed byte deltas at
|
||||
-- p, then count nibbles (low first) at p + 16, each adding its table delta to a running signed byte (wrapping).
|
||||
-- Writes count f32 (value / 128) to dst from float index d. Reads p .. p + 16 + ceil(count / 2) - 1.
|
||||
function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: number)
|
||||
local tab = table.create(16, 0)
|
||||
for k = 0, 15 do
|
||||
tab[k + 1] = buffer.readi8(src, p + k)
|
||||
end
|
||||
local v = 0
|
||||
for i = 0, count - 1 do
|
||||
local b = readu8(src, p + 16 + rshift(i, 1))
|
||||
local nib = if band(i, 1) == 0 then band(b, 15) else rshift(b, 4)
|
||||
v = (v + tab[nib + 1] + 128) % 256 - 128
|
||||
writef32(dst, (d + i) * 4, v / 128)
|
||||
end
|
||||
end
|
||||
|
||||
return Adpcm
|
||||
@@ -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
|
||||
@@ -10,7 +10,7 @@
|
||||
-- count = n, -- frames, duration, bitrate, tags, ...); read / seek / position
|
||||
-- start = function(i) return ... end, -- are added. start(i): packet i's first frame (absolute, before
|
||||
-- decode = function(i) return n, err end,-- trimming); decode(i) -> frames | nil, Err, the samples in pcm()
|
||||
-- pcm = function() return floats end, -- (interleaved, 1-based) until the next decode
|
||||
-- pcm = function() return floats end, -- (interleaved, 1-based; or a buffer of f32) until the next decode
|
||||
-- reset = function() end, -- forget codec state (before a seek)
|
||||
-- skip = priming, stop = lastFrame, -- output = absolute frames [skip, stop)
|
||||
-- preroll = 1, -- packets decoded before the one holding a seek target (AAC: 1)
|
||||
@@ -26,7 +26,7 @@ export type Spec = {
|
||||
count: number,
|
||||
start: (i: number) -> number,
|
||||
decode: (i: number) -> (number?, Err.Err?),
|
||||
pcm: () -> { number },
|
||||
pcm: () -> { number } | buffer, -- a buffer: interleaved f32 from byte 0
|
||||
reset: () -> (),
|
||||
skip: number?, -- default 0
|
||||
stop: number?, -- default start(count + 1)
|
||||
@@ -91,9 +91,13 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?)
|
||||
local src = pcmOf()
|
||||
local q = got * ch * 4
|
||||
local s = pendPos * ch
|
||||
for k = 1, take * ch do
|
||||
writef32(ob, q, src[s + k])
|
||||
q += 4
|
||||
if type(src) == "buffer" then
|
||||
buffer.copy(ob, q, src, s * 4, take * ch * 4)
|
||||
else
|
||||
for k = 1, take * ch do
|
||||
writef32(ob, q, src[s + k])
|
||||
q += 4
|
||||
end
|
||||
end
|
||||
pendPos += take
|
||||
got += take
|
||||
|
||||
@@ -5,13 +5,15 @@
|
||||
-- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga
|
||||
-- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files
|
||||
-- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies).
|
||||
-- Not supported: ModPlug ADPCM samples (read as silence), OpenMPT's stereo-sample / extra-effect extensions on write.
|
||||
-- ModPlug ADPCM samples decode (codecs/audio/Adpcm; written back as plain delta PCM). Not supported: OpenMPT's
|
||||
-- stereo-sample / extra-effect extensions on write.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Tracker = require("@formats/codecs/audio/Tracker")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xm = {
|
||||
@@ -19,7 +21,7 @@ local Xm = {
|
||||
category = "music",
|
||||
extensions = { "xm" },
|
||||
mime = { "audio/xm", "audio/x-xm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" },
|
||||
caps = { decode = true, encode = true, render = true, channels = { 1, 64 } },
|
||||
}
|
||||
|
||||
@@ -240,12 +242,19 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
s.relativeNote = h.rel
|
||||
s.pan = h.pan
|
||||
local frames = h.len // bps
|
||||
if h.res == 0xAD then
|
||||
-- ModPlug ADPCM: 16-byte table + 4 bits per sample (not decoded: silence of the right length)
|
||||
local bytes = 16 + (h.len + 1) // 2
|
||||
r:skip(math.min(bytes, r:remaining()))
|
||||
frames = h.len
|
||||
if h.res == 0xAD and bits == 8 then
|
||||
-- ModPlug ADPCM (codecs/audio/Adpcm): a 16-byte delta table, then 4 bits per sample; a cut file keeps
|
||||
-- the samples whose nibbles are present
|
||||
frames = math.max(0, math.min(h.len, (r:remaining() - 16) * 2))
|
||||
total += frames * 4
|
||||
if total > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
|
||||
end
|
||||
s.data = buffer.create(frames * 4)
|
||||
if frames > 0 then
|
||||
Adpcm.modplug(r.buf, r.pos, frames, s.data, 0)
|
||||
end
|
||||
r:skip(math.min(16 + (h.len + 1) // 2, r:remaining()))
|
||||
else
|
||||
local avail = r:remaining() // bps
|
||||
local got = math.min(frames, avail)
|
||||
|
||||
Reference in new issue
Block a user