diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..a2bd562 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index bc841c1..c47d098 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -5,6 +5,7 @@ | `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) | | `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code | | `src/Formats/containers/Ogg/` (init, Page) | ogg-luau be9f604 (same author), written from RFC 3533 | no licence chosen yet; no third-party code | +| `src/Formats/audio/wav/`, `src/Formats/containers/Riff/` (the chunk walker) | wav-luau fd9a909 (same author), written from the RIFF / WAVE / RF64 (EBU Tech 3306) specifications | no licence chosen yet; no third-party code | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..92c1b11 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -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 diff --git a/src/Formats/audio/wav/Codecs.luau b/src/Formats/audio/wav/Codecs.luau new file mode 100644 index 0000000..4094c07 --- /dev/null +++ b/src/Formats/audio/wav/Codecs.luau @@ -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 diff --git a/src/Formats/audio/wav/init.luau b/src/Formats/audio/wav/init.luau new file mode 100644 index 0000000..81ef5b4 --- /dev/null +++ b/src/Formats/audio/wav/init.luau @@ -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 diff --git a/src/Formats/containers/Riff/init.luau b/src/Formats/containers/Riff/init.luau new file mode 100644 index 0000000..63fd4d1 --- /dev/null +++ b/src/Formats/containers/Riff/init.luau @@ -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 diff --git a/tests/audio/wav.luau b/tests/audio/wav.luau new file mode 100644 index 0000000..dda6de4 --- /dev/null +++ b/tests/audio/wav.luau @@ -0,0 +1,314 @@ +-- audio/wav tests: every format / container / damaged variant from tools/fixtures/wav.py decoded in reads of mixed +-- sizes against ffmpeg's (or sox's) f32 decode, with tags, seeking and output-buffer reuse; hand-built files (header +-- parsing, errors, argument clamping, EXTENSIBLE with valid bits, the truncated flag); the encoder byte-exact against +-- ffmpeg -bitexact (u8 / s16 / s24 / s32 / f32, 1-8 channels, > 48 kHz, RF64), round trips from an Audio and from a +-- streaming Decoder, tags, encodeParts, the RF64 switch; the api (F.audio.load / open / save); the fuzz pass. +-- Ported from wav-luau tests/core.luau + tests/decode.luau. Fixtures: tools/fixtures/wav.py. +local T = require("@tests/T") +local Wav = require("@formats/audio/wav") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local F = require("@formats") +local Cases = require("@tests/gen/wav_cases") +local Enc = require("@tests/gen/wav_enc") + +local t = T.suite("wav") +local TOL = 2e-6 + +local function open(s: any): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Wav.open(Bytes.reader(b)) +end + +-- little-endian packers (no string.pack on LuaJIT) +local function u16(v: number): string + local b = buffer.create(2) + buffer.writeu16(b, 0, v % 65536) + return buffer.tostring(b) +end +local function u32(v: number): string + local b = buffer.create(4) + buffer.writeu32(b, 0, v % 4294967296) + return buffer.tostring(b) +end +local function i32(v: number): string + local b = buffer.create(4) + buffer.writei32(b, 0, v) + return buffer.tostring(b) +end +local function f32(v: number): string + local b = buffer.create(4) + buffer.writef32(b, 0, v) + return buffer.tostring(b) +end +local function i16s(...: number): string + local out = {} + for i, v in { ... } do + out[i] = u16(if v < 0 then v + 65536 else v) + end + return table.concat(out) +end + +local function chunk(id: string, body: string): string + local s = id .. u32(#body) .. body + return if #body % 2 == 1 then s .. "\0" else s +end +local function fmt(tag: number, ch: number, rate: number, bits: number, extra: string?): string + local ba = ch * ((bits + 7) // 8) + return chunk("fmt ", u16(tag) .. u16(ch) .. u32(rate) .. u32(rate * ba) .. u16(ba) .. u16(bits) .. (extra or "")) +end +local function riff(...: string): string + local body = "WAVE" .. table.concat({ ... }) + return "RIFF" .. u32(#body) .. body +end + +-- the contract +t:eq(Wav.name, "wav", "name") +t:eq(Wav.category, "audio", "category") +t:check(Wav.caps.decode and Wav.caps.encode and Wav.open ~= nil, "caps / open") + +-- ------------------------------------------------------------------------------------------------ fixtures +local function readAll(dec: any, sizes: { number }): (buffer, number) + local out = buffer.create(dec.frames * dec.channels * 4) + local got, i = 0, 0 + while true do + i += 1 + local c, n = dec:read(sizes[(i - 1) % #sizes + 1]) + if n == 0 then + break + end + buffer.copy(out, got * dec.channels * 4, c, 0, n * dec.channels * 4) + got += n + end + return out, got +end +local function maxDiff(a: buffer, aOff: number, b: buffer, bOff: number, count: number): number + local m = 0 + for i = 0, count - 1 do + local d = math.abs(buffer.readf32(a, (aOff + i) * 4) - buffer.readf32(b, (bOff + i) * 4)) + if d > m then + m = d + end + end + return m +end + +local samples = {} +for _, fx in Cases do + local name = fx.name + table.insert(samples, fx.file) + local ref = buffer.fromstring(fx.ref) + local dec, err = open(fx.file) + t:check(dec, name .. ": open: " .. tostring(err)) + t:eq(dec.channels, fx.channels, name .. ": channels") + t:eq(dec.sampleRate, fx.rate, name .. ": rate") + t:eq(dec.format, fx.format, name .. ": format") + t:eq(dec.container, fx.container, name .. ": container") + t:eq(dec.frames, fx.frames, name .. ": frames") + t:check(math.abs(dec.duration - fx.frames / fx.rate) < 1e-9, name .. ": duration") + t:check(dec.bitrate > 0, name .. ": bitrate") + for k, v in fx.tags or {} do + t:eq(dec.tags[k], v, name .. ": tag " .. k) + end + local out, got = readAll(dec, { 1, 7, 333, 1000, 4096 }) + t:eq(got, fx.frames, name .. ": frames read") + local d = maxDiff(out, 0, ref, 0, got * fx.channels) + t:check(d <= TOL, string.format("%s: max sample error %g", name, d)) + t:eq(dec:position(), fx.frames / fx.rate, name .. ": position at the end") + for _, f0 in { 1234, 0, fx.frames - 20, 517, 2047 } do + local f = math.min(f0, fx.frames) + dec:seek(f / fx.rate) + t:eq(dec:tell(), f, name .. ": seek to " .. f) + local c, n = dec:read(50) + t:eq(n, math.min(50, fx.frames - f), name .. ": read after seek " .. f) + t:check(maxDiff(c, 0, ref, f * fx.channels, n * fx.channels) <= TOL, name .. ": samples after seek " .. f) + end + dec:seek(0) + local reuse = buffer.create(64 * fx.channels * 4) + local b2, n2 = dec:read(64, reuse) + t:check(b2 == reuse and n2 == 64, name .. ": output buffer reused") + -- decode() = the whole stream as an Audio, also from a sub-range reader + local big = buffer.create(#fx.file + 9) + buffer.writestring(big, 5, fx.file) + local a, aerr = Wav.decode(Bytes.reader(big, 5, #fx.file)) + t:check(a and a.kind == "audio" and a.frames == fx.frames, name .. ": decode: " .. tostring(aerr)) + t:check(maxDiff(a.samples, 0, ref, 0, a.frames * fx.channels) <= TOL, name .. ": decode samples") + t:eq(a.meta.source.codec, fx.format, name .. ": meta.source.codec") +end +t:note("%d fixture files match ffmpeg / sox", #Cases) + +-- ------------------------------------------------------------------------------------------------ hand-built files +do + local dec = open(riff(fmt(1, 2, 8000, 16), chunk("data", i16s(16384, -16384, 32767, -32768)))) + t:check(dec, "open minimal") + t:check(dec.frames == 2 and dec.channels == 2 and dec.sampleRate == 8000 and dec.bitrate == 8000 * 4 * 8, "minimal fields") + t:check(dec.duration == 2 / 8000 and dec.blockAlign == 4 and dec.bitsPerSample == 16 and not dec.truncated, "minimal more") + local out, n = dec:read(10) + t:eq(n, 2, "read clamps to the stream") + t:check(buffer.readf32(out, 0) == 0.5 and buffer.readf32(out, 4) == -0.5, "s16 values") + t:check(buffer.readf32(out, 8) == 32767 / 32768 and buffer.readf32(out, 12) == -1, "s16 extremes") + t:eq(select(2, dec:read(10)), 0, "end of stream = 0 frames") + dec:seek(-5) + t:eq(dec:tell(), 0, "seek negative") + dec:seek(1e9) + t:eq(dec:tell(), 2, "seek past the end") + dec:seek(0 / 0) + t:eq(dec:tell(), 0, "seek NaN") + dec:seekFrame(1) + t:eq(dec:position(), 1 / 8000, "seekFrame / position") + t:eq(select(2, dec:read(-3)), 0, "read negative") + t:eq(select(2, dec:read(0 / 0)), 0, "read NaN") + local b, n5 = dec:read(1, buffer.create(2)) + t:check(n5 == 1 and buffer.len(b) == 8, "too-small output buffer is replaced") +end +do + local dec = open(riff(fmt(1, 1, 8000, 16), "data" .. u32(1000) .. i16s(1, 2, 3) .. "\9")) + t:check(dec and dec.frames == 3 and dec.truncated, "truncated: whole frames, flagged") +end +do -- EXTENSIBLE: 24 valid bits in a 32-bit container + local guid = u16(1) .. "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" + local ext = u16(22) .. u16(24) .. u32(3) .. guid + local dec = open(riff(fmt(0xFFFE, 2, 48000, 32, ext), chunk("data", i32(0x40000000) .. i32(-0x40000000)))) + t:check(dec and dec.format == "pcm" and dec.validBits == 24 and dec.channelMask == 3, "extensible fields") + local out = dec:read(1) + t:check(buffer.readf32(out, 0) == 0.5 and buffer.readf32(out, 4) == -0.5, "extensible values") + local guidF = u16(3) .. string.sub(guid, 3) + local fd = open(riff(fmt(0xFFFE, 1, 48000, 32, u16(22) .. u16(32) .. u32(4) .. guidF), chunk("data", f32(0.25)))) + t:check(fd and fd.format == "float" and buffer.readf32(fd:read(1), 0) == 0.25, "extensible float") + local _, e = open(riff(fmt(0xFFFE, 1, 8000, 16), chunk("data", "\0\0"))) + t:check(e and e.code == Err.CORRUPT, "extensible without extension") +end +do -- tags + local info = "INFO" .. "INAM" .. u32(3) .. "abc\0" .. "IART" .. u32(6) .. "xy\0\0\0\0" .. "IXYZ" .. u32(2) .. "zz" .. "ITRK" .. u32(2) .. "7\0" + local dec = open(riff(fmt(1, 1, 8000, 8), chunk("LIST", info), chunk("data", "\128\128\128"))) + t:check(dec and dec.tags.title == "abc" and dec.tags.artist == "xy" and dec.tags.IXYZ == "zz" and dec.tags.track == "7", "tags") + t:check(dec and dec.frames == 3, "8-bit odd data") +end +do -- 8-bit, A-law and mu-law values + local o = open(riff(fmt(1, 1, 8000, 8), chunk("data", "\0\128\255"))):read(3) + t:check(buffer.readf32(o, 0) == -1 and buffer.readf32(o, 4) == 0 and buffer.readf32(o, 8) == 127 / 128, "u8 values") + local m = open(riff(fmt(7, 1, 8000, 8), chunk("data", "\255\127\0\128"))):read(4) + t:check(buffer.readf32(m, 0) == 0 and buffer.readf32(m, 4) == 0, "mu-law zero") + t:check(buffer.readf32(m, 8) == -32124 / 32768 and buffer.readf32(m, 12) == 32124 / 32768, "mu-law extremes") + local a = open(riff(fmt(6, 1, 8000, 8), chunk("data", "\213\85\42\170"))):read(4) + t:check(buffer.readf32(a, 0) == 8 / 32768 and buffer.readf32(a, 4) == -8 / 32768, "A-law smallest") + t:check(buffer.readf32(a, 8) == -32256 / 32768 and buffer.readf32(a, 12) == 32256 / 32768, "A-law extremes") +end +do -- errors: nil, Err + local function fails(s: any, code: string, pattern: string, label: string) + local ok, dec, err = pcall(open, s) + t:check(ok, label .. ": threw " .. tostring(dec)) + t:check(dec == nil and Err.is(err) and err.code == code and string.find(err.message, pattern) ~= nil, label .. ": " .. tostring(err)) + end + fails("RIFF", Err.TRUNCATED, "too short", "too short") + fails("RIFF\0\0\0\0AVI LIST", Err.CORRUPT, "not a WAVE", "AVI") + fails("OggS\0\0\0\0WAVEfmt ", Err.CORRUPT, "not a RIFF", "ogg") + fails(riff(chunk("data", "\0\0")), Err.CORRUPT, "no fmt", "no fmt") + fails(riff(fmt(1, 2, 8000, 16)), Err.CORRUPT, "no data", "no data") + fails(riff(fmt(0x55, 2, 8000, 16), chunk("data", "")), Err.UNSUPPORTED, "format 0x0055", "mp3 in wav") + fails(riff(fmt(1, 0, 8000, 16), chunk("data", "")), Err.CORRUPT, "channel", "0 channels") + fails(riff(fmt(1, 1, 0, 16), chunk("data", "")), Err.CORRUPT, "sample rate", "rate 0") + fails(riff(fmt(3, 1, 8000, 16), chunk("data", "")), Err.UNSUPPORTED, "float size", "float16") + fails(riff(fmt(1, 1, 8000, 40), chunk("data", "")), Err.UNSUPPORTED, "PCM size", "pcm 40") + fails(riff(fmt(0x11, 2, 8000, 4), chunk("data", "")), Err.CORRUPT, "block", "ima block too small") + t:eq(Wav.sniff(Bytes.reader(buffer.fromstring(riff(fmt(1, 1, 8000, 8))))), 1, "sniff") + t:eq(Wav.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0AVI "))), 0, "sniff AVI") +end + +-- ------------------------------------------------------------------------------------------------ encoder +do + for _, c in Enc do + local a = Types.Audio.new(c.rate, c.channels, c.frames) + buffer.writestring(a.samples, 0, c.samples) + local out, err = Wav.encode(a, { sampleFormat = c.kind, rf64 = if c.rf64 then true else nil }) + t:check(out, c.name .. ": encode: " .. tostring(err)) + local same = buffer.tostring(out :: buffer) == c.file + if not same then + t:note("%s: ours %s", c.name, T.hex(out :: buffer, 80)) + t:note("%s: ffmpeg %s", c.name, T.hex(buffer.fromstring(c.file), 80)) + end + t:check(same, c.name .. ": identical to ffmpeg -bitexact") + -- and back + local back = Wav.decode(Bytes.reader(out :: buffer)) + t:check(back and back.frames == c.frames and buffer.tostring(back.samples) == c.samples, c.name .. ": round trip") + -- from a streaming Decoder (our own, over ffmpeg's file) + local dec = Wav.open(Bytes.reader(buffer.fromstring(c.file))) + local out2 = Wav.encode(dec, { sampleFormat = c.kind, rf64 = if c.rf64 then true else nil }) + t:check(out2 and buffer.tostring(out2) == c.file, c.name .. ": encode from a Decoder") + end + t:note("encoder: %d files identical to ffmpeg -bitexact", #Enc) + -- clamping and rounding + local a = Types.Audio.new(8000, 1, 6) + for i, v in { 2, -2, 0.5 / 32768, -0.5 / 32768, 1.5 / 32768, 0 / 0 } do + buffer.writef32(a.samples, (i - 1) * 4, v) + end + local d = Wav.decode(Bytes.reader(Wav.encode(a) :: buffer)) :: any + local want = { 32767, -32768, 1, 0, 2, 0 } + for i, w in want do + t:eq(math.floor(buffer.readf32(d.samples, (i - 1) * 4) * 32768 + 0.5), w, "s16 rounding / clamping " .. i) + end + -- tags + a.tags = { title = "Hello", artist = "Someone", IXYZ = "kept", comment = "" } + local tg = Wav.decode(Bytes.reader(Wav.encode(a, { sampleFormat = "u8" }) :: buffer)) :: any + t:check(tg.tags.title == "Hello" and tg.tags.artist == "Someone" and tg.tags.IXYZ == "kept" and tg.tags.comment == nil, "tag round trip") + -- encodeParts, and RF64 chosen automatically past the threshold + local big = Types.Audio.new(44100, 2, 3000) + for i = 0, 3000 * 2 - 1 do + buffer.writef32(big.samples, i * 4, ((i * 37) % 200 - 100) / 128) + end + local parts = Wav.encodeParts(big, { rf64Threshold = 1000 }) :: { buffer } + t:check(#parts >= 2, "encodeParts: pieces") + local w = Bytes.writer() + for _, p in parts do + w:bytes(p) + end + local joined = w:finish() + t:eq(buffer.readstring(joined, 0, 4), "RF64", "auto RF64 past the threshold") + local rd = Wav.open(Bytes.reader(joined)) :: any + t:check(rd.container == "RF64" and rd.frames == 3000, "RF64 reads back") + t:check(buffer.tostring(rd:read(3000)) == buffer.tostring(Wav.decode(Bytes.reader(Wav.encode(big) :: buffer)).samples), "RF64 samples") + t:eq(buffer.readstring(Wav.encode(big) :: buffer, 0, 4), "RIFF", "plain RIFF below the threshold") + -- bad arguments + local _, e1 = Wav.encode({} :: any) + t:check(e1 and e1.code == Err.ARG, "encode {}: " .. tostring(e1)) + local _, e2 = Wav.encode(a, { sampleFormat = "s12" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat") + local bad = Types.Audio.new(8000, 2, 10) + bad.frames = 99 + local _, e3 = Wav.encode(bad) + t:check(e3 and e3.code == Err.ARG, "short samples buffer") +end + +-- ------------------------------------------------------------------------------------------------ api +do + local c = Enc[1] + local a, err = F.audio.load(c.file) + t:check(a and a.kind == "audio" and a.frames == c.frames, "F.audio.load: " .. tostring(err)) + local dec = F.audio.open(c.file) + t:check(dec and dec.sampleRate == c.rate and type(dec.read) == "function", "F.audio.open") + local out = F.save(a, nil, { format = "wav", sampleFormat = "s16" }) + t:check(out and buffer.tostring(out) == c.file, "F.save wav") + t:eq(F.detect(c.file), "wav", "F.detect") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +t:fuzz("open + read + seek", function(b: buffer) + local dec = Wav.open(Bytes.reader(b)) + if dec then + for _ = 1, 100 do + local _, n = dec:read(1000) + if n == 0 then + break + end + end + dec:seek(dec.duration / 2) + dec:read(17) + end + return dec +end, samples, { mutations = 12 }) +t:fuzz("header mutations", function(b: buffer) + return Wav.decode(Bytes.reader(b)) +end, samples, { mutations = 6, garbage = 50, keepHeader = 0 }) + +t:done() diff --git a/tests/containers/riff.luau b/tests/containers/riff.luau new file mode 100644 index 0000000..82c8cf3 --- /dev/null +++ b/tests/containers/riff.luau @@ -0,0 +1,114 @@ +-- containers/Riff tests: the writer (RIFF, RIFX, forced RF64 with ds64, LIST/INFO, odd pad bytes, parts) read back by +-- the reader; lenient reading (missing pad byte, truncated chunk, open-ended data of size 0 / 0xFFFFFFFF, the ds64 +-- table, a sub-range Reader); errors; the fuzz pass. The WAVE form is checked against ffmpeg in tests/audio/wav.luau. +local T = require("@tests/T") +local Riff = require("@formats/containers/Riff") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") + +local t = T.suite("riff") + +local function u32(v: number): string + local b = buffer.create(4) + buffer.writeu32(b, 0, v) + return buffer.tostring(b) +end + +-- writer -> reader +local samples = {} +for _, mode in { "riff", "rifx", "rf64" } do + local w = Riff.writer("TEST", { bigEndian = mode == "rifx", rf64 = mode == "rf64", sampleCount = 77 }) + w:chunk("abcd", "odd") + w:chunk("efgh", buffer.fromstring("xxevenxx"), 2, 4) + w:list("INFO", { { "INAM", "name" }, { "IART", buffer.fromstring("raw") } }) + w:chunk("data", { buffer.fromstring("12345"), buffer.fromstring("678") }) + local file = w:finish() :: buffer + table.insert(samples, buffer.tostring(file)) + local f, err = Riff.read(Bytes.reader(file)) + t:check(f, mode .. ": read: " .. tostring(err)) + t:eq(f.container, if mode == "rifx" then "RIFX" elseif mode == "rf64" then "RF64" else "RIFF", mode .. ": container") + t:eq(f.form, "TEST", mode .. ": form") + t:eq(f.size, buffer.len(file) - 8, mode .. ": RIFF size") + local ids = {} + for _, c in f.chunks do + table.insert(ids, c.id) + end + t:eq(table.concat(ids, ","), if mode == "rf64" then "ds64,abcd,efgh,LIST,data" else "abcd,efgh,LIST,data", mode .. ": chunks") + local a = Riff.find(f, "abcd") :: any + t:check(a.size == 3 and buffer.readstring(file, a.offset, 3) == "odd", mode .. ": odd chunk") + local e = Riff.find(f, "efgh") :: any + t:eq(buffer.readstring(file, e.offset, e.size), "even", mode .. ": range chunk") + local l = Riff.find(f, "LIST") :: any + t:eq(Riff.listType(f, l), "INFO", mode .. ": list type") + local subs = Riff.list(f, l) + t:check(#subs == 2 and subs[1].id == "INAM" and buffer.readstring(file, subs[1].offset, subs[1].size) == "name\0", mode .. ": INFO item") + t:check(subs[2].size == 3 and subs[2].avail == 3, mode .. ": raw item") + local d = Riff.find(f, "data") :: any + t:check(d.size == 8 and buffer.readstring(file, d.offset, 8) == "12345678", mode .. ": data parts") + t:eq(buffer.tostring(Riff.body(f, d):bytes(8)), "12345678", mode .. ": body reader") + if mode == "rf64" then + t:check(f.ds64 and f.ds64.dataSize == 8 and f.ds64.sampleCount == 77 and d.declared == 0xFFFFFFFF, "rf64: ds64") + end + -- parts: the same bytes + local parts = w:finish({ parts = true }) :: { buffer } + local j = Bytes.writer() + for _, p in parts do + j:bytes(p) + end + t:check(buffer.tostring(j:finish()) == buffer.tostring(file), mode .. ": parts join to the file") +end +t:check(not Riff.writer("WAVE", { bigEndian = true, rf64 = true }):finish(), "RIFX RF64 refused") + +-- lenient reading +do + -- a missing pad byte after an odd chunk + local body = "WAVE" .. "abcd" .. u32(5) .. "12345" .. "next" .. u32(2) .. "ok" + local f = Riff.read(buffer.fromstring("RIFF" .. u32(#body) .. body)) :: any + t:check(#f.chunks == 2 and f.chunks[2].id == "next", "missing pad byte detected") + -- truncated + local tb = "WAVE" .. "data" .. u32(100) .. "short" + local ft = Riff.read(buffer.fromstring("RIFF" .. u32(#tb) .. tb)) :: any + t:check(ft.chunks[1].truncated and ft.chunks[1].avail == 5 and ft.chunks[1].size == 100, "truncated chunk") + -- open-ended + for _, sz in { 0, 0xFFFFFFFF } do + local ob = "WAVE" .. "data" .. u32(sz) .. "abcdefLIST" + local fo = Riff.read(buffer.fromstring("RIFF" .. u32(0) .. ob), { openEnded = { data = true } }) :: any + t:check(#fo.chunks == 1 and fo.chunks[1].streamed and fo.chunks[1].size == 10, "open-ended data " .. sz) + end + -- ds64 table + local ds = "ds64" .. u32(40) .. u32(0) .. u32(0) .. u32(4) .. u32(0) .. u32(0) .. u32(0) .. u32(1) .. "big " .. u32(3) .. u32(0) + local rb = "WAVE" .. ds .. "big " .. u32(0xFFFFFFFF) .. "xyz" .. "\0" + local fr = Riff.read(buffer.fromstring("RF64" .. u32(0xFFFFFFFF) .. rb)) :: any + t:check(fr.ds64 and fr.ds64.table["big "] == 3 and fr.chunks[2].size == 3, "ds64 table") + -- a sub-range reader + local s = samples[1] + local big = buffer.create(#s + 7) + buffer.writestring(big, 3, s) + local fs = Riff.read(Bytes.reader(big, 3, #s)) :: any + t:check(fs and fs.form == "TEST" and #fs.chunks == 4 and fs.base == 3, "sub-range reader") + t:eq(Riff.sniff(Bytes.reader(buffer.fromstring(s))), "TEST", "sniff") +end + +-- errors +do + local _, e1 = Riff.read(buffer.fromstring("RIFF")) + t:check(e1 and e1.code == Err.TRUNCATED, "too short") + local _, e2 = Riff.read(buffer.fromstring("OggS00000000")) + t:check(e2 and e2.code == Err.CORRUPT, "not RIFF") + local _, e3 = Riff.read(42 :: any) + t:check(e3 and e3.code == Err.ARG, "not a buffer") +end + +t:fuzz("read + list", function(b: buffer) + local f = Riff.read(Bytes.reader(b), { openEnded = { data = true } }) + if f then + for _, c in f.chunks do + if c.id == "LIST" then + Riff.list(f, c) + end + end + end + return f +end, samples, { mutations = 30 }) + +t:done() diff --git a/tools/fixtures/wav.py b/tools/fixtures/wav.py new file mode 100644 index 0000000..8f8281a --- /dev/null +++ b/tools/fixtures/wav.py @@ -0,0 +1,199 @@ +# WAV fixtures (tools/fixtures.py): audio/wav. Ported from wav-luau tools/mkfixtures.py. +# tests/gen/wav_cases.luau a short synthetic stereo signal in every supported format and container (ffmpeg / sox), +# plus hand-patched variants (data size 0 / 0xFFFFFFFF, truncation, odd chunks with and +# without the pad byte, tags after the data), with ffmpeg's (or sox's) f32le decode +# tests/gen/wav_enc.luau encoder references: random samples at each depth, written by ffmpeg with -bitexact +# (PCM u8 / s16 / s24 / s32 / f32, 1-8 channels, > 48 kHz, RF64); our encoder must +# produce the same bytes +import os, random, struct, tempfile + +CTX = None + + +def build_cases(): + work = tempfile.mkdtemp() + RATE, DUR = 16000, 0.2 + SRC = "aevalsrc=0.6*sin(2*PI*440*t)+0.25*sin(2*PI*3100*t*t*10)|0.5*sin(2*PI*660*t)+0.2*(random(1)*2-1):s=%d:d=%g" % (RATE, DUR) + + def run(*args): + CTX.nix(["ffmpeg", "sox"], list(args)) + + def path(n): + return os.path.join(work, n) + + def ffenc(name, *args, ac=2): + run("ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", SRC, "-ac", str(ac), *args, path(name)) + return path(name) + + def ref(p): + return CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-i", p, "-f", "f32le", "-c:a", "pcm_f32le", "-"]) + + def soxref(p): + # ffmpeg cannot read every RIFX file: sox decodes those (through its 32-bit integer pipeline) + return CTX.nix("sox", ["sox", p, "-t", "raw", "-e", "floating-point", "-b", "32", "-L", "-"]) + + def chunks(d): + be = d[:4] == b"RIFX" + p, out = 12, [] + while p + 8 <= len(d): + cid = d[p:p + 4] + size = struct.unpack_from(">I" if be else "= frames * 8 + add("truncated_ima", dima[:cut], rima[:frames * 2 * 4], 2, "ima_adpcm") + + # odd-sized chunks before the data, padded and unpadded + fp, fs = find(d16, b"fmt ") + head, rest = d16[:fp + 8 + fs], d16[fp + 8 + fs:] + def riff(body): + return b"RIFF" + struct.pack("