--!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