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:
4DBug committed 2026-10-31 08:34:39 -05:00
1 parent e3f9d0fb38
commit 85fb079068
9 files changed
+1989

No files matched your search

+12
View File
@@ -26,6 +26,18 @@ local list: { Entry } = {
return require("@formats/image/png")
end,
},
{
name = "wav",
category = "audio",
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" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
load = function()
return require("@formats/audio/wav")
end,
},
}
return list
+326
View File
@@ -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
+650
View File
@@ -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
+372
View File
@@ -0,0 +1,372 @@
--!strict
-- containers/Riff: the RIFF chunk container (RIFF, RIFX big-endian, RF64 / BW64 with the ds64 chunk), read leniently
-- and written. Shared by audio/wav and the other RIFF forms (AVI, WebP, ANI, ...). The chunk walker comes from
-- wav-luau fd9a909 (same author, no third-party code); the writer is new.
--
-- local f, err = Riff.read(r, { openEnded = { data = true } }) -- r: a core/Bytes Reader or a buffer
-- f.container, f.form, f.bigEndian -- "RIFF" | "RIFX" | "RF64", "WAVE", false
-- for _, c in f.chunks do print(c.id, c.offset, c.size, c.avail) end -- offsets are absolute in f.buf
-- local c = Riff.find(f, "fmt ")
-- local subs = Riff.list(f, c) -- the sub-chunks of a LIST body (after its type)
--
-- local w = Riff.writer("WAVE", { rf64 = "auto" }) -- or bigEndian = true (RIFX)
-- w:chunk("fmt ", fmtBody) w:chunk("data", samples) w:list("INFO", { { "INAM", "title" } })
-- local file = w:finish() -- RF64 + ds64 when a size passes 4 GiB
-- local parts = w:finish({ parts = true }) -- { buffer }: no copy, for files over 1 GiB
--
-- Lenient reading (what real files need): an odd-sized chunk without its pad byte is detected; a chunk declared past
-- the end keeps what is there (avail < size, truncated = true) and ends the walk; for the ids in opts.openEnded a
-- size of 0 or 0xFFFFFFFF means "up to the end of the file" (streamed writers) and ends the walk; RF64 sizes of
-- 0xFFFFFFFF come from the ds64 chunk (and its table). Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring
local Riff = {}
export type Chunk = {
id: string,
offset: number, -- absolute offset of the body in the file's buffer
size: number, -- declared size (ds64-resolved), or what is available for open-ended / truncated chunks
declared: number, -- the raw size field
avail: number, -- body bytes present in the file (<= size)
truncated: boolean, -- declared past the end of the file
streamed: boolean, -- an open-ended chunk (size 0 / 0xFFFFFFFF up to the end)
}
export type File = {
container: string, -- "RIFF" | "RIFX" | "RF64" (BW64 reads as RF64)
form: string, -- the form type: "WAVE", "AVI ", "WEBP", ...
bigEndian: boolean,
buf: buffer,
base: number, -- absolute offset of the file's first byte
limit: number, -- absolute offset past its last byte
size: number, -- the RIFF size field (ds64-resolved)
chunks: { Chunk },
ds64: { riffSize: number, dataSize: number, sampleCount: number, table: { [string]: number } }?,
}
export type ReadOptions = {
openEnded: { [string]: boolean }?, -- chunk ids whose size 0 / 0xFFFFFFFF means "to the end" (wav: data)
maxChunks: number?, -- stop after this many chunks (default 100000)
}
-- ------------------------------------------------------------------------------------------------ read
local function printable4(b: buffer, p: number, limit: number): boolean
if p + 4 > limit then
return false
end
for i = 0, 3 do
local c = readu8(b, p + i)
if c < 32 or c > 126 then
return false
end
end
return true
end
local function u32(b: buffer, o: number, be: boolean): number
local v = readu32(b, o)
return if be then bit32.byteswap(v) else v
end
-- sniff(r) -> the form type ("WAVE", ...) when r starts with a RIFF / RIFX / RF64 / BW64 header, else nil
function Riff.sniff(r: any): string?
local magic = r:peek(4)
if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then
return nil
end
local form = r:peek(4, 8)
return if #form == 4 then form else nil
end
-- walk the chunks of [p, limit) into list; returns the list
local function walk(b: buffer, p: number, limit: number, be: boolean, opts: ReadOptions?, ds64: any, list: { Chunk }): { Chunk }
local openEnded = opts and opts.openEnded
local maxChunks = opts and opts.maxChunks or 100000
while p + 8 <= limit and #list < maxChunks do
local id = readstring(b, p, 4)
local declared = u32(b, p + 4, be)
local size = declared
local body = p + 8
local avail = limit - body
if declared == 0xFFFFFFFF and ds64 then
if id == "data" then
size = ds64.dataSize
elseif ds64.table[id] then
size = ds64.table[id]
end
end
local c: Chunk = { id = id, offset = body, size = size, declared = declared, avail = math.min(size, avail), truncated = false, streamed = false }
table.insert(list, c)
if openEnded and openEnded[id] and (size == 0 or size == 0xFFFFFFFF or size > avail) then
c.streamed = size == 0 or size == 0xFFFFFFFF
c.truncated = not c.streamed
c.size, c.avail = avail, avail
break
end
if size > avail then
c.truncated = true
break
end
local nextPos = body + size + size % 2
-- an odd-sized chunk written without its pad byte: the next id starts right after the body
if size % 2 == 1 and not printable4(b, nextPos, limit) and printable4(b, body + size, limit) then
nextPos = body + size
end
p = nextPos
end
return list
end
-- read(src, opts?) -> File | nil, Err. src: a core/Bytes Reader (its range) or a buffer.
function Riff.read(src: any, opts: ReadOptions?): (File?, Err.Err?)
local r = if type(src) == "buffer" then Bytes.reader(src) else src
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "read: expected a buffer or a Reader")
end
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 12 then
return nil, Err.new(Err.TRUNCATED, "file too short for a RIFF header", base)
end
local magic = readstring(b, base, 4)
if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then
return nil, Err.new(Err.CORRUPT, "not a RIFF / RIFX / RF64 file", base)
end
local be = magic == "RIFX"
local f: File = {
container = if magic == "BW64" then "RF64" else magic,
form = readstring(b, base + 8, 4),
bigEndian = be,
buf = b,
base = base,
limit = limit,
size = u32(b, base + 4, be),
chunks = {},
ds64 = nil,
}
-- RF64: the ds64 chunk comes first
if f.container == "RF64" and base + 20 <= limit and readstring(b, base + 12, 4) == "ds64" then
local sz = readu32(b, base + 16)
local o = base + 20
if sz >= 24 and o + 24 <= limit then
local d = {
riffSize = readu32(b, o) + readu32(b, o + 4) * 4294967296,
dataSize = readu32(b, o + 8) + readu32(b, o + 12) * 4294967296,
sampleCount = readu32(b, o + 16) + readu32(b, o + 20) * 4294967296,
table = {} :: { [string]: number },
}
if sz >= 28 and o + 28 <= limit then
local n = readu32(b, o + 24)
local q = o + 28
for _ = 1, math.min(n, 1000) do
if q + 12 > limit or q + 12 > o + sz then
break
end
d.table[readstring(b, q, 4)] = readu32(b, q + 4) + readu32(b, q + 8) * 4294967296
q += 12
end
end
f.ds64 = d
if f.size == 0xFFFFFFFF then
f.size = d.riffSize
end
end
end
walk(b, base + 12, limit, be, opts, f.ds64, f.chunks)
return f, nil
end
-- find(file, id, from?) -> the first chunk with that id (after index from), and its index
function Riff.find(f: File, id: string, from: number?): (Chunk?, number?)
for i = (from or 0) + 1, #f.chunks do
if f.chunks[i].id == id then
return f.chunks[i], i
end
end
return nil, nil
end
-- listType(file, chunk) -> the 4-byte type of a LIST / RIFF chunk ("INFO", "movi", ...) or nil
function Riff.listType(f: File, c: Chunk): string?
if c.avail < 4 then
return nil
end
return readstring(f.buf, c.offset, 4)
end
-- list(file, chunk, opts?) -> the sub-chunks of a LIST body (after its 4-byte type)
function Riff.list(f: File, c: Chunk, opts: ReadOptions?): { Chunk }
if c.avail < 4 then
return {}
end
return walk(f.buf, c.offset + 4, c.offset + c.avail, f.bigEndian, opts, nil, {})
end
-- body(file, chunk) -> a Reader over the chunk's available body
function Riff.body(f: File, c: Chunk): Bytes.Reader
return Bytes.reader(f.buf, c.offset, c.avail)
end
-- u16 / u32 in the file's byte order (for chunk bodies)
function Riff.u16(f: File, o: number): number
if f.bigEndian then
return readu8(f.buf, o) * 256 + readu8(f.buf, o + 1)
end
return readu16(f.buf, o)
end
function Riff.u32(f: File, o: number): number
return u32(f.buf, o, f.bigEndian)
end
-- ------------------------------------------------------------------------------------------------ write
local Writer = {}
Writer.__index = Writer
export type WriteOptions = {
bigEndian: boolean?, -- RIFX (default false)
rf64: (boolean | "auto")?, -- true: always RF64; false: never (sizes over 4 GiB are an error); default "auto"
sampleCount: number?, -- the ds64 sample count (RF64 WAVE: frames)
rf64Threshold: number?, -- "auto" switches to RF64 when the RIFF size would pass this (default 0xFFFFFFFF)
}
-- writer(form, opts?) -> Writer: collects chunks; finish() lays out the file
function Riff.writer(form: string, opts: WriteOptions?): any
return setmetatable({
form = string.sub(form .. " ", 1, 4),
be = opts and opts.bigEndian or false,
rf64 = if opts and opts.rf64 ~= nil then opts.rf64 else "auto",
sampleCount = opts and opts.sampleCount or 0,
threshold = opts and opts.rf64Threshold or 0xFFFFFFFF,
chunks = {} :: { any },
}, Writer)
end
-- chunk(id, body, offset?, length?): body is a buffer or a string (a range of a buffer with offset / length), or a
-- list of buffers written one after the other (a data chunk bigger than one buffer)
function Writer.chunk(self: any, id: string, body: any, offset: number?, length: number?)
local parts = {}
local n = 0
if type(body) == "table" then
for _, b in body do
table.insert(parts, { b, 0, buffer.len(b) })
n += buffer.len(b)
end
else
local b: buffer = if type(body) == "string" then buffer.fromstring(body) else body
local o = offset or 0
n = length or (buffer.len(b) - o)
parts[1] = { b, o, n }
end
table.insert(self.chunks, { id = string.sub(id .. " ", 1, 4), parts = parts, length = n })
end
-- list(type, items): a LIST chunk of { id, string-or-buffer } sub-chunks (strings get a NUL terminator, INFO style)
function Writer.list(self: any, listType: string, items: { { any } })
local w = Bytes.writer()
w:string(string.sub(listType .. " ", 1, 4))
for _, it in items do
local v = it[2]
local data: buffer = if type(v) == "string" then buffer.fromstring(v .. "\0") else v
local n = buffer.len(data)
w:string(string.sub(it[1] .. " ", 1, 4))
if self.be then
w:u32be(n)
else
w:u32le(n)
end
w:bytes(data)
if n % 2 == 1 then
w:u8(0)
end
end
self:chunk("LIST", w:finish())
end
-- finish(opts?) -> buffer | nil, Err; with opts.parts: { buffer } (the header pieces and the chunk bodies, not copied)
function Writer.finish(self: any, opts: { parts: boolean? }?): (any, Err.Err?)
local total = 4 -- the form type
local big = false
local dataSize = 0
for _, c in self.chunks do
total += 8 + c.length + c.length % 2
if c.length > 0xFFFFFFFE then
big = true
end
if c.id == "data" then
dataSize = c.length
end
end
local rf64 = self.rf64 == true or (self.rf64 == "auto" and (big or total > self.threshold))
if not rf64 and (big or total > 0xFFFFFFFF) then
return nil, Err.new(Err.LIMIT, "over 4 GiB without RF64")
end
if rf64 and self.be then
return nil, Err.new(Err.ARG, "RF64 is little-endian only")
end
if rf64 then
total += 36 -- ds64
end
local asParts = opts and opts.parts
if not asParts and total + 8 > 0x40000000 then
return nil, Err.new(Err.LIMIT, "the file would not fit in a buffer (1 GiB): use finish({ parts = true })")
end
local out: { buffer } = {}
local w = Bytes.writer(if asParts then 256 else total + 8)
local function size32(v: number)
if self.be then
w:u32be(v)
else
w:u32le(v)
end
end
if rf64 then
w:string("RF64")
w:u32le(0xFFFFFFFF)
w:string(self.form)
w:string("ds64")
w:u32le(28)
w:u64le(total)
w:u64le(dataSize)
w:u64le(self.sampleCount)
w:u32le(0) -- no table: only data may be over 4 GiB
else
w:string(if self.be then "RIFX" else "RIFF")
size32(total)
w:string(self.form)
end
for _, c in self.chunks do
w:string(c.id)
if rf64 and (c.id == "data" or c.length > 0xFFFFFFFE) then
w:u32le(0xFFFFFFFF)
else
size32(c.length)
end
for _, p in c.parts do
if asParts then
table.insert(out, w:finish())
w = Bytes.writer(64)
if p[2] == 0 and p[3] == buffer.len(p[1]) then
table.insert(out, p[1])
else
local cp = buffer.create(p[3])
buffer.copy(cp, 0, p[1], p[2], p[3])
table.insert(out, cp)
end
else
w:bytes(p[1], p[2], p[3])
end
end
if c.length % 2 == 1 then
w:u8(0)
end
end
if asParts then
if w:tell() > 0 then
table.insert(out, w:finish())
end
return out, nil
end
return w:finish(), nil
end
return Riff