From 315e819b01e1b0d0f376c371dfcee6dd8f018c19 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:38:56 -0500 Subject: [PATCH] ws-audio: audio/aiff (AIFF/AIFC incl. sowt/fl32/fl64/ulaw/alaw), audio/au, audio/voc: decode/open/encode; codecs/Pcm folder (+ Convert: raw sample formats <-> f32, G.711, rawDecoder/audioDecoder/encode); fixtures vs ffmpeg/sox, encoder outputs decoded by ffmpeg in the fixture step --- docs/FORMATS.md | 5 +- src/Formats/Registry.luau | 36 ++ src/Formats/audio/aiff/init.luau | 384 ++++++++++++++++++ src/Formats/audio/au/init.luau | 166 ++++++++ src/Formats/audio/voc/init.luau | 278 +++++++++++++ src/Formats/codecs/Pcm/Convert.luau | 308 ++++++++++++++ .../codecs/{Pcm.luau => Pcm/init.luau} | 93 ++++- tests/audio/aiff.luau | 183 +++++++++ tests/audio/au.luau | 147 +++++++ tests/audio/voc.luau | 129 ++++++ tools/fixtures/_audio.py | 80 ++++ tools/fixtures/aiff.py | 51 +++ tools/fixtures/au.py | 47 +++ tools/fixtures/voc.py | 39 ++ 14 files changed, 1940 insertions(+), 6 deletions(-) create mode 100644 src/Formats/audio/aiff/init.luau create mode 100644 src/Formats/audio/au/init.luau create mode 100644 src/Formats/audio/voc/init.luau create mode 100644 src/Formats/codecs/Pcm/Convert.luau rename src/Formats/codecs/{Pcm.luau => Pcm/init.luau} (56%) create mode 100644 tests/audio/aiff.luau create mode 100644 tests/audio/au.luau create mode 100644 tests/audio/voc.luau create mode 100644 tools/fixtures/aiff.py create mode 100644 tools/fixtures/au.py create mode 100644 tools/fixtures/voc.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 1df48b9..049bd15 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,9 +6,12 @@ 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 | aiff | .aiff .aif .aifc .afc | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/aiff.luau` | +| audio | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.luau` | +| audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. - codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point -- codecs/Pcm: PCM plumbing for audio encoders: one pull interface over an Audio or a Decoder, int <-> float samples. +- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..2eaac3a 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,42 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "aiff", + category = "audio", + path = "audio/aiff", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, + load = function() + return require("@formats/audio/aiff") + end, + }, + { + name = "au", + category = "audio", + path = "audio/au", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, + load = function() + return require("@formats/audio/au") + end, + }, + { + name = "voc", + category = "audio", + path = "audio/voc", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, + load = function() + return require("@formats/audio/voc") + end, + }, } return list diff --git a/src/Formats/audio/aiff/init.luau b/src/Formats/audio/aiff/init.luau new file mode 100644 index 0000000..94b02c2 --- /dev/null +++ b/src/Formats/audio/aiff/init.luau @@ -0,0 +1,384 @@ +--!strict +-- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs. +-- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw +-- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated +-- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 / +-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. Not supported: compressed AIFF-C codecs (ima4, MAC3 / +-- MAC6, Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Aiff = { + name = "aiff", + category = "audio", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, +} + +export type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +export type EncodeOptions = { + sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" + littleEndian: boolean?, -- 16-bit samples as AIFF-C "sowt" (default false: big endian; readers such as ffmpeg only + -- take 16-bit sowt, so other formats return Err.ARG) + aifc: boolean?, -- always write AIFF-C (default: only when the sample format needs it) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" } +local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } } +local AIFC_VERSION = 0xA2805140 + +-- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian) +local function ext80(b: buffer, o: number): number + local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) + local hi = bit32.byteswap(buffer.readu32(b, o + 2)) + local lo = bit32.byteswap(buffer.readu32(b, o + 6)) + local e = bit32.band(se, 0x7FFF) + if e == 0 and hi == 0 and lo == 0 then + return 0 + end + if e == 0x7FFF then + return math.huge + end + local v = (hi * 4294967296 + lo) * 2 ^ (e - 16383 - 63) + return if se >= 0x8000 then -v else v +end + +-- the 10 bytes of x (> 0) as an 80-bit extended float +local function writeExt80(w: Bytes.Writer, x: number) + if x <= 0 or x ~= x then + w:fill(0, 10) + return + end + local e = 0 + while x >= 2 ^ (e + 1) do + e += 1 + end + while x < 2 ^ e do + e -= 1 + end + local m = x * 2 ^ (63 - e) -- in [2^63, 2^64) + local hi = math.floor(m / 4294967296) + local lo = m - hi * 4294967296 + w:u16be(e + 16383) + w:u32be(hi) + w:u32be(math.floor(lo)) +end + +-- the sample format of a COMM chunk: Pcm format name | nil, message +local function sampleFormat(comp: string, bits: number): (string?, string?) + if comp == "NONE" or comp == "twos" or comp == "" then + if bits >= 1 and bits <= 8 then + return "s8" + elseif bits <= 16 then + return "s16be" + elseif bits <= 24 then + return "s24be" + elseif bits <= 32 then + return "s32be" + end + return nil, "bad sample size " .. bits + elseif comp == "sowt" then + if bits >= 1 and bits <= 8 then + return "s8" + elseif bits <= 16 then + return "s16le" + elseif bits <= 24 then + return "s24le" + elseif bits <= 32 then + return "s32le" + end + return nil, "bad sample size " .. bits + elseif comp == "raw " then + return "u8" + elseif comp == "in24" then + return "s24be" + elseif comp == "in32" then + return "s32be" + elseif comp == "42ni" then + return "s32le" + elseif comp == "fl32" or comp == "FL32" then + return "f32be" + elseif comp == "fl64" or comp == "FL64" then + return "f64be" + elseif comp == "ulaw" or comp == "ULAW" then + return "ulaw" + elseif comp == "alaw" or comp == "ALAW" then + return "alaw" + end + return nil, "compression " .. string.format("%q", comp) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Aiff.sniff(r: Bytes.Reader): number + if r:remaining() < 12 or r:peek(4) ~= "FORM" then + return 0 + end + local form = buffer.readstring(r.buf, r.pos + 8, 4) + return if form == "AIFF" or form == "AIFC" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Info = { + channels: number, + frames: number, + sampleRate: number, + bits: number, + format: string, + compression: string, + aifc: boolean, + dataOffset: number, -- absolute in r.buf + truncated: boolean, + tags: Types.Tags, +} + +-- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples) +local function parse(r: Bytes.Reader): (Info?, Err.Err?) + local b = r.buf + local base, limit = r.base, r.limit + if limit - base < 12 or buffer.readstring(b, base, 4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not a FORM file", base) + end + local form = buffer.readstring(b, base + 8, 4) + if form ~= "AIFF" and form ~= "AIFC" then + return nil, Err.new(Err.CORRUPT, "FORM type " .. string.format("%q", form) .. " is not AIFF / AIFC", base + 8) + end + local aifc = form == "AIFC" + local formEnd = math.min(limit, base + 8 + bit32.byteswap(buffer.readu32(b, base + 4))) + local info: Info? = nil + local comm = false + local ssnd: number? = nil + local ssndLen = 0 + local tags: Types.Tags = {} + local p = base + 12 + while p + 8 <= formEnd do + local id = buffer.readstring(b, p, 4) + local len = bit32.byteswap(buffer.readu32(b, p + 4)) + local d = p + 8 + local avail = math.min(len, limit - d) + if id == "COMM" then + if avail < 18 or (aifc and avail < 22) then + return nil, Err.new(Err.TRUNCATED, "COMM chunk too short", p) + end + local ch = buffer.readu8(b, d) * 256 + buffer.readu8(b, d + 1) + local frames = bit32.byteswap(buffer.readu32(b, d + 2)) + local bits = buffer.readu8(b, d + 6) * 256 + buffer.readu8(b, d + 7) + local rate = ext80(b, d + 8) + local comp = if aifc then buffer.readstring(b, d + 18, 4) else "NONE" + if ch < 1 then + return nil, Err.new(Err.CORRUPT, "no channels", d) + end + if not (rate > 0 and rate < 2 ^ 31) then + return nil, Err.new(Err.CORRUPT, "bad sample rate", d + 8) + end + local fmt, why = sampleFormat(comp, bits) + if not fmt then + return nil, Err.new(if comp == "NONE" or comp == "twos" or comp == "sowt" then Err.CORRUPT else Err.UNSUPPORTED, why :: string, d + 18) + end + info = { + channels = ch, + frames = frames, + sampleRate = rate, + bits = bits, + format = fmt, + compression = comp, + aifc = aifc, + dataOffset = 0, + truncated = false, + tags = tags, + } + comm = true + elseif id == "SSND" then + if avail < 8 then + return nil, Err.new(Err.TRUNCATED, "SSND chunk too short", p) + end + local off = bit32.byteswap(buffer.readu32(b, d)) + ssnd = d + 8 + off + ssndLen = math.max(0, avail - 8 - off) + if len >= 8 + off then + ssndLen = math.min(ssndLen, len - 8 - off) + end + elseif TEXT_TAGS[id] then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + local key = TEXT_TAGS[id] + tags[key] = if tags[key] then tags[key] .. "\n" .. s else s + end + if len > formEnd - d then + break + end + p = d + len + len % 2 + end + if not comm or not info then + return nil, Err.new(Err.CORRUPT, "no COMM chunk", base) + end + local fi = info :: Info + if fi.frames > 0 and not ssnd then + return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base) + end + local frameBytes = fi.channels * Pcm.Convert.SIZE[fi.format] + local present = if ssnd then ssndLen // frameBytes else 0 + if present < fi.frames then + fi.frames = present + fi.truncated = true + end + fi.dataOffset = ssnd or base + return fi, nil +end + +-- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err +function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?) + return parse(r) +end + +function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Aiff.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local a = Types.Audio.new(d.sampleRate, d.channels, d.frames) + d:read(d.frames, a.samples) + a.tags = d.tags + a.meta.source = d.source + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local FORMATS = { + s8 = { "s8", 8, "NONE" }, + s16 = { "s16be", 16, "NONE" }, + s24 = { "s24be", 24, "NONE" }, + s32 = { "s32be", 32, "NONE" }, + f32 = { "f32be", 32, "fl32" }, + f64 = { "f64be", 64, "fl64" }, + ulaw = { "ulaw", 16, "ulaw" }, + alaw = { "alaw", 16, "alaw" }, +} +local LE = { s16be = "s16le" } +local COMP_NAMES = { NONE = "not compressed", sowt = "", fl32 = "32-bit floating point", fl64 = "64-bit floating point", ulaw = "\181Law 2:1", alaw = "ALaw 2:1" } + +function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = FORMATS[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + local fmt, bits, comp = spec[1], spec[2], spec[3] + if o.littleEndian then + if not LE[fmt] then + return nil, Err.new(Err.ARG, "littleEndian needs 16-bit samples") + end + fmt, comp = LE[fmt], "sowt" + end + if src.channels > 65535 then + return nil, Err.new(Err.ARG, "too many channels") + end + local aifc = o.aifc or comp ~= "NONE" + local w = Bytes.writer(65536) + w:string("FORM") + w:u32be(0) -- patched + w:string(if aifc then "AIFC" else "AIFF") + if aifc then + w:string("FVER") + w:u32be(4) + w:u32be(AIFC_VERSION) + end + -- text chunks from the tags + for _, pair in TEXT_ORDER do + local id, key = pair[1], pair[2] + local s = src.tags[key] + if type(s) == "string" and #s > 0 then + w:string(id) + w:u32be(#s) + w:string(s) + if #s % 2 == 1 then + w:u8(0) + end + end + end + local commAt = w:tell() + w:string("COMM") + if aifc then + local name = COMP_NAMES[comp] or "" + local plen = 1 + #name + plen += plen % 2 + w:u32be(22 + plen) + else + w:u32be(18) + end + w:u16be(src.channels) + w:u32be(0) -- frames, patched + w:u16be(bits) + writeExt80(w, src.sampleRate) + if aifc then + w:string(comp) + local name = COMP_NAMES[comp] or "" + w:u8(#name) + w:string(name) + if (1 + #name) % 2 == 1 then + w:u8(0) + end + end + local ssndAt = w:tell() + w:string("SSND") + w:u32be(0) -- patched + w:u32be(0) -- offset + w:u32be(0) -- block size + local frames, perr = Pcm.encode(src, fmt, w) + if not frames then + return nil, perr + end + local dataLen = w:tell() - ssndAt - 16 + if dataLen % 2 == 1 then + w:u8(0) + end + w:setU32be(ssndAt + 4, dataLen + 8) + w:setU32be(commAt + 10, frames) + w:setU32be(4, w:tell() - 8) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local info, err = parse(r) + if not info then + return nil, err + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if info.frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames)) + end + local dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags) + if not dec then + return nil, derr + end + local d = dec :: any + d.source = { + format = "aiff", + aifc = info.aifc, + compression = info.compression, + bitDepth = info.bits, + sampleFormat = info.format, + truncated = info.truncated or nil, + } + return dec, nil +end + +return Aiff diff --git a/src/Formats/audio/au/init.luau b/src/Formats/audio/au/init.luau new file mode 100644 index 0000000..0215799 --- /dev/null +++ b/src/Formats/audio/au/init.luau @@ -0,0 +1,166 @@ +--!strict +-- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description. +-- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear), +-- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file); +-- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit). +-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Au = { + name = "au", + category = "audio", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, +} + +export type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +export type EncodeOptions = { + sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" +} + +-- ------------------------------------------------------------------------------------------------ constants +local ENCODINGS: { [number]: string } = { + [1] = "ulaw", + [2] = "s8", + [3] = "s16be", + [4] = "s24be", + [5] = "s32be", + [6] = "f32be", + [7] = "f64be", + [27] = "alaw", +} +local WRITE = { + ulaw = { 1, "ulaw" }, + s8 = { 2, "s8" }, + s16 = { 3, "s16be" }, + s24 = { 4, "s24be" }, + s32 = { 5, "s32be" }, + f32 = { 6, "f32be" }, + f64 = { 7, "f64be" }, + alaw = { 27, "alaw" }, +} +local BITS = { ulaw = 8, alaw = 8, s8 = 8, s16be = 16, s24be = 24, s32be = 32, f32be = 32, f64be = 64 } + +local function be32(b: buffer, o: number): number + return bit32.byteswap(buffer.readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Au.sniff(r: Bytes.Reader): number + return if r:peek(4) == ".snd" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Au.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local a = Types.Audio.new(d.sampleRate, d.channels, d.frames) + d:read(d.frames, a.samples) + a.tags = d.tags + a.meta.source = d.source + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + -- annotation: the comment tag, NUL-terminated, padded to a multiple of 8 (at least 4 bytes, as Sun requires) + local note = if type(src.tags.comment) == "string" then src.tags.comment else "" + local alen = #note + 1 + alen = math.max(8, alen + (8 - alen % 8) % 8) + local w = Bytes.writer(65536) + w:string(".snd") + w:u32be(24 + alen) + w:u32be(0xFFFFFFFF) -- patched + w:u32be(spec[1]) + w:u32be(src.sampleRate) + w:u32be(src.channels) + w:string(note) + w:fill(0, alen - #note) + local frames, perr = Pcm.encode(src, spec[2], w) + if not frames then + return nil, perr + end + w:setU32be(8, w:tell() - 24 - alen) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Au.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 24 or buffer.readstring(b, base, 4) ~= ".snd" then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local off, size, enc, rate, ch = be32(b, base + 4), be32(b, base + 8), be32(b, base + 12), be32(b, base + 16), be32(b, base + 20) + local fmt = ENCODINGS[enc] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "encoding " .. enc, base + 12) + end + if ch < 1 or ch > 65535 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch, base + 20) + end + if rate < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate", base + 16) + end + if off < 24 or off > limit - base then + return nil, Err.new(Err.CORRUPT, "bad data offset", base + 4) + end + local tags: Types.Tags = {} + if off > 24 then + local s = buffer.readstring(b, base + 24, off - 24) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + if #s > 0 then + tags.comment = s + end + end + local avail = limit - base - off + local truncated = false + if size == 0xFFFFFFFF then + size = avail + elseif size > avail then + size = avail + truncated = true + end + local frameBytes = ch * Pcm.Convert.SIZE[fmt] + local frames = size // frameBytes + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", frames, maxFrames)) + end + local dec, derr = Pcm.rawDecoder(b, base + off, frames, ch, rate, fmt, tags) + if not dec then + return nil, derr + end + local d = dec :: any + d.source = { format = "au", encoding = enc, sampleFormat = fmt, bitDepth = BITS[fmt], truncated = truncated or nil } + return dec, nil +end + +return Au diff --git a/src/Formats/audio/voc/init.luau b/src/Formats/audio/voc/init.luau new file mode 100644 index 0000000..3feca49 --- /dev/null +++ b/src/Formats/audio/voc/init.luau @@ -0,0 +1,278 @@ +--!strict +-- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description. +-- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence), +-- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit +-- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played +-- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version +-- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM +-- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Voc = { + name = "voc", + category = "audio", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, +} + +export type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +export type EncodeOptions = { + sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16" +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "Creative Voice File\26" +local T9_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le", [6] = "alaw", [7] = "ulaw" } +local T1_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le" } +local WRITE = { u8 = { 0, "u8", 8 }, s16 = { 4, "s16le", 16 }, alaw = { 6, "alaw", 8 }, ulaw = { 7, "ulaw", 8 } } +local MAX_BLOCK = 0xFFFFFF - 12 -- payload bytes of one type 9 block (a 24-bit size, 12 header bytes) + +local readu8 = buffer.readu8 +local function u16(b: buffer, o: number): number + return readu8(b, o) + readu8(b, o + 1) * 256 +end +local function u24(b: buffer, o: number): number + return readu8(b, o) + readu8(b, o + 1) * 256 + readu8(b, o + 2) * 65536 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Voc.sniff(r: Bytes.Reader): number + return if r:peek(20) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Segment = { at: number, frames: number, fmt: string? } -- fmt nil: silence + +function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 26 or buffer.readstring(b, base, 20) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local hsize = u16(b, base + 20) + local version = u16(b, base + 22) + if hsize < 26 or hsize > limit - base then + return nil, Err.new(Err.CORRUPT, "bad header size", base + 20) + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + local rate, channels = 0, 0 + local extRate, extChannels = 0, 0 -- a type 8 block's settings for the next type 1 block + local lastFmt: string? = nil + local codec = -1 + local segments: { Segment } = {} + local total = 0 + local truncated = false + local tags: Types.Tags = {} + local p = base + hsize + -- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames) + local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err? + if channels == 0 then + channels, rate = ch, sr + elseif ch ~= channels then + return Err.new(Err.UNSUPPORTED, "the channel count changes mid-file", at) + end + local frames = if fmt then bytes // (ch * Pcm.Convert.SIZE[fmt]) else bytes + if frames > 0 then + total += frames + if total > maxFrames then + return Err.new(Err.LIMIT, string.format("over the %d frame limit", maxFrames)) + end + table.insert(segments, { at = at, frames = frames, fmt = fmt }) + end + return nil + end + while p < limit do + local t = readu8(b, p) + if t == 0 then + break + end + if p + 4 > limit then + truncated = true + break + end + local size = u24(b, p + 1) + local d = p + 4 + local avail = math.min(size, limit - d) + if avail < size then + truncated = true + end + local err: Err.Err? = nil + if t == 1 then + if avail < 2 then + break + end + local div, c = readu8(b, d), readu8(b, d + 1) + local fmt = T1_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "Creative ADPCM (codec " .. c .. ")", d + 1) + end + local ch, sr = 1, 1000000 // (256 - div) + if extChannels > 0 then + ch, sr = extChannels, extRate + extChannels = 0 + end + lastFmt, codec = fmt, c + err = add(d + 2, avail - 2, fmt, ch, sr) + elseif t == 2 then + if lastFmt == nil then + return nil, Err.new(Err.CORRUPT, "continuation block before any sound data", p) + end + err = add(d, avail, lastFmt, channels, rate) + elseif t == 3 then + if avail < 3 then + break + end + local len, div = u16(b, d) + 1, readu8(b, d + 2) + err = add(d, len, nil, if channels > 0 then channels else 1, if rate > 0 then rate else 1000000 // (256 - div)) + elseif t == 5 then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + tags.comment = if tags.comment then tags.comment .. "\n" .. s else s + elseif t == 8 then + if avail < 4 then + break + end + local tc, mode = u16(b, d), readu8(b, d + 3) + extChannels = mode + 1 + extRate = 256000000 // (extChannels * (65536 - tc)) + elseif t == 9 then + if avail < 12 then + break + end + local sr = readu8(b, d) + readu8(b, d + 1) * 256 + readu8(b, d + 2) * 65536 + readu8(b, d + 3) * 16777216 + local ch, c = readu8(b, d + 5), u16(b, d + 6) + local fmt = T9_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "codec " .. c, d + 6) + end + if ch < 1 or sr < 1 then + return nil, Err.new(Err.CORRUPT, "bad channels or sample rate", d) + end + lastFmt, codec = fmt, c + err = add(d + 12, avail - 12, fmt, ch, sr) + end + if err then + return nil, err + end + p = d + size + end + if channels == 0 then + return nil, Err.new(if truncated then Err.TRUNCATED else Err.CORRUPT, "no sound data", p) + end + local a = Types.Audio.new(rate, channels, total) + local o = 0 + for _, s in segments do + local n = s.frames * channels + if s.fmt then + Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o) + end -- silence: the buffer is already zero + o += n * 4 + end + a.tags = tags + a.meta.source = { + format = "voc", + version = string.format("%d.%02d", version // 256, version % 256), + codec = codec, + sampleFormat = lastFmt, + bitDepth = if lastFmt == "s16le" then 16 else 8, + truncated = truncated or nil, + } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + w:u16le(26) + w:u16le(0x0114) + w:u16le((0xFFFF - 0x0114 + 0x1234 + 1) % 65536) -- ~version + 0x1234 + if type(src.tags.comment) == "string" and #src.tags.comment > 0 then + local s = string.sub(src.tags.comment, 1, 0xFFFFFE) + w:u8(5) + w:u24le(#s + 1) + w:string(s) + w:u8(0) + end + local size = Pcm.Convert.SIZE[spec[2]] + local frameBytes = size * src.channels + local framesPerBlock = MAX_BLOCK // frameBytes + local blockAt, blockFrames = -1, 0 + local tmp: buffer? = nil + while true do + local bf, n = src:read(math.min(8192, framesPerBlock), tmp) + if n <= 0 then + break + end + tmp = bf + local i = 0 + while i < n do + if blockAt < 0 or blockFrames == framesPerBlock then + blockAt = w:tell() + blockFrames = 0 + w:u8(9) + w:u24le(0) -- patched + w:u32le(src.sampleRate) + w:u8(spec[3]) + w:u8(src.channels) + w:u16le(spec[1]) + w:u32le(0) + end + local take = math.min(n - i, framesPerBlock - blockFrames) + local at = w:reserve(take * frameBytes) + Pcm.Convert.encode(bf, i * src.channels * 4, take * src.channels, spec[2], w.buf, at) + w.pos = at + take * frameBytes + blockFrames += take + i += take + local len = blockFrames * frameBytes + 12 + w:setU8(blockAt + 1, len % 256) + w:setU8(blockAt + 2, (len // 256) % 256) + w:setU8(blockAt + 3, len // 65536) + end + end + if src.err then + return nil, src.err + end + w:u8(0) -- terminator + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Voc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local a, err = Voc.decode(r, opts) + if not a then + return nil, err + end + local dec = Pcm.audioDecoder(a) :: any + dec.source = a.meta.source + return dec, nil +end + +return Voc diff --git a/src/Formats/codecs/Pcm/Convert.luau b/src/Formats/codecs/Pcm/Convert.luau new file mode 100644 index 0000000..5d88d6e --- /dev/null +++ b/src/Formats/codecs/Pcm/Convert.luau @@ -0,0 +1,308 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/Pcm). Integers map to +-- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the +-- classic Sun g711.c algorithm, written from the spec). +-- +-- Formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw (u8: offset binary). +-- Never throws: callers check ranges (Convert.SIZE[fmt] * count bytes) before calling. +local Convert = {} + +local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32 +local readf32, readf64, writef32, writef64 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writef64 +local writeu8, writeu16, writeu32, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei16, buffer.writei32 +local floor = math.floor +local byteswap = bit32.byteswap + +local SIZE: { [string]: number } = { + u8 = 1, + s8 = 1, + s16le = 2, + s16be = 2, + s24le = 3, + s24be = 3, + s32le = 4, + s32be = 4, + f32le = 4, + f32be = 4, + f64le = 8, + f64be = 8, + alaw = 1, + ulaw = 1, +} +Convert.SIZE = SIZE +-- the integer bit depth of each format (float: 32 / 64; G.711: 16 after expansion) +Convert.BITS = { + u8 = 8, + s8 = 8, + s16le = 16, + s16be = 16, + s24le = 24, + s24be = 24, + s32le = 32, + s32be = 32, + f32le = 32, + f32be = 32, + f64le = 64, + f64be = 64, + alaw = 16, + ulaw = 16, +} + +-- ------------------------------------------------------------------------------------------------ G.711 +local ALAW = table.create(256, 0) -- code -> linear s16 +local ULAW = table.create(256, 0) +for code = 0, 255 do + -- A-law + local a = bit32.bxor(code, 0x55) + local t = bit32.band(a, 0x0F) * 16 + local seg = bit32.rshift(bit32.band(a, 0x70), 4) + if seg == 0 then + t += 8 + elseif seg == 1 then + t += 0x108 + else + t = (t + 0x108) * 2 ^ (seg - 1) + end + ALAW[code + 1] = if bit32.band(a, 0x80) ~= 0 then t else -t + -- mu-law + local u = bit32.bxor(code, 0xFF) + local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4) + ULAW[code + 1] = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84 +end + +local SEG_AEND = { 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF } +local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF } +local function segment(v: number, ends: { number }): number + for i = 1, 8 do + if v <= ends[i] then + return i - 1 + end + end + return 8 +end + +-- linear s16 -> A-law code +local function alawEncode(pcm: number): number + local mask + local v = floor(pcm / 8) -- 13-bit magnitude domain + if v >= 0 then + mask = 0xD5 + else + mask = 0x55 + v = -v - 1 + end + local seg = segment(v, SEG_AEND) + local aval + if seg >= 8 then + aval = 0x7F + else + aval = seg * 16 + if seg < 2 then + aval += bit32.band(floor(v / 2), 0x0F) + else + aval += bit32.band(floor(v / 2 ^ seg), 0x0F) + end + end + return bit32.bxor(aval, mask) +end + +-- linear s16 -> mu-law code +local function ulawEncode(pcm: number): number + local v = floor(pcm / 4) -- 14-bit + local mask + if v < 0 then + v = -v + mask = 0x7F + else + mask = 0xFF + end + if v > 8159 then + v = 8159 + end + v += 0x21 + local seg = segment(v, SEG_UEND) + local uval + if seg >= 8 then + uval = 0x7F + else + uval = seg * 16 + bit32.band(floor(v / 2 ^ (seg + 1)), 0x0F) + end + return bit32.bxor(uval, mask) +end +Convert.alawEncode = alawEncode +Convert.ulawEncode = ulawEncode +Convert.ALAW = ALAW +Convert.ULAW = ULAW + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(src, so, fmt, count, dst, do_) -> true | false (unknown fmt): count samples at src[so] -> f32 at dst[do_] +function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean + if fmt == "s16le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi16(src, so + i * 2) / 32768) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local p = so + i * 2 + local v = readu8(src, p) * 256 + readu8(src, p + 1) + if v >= 32768 then + v -= 65536 + end + writef32(dst, d + i * 4, v / 32768) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, (readu8(src, so + i) - 128) / 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi8(src, so + i) / 128) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readu8(src, p) + readu8(src, p + 1) * 256 + readi8(src, p + 2) * 65536 + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readi8(src, p) * 65536 + readu8(src, p + 1) * 256 + readu8(src, p + 2) + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi32(src, so + i * 4) / 2147483648) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + local v = byteswap(readu32(src, so + i * 4)) + if v >= 2147483648 then + v -= 4294967296 + end + writef32(dst, d + i * 4, v / 2147483648) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readf64(src, so + i * 8)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + local p = so + i * 8 + writeu32(tmp, 0, byteswap(readu32(src, p + 4))) + writeu32(tmp, 4, byteswap(readu32(src, p))) + writef32(dst, d + i * 4, readf64(tmp, 0)) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ALAW[readu8(src, so + i) + 1] / 32768) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ULAW[readu8(src, so + i) + 1] / 32768) + end + else + return false + end + return true +end + +-- ------------------------------------------------------------------------------------------------ encode +local function q(x: number, s: number): number + local v = floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +-- encode(src, so, count, fmt, dst, do_) -> true | false: count f32 samples at src[so] -> fmt at dst[do_] +function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean + if fmt == "s16le" then + for i = 0, count - 1 do + writei16(dst, d + i * 2, q(readf32(src, so + i * 4), 32768)) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 32768) % 65536 + writeu16(dst, d + i * 2, (v % 256) * 256 + v // 256) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) + 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) % 256) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v % 256) + writeu8(dst, p + 1, (v // 256) % 256) + writeu8(dst, p + 2, v // 65536) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v // 65536) + writeu8(dst, p + 1, (v // 256) % 256) + writeu8(dst, p + 2, v % 256) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writei32(dst, d + i * 4, q(readf32(src, so + i * 4), 2147483648)) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(q(readf32(src, so + i * 4), 2147483648) % 4294967296)) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef64(dst, d + i * 8, readf32(src, so + i * 4)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + writef64(tmp, 0, readf32(src, so + i * 4)) + local p = d + i * 8 + writeu32(dst, p, byteswap(readu32(tmp, 4))) + writeu32(dst, p + 4, byteswap(readu32(tmp, 0))) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, alawEncode(q(readf32(src, so + i * 4), 32768))) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, ulawEncode(q(readf32(src, so + i * 4), 32768))) + end + else + return false + end + return true +end + +return Convert diff --git a/src/Formats/codecs/Pcm.luau b/src/Formats/codecs/Pcm/init.luau similarity index 56% rename from src/Formats/codecs/Pcm.luau rename to src/Formats/codecs/Pcm/init.luau index 077f6dc..8d60d05 100644 --- a/src/Formats/codecs/Pcm.luau +++ b/src/Formats/codecs/Pcm/init.luau @@ -1,20 +1,28 @@ --!strict --- codecs/Pcm: PCM plumbing for audio encoders: one pull interface over an Audio or a Decoder, int <-> float samples. --- An encoder accepts a Types.Audio (fully decoded) or a --- Types.Decoder (streamed); Pcm.source turns either into one pull interface, so encoders stream in blocks without --- caring which they got. Also the float <-> integer sample conversions (the same rounding and clipping everywhere). +-- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. +-- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one +-- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au, +-- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder. -- -- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else -- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read +-- local audio = Pcm.collect(src) -- read everything into a Types.Audio +-- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder +-- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio +-- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer +-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/Pcm/Convert) -- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767] -- local x = Pcm.fromInt(s16, 16) -- s / 32768 --- local audio = Pcm.collect(src) -- read everything into a Types.Audio -- +-- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw. -- Never throws (a decoder's read that throws is caught and ends the stream). local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") +local Convert = require("@formats/codecs/Pcm/Convert") local Pcm = {} +Pcm.Convert = Convert export type Source = { sampleRate: number, @@ -128,6 +136,81 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) return a, nil end +-- ------------------------------------------------------------------------------------------------ decoders +-- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming +-- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf) +function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: number, sampleRate: number, fmt: string, tags: Types.Tags?): (Types.Decoder?, Err.Err?) + local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + if channels < 1 or sampleRate <= 0 or frames < 0 or offset < 0 or offset + frames * channels * size > buffer.len(buf) then + return nil, Err.new(Err.ARG, "bad raw PCM layout") + end + local pos = 0 + local frameBytes = channels * size + local dec = { + sampleRate = sampleRate, + channels = channels, + frames = frames, + duration = frames / sampleRate, + bitrate = sampleRate * frameBytes * 8, + tags = tags or {}, + } + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.clamp(math.floor(n), 0, frames - pos) + local bytes = n * channels * 4 + local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) + if n > 0 then + Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0) + pos += n + end + return b, n + end + function dec.seek(_self: any, seconds: number) + local f = math.floor(seconds * sampleRate + 0.5) + pos = if f ~= f then 0 else math.clamp(f, 0, frames) + end + function dec.position(_self: any): number + return pos / sampleRate + end + return dec :: any, nil +end + +-- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples) +function Pcm.audioDecoder(a: Types.Audio): Types.Decoder + local d = Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) :: any + d.bitrate = a.sampleRate * a.channels * 32 + return d +end + +-- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples +function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?) + local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + local ch = src.channels + local total = 0 + local tmp: buffer? = nil + while true do + local b, n = src:read(8192, tmp) + if n <= 0 then + break + end + tmp = b + local at = w:reserve(n * ch * size) + Convert.encode(b, 0, n * ch, fmt, w.buf, at) + w.pos = at + n * ch * size + total += n + end + if src.err then + return nil, src.err + end + return total, nil +end + +-- ------------------------------------------------------------------------------------------------ conversions -- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0) function Pcm.toInt(x: number, bits: number): number local s = 2 ^ (bits - 1) diff --git a/tests/audio/aiff.luau b/tests/audio/aiff.luau new file mode 100644 index 0000000..079f34a --- /dev/null +++ b/tests/audio/aiff.luau @@ -0,0 +1,183 @@ +-- audio/aiff tests: files written by ffmpeg and sox in every sample format (AIFF 8 / 12 / 16 / 24 / 32-bit, AIFF-C +-- sowt / fl32 / fl64 / ulaw / alaw, 6 channels, text chunks) against ffmpeg's decode; streaming reads and seeks; +-- our encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz. +-- Fixtures: tools/fixtures/aiff.py. +local T = require("@tests/T") +local Aiff = require("@formats/audio/aiff") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/aiff_cases") +local Enc = require("@tests/gen/aiff_enc") +local Sig = require("@tests/gen/aiff_sig") + +local t = T.suite("aiff") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +-- max |a - b| over n f32 samples (a at byte ao, b at byte bo) +local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4)) + if d > m then + m = d + end + end + return m +end + +-- the contract +t:eq(Aiff.name, "aiff", "name") +t:eq(Aiff.category, "audio", "category") +t:check(Aiff.caps.decode and Aiff.caps.encode and table.find(Aiff.extensions, "aif") ~= nil, "caps / extensions") + +-- reference files: decode, stream, seek +for _, c in Cases do + local a, err = Aiff.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.kind == "audio" and a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + local ref = buffer.fromstring(c.ref) + local n = c.frames * c.channels + t:check(maxDiff(a.samples, 0, ref, 0, n) < 1e-6, c.name .. ": samples match ffmpeg") + -- streaming in odd chunks + local dec = Aiff.open(reader(c.data)) :: Types.Decoder + local got, out = 0, buffer.create(0) + local ok = true + while true do + local b, k = dec:read(777, out) + if k == 0 then + break + end + out = b + ok = ok and maxDiff(b, 0, ref, got * c.channels * 4, k * c.channels) < 1e-6 + got += k + end + t:check(ok and got == c.frames, c.name .. ": streamed reads") + dec:seek(1000 / c.rate) + t:check(math.abs(dec:position() - 1000 / c.rate) < 1e-9, c.name .. ": position") + local b, k = dec:read(50) + t:check(k == 50 and maxDiff(b, 0, ref, 1000 * c.channels * 4, 50 * c.channels) < 1e-6, c.name .. ": seek") +end +t:note("%d reference files match ffmpeg", #Cases) + +-- details of particular files +local function case(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end +do + local a = Aiff.decode(reader(case("ffmpeg-tags").data)) :: Types.Audio + t:eq(a.tags.title, "Song Name", "NAME chunk") + t:eq(a.tags.artist, "Some One", "AUTH chunk") + local fl = Aiff.decode(reader(case("ffmpeg-fl32").data)) :: Types.Audio + t:check(fl.meta.source.aifc and fl.meta.source.compression == "fl32", "fl32 meta") + -- a 12-bit sample size: samples sit left-justified in 16-bit containers + local s16 = case("sox-aiff-s16") + local q = string.find(s16.data, "COMM", 1, true) :: number + local d12 = string.sub(s16.data, 1, q + 13) .. "\0\12" .. string.sub(s16.data, q + 16) + local s12 = Aiff.decode(reader(d12)) :: Types.Audio + t:check(s12.meta.source.bitDepth == 12 and maxDiff(s12.samples, 0, buffer.fromstring(s16.ref), 0, s16.frames * 2) < 1e-6, "12-bit sample size") + local sw = Aiff.info(reader(case("ffmpeg-sowt").data)) + t:check(sw and sw.compression == "sowt" and sw.format == "s16le", "info: sowt") + -- inside a bigger buffer + local c = case("ffmpeg-s16be") + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 5, c.data) + local a2 = Aiff.decode(Bytes.reader(big, 5, #c.data)) :: Types.Audio + t:check(a2 and maxDiff(a2.samples, 0, buffer.fromstring(c.ref), 0, c.frames * c.channels) < 1e-6, "decode from a sub-range") + -- truncated sample data: the frames present + local cut = string.sub(c.data, 1, #c.data - 1001) + local a3 = Aiff.decode(reader(cut)) :: Types.Audio + t:check(a3 and a3.frames < c.frames and a3.frames > 0 and a3.meta.source.truncated, "truncated SSND") +end + +-- our encoder: ffmpeg decodes every sample format (fixture step), within the format's step; streamed == from Audio +local TOL = { s8 = 0.5 / 128, ["s16-mono"] = 0.5 / 32768, s16 = 0.5 / 32768, sowt16 = 0.5 / 32768, ["aifc-s16"] = 0.5 / 32768, s24 = 0.5 / 8388608, sowt24 = 0.5 / 8388608, s32 = 1e-7, f32 = 0, f64 = 0, ulaw = 0.04, alaw = 0.04 } +local sig = buffer.fromstring(Sig.data) +for _, e in Enc do + t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors") + t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate") + t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff)) + t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes") + local back = Aiff.decode(reader(e.data)) :: Types.Audio + t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file") + if e.channels == 2 then + t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip") + end +end +t:note("%d encoder outputs read back by ffmpeg and by us", #Enc) + +-- encoder: tags, odd sizes, errors +do + local a = Types.Audio.new(44100, 1, 3) + buffer.writef32(a.samples, 0, 0.5) + buffer.writef32(a.samples, 4, -1) + buffer.writef32(a.samples, 8, 2) -- clips + a.tags = { title = "odd", artist = "me", comment = "x" } + local b = Aiff.encode(a, { sampleFormat = "s8" }) :: buffer + local back = Aiff.decode(Bytes.reader(b)) :: Types.Audio + t:check(back.frames == 3 and back.tags.title == "odd" and back.tags.artist == "me" and back.tags.comment == "x", "odd length + tags") + t:check(buffer.readf32(back.samples, 0) == 0.5 and buffer.readf32(back.samples, 4) == -1 and buffer.readf32(back.samples, 8) == 127 / 128, "s8 values, clipping") + t:eq(buffer.len(b) % 2, 0, "chunks padded to even sizes") + t:check(Aiff.info(Bytes.reader(b)).sampleRate == 44100, "80-bit rate round trip") + local empty = Aiff.encode(Types.Audio.new(8000, 2, 0)) :: buffer + local e0 = Aiff.decode(Bytes.reader(empty)) + t:check(e0 and e0.frames == 0, "empty audio") + local _, e1 = Aiff.encode({} :: any) + t:check(e1 and e1.code == Err.ARG, "encode junk: ARG") + local _, e2 = Aiff.encode(a, { sampleFormat = "s12" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG") + local _, e3 = Aiff.encode(a, { sampleFormat = "f32", littleEndian = true }) + t:check(e3 and e3.code == Err.ARG, "littleEndian float: ARG") + local _, e5 = Aiff.encode(a, { sampleFormat = "s24", littleEndian = true }) + t:check(e5 and e5.code == Err.ARG, "littleEndian 24-bit: ARG") + t:eq(Aiff.sniff(Bytes.reader(b)), 1, "sniff") + t:eq(Aiff.sniff(reader("RIFF....WAVE")), 0, "sniff wav") + t:eq(Aiff.sniff(reader("")), 0, "sniff nothing") +end + +-- errors +do + local _, e = Aiff.decode(reader("FORM\0\0\0\4WAVE")) + t:check(e and e.code == Err.CORRUPT, "wrong FORM type: " .. tostring(e)) + local c = case("ffmpeg-fl32").data + local p = string.find(c, "fl32", 1, true) :: number + local ima = string.sub(c, 1, p - 1) .. "ima4" .. string.sub(c, p + 4) + local _, e2 = Aiff.decode(reader(ima)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "ima4: UNSUPPORTED: " .. tostring(e2)) + local _, e3 = Aiff.decode(reader(string.sub(c, 1, 30))) + t:check(e3 and (e3.code == Err.TRUNCATED or e3.code == Err.CORRUPT), "cut in COMM: " .. tostring(e3)) + local _, e4 = Aiff.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 10 }) + t:check(e4 and e4.code == Err.LIMIT, "maxFrames: LIMIT") +end + +-- fuzz +do + local samples = {} + for i, c in Cases do + if i % 3 == 1 then + table.insert(samples, string.sub(c.data, 1, 600)) + end + end + t:fuzz("decode", function(b: buffer) + return Aiff.decode(Bytes.reader(b)) + end, samples, { mutations = 30, keepHeader = 0 }) + t:fuzz("open + read", function(b: buffer) + local d = Aiff.open(Bytes.reader(b)) + if d then + d:read(100) + d:seek(0.001) + d:read(100) + end + return d + end, samples, { mutations = 10, garbage = 50 }) +end + +t:done() diff --git a/tests/audio/au.luau b/tests/audio/au.luau new file mode 100644 index 0000000..c38e8c5 --- /dev/null +++ b/tests/audio/au.luau @@ -0,0 +1,147 @@ +-- audio/au tests: files written by ffmpeg and sox in every encoding (8 / 16 / 24 / 32-bit, float, double, mu-law, +-- A-law, an annotation) against ffmpeg's decode; streaming reads and seeks; our encoder's output for every encoding +-- decoded by ffmpeg (fixture step) and by us; an unknown data size; errors; fuzz. Fixtures: tools/fixtures/au.py. +local T = require("@tests/T") +local Au = require("@formats/audio/au") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/au_cases") +local Enc = require("@tests/gen/au_enc") +local Sig = require("@tests/gen/au_sig") + +local t = T.suite("au") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4)) + if d > m then + m = d + end + end + return m +end +local function case(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +t:eq(Au.name, "au", "name") +t:eq(Au.category, "audio", "category") +t:check(Au.caps.decode and Au.caps.encode and table.find(Au.extensions, "snd") ~= nil, "caps / extensions") + +for _, c in Cases do + local a, err = Au.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + local ref = buffer.fromstring(c.ref) + t:check(maxDiff(a.samples, 0, ref, 0, c.frames * c.channels) < 1e-6, c.name .. ": samples match ffmpeg") + local dec = Au.open(reader(c.data)) :: Types.Decoder + local got, ok = 0, true + while true do + local b, k = dec:read(1000) + if k == 0 then + break + end + ok = ok and maxDiff(b, 0, ref, got * c.channels * 4, k * c.channels) < 1e-6 + got += k + end + t:check(ok and got == c.frames, c.name .. ": streamed reads") + dec:seek(700 / c.rate) + local b, k = dec:read(40) + t:check(k == 40 and maxDiff(b, 0, ref, 700 * c.channels * 4, 40 * c.channels) < 1e-6, c.name .. ": seek") +end +t:note("%d reference files match ffmpeg", #Cases) + +do + local a = Au.decode(reader(case("sox-comment").data)) :: Types.Audio + t:check(a.tags.comment ~= nil and string.find(a.tags.comment, "hello sun", 1, true) ~= nil, "annotation as comment") + -- an unknown data size (0xFFFFFFFF) runs to the end of the file + local c = case("ffmpeg-s16be") + local unk = string.sub(c.data, 1, 8) .. "\255\255\255\255" .. string.sub(c.data, 13) + local a2 = Au.decode(reader(unk)) :: Types.Audio + t:check(a2 and a2.frames == c.frames, "unknown data size") + local cut = Au.decode(reader(string.sub(c.data, 1, #c.data - 400))) :: Types.Audio + t:check(cut and cut.frames == c.frames - 100 and cut.meta.source.truncated, "truncated data") + local big = buffer.create(#c.data + 3) + buffer.writestring(big, 3, c.data) + local a3 = Au.decode(Bytes.reader(big, 3, #c.data)) :: Types.Audio + t:check(a3 and maxDiff(a3.samples, 0, buffer.fromstring(c.ref), 0, c.frames * 2) < 1e-6, "decode from a sub-range") +end + +local TOL = { s8 = 0.5 / 128, ["s16-mono"] = 0.5 / 32768, s16 = 0.5 / 32768, s24 = 0.5 / 8388608, s32 = 1e-7, f32 = 0, f64 = 0, ulaw = 0.04, alaw = 0.04 } +local sig = buffer.fromstring(Sig.data) +for _, e in Enc do + t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors") + t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate") + t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff)) + t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes") + local back = Au.decode(reader(e.data)) :: Types.Audio + t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file") + if e.channels == 2 then + t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip") + end +end +t:note("%d encoder outputs read back by ffmpeg and by us", #Enc) + +do + local a = Types.Audio.new(8000, 1, 2) + buffer.writef32(a.samples, 0, 0.25) + buffer.writef32(a.samples, 4, -0.25) + a.tags = { comment = "annotated!" } + local b = Au.encode(a) :: buffer + t:eq(bit32.byteswap(buffer.readu32(b, 4)) % 8, 0, "data offset is a multiple of 8") + local back = Au.decode(Bytes.reader(b)) :: Types.Audio + t:check(back.frames == 2 and back.tags.comment == "annotated!" and buffer.readf32(back.samples, 0) == 0.25, "comment + samples") + local _, e1 = Au.encode(42 :: any) + t:check(e1 and e1.code == Err.ARG, "encode junk: ARG") + local _, e2 = Au.encode(a, { sampleFormat = "u8" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG") + local frac = Types.Audio.new(8000.5, 1, 1) + local _, e3 = Au.encode(frac) + t:check(e3 and e3.code == Err.ARG, "fractional rate: ARG") + t:eq(Au.sniff(Bytes.reader(b)), 1, "sniff") + t:eq(Au.sniff(reader("FORM")), 0, "sniff other") + -- G.721 ADPCM (encoding 23): unsupported + local adpcm = string.sub(buffer.tostring(b), 1, 12) .. "\0\0\0\23" .. string.sub(buffer.tostring(b), 17) + local _, e4 = Au.decode(reader(adpcm)) + t:check(e4 and e4.code == Err.UNSUPPORTED, "encoding 23: UNSUPPORTED") + local _, e5 = Au.decode(reader(".snd\0\0\0\24")) + t:check(e5 and e5.code == Err.CORRUPT, "short header: CORRUPT") + local _, e6 = Au.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 5 }) + t:check(e6 and e6.code == Err.LIMIT, "maxFrames: LIMIT") +end + +do + local samples = {} + for i, c in Cases do + if i % 2 == 1 then + table.insert(samples, string.sub(c.data, 1, 400)) + end + end + t:fuzz("decode", function(b: buffer) + return Au.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) + t:fuzz("open + read", function(b: buffer) + local d = Au.open(Bytes.reader(b)) + if d then + d:read(64) + d:seek(1e9) + d:read(64) + d:seek(-1) + d:read(64) + end + return d + end, samples, { mutations = 10, garbage = 50 }) +end + +t:done() diff --git a/tests/audio/voc.luau b/tests/audio/voc.luau new file mode 100644 index 0000000..129c6b6 --- /dev/null +++ b/tests/audio/voc.luau @@ -0,0 +1,129 @@ +-- audio/voc tests: files written by ffmpeg (type 1 + 8 blocks for 8-bit, type 9 otherwise) and sox against ffmpeg's +-- decode; silence / text / continuation blocks and repeat markers built here; streaming reads and seeks; our +-- encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz. +-- Fixtures: tools/fixtures/voc.py. +local T = require("@tests/T") +local Voc = require("@formats/audio/voc") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/voc_cases") +local Enc = require("@tests/gen/voc_enc") +local Sig = require("@tests/gen/voc_sig") + +local t = T.suite("voc") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4)) + if d > m then + m = d + end + end + return m +end + +t:eq(Voc.name, "voc", "name") +t:eq(Voc.category, "audio", "category") +t:check(Voc.caps.decode and Voc.caps.encode, "caps") + +for _, c in Cases do + local a, err = Voc.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.sampleRate == c.rate and a.channels == c.channels, string.format("%s: format %d Hz x %d, want %d x %d", c.name, a.sampleRate, a.channels, c.rate, c.channels)) + t:eq(a.frames, c.frames, c.name .. ": frames") + local ref = buffer.fromstring(c.ref) + t:check(maxDiff(a.samples, 0, ref, 0, c.frames * c.channels) < 1e-6, c.name .. ": samples match ffmpeg") + local dec = Voc.open(reader(c.data)) :: Types.Decoder + dec:seek(500 / c.rate) + local b, k = dec:read(64) + t:check(k == 64 and maxDiff(b, 0, ref, 500 * c.channels * 4, 64 * c.channels) < 1e-6, c.name .. ": seek") +end +t:note("%d reference files match ffmpeg", #Cases) + +-- hand-built blocks: text, type 1 u8, silence, continuation, repeat markers, terminator +do + local hdr = "Creative Voice File\26\26\0\10\1\41\17" + local function blk(typ: number, payload: string): string + local n = #payload + return string.char(typ, n % 256, (n // 256) % 256, n // 65536) .. payload + end + local data = hdr + .. blk(5, "made by hand\0") + .. blk(1, string.char(156, 0) .. string.char(128, 192, 64)) -- 10 kHz, 3 samples + .. blk(3, string.char(4, 0, 156)) -- 5 frames of silence + .. blk(6, string.char(2, 0)) -- repeat start (ignored) + .. blk(2, string.char(255, 0)) -- continuation + .. blk(7, "") -- repeat end + .. blk(4, string.char(1, 0)) -- marker + .. "\0" + local a, err = Voc.decode(reader(data)) + t:check(a, "hand-built: " .. tostring(err)) + t:check(a.sampleRate == 10000 and a.channels == 1 and a.frames == 10, "hand-built: 10 kHz, 3 + 5 + 2 frames") + t:eq(a.tags.comment, "made by hand", "text block") + local want = { 0, 0.5, -0.5, 0, 0, 0, 0, 0, 127 / 128, -1 } + local ok = true + for i, v in want do + ok = ok and buffer.readf32(a.samples, (i - 1) * 4) == v + end + t:check(ok, "hand-built samples") + -- no terminator, a block cut short: the data present + local cut = Voc.decode(reader(string.sub(data, 1, 26 + 17 + 4 + 2 + 2))) + t:check(cut and cut.frames == 2 and cut.meta.source.truncated, "cut in a block") + -- Creative ADPCM: unsupported + local _, e = Voc.decode(reader(hdr .. blk(1, string.char(156, 1) .. "\0\0") .. "\0")) + t:check(e and e.code == Err.UNSUPPORTED, "ADPCM: UNSUPPORTED") + local _, e2 = Voc.decode(reader(hdr .. blk(2, "\0\0") .. "\0")) + t:check(e2 and e2.code == Err.CORRUPT, "continuation first: CORRUPT") + local _, e3 = Voc.decode(reader(hdr .. "\0")) + t:check(e3 and e3.code == Err.CORRUPT, "no sound: CORRUPT") + local _, e4 = Voc.decode(reader("Creative Voice Fil")) + t:check(e4 and e4.code == Err.CORRUPT, "short: CORRUPT") + t:eq(Voc.sniff(reader(data)), 1, "sniff") + t:eq(Voc.sniff(reader(".snd")), 0, "sniff other") +end + +local TOL = { s16 = 0.5 / 32768, ["s16-mono"] = 0.5 / 32768, u8 = 0.5 / 128, ulaw = 0.04, alaw = 0.04 } +local sig = buffer.fromstring(Sig.data) +for _, e in Enc do + t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors") + t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate") + t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff)) + t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes") + local back = Voc.decode(reader(e.data)) :: Types.Audio + t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file") + if e.channels == 2 then + t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip") + end +end +t:note("%d encoder outputs read back by ffmpeg and by us", #Enc) + +do + local a = Types.Audio.new(22050, 2, 1) + a.tags = { comment = "hi" } + local b = Voc.encode(a) :: buffer + local back = Voc.decode(Bytes.reader(b)) :: Types.Audio + t:check(back.frames == 1 and back.tags.comment == "hi", "one frame + comment") + local _, e1 = Voc.encode(nil :: any) + t:check(e1 and e1.code == Err.ARG, "encode nil: ARG") + local _, e2 = Voc.encode(a, { sampleFormat = "s24" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG") + local _, e3 = Voc.decode(reader(Cases[1].data), { maxFrames = 5 }) + t:check(e3 and e3.code == Err.LIMIT, "maxFrames: LIMIT") +end + +do + local samples = {} + for _, c in Cases do + table.insert(samples, string.sub(c.data, 1, 300)) + end + t:fuzz("decode", function(b: buffer) + return Voc.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) +end + +t:done() diff --git a/tools/fixtures/_audio.py b/tools/fixtures/_audio.py index cf0f16f..b9680c3 100644 --- a/tools/fixtures/_audio.py +++ b/tools/fixtures/_audio.py @@ -192,3 +192,83 @@ def luau(ctx, code): return out[:-1] if out.endswith(b"\n") else out finally: os.unlink(path) + + +def emit_signal(ctx, name, samples, rate, ch): + """emit tests/gen/.luau = { rate, channels, frames, data = f32le bytes } (the input encoders are tested on)""" + ctx.emit(name, {"rate": rate, "channels": ch, "frames": len(samples) // ch, "data": f32le(samples)}) + + +def encode_luau(ctx, module, sigmod, opts_lua="nil", source="audio"): + """encode the emitted signal module `sigmod` with require("@formats/").encode(audio, opts) in Luau; returns + the encoded bytes. source = "decoder" feeds a streaming Decoder (codecs/Pcm.audioDecoder) instead of the Audio.""" + code = """ +local S = require("@tests/gen/%s") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local M = require("@formats/%s") +local a = Types.Audio.new(S.rate, S.channels, S.frames) +buffer.writestring(a.samples, 0, S.data) +local src: any = a +if "%s" == "decoder" then src = Pcm.audioDecoder(a) end +local out, err = M.encode(src, %s) +if not out then error("encode failed: " .. tostring(err)) end +print(buffer.tostring(out)) +""" % (sigmod, module, source, opts_lua) + return luau(ctx, code) + + +def max_diff(a, b): + if len(a) != len(b): + return float("inf") + return max((abs(x - y) for x, y in zip(a, b)), default=0.0) + + +def pcm_fixtures(ctx, fmt, made, encodes, sig_rate=22050, sig_frames=3000): + """The fixtures of an uncompressed container (aiff, au, voc): + made = [(name, packages, argv)]: reference tools write files from {in} (a stereo / mono 16-bit or float WAV of + the test signal; argv may use {in_mono}, {in_float}) into {out}; each file is decoded by ffmpeg as the + reference (f32le) + encodes = [(name, opts_lua, channels)]: our encoder's output (in the fixture step) decoded by ffmpeg, compared + against the f32 input (max abs difference, which the test bounds by the format's quantization step) + Emits _cases (files + references), _sig / _sig1 (the inputs, stereo / mono) and _enc.""" + stereo = signal("music", sig_rate, 2, sig_frames, seed=3) + mono = signal("sweep", sig_rate, 1, sig_frames, seed=4) + emit_signal(ctx, fmt + "_sig", stereo, sig_rate, 2) + emit_signal(ctx, fmt + "_sig1", mono, sig_rate, 1) + inputs = {"{in}": wav(stereo, sig_rate, 2, 16), "{in_mono}": wav(mono, sig_rate, 1, 16), + "{in_float}": wav(stereo, sig_rate, 2, float_=True)} + cases = [] + for name, packages, argv in made: + d = tempfile.mkdtemp(prefix="fmt-audio-") + try: + paths = {} + for key, data in inputs.items(): + paths[key] = os.path.join(d, key.strip("{}") + ".wav") + with open(paths[key], "wb") as f: + f.write(data) + out = os.path.join(d, "out." + fmt) + args = [] + for a in argv: + for key, p in paths.items(): + a = a.replace(key, p) + args.append(a.replace("{out}", out)) + ctx.nix(packages, args) + with open(out, "rb") as f: + data = f.read() + finally: + shutil.rmtree(d, ignore_errors=True) + rate, ch, ref = ffdecode(ctx, data, ext=fmt) + cases.append({"name": name, "data": data, "rate": rate, "channels": ch, "frames": len(ref) // ch, "ref": f32le(ref)}) + ctx.emit(fmt + "_cases", cases) + results = [] + for name, opts_lua, ch in encodes: + sig = stereo if ch == 2 else mono + out = encode_luau(ctx, "audio/" + fmt, fmt + ("_sig" if ch == 2 else "_sig1"), opts_lua) + streamed = encode_luau(ctx, "audio/" + fmt, fmt + ("_sig" if ch == 2 else "_sig1"), opts_lua, source="decoder") + rate, dch, dec = ffdecode(ctx, out, ext=fmt) + errs = tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], out, fmt) + results.append({"name": name, "opts": opts_lua, "channels": dch, "rate": rate, "frames": len(dec) // max(1, dch), + "maxDiff": max_diff(sig, dec) if dch == ch else 99.0, "ffmpegErrors": errs.decode(errors="replace"), + "bytes": len(out), "sameStreamed": out == streamed, "data": out}) + ctx.emit(fmt + "_enc", results) diff --git a/tools/fixtures/aiff.py b/tools/fixtures/aiff.py new file mode 100644 index 0000000..15fbdb2 --- /dev/null +++ b/tools/fixtures/aiff.py @@ -0,0 +1,51 @@ +# AIFF / AIFF-C fixtures (tools/fixtures.py): files written by ffmpeg and sox in every sample format we read, each +# with ffmpeg's f32 decode as the reference; our encoder's output for every sample format, decoded by ffmpeg in the +# fixture step (tools/fixtures/_audio.py pcm_fixtures). +# tests/gen/aiff_cases.luau { name, data, rate, channels, frames, ref (f32le) } +# tests/gen/aiff_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data } +# tests/gen/aiff_sig*.luau the encoder inputs +import importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/Pcm"] + + +def ff(codec, src="{in}", extra=()): + return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "aiff", "-y", "{out}"] + + +def generate(ctx): + made = [ + ("ffmpeg-s16be", "ffmpeg", ff("pcm_s16be")), + ("ffmpeg-s16be-mono", "ffmpeg", ff("pcm_s16be", "{in_mono}")), + ("ffmpeg-s8", "ffmpeg", ff("pcm_s8")), + ("ffmpeg-s24be", "ffmpeg", ff("pcm_s24be", "{in_float}")), + ("ffmpeg-s32be", "ffmpeg", ff("pcm_s32be", "{in_float}")), + ("ffmpeg-sowt", "ffmpeg", ff("pcm_s16le")), + ("ffmpeg-fl32", "ffmpeg", ff("pcm_f32be", "{in_float}")), + ("ffmpeg-fl64", "ffmpeg", ff("pcm_f64be", "{in_float}")), + ("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw")), + ("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")), + ("ffmpeg-48k-6ch", "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-af", "aresample=48000,pan=5.1|c0=c0|c1=c1|c2=c0|c3=c1|c4=c0|c5=c1", "-c:a", "pcm_s16be", "-f", "aiff", "-y", "{out}"]), + ("ffmpeg-tags", "ffmpeg", ff("pcm_s16be", extra=("-metadata", "title=Song Name", "-metadata", "author=Some One", "-metadata", "comment=hello"))), + ("sox-aiff-s16", "sox", ["sox", "{in}", "-t", "aiff", "{out}"]), + ("sox-aiff-s24-mono", "sox", ["sox", "{in_mono}", "-b", "24", "-t", "aiff", "{out}"]), + ("sox-aifc-s16", "sox", ["sox", "{in}", "-t", "aifc", "{out}"]), + ] + encodes = [ + ("s16", "nil", 2), + ("s16-mono", "nil", 1), + ("s8", '{ sampleFormat = "s8" }', 2), + ("s24", '{ sampleFormat = "s24" }', 2), + ("s32", '{ sampleFormat = "s32" }', 1), + ("f32", '{ sampleFormat = "f32" }', 2), + ("f64", '{ sampleFormat = "f64" }', 2), + ("ulaw", '{ sampleFormat = "ulaw" }', 2), + ("alaw", '{ sampleFormat = "alaw" }', 1), + ("sowt16", '{ littleEndian = true }', 2), + ("aifc-s16", '{ aifc = true }', 2), + ] + A.pcm_fixtures(ctx, "aiff", made, encodes) diff --git a/tools/fixtures/au.py b/tools/fixtures/au.py new file mode 100644 index 0000000..eb34539 --- /dev/null +++ b/tools/fixtures/au.py @@ -0,0 +1,47 @@ +# Sun AU fixtures (tools/fixtures.py): files written by ffmpeg and sox in every encoding we read, each with ffmpeg's +# f32 decode as the reference; our encoder's output for every encoding, decoded by ffmpeg in the fixture step +# (tools/fixtures/_audio.py pcm_fixtures). +# tests/gen/au_cases.luau { name, data, rate, channels, frames, ref (f32le) } +# tests/gen/au_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data } +# tests/gen/au_sig*.luau the encoder inputs +import importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/au", "src/Formats/codecs/Pcm"] + + +def ff(codec, src="{in}", extra=()): + return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "au", "-y", "{out}"] + + +def generate(ctx): + made = [ + ("ffmpeg-s16be", "ffmpeg", ff("pcm_s16be")), + ("ffmpeg-s16be-mono", "ffmpeg", ff("pcm_s16be", "{in_mono}")), + ("ffmpeg-s8", "ffmpeg", ff("pcm_s8")), + ("ffmpeg-s24be", "ffmpeg", ff("pcm_s24be", "{in_float}")), + ("ffmpeg-s32be", "ffmpeg", ff("pcm_s32be", "{in_float}")), + ("ffmpeg-f32be", "ffmpeg", ff("pcm_f32be", "{in_float}")), + ("ffmpeg-f64be", "ffmpeg", ff("pcm_f64be", "{in_float}")), + ("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw")), + ("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")), + ("sox-comment", "sox", ["sox", "{in}", "--comment", "hello sun", "-t", "au", "{out}"]), + ("sox-ulaw-8k", "sox", ["sox", "{in_mono}", "-r", "8000", "-e", "mu-law", "-t", "au", "{out}"]), + ("sox-s16", "sox", ["sox", "{in}", "-t", "au", "{out}"]), + ("sox-f32", "sox", ["sox", "{in_float}", "-e", "floating-point", "-b", "32", "-t", "au", "{out}"]), + ] + encodes = [ + ("s16", "nil", 2), + ("s16-mono", "nil", 1), + ("s8", '{ sampleFormat = "s8" }', 2), + ("s24", '{ sampleFormat = "s24" }', 2), + ("s32", '{ sampleFormat = "s32" }', 1), + ("f32", '{ sampleFormat = "f32" }', 2), + ("f64", '{ sampleFormat = "f64" }', 2), + ("ulaw", '{ sampleFormat = "ulaw" }', 2), + ("alaw", '{ sampleFormat = "alaw" }', 1), + ] + A.pcm_fixtures(ctx, "au", made, encodes) diff --git a/tools/fixtures/voc.py b/tools/fixtures/voc.py new file mode 100644 index 0000000..b207bd8 --- /dev/null +++ b/tools/fixtures/voc.py @@ -0,0 +1,39 @@ +# Creative VOC fixtures (tools/fixtures.py): files written by ffmpeg (type 1 + type 8 blocks for 8-bit, type 9 for the +# rest) and sox, each with ffmpeg's f32 decode as the reference; our encoder's output for every sample format, decoded +# by ffmpeg in the fixture step (tools/fixtures/_audio.py pcm_fixtures). +# tests/gen/voc_cases.luau { name, data, rate, channels, frames, ref (f32le) } +# tests/gen/voc_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data } +# tests/gen/voc_sig*.luau the encoder inputs +import importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/voc", "src/Formats/codecs/Pcm"] + + +def ff(codec, src="{in}", extra=()): + return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "voc", "-y", "{out}"] + + +def generate(ctx): + made = [ + ("ffmpeg-u8-stereo", "ffmpeg", ff("pcm_u8")), + ("ffmpeg-u8-mono", "ffmpeg", ff("pcm_u8", "{in_mono}")), + ("ffmpeg-s16", "ffmpeg", ff("pcm_s16le")), + ("ffmpeg-s16-mono-44k", "ffmpeg", ff("pcm_s16le", "{in_mono}", ("-ar", "44100"))), + ("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")), + ("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw", "{in_mono}")), + ("sox-u8-mono-11k", "sox", ["sox", "{in_mono}", "-r", "11025", "-b", "8", "-t", "voc", "{out}"]), + ("sox-u8-stereo", "sox", ["sox", "{in}", "-b", "8", "-t", "voc", "{out}"]), + ("sox-s16-stereo", "sox", ["sox", "{in}", "-b", "16", "-t", "voc", "{out}"]), + ] + encodes = [ + ("s16", "nil", 2), + ("s16-mono", "nil", 1), + ("u8", '{ sampleFormat = "u8" }', 2), + ("alaw", '{ sampleFormat = "alaw" }', 2), + ("ulaw", '{ sampleFormat = "ulaw" }', 1), + ] + A.pcm_fixtures(ctx, "voc", made, encodes)