absorb: containers/Riff (lenient reader from wav-luau + new writer: RIFX, RF64/ds64, LIST, parts) and audio/wav (decoder from wav-luau fd9a909 on Riff + new encoder u8/s16/s24/s32/f32, EXTENSIBLE, RF64; byte-exact vs ffmpeg -bitexact)
This commit is contained in:
1 parent
e3f9d0fb38
commit
85fb079068
9 files changed
+1989
No files matched your search
@@ -0,0 +1,326 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers).
|
||||
-- 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 =
|
||||
buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32
|
||||
local readf32, readf64, writef32, writeu32 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writeu32
|
||||
local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap
|
||||
local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writei16, buffer.writei32
|
||||
|
||||
local Codecs = {}
|
||||
|
||||
-- Integer PCM: count samples of `bytes` bytes each (1 = unsigned 8-bit, 2 / 3 / 4 = signed), little- or big-endian,
|
||||
-- from src[off] to dst (f32) starting at sample index d.
|
||||
function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean)
|
||||
local o = d * 4
|
||||
if bytes == 1 then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, o + i * 4, (readu8(src, off + i) - 128) / 128)
|
||||
end
|
||||
elseif bytes == 2 then
|
||||
if be then
|
||||
for i = 0, count - 1 do
|
||||
local s = off + i * 2
|
||||
local v = readi8(src, s) * 256 + readu8(src, s + 1)
|
||||
writef32(dst, o + i * 4, v / 32768)
|
||||
end
|
||||
else
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, o + i * 4, readi16(src, off + i * 2) / 32768)
|
||||
end
|
||||
end
|
||||
elseif bytes == 3 then
|
||||
if be then
|
||||
for i = 0, count - 1 do
|
||||
local s = off + i * 3
|
||||
local v = readi8(src, s) * 65536 + readu8(src, s + 1) * 256 + readu8(src, s + 2)
|
||||
writef32(dst, o + i * 4, v / 8388608)
|
||||
end
|
||||
else
|
||||
for i = 0, count - 1 do
|
||||
local s = off + i * 3
|
||||
local v = readi8(src, s + 2) * 65536 + readu16(src, s)
|
||||
writef32(dst, o + i * 4, v / 8388608)
|
||||
end
|
||||
end
|
||||
else
|
||||
if be then
|
||||
for i = 0, count - 1 do
|
||||
local v = byteswap(readu32(src, off + i * 4))
|
||||
if v >= 0x80000000 then
|
||||
v -= 0x100000000
|
||||
end
|
||||
writef32(dst, o + i * 4, v / 2147483648)
|
||||
end
|
||||
else
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, o + i * 4, readi32(src, off + i * 4) / 2147483648)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- IEEE float, 4 or 8 bytes. tmp: an 8-byte scratch buffer for byte-swapping big-endian values.
|
||||
function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean,
|
||||
tmp: buffer)
|
||||
local o = d * 4
|
||||
if bytes == 4 then
|
||||
if be then
|
||||
for i = 0, count - 1 do
|
||||
writeu32(tmp, 0, byteswap(readu32(src, off + i * 4)))
|
||||
writef32(dst, o + i * 4, readf32(tmp, 0))
|
||||
end
|
||||
else
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, o + i * 4, readf32(src, off + i * 4))
|
||||
end
|
||||
end
|
||||
else
|
||||
if be then
|
||||
for i = 0, count - 1 do
|
||||
local s = off + i * 8
|
||||
writeu32(tmp, 0, byteswap(readu32(src, s + 4)))
|
||||
writeu32(tmp, 4, byteswap(readu32(src, s)))
|
||||
writef32(dst, o + i * 4, readf64(tmp, 0))
|
||||
end
|
||||
else
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, o + i * 4, readf64(src, off + i * 8))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- 8-bit companded (A-law / mu-law) through a 256-entry f32 table
|
||||
function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: number, tbl: buffer)
|
||||
local o = d * 4
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, o + i * 4, readf32(tbl, readu8(src, off + i) * 4))
|
||||
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)
|
||||
end
|
||||
|
||||
-- Encoder: count f32 samples from src (sample index s) to dst[off] as `kind` ("u8", "s16", "s24", "s32", "f32"),
|
||||
-- little-endian, rounding to nearest and clamping to the integer range. Ranges are checked by the caller.
|
||||
function Codecs.quantize(src: buffer, s: number, dst: buffer, off: number, count: number, kind: string)
|
||||
local so = s * 4
|
||||
if kind == "f32" then
|
||||
buffer.copy(dst, off, src, so, count * 4)
|
||||
elseif kind == "s16" then
|
||||
for i = 0, count - 1 do
|
||||
local v = math.floor(readf32(src, so + i * 4) * 32768 + 0.5)
|
||||
if v > 32767 then
|
||||
v = 32767
|
||||
elseif v < -32768 then
|
||||
v = -32768
|
||||
elseif v ~= v then
|
||||
v = 0
|
||||
end
|
||||
writei16(dst, off + i * 2, v)
|
||||
end
|
||||
elseif kind == "s24" then
|
||||
for i = 0, count - 1 do
|
||||
local v = math.floor(readf32(src, so + i * 4) * 8388608 + 0.5)
|
||||
if v > 8388607 then
|
||||
v = 8388607
|
||||
elseif v < -8388608 then
|
||||
v = -8388608
|
||||
elseif v ~= v then
|
||||
v = 0
|
||||
end
|
||||
if v < 0 then
|
||||
v += 16777216
|
||||
end
|
||||
local o = off + i * 3
|
||||
writeu16(dst, o, v % 65536)
|
||||
writeu8(dst, o + 2, v // 65536)
|
||||
end
|
||||
elseif kind == "s32" then
|
||||
for i = 0, count - 1 do
|
||||
local v = math.floor(readf32(src, so + i * 4) * 2147483648 + 0.5)
|
||||
if v > 2147483647 then
|
||||
v = 2147483647
|
||||
elseif v < -2147483648 then
|
||||
v = -2147483648
|
||||
elseif v ~= v then
|
||||
v = 0
|
||||
end
|
||||
writei32(dst, off + i * 4, v)
|
||||
end
|
||||
else -- u8
|
||||
for i = 0, count - 1 do
|
||||
local v = math.floor(readf32(src, so + i * 4) * 128 + 0.5)
|
||||
if v > 127 then
|
||||
v = 127
|
||||
elseif v < -128 then
|
||||
v = -128
|
||||
elseif v ~= v then
|
||||
v = 0
|
||||
end
|
||||
writeu8(dst, off + i, v + 128)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Codecs
|
||||
@@ -0,0 +1,650 @@
|
||||
--!strict
|
||||
--!optimize 2
|
||||
-- audio/wav: WAVE in RIFF / RIFX (big-endian) / RF64 / BW64. Absorbed from wav-luau fd9a909 (same author, no
|
||||
-- third-party code; the streaming decoder) on the shared containers/Riff, plus a new encoder.
|
||||
-- Decode: PCM 8 / 16 / 24 / 32 bit, IEEE float 32 / 64, A-law, mu-law, IMA ADPCM, MS ADPCM, WAVE_FORMAT_EXTENSIBLE
|
||||
-- wrapping any of them; odd-sized chunks with or without the pad byte; LIST/INFO tags; a data size of 0 or 0xFFFFFFFF
|
||||
-- (streamed output) or past the end means "up to the end of the file" (a truncated file decodes what it has).
|
||||
-- Encode: PCM u8 / s16 / s24 / s32 and float32 from an Audio or a streaming Decoder, WAVE_FORMAT_EXTENSIBLE when
|
||||
-- there are more than 2 channels, more than 16 bits or over 48 kHz (as ffmpeg), fact for float, LIST/INFO tags,
|
||||
-- RF64 (ds64) automatically past 4 GiB (Wav.encodeParts streams files over the 1 GiB buffer limit) or on request.
|
||||
-- Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output.
|
||||
--
|
||||
-- local dec = Wav.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(4096) -> f32 buffer, frames
|
||||
-- local audio = Wav.decode(Bytes.reader(buf)) -- Types.Audio
|
||||
-- local file = Wav.encode(audio, { sampleFormat = "s24" })
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Riff = require("@formats/containers/Riff")
|
||||
local Codecs = require("@formats/audio/wav/Codecs")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Wav = {
|
||||
name = "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" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type Tags = { [string]: string }
|
||||
export type OpenOptions = {
|
||||
maxBytes: number?, -- unused (the file is already in memory); kept for symmetry
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
sampleFormat: ("u8" | "s16" | "s24" | "s32" | "f32")?, -- default "s16"
|
||||
rf64: (boolean | "auto")?, -- default "auto": RF64 only when the file passes 4 GiB
|
||||
extensible: boolean?, -- force (true) or forbid (false) WAVE_FORMAT_EXTENSIBLE; default as ffmpeg
|
||||
channelMask: number?, -- the EXTENSIBLE speaker mask (default: ffmpeg's default layout for the channel count)
|
||||
tags: Tags?, -- default: the Audio's tags (title, artist, album, comment, date, genre, track, ...)
|
||||
rf64Threshold: number?, -- testing: the RIFF size past which "auto" switches to RF64 (default 0xFFFFFFFF)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
Wav.FORMAT_PCM = 1
|
||||
Wav.FORMAT_MS_ADPCM = 2
|
||||
Wav.FORMAT_FLOAT = 3
|
||||
Wav.FORMAT_ALAW = 6
|
||||
Wav.FORMAT_MULAW = 7
|
||||
Wav.FORMAT_IMA_ADPCM = 0x11
|
||||
Wav.FORMAT_EXTENSIBLE = 0xFFFE
|
||||
|
||||
local FORMAT_NAMES = {
|
||||
[1] = "pcm",
|
||||
[2] = "ms_adpcm",
|
||||
[3] = "float",
|
||||
[6] = "alaw",
|
||||
[7] = "mulaw",
|
||||
[0x11] = "ima_adpcm",
|
||||
}
|
||||
|
||||
-- LIST/INFO ids -> tag names
|
||||
local INFO_TAGS = {
|
||||
INAM = "title",
|
||||
IART = "artist",
|
||||
IPRD = "album",
|
||||
ICMT = "comment",
|
||||
ICRD = "date",
|
||||
IGNR = "genre",
|
||||
ITRK = "track",
|
||||
IPRT = "track",
|
||||
ISFT = "encoder",
|
||||
ICOP = "copyright",
|
||||
IENG = "engineer",
|
||||
ISBJ = "subject",
|
||||
IKEY = "keywords",
|
||||
}
|
||||
|
||||
-- A-law / mu-law -> f32 tables (G.711, as ffmpeg's alaw2linear / ulaw2linear)
|
||||
local ALAW, MULAW = buffer.create(1024), buffer.create(1024)
|
||||
do
|
||||
for i = 0, 255 do
|
||||
local a = bit32.bxor(i, 0x55)
|
||||
local t = bit32.band(a, 15)
|
||||
local seg = bit32.rshift(bit32.band(a, 0x70), 4)
|
||||
if seg > 0 then
|
||||
t = bit32.lshift(t * 2 + 1 + 32, seg + 2)
|
||||
else
|
||||
t = bit32.lshift(t * 2 + 1, 3)
|
||||
end
|
||||
if bit32.band(a, 0x80) == 0 then
|
||||
t = -t
|
||||
end
|
||||
buffer.writef32(ALAW, i * 4, t / 32768)
|
||||
local u = bit32.band(bit32.bnot(i), 255)
|
||||
local m = bit32.lshift(bit32.lshift(bit32.band(u, 15), 3) + 0x84, bit32.rshift(bit32.band(u, 0x70), 4))
|
||||
local v = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84
|
||||
buffer.writef32(MULAW, i * 4, v / 32768)
|
||||
end
|
||||
end
|
||||
|
||||
local Decoder = {}
|
||||
Decoder.__index = Decoder
|
||||
|
||||
export type Decoder = typeof(setmetatable(
|
||||
{} :: {
|
||||
sampleRate: number,
|
||||
channels: number,
|
||||
frames: number,
|
||||
duration: number,
|
||||
bitrate: number,
|
||||
tags: Tags,
|
||||
format: string,
|
||||
formatTag: number,
|
||||
bitsPerSample: number,
|
||||
blockAlign: number,
|
||||
container: string,
|
||||
dataOffset: number,
|
||||
dataSize: number,
|
||||
truncated: boolean,
|
||||
channelMask: number?,
|
||||
validBits: number?,
|
||||
_buf: buffer,
|
||||
_pos: number,
|
||||
_be: boolean,
|
||||
_bytes: number,
|
||||
_kind: string,
|
||||
_spb: number,
|
||||
_cache: buffer?,
|
||||
_cacheBlock: number,
|
||||
_cacheFrames: number,
|
||||
_coefs: buffer?,
|
||||
_ncoef: number,
|
||||
_state: buffer?,
|
||||
_tmp: buffer,
|
||||
},
|
||||
Decoder
|
||||
))
|
||||
|
||||
local function trimTag(s: string): string
|
||||
-- strip trailing NULs / spaces
|
||||
local e = #s
|
||||
while e > 0 do
|
||||
local c = string.byte(s, e)
|
||||
if c ~= 0 and c ~= 32 then
|
||||
break
|
||||
end
|
||||
e -= 1
|
||||
end
|
||||
local z = string.find(s, "\0", 1, true)
|
||||
if z and z <= e then
|
||||
e = z - 1
|
||||
end
|
||||
return string.sub(s, 1, e)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Wav.sniff(r: Bytes.Reader): number
|
||||
return if Riff.sniff(r) == "WAVE" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole file
|
||||
function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Wav.open(r, opts)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local a = Types.Audio.new(dec.sampleRate, dec.channels, dec.frames)
|
||||
local _, n = dec:read(dec.frames, a.samples)
|
||||
if n < dec.frames then
|
||||
local s = buffer.create(n * dec.channels * 4)
|
||||
buffer.copy(s, 0, a.samples, 0, n * dec.channels * 4)
|
||||
a.samples, a.frames = s, n
|
||||
end
|
||||
a.tags = dec.tags
|
||||
a.meta.source = {
|
||||
format = "wav",
|
||||
codec = dec.format,
|
||||
bitDepth = dec.bitsPerSample,
|
||||
container = dec.container,
|
||||
channelMask = dec.channelMask,
|
||||
truncated = dec.truncated,
|
||||
}
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local SAMPLE_BYTES = { u8 = 1, s16 = 2, s24 = 3, s32 = 4, f32 = 4 }
|
||||
-- ffmpeg's default speaker masks per channel count (av_channel_layout_default)
|
||||
local MASKS = { [1] = 0x4, [2] = 0x3, [3] = 0xB, [4] = 0x107, [5] = 0x37, [6] = 0x3F, [7] = 0x70F, [8] = 0x63F }
|
||||
local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTYPE_* after the 2-byte format tag
|
||||
-- tags -> LIST/INFO ids (the first id per name)
|
||||
local TAG_IDS = { title = "INAM", artist = "IART", album = "IPRD", comment = "ICMT", date = "ICRD", genre = "IGNR", track = "ITRK", encoder = "ISFT", copyright = "ICOP", engineer = "IENG", subject = "ISBJ", keywords = "IKEY" }
|
||||
local BLOCK = 65536 -- frames per data piece when streaming a Decoder
|
||||
|
||||
-- the body of the encoder: { buffer } pieces of the file | nil, Err
|
||||
local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): (any, Err.Err?)
|
||||
if type(value) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder")
|
||||
end
|
||||
local o: EncodeOptions = opts or {}
|
||||
local kind = o.sampleFormat or "s16"
|
||||
local bytes: number? = SAMPLE_BYTES[kind]
|
||||
if not bytes then
|
||||
return nil, Err.new(Err.ARG, "encode: sampleFormat must be u8, s16, s24, s32 or f32")
|
||||
end
|
||||
local rate: number, ch: number = value.sampleRate, value.channels
|
||||
if type(rate) ~= "number" or rate < 1 or rate > 4294967295 or rate % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "encode: bad sample rate")
|
||||
end
|
||||
if type(ch) ~= "number" or ch < 1 or ch > 65535 or ch % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "encode: bad channel count")
|
||||
end
|
||||
local isAudio = type(value.samples) == "buffer"
|
||||
if not isAudio and type(value.read) ~= "function" then
|
||||
return nil, Err.new(Err.ARG, "encode: needs an Audio (samples) or a Decoder (read)")
|
||||
end
|
||||
local frameBytes = bytes * ch
|
||||
local pieces: { buffer } = {}
|
||||
local frames: number = 0
|
||||
if isAudio then
|
||||
frames = (value.frames :: number?) or (buffer.len(value.samples) // (ch * 4))
|
||||
if type(frames) ~= "number" or frames < 0 or buffer.len(value.samples) < frames * ch * 4 then
|
||||
return nil, Err.new(Err.ARG, "encode: the samples buffer is shorter than frames * channels")
|
||||
end
|
||||
if not asParts and frames * frameBytes > 0x3FFFFF00 then
|
||||
return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)")
|
||||
end
|
||||
-- pieces of at most 256 MiB
|
||||
local per = math.max(1, 0x10000000 // frameBytes)
|
||||
local f0 = 0
|
||||
while f0 < frames do
|
||||
local n = math.min(per, frames - f0)
|
||||
local b = buffer.create(n * frameBytes)
|
||||
Codecs.quantize(value.samples, f0 * ch, b, 0, n * ch, kind)
|
||||
table.insert(pieces, b)
|
||||
f0 += n
|
||||
end
|
||||
else
|
||||
local tmp = buffer.create(BLOCK * ch * 4)
|
||||
while true do
|
||||
local ok, out, n = pcall(value.read, value, BLOCK, tmp)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "encode: the decoder failed: " .. tostring(out))
|
||||
end
|
||||
if type(n) ~= "number" or n <= 0 or type(out) ~= "buffer" then
|
||||
break
|
||||
end
|
||||
n = math.min(n, buffer.len(out) // (ch * 4))
|
||||
local b = buffer.create(n * frameBytes)
|
||||
Codecs.quantize(out, 0, b, 0, n * ch, kind)
|
||||
table.insert(pieces, b)
|
||||
frames += n
|
||||
if not asParts and frames * frameBytes > 0x3FFFFF00 then
|
||||
return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)")
|
||||
end
|
||||
end
|
||||
end
|
||||
local dataSize = frames * frameBytes
|
||||
local bits = bytes * 8
|
||||
local float = kind == "f32"
|
||||
local tag = if float then 3 else 1
|
||||
local extensible = ch > 2 or rate > 48000 or (not float and bits > 16)
|
||||
if o.extensible ~= nil then
|
||||
extensible = o.extensible
|
||||
end
|
||||
local w = Riff.writer("WAVE", { rf64 = if o.rf64 ~= nil then o.rf64 else "auto", sampleCount = frames, rf64Threshold = o.rf64Threshold })
|
||||
local fmt = Bytes.writer(40)
|
||||
fmt:u16le(if extensible then 0xFFFE else tag)
|
||||
fmt:u16le(ch)
|
||||
fmt:u32le(rate)
|
||||
fmt:u32le(rate * frameBytes)
|
||||
fmt:u16le(frameBytes)
|
||||
fmt:u16le(bits)
|
||||
if extensible then
|
||||
fmt:u16le(22)
|
||||
fmt:u16le(bits)
|
||||
fmt:u32le(o.channelMask or MASKS[ch] or 0)
|
||||
fmt:u16le(tag)
|
||||
fmt:string(GUID_TAIL)
|
||||
elseif float then
|
||||
fmt:u16le(0) -- cbSize
|
||||
end
|
||||
w:chunk("fmt ", fmt:finish())
|
||||
if float then
|
||||
local fact = Bytes.writer(4)
|
||||
fact:u32le(if w.rf64 == true or frames > 0xFFFFFFFF then 0xFFFFFFFF else frames) -- RF64: in ds64 (as ffmpeg)
|
||||
w:chunk("fact", fact:finish())
|
||||
end
|
||||
local tags = o.tags or value.tags
|
||||
if type(tags) == "table" then
|
||||
local items = {}
|
||||
local keys = {}
|
||||
for k in tags do
|
||||
if type(k) == "string" then
|
||||
table.insert(keys, k)
|
||||
end
|
||||
end
|
||||
table.sort(keys)
|
||||
for _, k in keys do
|
||||
local v = tags[k]
|
||||
local id = TAG_IDS[k] or (if #k == 4 and string.upper(k) == k then k else nil)
|
||||
if id and type(v) == "string" and v ~= "" then
|
||||
table.insert(items, { id, v })
|
||||
end
|
||||
end
|
||||
if #items > 0 then
|
||||
w:list("INFO", items)
|
||||
end
|
||||
end
|
||||
w:chunk("data", pieces)
|
||||
local _ = dataSize
|
||||
return w:finish({ parts = asParts })
|
||||
end
|
||||
|
||||
-- encode(audio or decoder, opts?) -> buffer | nil, Err
|
||||
function Wav.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
return encodeParts(value, opts, false)
|
||||
end
|
||||
|
||||
-- encodeParts(audio or decoder, opts?) -> { buffer } | nil, Err: the file as pieces to write one after the other
|
||||
-- (header, sample blocks, ...), without the 1 GiB single-buffer limit; RF64 past 4 GiB
|
||||
function Wav.encodeParts(value: any, opts: EncodeOptions?): ({ buffer }?, Err.Err?)
|
||||
return encodeParts(value, opts, true)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> Decoder | nil, Err: the streaming decoder (Types.Decoder) over the file in r's range
|
||||
function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?)
|
||||
if type(r) == "buffer" or type(r) == "string" then
|
||||
r = Bytes.reader(if type(r) == "string" then buffer.fromstring(r) else r :: any)
|
||||
end
|
||||
local f, ferr = Riff.read(r, { openEnded = { data = true } })
|
||||
if not f then
|
||||
return nil, ferr
|
||||
end
|
||||
if f.form ~= "WAVE" then
|
||||
return nil, Err.new(Err.CORRUPT, "not a WAVE file (" .. f.form .. ")", f.base + 8)
|
||||
end
|
||||
local buf = f.buf
|
||||
local magic = f.container
|
||||
local be = f.bigEndian
|
||||
|
||||
local fmt: any = nil
|
||||
local tags: Tags = {}
|
||||
local dataOff, dataSize = -1, 0
|
||||
local truncated = false
|
||||
local ds64Frames: number? = if f.ds64 and f.ds64.sampleCount > 0 then f.ds64.sampleCount else nil
|
||||
local factFrames: number? = nil
|
||||
local function u16(o: number): number
|
||||
return Riff.u16(f, o)
|
||||
end
|
||||
local function u32(o: number): number
|
||||
return Riff.u32(f, o)
|
||||
end
|
||||
local function i16(o: number): number
|
||||
local v = u16(o)
|
||||
return if v >= 32768 then v - 65536 else v
|
||||
end
|
||||
for _, c in f.chunks do
|
||||
local id, size, body, avail = c.id, c.size, c.offset, c.avail
|
||||
if id == "fmt " and avail >= 14 then
|
||||
fmt = {
|
||||
tag = u16(body),
|
||||
channels = u16(body + 2),
|
||||
rate = u32(body + 4),
|
||||
byteRate = u32(body + 8),
|
||||
blockAlign = u16(body + 12),
|
||||
bits = if avail >= 16 then u16(body + 14) else 8,
|
||||
body = body,
|
||||
avail = avail,
|
||||
}
|
||||
elseif id == "fact" and avail >= 4 then
|
||||
factFrames = u32(body)
|
||||
elseif id == "LIST" and Riff.listType(f, c) == "INFO" then
|
||||
for _, sc in Riff.list(f, c) do
|
||||
local name = INFO_TAGS[sc.id]
|
||||
if sc.avail > 0 then
|
||||
local v = trimTag(buffer.readstring(buf, sc.offset, sc.avail))
|
||||
if v ~= "" then
|
||||
tags[name or sc.id] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif id == "data" and dataOff < 0 then
|
||||
dataOff = body
|
||||
dataSize = avail
|
||||
truncated = c.truncated
|
||||
end
|
||||
local _ = size
|
||||
end
|
||||
|
||||
if not fmt then
|
||||
return nil, Err.new(Err.CORRUPT, "no fmt chunk")
|
||||
end
|
||||
if dataOff < 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no data chunk")
|
||||
end
|
||||
local tag, ch, rate, bits = fmt.tag, fmt.channels, fmt.rate, fmt.bits
|
||||
local channelMask: number? = nil
|
||||
local validBits: number? = nil
|
||||
if tag == 0xFFFE then
|
||||
if fmt.avail < 40 then
|
||||
return nil, Err.new(Err.CORRUPT, "WAVE_FORMAT_EXTENSIBLE without its extension")
|
||||
end
|
||||
local valid = u16(fmt.body + 18)
|
||||
channelMask = u32(fmt.body + 20)
|
||||
tag = u16(fmt.body + 24) -- the GUID's first two bytes are the format tag
|
||||
-- valid bits < container bits: the samples are left-justified, so decoding the container is right
|
||||
validBits = valid
|
||||
end
|
||||
if ch < 1 or ch > 255 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch)
|
||||
end
|
||||
if rate < 1 or rate > 4000000 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate)
|
||||
end
|
||||
local name: string? = FORMAT_NAMES[tag]
|
||||
if not name then
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("format 0x%04X", tag))
|
||||
end
|
||||
|
||||
local dec = setmetatable({}, Decoder) :: any
|
||||
dec.sampleRate = rate
|
||||
dec.channels = ch
|
||||
dec.tags = tags
|
||||
dec.format = name
|
||||
dec.formatTag = tag
|
||||
dec.bitsPerSample = bits
|
||||
dec.container = magic
|
||||
dec.dataOffset = dataOff
|
||||
dec.dataSize = dataSize
|
||||
dec.channelMask = channelMask
|
||||
dec._buf = buf
|
||||
dec._pos = 0
|
||||
dec._be = be
|
||||
dec._tmp = buffer.create(8)
|
||||
dec._cacheBlock = -1
|
||||
dec._cacheFrames = 0
|
||||
dec._ncoef = 0
|
||||
|
||||
local blockAlign: number = fmt.blockAlign
|
||||
local frames: number
|
||||
if name == "pcm" or name == "float" or name == "alaw" or name == "mulaw" then
|
||||
local bytes
|
||||
if name == "alaw" or name == "mulaw" then
|
||||
bytes = 1
|
||||
elseif name == "float" then
|
||||
if bits ~= 32 and bits ~= 64 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "float size " .. bits)
|
||||
end
|
||||
bytes = bits // 8
|
||||
else
|
||||
if bits < 1 or bits > 32 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "PCM size " .. bits)
|
||||
end
|
||||
-- container: from blockAlign when it is consistent, else from the bit depth
|
||||
bytes = (bits + 7) // 8
|
||||
if blockAlign >= ch and blockAlign % ch == 0 and blockAlign // ch >= bytes and blockAlign // ch <= 4 then
|
||||
bytes = blockAlign // ch
|
||||
end
|
||||
end
|
||||
blockAlign = bytes * ch
|
||||
dec._bytes = bytes
|
||||
dec._kind = name
|
||||
frames = dataSize // blockAlign
|
||||
dec._spb = 1
|
||||
elseif name == "ima_adpcm" or name == "ms_adpcm" then
|
||||
if blockAlign < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "ADPCM with blockAlign 0")
|
||||
end
|
||||
local spb = if fmt.avail >= 20 then u16(fmt.body + 18) else 0
|
||||
if name == "ima_adpcm" then
|
||||
if bits ~= 4 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM size " .. bits)
|
||||
end
|
||||
if blockAlign < 4 * ch then
|
||||
return nil, Err.new(Err.CORRUPT, "IMA ADPCM block too small")
|
||||
end
|
||||
local computed = (blockAlign - 4 * ch) * 2 // ch + 1
|
||||
if spb < 1 or spb > computed then
|
||||
spb = computed
|
||||
end
|
||||
else
|
||||
if blockAlign < 7 * ch then
|
||||
return nil, Err.new(Err.CORRUPT, "MS ADPCM block too small")
|
||||
end
|
||||
local computed = (blockAlign - 7 * ch) * 2 // ch + 2
|
||||
if spb < 2 or spb > computed then
|
||||
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 ncoef = 7
|
||||
if fmt.avail >= 22 then
|
||||
local k = u16(fmt.body + 20)
|
||||
if k >= 1 and k <= 256 and fmt.avail >= 22 + 4 * k then
|
||||
ncoef = k
|
||||
c1, c2 = {}, {}
|
||||
for i = 1, k do
|
||||
c1[i] = i16(fmt.body + 22 + (i - 1) * 4)
|
||||
c2[i] = i16(fmt.body + 24 + (i - 1) * 4)
|
||||
end
|
||||
end
|
||||
end
|
||||
local coefs = buffer.create(ncoef * 8)
|
||||
for i = 1, ncoef do
|
||||
buffer.writei32(coefs, (i - 1) * 8, c1[i])
|
||||
buffer.writei32(coefs, (i - 1) * 8 + 4, c2[i])
|
||||
end
|
||||
dec._coefs = coefs
|
||||
dec._ncoef = ncoef
|
||||
dec._state = buffer.create(20 * ch)
|
||||
end
|
||||
if spb * ch > 2 ^ 20 then
|
||||
return nil, Err.new(Err.LIMIT, "ADPCM block too large")
|
||||
end
|
||||
dec._kind = name
|
||||
dec._spb = spb
|
||||
dec._cache = buffer.create(spb * ch * 4)
|
||||
local full = dataSize // blockAlign
|
||||
frames = full * spb
|
||||
local rest = dataSize - full * blockAlign
|
||||
if rest > 0 then
|
||||
-- a partial last block: the frames it holds whole
|
||||
if name == "ima_adpcm" then
|
||||
if rest >= 4 * ch then
|
||||
frames += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8)
|
||||
end
|
||||
elseif rest >= 7 * ch then
|
||||
frames += math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch)
|
||||
end
|
||||
end
|
||||
-- fact: the true length (the last block is padded)
|
||||
if factFrames and factFrames > 0 and factFrames < frames then
|
||||
frames = factFrames
|
||||
end
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, "format " .. name)
|
||||
end
|
||||
if ds64Frames and ds64Frames > 0 and ds64Frames < frames then
|
||||
frames = ds64Frames
|
||||
end
|
||||
dec.blockAlign = blockAlign
|
||||
dec.frames = frames
|
||||
dec.duration = frames / rate
|
||||
dec.truncated = truncated
|
||||
dec.validBits = validBits
|
||||
dec.bitrate = if fmt.byteRate > 0 then fmt.byteRate * 8 else math.floor(rate * blockAlign * 8 / dec._spb)
|
||||
return dec, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- Decodes up to maxFrames frames from the current position. Returns a buffer of interleaved f32 samples
|
||||
-- (frames * channels values; `out` is reused when given and large enough) and the frame count (0 = end).
|
||||
function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, number)
|
||||
local ch = self.channels
|
||||
local req = math.floor(tonumber(maxFrames) or 0)
|
||||
if req ~= req then -- NaN (math.min / max treat it differently on LuaJIT)
|
||||
req = 0
|
||||
end
|
||||
local want = math.max(0, math.min(req, self.frames - self._pos))
|
||||
local dst: buffer = if out and type(out) == "buffer" and buffer.len(out) >= want * ch * 4
|
||||
then out
|
||||
else buffer.create(want * ch * 4)
|
||||
if want == 0 then
|
||||
return dst, 0
|
||||
end
|
||||
local kind = self._kind
|
||||
if self._spb == 1 then
|
||||
local off = self.dataOffset + self._pos * self.blockAlign
|
||||
local count = want * ch
|
||||
if kind == "pcm" then
|
||||
Codecs.int(self._buf, off, dst, 0, count, self._bytes, self._be)
|
||||
elseif kind == "float" then
|
||||
Codecs.float(self._buf, off, dst, 0, count, self._bytes, self._be, self._tmp)
|
||||
elseif kind == "alaw" then
|
||||
Codecs.law(self._buf, off, dst, 0, count, ALAW)
|
||||
else
|
||||
Codecs.law(self._buf, off, dst, 0, count, MULAW)
|
||||
end
|
||||
self._pos += want
|
||||
return dst, want
|
||||
end
|
||||
-- block formats: decode a block into the cache, copy out of it
|
||||
local spb, ba = self._spb, self.blockAlign
|
||||
local cache = self._cache :: buffer
|
||||
local done = 0
|
||||
while done < want do
|
||||
local block = self._pos // spb
|
||||
if block ~= self._cacheBlock then
|
||||
local off = self.dataOffset + block * ba
|
||||
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)
|
||||
else
|
||||
got = Codecs.msBlock(self._buf, off, avail, ch, spb, cache, self._coefs :: buffer, self._ncoef,
|
||||
self._state :: buffer)
|
||||
end
|
||||
self._cacheBlock = block
|
||||
self._cacheFrames = got
|
||||
end
|
||||
local inBlock = self._pos - block * spb
|
||||
local k = math.min(want - done, self._cacheFrames - inBlock)
|
||||
if k <= 0 then
|
||||
break
|
||||
end
|
||||
Codecs.copy(cache, inBlock * ch, dst, done * ch, k * ch)
|
||||
done += k
|
||||
self._pos += k
|
||||
end
|
||||
return dst, done
|
||||
end
|
||||
|
||||
-- Moves to a time in seconds (clamped to the stream).
|
||||
function Decoder.seek(self: Decoder, seconds: number)
|
||||
local f = math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)
|
||||
if f ~= f then
|
||||
f = 0
|
||||
end
|
||||
self._pos = math.clamp(f, 0, self.frames)
|
||||
end
|
||||
|
||||
-- Moves to a frame index (clamped).
|
||||
function Decoder.seekFrame(self: Decoder, frame: number)
|
||||
local f = math.floor(tonumber(frame) or 0)
|
||||
if f ~= f then
|
||||
f = 0
|
||||
end
|
||||
self._pos = math.clamp(f, 0, self.frames)
|
||||
end
|
||||
|
||||
-- Current position in seconds.
|
||||
function Decoder.position(self: Decoder): number
|
||||
return self._pos / self.sampleRate
|
||||
end
|
||||
|
||||
-- Current position in frames.
|
||||
function Decoder.tell(self: Decoder): number
|
||||
return self._pos
|
||||
end
|
||||
|
||||
return Wav
|
||||
Reference in new issue
Block a user