Files
rosetta/src/Rosetta/audio/wavpack/init.luau
T

207 lines
6.8 KiB
Luau

--!strict
--!optimize 2
-- audio/wavpack: WavPack (.wv) via codecs/audio/WavPack, from the WavPack 5 file format document and WavPack 5.9.0's
-- open_utils.c (BSD 3-clause, licenses/wavpack-LICENSE.txt). Supports: lossless and hybrid (lossy without the .wvc, as
-- wvunpack), 8-32-bit integer and float, 1-4096 channels, seeking, APEv2. Not supported: DSD, WavPack 1-3, encoding.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Stream = require("@rosetta/codecs/audio/Stream")
local ApeTag = require("@rosetta/codecs/audio/ApeTag")
local WavPackCodec = require("@rosetta/codecs/audio/WavPack")
-- ------------------------------------------------------------------------------------------------ contract
local WavPack = {
name = "wavpack",
category = "audio",
extensions = { "wv" },
mime = { "audio/x-wavpack", "audio/wavpack" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
correction: (buffer | string)?, -- the .wvc file of a hybrid file (default: opts.resolve(name .. "c") when given)
resolve: ((uri: string) -> buffer?)?,
name: string?,
maxFrames: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ sniff
function WavPack.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "wvpk" then
return 0
end
local v = r:peekU8(9)
return if v == 4 then 1 else 0.5
end
-- ------------------------------------------------------------------------------------------------ decode
function WavPack.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = WavPack.open(r, opts)
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, d.source, limit)
end
-- ------------------------------------------------------------------------------------------------ open
type Index = { offsets: { { number } }, starts: { number }, samples: { number }, total: number, first: number, md5: string? }
local function index(buf: buffer, base: number, limit: number): (Index?, string?)
local at = base
local idx: Index = { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 }
local cur: { number }? = nil
local initial = -1
local resyncs = 0
while at + 32 <= limit do
local h = WavPackCodec.header(buf, at, limit)
if not h then
-- garbage (or a tag) between blocks: search the next header
if resyncs > 64 then
break
end
local s = buffer.readstring(buf, at + 1, math.min(limit - at - 1, 1048576))
local k = string.find(s, "wvpk", 1, true)
if not k then
break
end
at = at + k
resyncs += 1
continue
end
if initial < 0 then
initial = h.index
idx.total = h.total
end
if h.samples > 0 then
if bit32.band(h.flags, WavPackCodec.INITIAL) ~= 0 or not cur then
cur = { at }
table.insert(idx.offsets, cur)
table.insert(idx.starts, h.index - initial)
table.insert(idx.samples, h.samples)
if idx.first < 0 then
idx.first = at
end
else
table.insert(cur, at)
end
if bit32.band(h.flags, WavPackCodec.FINAL) ~= 0 then
cur = nil
end
else
idx.md5 = idx.md5 or WavPackCodec.md5(buf, at, limit)
end
at += h.size
end
if idx.first < 0 then
return nil, "no audio blocks"
end
return idx, nil
end
local function correctionFile(opts: OpenOptions?): buffer?
if not opts then
return nil
end
local c = opts.correction
if type(c) == "string" then
return buffer.fromstring(c)
elseif type(c) == "buffer" then
return c
end
if type(opts.resolve) == "function" and type(opts.name) == "string" then
local base = string.match(opts.name, "([^/\\]+)$")
if base then
local ok, b = pcall(opts.resolve, base .. "c")
if ok and type(b) == "buffer" then
return b
end
end
end
return nil
end
function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
if type(r) == "buffer" then
r = Bytes.reader(r :: any)
end
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local buf, base, limit = r.buf, r.base, r.limit
local tags, tagInfo = ApeTag.find(buf, base, limit)
local stop = if tagInfo then tagInfo.start else limit
local idx, ierr = index(buf, base, stop)
if not idx then
return nil, Err.from(ierr, base)
end
local info, err = WavPackCodec.info(buf, idx.first, stop)
if not info then
return nil, err
end
if info.channels > 256 then
return nil, Err.new(Err.LIMIT, info.channels .. " channels")
end
local count = #idx.offsets
local last = idx.starts[count] + idx.samples[count]
local frames = if idx.total >= 0 then math.min(idx.total, last) else last
local cbuf = if info.hybrid then correctionFile(opts) else nil
local cfor: { [number]: { number } } = {}
if cbuf then
local cidx = index(cbuf, 0, buffer.len(cbuf))
if cidx then
for i, offs in cidx.offsets do
cfor[cidx.starts[i]] = offs
end
else
cbuf = nil
end
end
local codec = WavPackCodec.decoder(info.channels)
local dec: any = {
sampleRate = info.sampleRate,
channels = info.channels,
frames = frames,
duration = frames / info.sampleRate,
bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0,
tags = tags or {},
bitsPerSample = info.bitsPerSample,
float = info.float,
hybrid = info.hybrid,
lossless = not info.hybrid or cbuf ~= nil,
channelMask = info.channelMask,
md5 = idx.md5,
source = { format = "wavpack", bitDepth = info.bitsPerSample, float = info.float, hybrid = info.hybrid, correction = cbuf ~= nil, version = info.version, tags = tagInfo and tagInfo.items },
}
local starts, offsets = idx.starts, idx.offsets
return Stream.packets(dec, {
count = count,
start = function(i: number): number
return if i > count then last else starts[i]
end,
decode = function(i: number): (number?, Err.Err?)
local co = if cbuf then cfor[starts[i]] else nil
return codec:frame(buf, offsets[i], if co then cbuf else nil, co)
end,
pcm = function(): { number }
return codec.pcm
end,
reset = function() end,
stop = frames,
scale = if info.float then 1 else 1 / 2 ^ (info.bytesPerSample * 8 - 1),
ints = not info.float,
})
end
return WavPack