From b7006dbbede5b8b930477c6d98a7f680b5e66e2c Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 13:54:05 -0500 Subject: [PATCH 1/7] ws-audio2: codecs/audio/ApeTag: APEv1 / APEv2 tags -> Types.Tags (find / parse / tagKey), shared by WavPack, APE, TTA, Musepack --- src/Formats/codecs/audio/ApeTag.luau | 110 +++++++++++++++++++++++++++ tests/codecs/apetag.luau | 79 +++++++++++++++++++ 2 files changed, 189 insertions(+) create mode 100644 src/Formats/codecs/audio/ApeTag.luau create mode 100644 tests/codecs/apetag.luau diff --git a/src/Formats/codecs/audio/ApeTag.luau b/src/Formats/codecs/audio/ApeTag.luau new file mode 100644 index 0000000..259bdcf --- /dev/null +++ b/src/Formats/codecs/audio/ApeTag.luau @@ -0,0 +1,110 @@ +--!strict +-- codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and +-- some MP3s) -> Types.Tags. Written from the APEv2 specification (wiki.hydrogenaud.io "APEv2 specification"); no +-- third-party code. A tag sits at the end of the file (before an optional ID3v1 tag) as items + a 32-byte footer +-- "APETAGEX", with an optional 32-byte header in front (APEv2). Item keys become lower case tag keys (Year -> date, +-- Track -> track, Album Artist -> albumartist, Disc -> disc, Comment -> comment); text values holding several +-- values (NUL separated) are joined with "; "; binary items (cover art) and external links stay in info.items. +-- Never throws. +-- +-- local tags, info = ApeTag.find(buf, start, limit) -- the tag ending at limit (or before an ID3v1 tag there) +-- -- tags: { title = ..., artist = ... } | nil (no tag / malformed) +-- -- info: { start = first byte (the header when present), stop = past the footer, version = 1000 | 2000, +-- -- items = { { key = "Title", value = "...", kind = "text" | "binary" | "link" } } } +-- local tags, info = ApeTag.parse(buf, footer, start) -- the tag whose footer is at byte `footer` (>= start) +local ApeTag = {} + +export type Item = { key: string, value: string, kind: string } +export type Info = { start: number, stop: number, version: number, items: { Item } } + +local TO_TAG: { [string]: string } = { + year = "date", + ["album artist"] = "albumartist", + albumartist = "albumartist", + tracknumber = "track", + discnumber = "disc", + description = "comment", +} +local KINDS = { [0] = "text", "binary", "link", "text" } + +-- tagKey(itemKey) -> the Types.Tags key +function ApeTag.tagKey(key: string): string + local k = string.lower(key) + return TO_TAG[k] or k +end + +-- parse(buf, footer, start?) -> tags, info | nil: the tag whose 32-byte footer starts at byte `footer`; the items +-- must lie at or after `start` (default 0) +function ApeTag.parse(buf: buffer, footer: number, start: number?): ({ [string]: string }?, Info?) + local lo = start or 0 + local n = buffer.len(buf) + if footer < lo or footer + 32 > n or buffer.readstring(buf, footer, 8) ~= "APETAGEX" then + return nil, nil + end + local version = buffer.readu32(buf, footer + 8) + local size = buffer.readu32(buf, footer + 12) -- items + footer + local count = buffer.readu32(buf, footer + 16) + local flags = buffer.readu32(buf, footer + 20) + if size < 32 or footer + 32 - size < lo then + return nil, nil + end + local p = footer + 32 - size + local first = p + if version >= 2000 and bit32.band(flags, 0x80000000) ~= 0 and p - 32 >= lo and buffer.readstring(buf, p - 32, 8) == "APETAGEX" then + first = p - 32 + end + local stop = footer + local tags: { [string]: string } = {} + local items: { Item } = {} + for _ = 1, math.min(count, 65536) do + if p + 9 > stop then + break + end + local len = buffer.readu32(buf, p) + local iflags = buffer.readu32(buf, p + 4) + local k = p + 8 + while k < stop and buffer.readu8(buf, k) ~= 0 do + k += 1 + end + if k >= stop then + break + end + local key = buffer.readstring(buf, p + 8, k - p - 8) + local v0 = k + 1 + if len > stop - v0 then + break + end + local value = buffer.readstring(buf, v0, len) + local kind = if version >= 2000 then KINDS[bit32.band(bit32.rshift(iflags, 1), 3)] else "text" + table.insert(items, { key = key, value = value, kind = kind }) + if kind == "text" and key ~= "" then + local tk = ApeTag.tagKey(key) + local s = (string.gsub(value, "%z+$", "")) + s = (string.gsub(s, "%z", "; ")) + local old = tags[tk] + tags[tk] = if old then old .. "; " .. s else s + end + p = v0 + len + end + return tags, { start = first, stop = footer + 32, version = version, items = items } +end + +-- find(buf, start, limit) -> tags, info | nil: the tag at the end of [start, limit), or just before a 128-byte +-- ID3v1 tag ("TAG") there +function ApeTag.find(buf: buffer, start: number, limit: number): ({ [string]: string }?, Info?) + if limit > buffer.len(buf) then + limit = buffer.len(buf) + end + if limit - start >= 32 then + local tags, info = ApeTag.parse(buf, limit - 32, start) + if tags then + return tags, info + end + end + if limit - start >= 160 and buffer.readstring(buf, limit - 128, 3) == "TAG" then + return ApeTag.parse(buf, limit - 160, start) + end + return nil, nil +end + +return ApeTag diff --git a/tests/codecs/apetag.luau b/tests/codecs/apetag.luau new file mode 100644 index 0000000..5506acc --- /dev/null +++ b/tests/codecs/apetag.luau @@ -0,0 +1,79 @@ +-- codecs/audio/ApeTag tests: APEv2 tags with and without a header, APEv1, multi-value items, binary items, an ID3v1 +-- tag after the APE tag, a tag inside a sub-range, malformed sizes / counts; the fuzz no-throw pass. The real files +-- (wavpack -w, mac -t, ...) are covered by tests/audio/wavpack.luau and tests/audio/ape.luau. +local T = require("@tests/T") +local ApeTag = require("@formats/codecs/audio/ApeTag") + +local t = T.suite("apetag") + +local function u32(v: number): string + return string.char(v % 256, (v // 256) % 256, (v // 65536) % 256, (v // 16777216) % 256) +end +-- tag(items, version, header) -> the tag bytes; items = { { key, value, flags? } } +local function tag(items: { any }, version: number, header: boolean): string + local body = {} + for _, it in items do + table.insert(body, u32(#it[2]) .. u32(it[3] or 0) .. it[1] .. "\0" .. it[2]) + end + local b = table.concat(body) + local flags = if header then 0x80000000 else 0 + local function block(isHeader: boolean): string + return "APETAGEX" .. u32(version) .. u32(#b + 32) .. u32(#items) .. u32(flags + (if isHeader then 0x20000000 else 0)) .. string.rep("\0", 8) + end + return (if header then block(true) else "") .. b .. block(false) +end + +do + local s = "audio data" .. tag({ { "Title", "Hello" }, { "Artist", "A\0B" }, { "Year", "2026" }, { "Track", "3/9" }, + { "Cover Art (Front)", "f.png\0PNG", 2 }, { "Album Artist", "Band" } }, 2000, true) + local b = buffer.fromstring(s) + local tags, info = ApeTag.find(b, 0, #s) + t:check(tags and info, "v2 found") + t:eq(tags.title, "Hello", "title") + t:eq(tags.artist, "A; B", "multi value") + t:eq(tags.date, "2026", "year -> date") + t:eq(tags.track, "3/9", "track") + t:eq(tags.albumartist, "Band", "album artist") + t:eq(tags["cover art (front)"], nil, "binary item not a tag") + t:eq(info.start, 10, "start at the header") + t:eq(info.stop, #s, "stop") + t:eq(info.version, 2000, "version") + t:eq(#info.items, 6, "items") + t:eq(info.items[5].kind, "binary", "binary kind") + t:eq(info.items[5].value, "f.png\0PNG", "binary value") + -- ID3v1 after it + local s2 = s .. "TAG" .. string.rep("x", 125) + local tags2, info2 = ApeTag.find(buffer.fromstring(s2), 0, #s2) + t:check(tags2 and tags2.title == "Hello" and info2.stop == #s, "before ID3v1") + -- inside a sub-range + local s3 = "zz" .. s .. "yyy" + local tags3, info3 = ApeTag.find(buffer.fromstring(s3), 2, 2 + #s) + t:check(tags3 and tags3.title == "Hello" and info3.start == 12, "sub-range") + -- the start bounds the header + local tags4, info4 = ApeTag.find(b, 50, #s) + t:check(tags4 == nil and info4 == nil, "items before start") +end +do + local s = tag({ { "Title", "Old" } }, 1000, false) + local tags, info = ApeTag.find(buffer.fromstring(s), 0, #s) + t:check(tags and tags.title == "Old" and info.start == 0 and info.version == 1000, "v1") + t:eq(ApeTag.find(buffer.fromstring("no tag here at all, not even close to it"), 0, 40), nil, "none") +end +-- malformed: a huge item length, a huge count, a size larger than the file +do + local s = tag({ { "Title", "Hello" } }, 2000, false) + local bad = string.sub(s, 1, 0) .. u32(0x7FFFFFFF) .. string.sub(s, 5) + local tags = ApeTag.find(buffer.fromstring(bad), 0, #bad) + t:check(tags and tags.title == nil, "bad item length stops") + local big = string.sub(s, 1, #s - 32 + 12) .. u32(1e9) .. string.sub(s, #s - 32 + 17) + t:eq(ApeTag.find(buffer.fromstring(big), 0, #big), nil, "size past the start") +end + +local samples = { + buffer.fromstring("data" .. tag({ { "Title", "Hello" }, { "Artist", "X" } }, 2000, true)), + buffer.fromstring(tag({ { "A", "b" } }, 1000, false) .. "TAG" .. string.rep("\0", 125)), +} +t:fuzz("find", function(b: buffer) + return ApeTag.find(b, 0, buffer.len(b)) +end, samples, { mutations = 400 }) +t:done() From 22615b503e1305e13074bc28f8b8089f894ebba1 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:14:29 -0500 Subject: [PATCH 2/7] ws-audio2: audio/mpc + codecs/audio/Musepack: Musepack SV7 / SV8 decoding (libmpcdec r475 port, BSD) Gapless (synthesis delay, SV8 leading silence, SV7 last frame length), seeking (SV8 by packet with one packet of pre-roll: exact; SV7 by frame with 32 frames of pre-roll like libmpcdec), APEv2 tags via codecs/audio/ApeTag (merged from ws/audio2-lossless), ID3v2 skipped. Fixtures build mpcenc / mppenc / a float libmpcdec dumper from the pinned upstream tarballs through nix; 132-140 dB SNR vs libmpcdec float, 82.7 dB vs ffmpeg's s16 decode. --- docs/FORMATS.md | 3 + licenses/NOTICE.md | 1 + licenses/libmpcdec-BSD.txt | 36 + src/Formats/Registry.luau | 12 + src/Formats/audio/mpc/init.luau | 96 ++ src/Formats/codecs/audio/Musepack/Decode.luau | 899 ++++++++++++++++++ src/Formats/codecs/audio/Musepack/Tables.luau | 379 ++++++++ src/Formats/codecs/audio/Musepack/init.luau | 359 +++++++ tests/audio/mpc.luau | 145 +++ tools/fixtures/mpc.py | 130 +++ 10 files changed, 2060 insertions(+) create mode 100644 licenses/libmpcdec-BSD.txt create mode 100644 src/Formats/audio/mpc/init.luau create mode 100644 src/Formats/codecs/audio/Musepack/Decode.luau create mode 100644 src/Formats/codecs/audio/Musepack/Tables.luau create mode 100644 src/Formats/codecs/audio/Musepack/init.luau create mode 100644 tests/audio/mpc.luau create mode 100644 tools/fixtures/mpc.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..52a4021 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -23,6 +23,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | flac | .flac .oga | yes | yes | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | | audio | m4a | .m4a .m4b .m4r | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` | | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, encodeLayers: 2, 3, channels: 2 | `tests/audio/mp3.luau` | +| audio | mpc | .mpc .mp+ .mpp | yes | - | codecs: "musepack", versions: 7, 8, streaming: true, lossy: true | `tests/audio/mpc.luau` | | audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt", encodeChannels: 2 | `tests/audio/opus.luau` | | audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | | audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | @@ -88,9 +89,11 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **audio** - codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program - codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). + - codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and - codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim, - codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point - codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it: + - codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped - codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT - codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. - codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index d61e1b4..4137ed6 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -38,6 +38,7 @@ | `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | +| `src/Formats/codecs/audio/Musepack/` (Decode, Tables, init: the SV7 / SV8 bitstream, Huffman tables, requantisation, synthesis, stream headers) | port of libmpcdec (musepack_src_r475, The Musepack Development Team) | BSD-3-Clause: [libmpcdec-BSD.txt](libmpcdec-BSD.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/libmpcdec-BSD.txt b/licenses/libmpcdec-BSD.txt new file mode 100644 index 0000000..156247c --- /dev/null +++ b/licenses/libmpcdec-BSD.txt @@ -0,0 +1,36 @@ +libmpcdec (musepack_src_r475, https://files.musepack.net/source/musepack_src_r475.tar.gz), ported to +src/Formats/codecs/audio/Musepack (Decode.luau, Tables.luau, init.luau): + +Copyright (c) 2005, The Musepack Development Team +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of the The Musepack Development Team nor the + names of its contributors may be used to endorse or promote + products derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The 2005-2009 copyright headers of mpc_decoder.c / synth_filter.c / huffman.c carry the same licence. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..54af336 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -230,6 +230,18 @@ local list: { Entry } = { return require("@formats/audio/mp3") end, }, + { + name = "mpc", + category = "audio", + path = "audio/mpc", + extensions = { "mpc", "mp+", "mpp" }, + mime = { "audio/x-musepack", "audio/musepack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" }, + caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true }, + load = function() + return require("@formats/audio/mpc") + end, + }, { name = "opus", category = "audio", diff --git a/src/Formats/audio/mpc/init.luau b/src/Formats/audio/mpc/init.luau new file mode 100644 index 0000000..a75a254 --- /dev/null +++ b/src/Formats/audio/mpc/init.luau @@ -0,0 +1,96 @@ +--!strict +-- audio/mpc: Musepack (.mpc / .mp+ / .mpp), stream versions 7 and 8, through codecs/audio/Musepack (a libmpcdec +-- port). Supports: SV7 (mppenc 1.x) and SV8 (mpcenc 1.30) streams, mono / stereo, every rate (32 / 37.8 / 44.1 / +-- 48 kHz), gapless length (the synthesis delay, SV8 leading silence and the last frame's length are honoured), seeking +-- (SV8: by audio packet, exact; SV7: by frame with 32 frames of pre-roll, as libmpcdec), APEv2 tags +-- (codecs/audio/ApeTag), a leading ID3v2 tag (skipped), ReplayGain values in meta (not applied). Not supported: +-- writing, SV4 - SV6 (UNSUPPORTED), chapters. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Stream = require("@formats/codecs/audio/Stream") +local ApeTag = require("@formats/codecs/audio/ApeTag") +local Musepack = require("@formats/codecs/audio/Musepack") + +-- ------------------------------------------------------------------------------------------------ contract +local Mpc = { + name = "mpc", + category = "audio", + extensions = { "mpc", "mp+", "mpp" }, + mime = { "audio/x-musepack", "audio/musepack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" }, + caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFrames: number?, -- Err.LIMIT past this many output sample frames (default 2^31) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- the size of an ID3v2 tag at p (0 if none) +local function id3v2(b: buffer, p: number, limit: number): number + if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then + return 0 + end + local n = 10 + for i = 6, 9 do + n += bit32.band(buffer.readu8(b, p + i), 127) * 128 ^ (9 - i) + end + return n + (if bit32.band(buffer.readu8(b, p + 5), 0x10) ~= 0 then 10 else 0) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Mpc.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + p += id3v2(b, p, limit) + local v = Musepack.magic(b, p, limit) + if v == 8 then + return 1 + end + return if v == 7 then 0.9 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mpc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local b, base, limit = r.buf, r.base, r.limit + local start = base + id3v2(b, base, limit) + local tags, info = ApeTag.find(b, start, limit) + local stop = if info and info.start > start then info.start else limit + local s, err = Musepack.open(b, start, stop) + if not s then + return nil, err + end + if s.frames > (o.maxFrames or 2 ^ 31) then + return nil, Err.new(Err.LIMIT, "more than " .. (o.maxFrames or 2 ^ 31) .. " frames") + end + local duration = s.frames / s.sampleRate + local dec = { + sampleRate = s.sampleRate, + channels = s.channels, + frames = s.frames, + duration = duration, + bitrate = if duration > 0 then math.floor(s.bytes * 8 / duration + 0.5) else 0, + tags = tags or {}, + codec = "musepack", + version = s.version, + profile = s.profile, + gain = s.gain, + } + return Stream.packets(dec, s :: any) +end + +function Mpc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Mpc.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "mpc", codec = "musepack", version = d.version, profile = d.profile, gain = d.gain, bitrate = d.bitrate }) +end + +return Mpc diff --git a/src/Formats/codecs/audio/Musepack/Decode.luau b/src/Formats/codecs/audio/Musepack/Decode.luau new file mode 100644 index 0000000..8b96245 --- /dev/null +++ b/src/Formats/codecs/audio/Musepack/Decode.luau @@ -0,0 +1,899 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel): the bitstream (band +-- resolutions, scalefactor indices, quantised subband samples, with SV8's canonical Huffman / enumerative codes), +-- requantisation (M/S or L/R) and the 32-band polyphase synthesis. A line-by-line port of libmpcdec's mpc_decoder.c, +-- requant.c and synth_filter.c (musepack_src_r475, BSD-3-Clause, (c) The Musepack Development Team, +-- licenses/libmpcdec-BSD.txt) in double precision float. The bit reader is module state (decoding is synchronous) over +-- a buffer the caller pads by at least PAD bytes past `limit`: the band loops stop as soon as the position passes the +-- limit, so every read stays inside the buffer. No error / assert: failures return nil, "message". +local T = require("@formats/codecs/audio/Musepack/Tables") + +local readu32, bswap, extract, band, bor, rshift, lshift, bnot, bxor = + buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.bnot, bit32.bxor +local abs = math.abs + +local Decode = {} +Decode.PAD = 8192 +Decode.DELAY = 481 -- MPC_DECODER_SYNTH_DELAY +Decode.FRAME = 1152 + +-- ------------------------------------------------------------------------------------------------ tables +local L = T.lut +local HDR, SCFI7, DSCF7 = L(T.HuffHdr), L(T.HuffSCFI), L(T.HuffDSCF) +local Q7: { { T.Lut } } = { + { L(T.HuffQ1_0), L(T.HuffQ1_1) }, + { L(T.HuffQ2_0), L(T.HuffQ2_1) }, + { L(T.HuffQ3_0), L(T.HuffQ3_1) }, + { L(T.HuffQ4_0), L(T.HuffQ4_1) }, + { L(T.HuffQ5_0), L(T.HuffQ5_1) }, + { L(T.HuffQ6_0), L(T.HuffQ6_1) }, + { L(T.HuffQ7_0), L(T.HuffQ7_1) }, +} +local BANDS8 = L(T.H_Bands, T.S_Bands) +local SCFI8 = { L(T.H_SCFI_1, T.S_SCFI_1), L(T.H_SCFI_2, T.S_SCFI_2) } +local DSCF8 = { L(T.H_DSCF_1, T.S_DSCF_1), L(T.H_DSCF_2, T.S_DSCF_2) } +local RES8 = { L(T.H_Res_1, T.S_Res_1), L(T.H_Res_2, T.S_Res_2) } +local Q1_8 = L(T.H_Q1, T.S_Q1) +local Q9UP = L(T.H_Q9up, T.S_Q9up) +-- mpc_can_Q[res - 2][0 / 1] for res 2 and 5 .. 8; res 3 / 4 use Q34[res - 2] +local Q8: { [number]: { T.Lut } } = { + [2] = { L(T.H_Q2_1, T.S_Q2_1), L(T.H_Q2_2, T.S_Q2_2) }, + [5] = { L(T.H_Q5_1, T.S_Q5_1), L(T.H_Q5_2, T.S_Q5_2) }, + [6] = { L(T.H_Q6_1, T.S_Q6_1), L(T.H_Q6_2, T.S_Q6_2) }, + [7] = { L(T.H_Q7_1, T.S_Q7_1), L(T.H_Q7_2, T.S_Q7_2) }, + [8] = { L(T.H_Q8_1, T.S_Q8_1), L(T.H_Q8_2, T.S_Q8_2) }, +} +local Q34 = { L(T.H_Q3, T.S_Q3), L(T.H_Q4, T.S_Q4) } +local THRES = { [2] = 3, [5] = 1, [6] = 3, [7] = 4, [8] = 8 } +local CC, DC, RES_BIT = T.CC, T.DC, T.RES_BIT +local CNK, CNK_LEN, CNK_LOST, LOG2, LOG2_LOST = T.CNK, T.CNK_LEN, T.CNK_LOST, T.LOG2, T.LOG2_LOST + +-- the f32 rounding of the C tables (libmpcdec decodes in single precision) +local F32 = buffer.create(4) +local function f32(x: number): number + buffer.writef32(F32, 0, x) + return buffer.readf32(F32, 0) +end +for i, v in CC do + CC[i] = f32(v) +end + +-- SCF[i]: the scalefactor of index i (0 .. 255, the index's low byte): 2^-15 * 0.83298...^(s - 1), s = i as int8 +-- (libmpcdec's mpc_decoder_scale_output in float mode: 1 dB steps, the table filled outwards from index 1) +local SCF = table.create(256, 0) +do + local f1 = 1 / 32768 + local f2 = f1 + SCF[2] = f32(f1) + f1 *= 0.83298066476582673961 + f2 *= 1 / 0.83298066476582673961 + for n = 1, 128 do + SCF[band(1 + n, 255) + 1] = f32(f1) + SCF[band(1 - n, 255) + 1] = f32(f2) + f1 *= 0.83298066476582673961 + f2 *= 1 / 0.83298066476582673961 + end +end + +-- the synthesis window D (Di_opt / 65536), 32 x 16, row-major +local DW = table.create(512, 0) +for i, v in T.DI do + DW[i] = f32(v / 65536) +end + +-- ------------------------------------------------------------------------------------------------ bit reader +local B: buffer = buffer.create(0) +local P = 0 -- bit position + +local function bits(n: number): number + if n <= 0 then + return 0 + end + if n > 24 then + local hi = bits(n - 16) + return hi * 65536 + bits(16) + end + local w = bswap(readu32(B, rshift(P, 3))) + local v = extract(w, 32 - band(P, 7) - n, n) + P += n + return v +end + +local function peek16(): number + local w = bswap(readu32(B, rshift(P, 3))) + return extract(w, 16 - band(P, 7), 16) +end + +-- a table-driven Huffman symbol (plain or canonical) +local function huff(t: T.Lut): number + local code = peek16() + local k = rshift(code, 8) + 1 + local n = t.len[k] + if n > 0 then + P += n + return t.val[k] + end + local j = t.val[k] + local codes = t.codes + while code < codes[j] do + j += 1 + end + n = t.lens[j] + P += n + local sym = t.sym + if sym then + return sym[band(t.vals[j] - rshift(code, 16 - n), 255) + 1] or 0 + end + return t.vals[j] +end + +-- mpc_bits_log_dec: 0 .. max +local function logDec(max: number): number + if max <= 0 then + return 0 + end + local v = 0 + local len, lost = LOG2[max], LOG2_LOST[max] + if len > 1 then + v = bits(len - 1) + end + if v >= lost then + v = v * 2 + bits(1) - lost + end + return v +end + +-- mpc_bits_enum_dec: an n-bit word with k bits set +local function enumDec(k: number, n: number): number + local out = 0 + local code = bits(CNK_LEN[k][n] - 1) + local lost = CNK_LOST[k][n] + if code >= lost then + code = code * 2 + bits(1) - lost + end + repeat + n -= 1 + local c = CNK[k][n + 1] + if code >= c then + out = bor(out, lshift(1, n)) + code -= c + k -= 1 + end + until k <= 0 or n <= 0 + return out +end + +-- mpc_random_int: two polynomial counters, XORed +local PARITY = table.create(256, 0) +for i = 0, 255 do + local p, v = 0, i + while v > 0 do + p = bxor(p, band(v, 1)) + v = rshift(v, 1) + end + PARITY[i + 1] = p +end + +-- ------------------------------------------------------------------------------------------------ synthesis +-- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing +-- through Byeong Gi Lee's fast DCT) +local function newV(Y: { number }, y: number, V: { number }, o: number) + local A00 = Y[y] + Y[y + 31] + local A01 = Y[y + 1] + Y[y + 30] + local A02 = Y[y + 2] + Y[y + 29] + local A03 = Y[y + 3] + Y[y + 28] + local A04 = Y[y + 4] + Y[y + 27] + local A05 = Y[y + 5] + Y[y + 26] + local A06 = Y[y + 6] + Y[y + 25] + local A07 = Y[y + 7] + Y[y + 24] + local A08 = Y[y + 8] + Y[y + 23] + local A09 = Y[y + 9] + Y[y + 22] + local A10 = Y[y + 10] + Y[y + 21] + local A11 = Y[y + 11] + Y[y + 20] + local A12 = Y[y + 12] + Y[y + 19] + local A13 = Y[y + 13] + Y[y + 18] + local A14 = Y[y + 14] + Y[y + 17] + local A15 = Y[y + 15] + Y[y + 16] + local B00 = A00 + A15 + local B01 = A01 + A14 + local B02 = A02 + A13 + local B03 = A03 + A12 + local B04 = A04 + A11 + local B05 = A05 + A10 + local B06 = A06 + A09 + local B07 = A07 + A08 + local B08 = (A00 - A15) * 0.5024192929 + local B09 = (A01 - A14) * 0.5224986076 + local B10 = (A02 - A13) * 0.5669440627 + local B11 = (A03 - A12) * 0.6468217969 + local B12 = (A04 - A11) * 0.7881546021 + local B13 = (A05 - A10) * 1.0606776476 + local B14 = (A06 - A09) * 1.7224471569 + local B15 = (A07 - A08) * 5.1011486053 + A00 = B00 + B07 + A01 = B01 + B06 + A02 = B02 + B05 + A03 = B03 + B04 + A04 = (B00 - B07) * 0.5097956061 + A05 = (B01 - B06) * 0.6013448834 + A06 = (B02 - B05) * 0.8999761939 + A07 = (B03 - B04) * 2.5629155636 + A08 = B08 + B15 + A09 = B09 + B14 + A10 = B10 + B13 + A11 = B11 + B12 + A12 = (B08 - B15) * 0.5097956061 + A13 = (B09 - B14) * 0.6013448834 + A14 = (B10 - B13) * 0.8999761939 + A15 = (B11 - B12) * 2.5629155636 + B00 = A00 + A03 + B01 = A01 + A02 + B02 = (A00 - A03) * 0.5411961079 + B03 = (A01 - A02) * 1.3065630198 + B04 = A04 + A07 + B05 = A05 + A06 + B06 = (A04 - A07) * 0.5411961079 + B07 = (A05 - A06) * 1.3065630198 + B08 = A08 + A11 + B09 = A09 + A10 + B10 = (A08 - A11) * 0.5411961079 + B11 = (A09 - A10) * 1.3065630198 + B12 = A12 + A15 + B13 = A13 + A14 + B14 = (A12 - A15) * 0.5411961079 + B15 = (A13 - A14) * 1.3065630198 + A00 = B00 + B01 + A01 = (B00 - B01) * 0.7071067691 + A02 = B02 + B03 + A03 = (B02 - B03) * 0.7071067691 + A04 = B04 + B05 + A05 = (B04 - B05) * 0.7071067691 + A06 = B06 + B07 + A07 = (B06 - B07) * 0.7071067691 + A08 = B08 + B09 + A09 = (B08 - B09) * 0.7071067691 + A10 = B10 + B11 + A11 = (B10 - B11) * 0.7071067691 + A12 = B12 + B13 + A13 = (B12 - B13) * 0.7071067691 + A14 = B14 + B15 + A15 = (B14 - B15) * 0.7071067691 + V[o + 48] = -A00 + V[o] = A01 + V[o + 8] = A03 + V[o + 40] = -A02 - A03 + V[o + 12] = A07 + local t = A05 + A07 + V[o + 4] = t + V[o + 36] = -(t + A06) + V[o + 44] = -A04 - A06 - A07 + V[o + 14] = A15 + t = A11 + A15 + V[o + 10] = t + V[o + 6] = t + A13 + t = A09 + A13 + A15 + V[o + 2] = t + t = -t - A14 + V[o + 34] = t + V[o + 38] = t + A09 - A10 - A11 + t = -(A12 + A14 + A15) + V[o + 46] = t - A08 + V[o + 42] = t - A10 - A11 + A00 = (Y[y] - Y[y + 31]) * 0.5006030202 + A01 = (Y[y + 1] - Y[y + 30]) * 0.5054709315 + A02 = (Y[y + 2] - Y[y + 29]) * 0.5154473186 + A03 = (Y[y + 3] - Y[y + 28]) * 0.5310425758 + A04 = (Y[y + 4] - Y[y + 27]) * 0.5531039238 + A05 = (Y[y + 5] - Y[y + 26]) * 0.5829349756 + A06 = (Y[y + 6] - Y[y + 25]) * 0.6225041151 + A07 = (Y[y + 7] - Y[y + 24]) * 0.6748083234 + A08 = (Y[y + 8] - Y[y + 23]) * 0.7445362806 + A09 = (Y[y + 9] - Y[y + 22]) * 0.8393496275 + A10 = (Y[y + 10] - Y[y + 21]) * 0.9725682139 + A11 = (Y[y + 11] - Y[y + 20]) * 1.1694399118 + A12 = (Y[y + 12] - Y[y + 19]) * 1.4841645956 + A13 = (Y[y + 13] - Y[y + 18]) * 2.0577809811 + A14 = (Y[y + 14] - Y[y + 17]) * 3.4076085091 + A15 = (Y[y + 15] - Y[y + 16]) * 10.1900081635 + B00 = A00 + A15 + B01 = A01 + A14 + B02 = A02 + A13 + B03 = A03 + A12 + B04 = A04 + A11 + B05 = A05 + A10 + B06 = A06 + A09 + B07 = A07 + A08 + B08 = (A00 - A15) * 0.5024192929 + B09 = (A01 - A14) * 0.5224986076 + B10 = (A02 - A13) * 0.5669440627 + B11 = (A03 - A12) * 0.6468217969 + B12 = (A04 - A11) * 0.7881546021 + B13 = (A05 - A10) * 1.0606776476 + B14 = (A06 - A09) * 1.7224471569 + B15 = (A07 - A08) * 5.1011486053 + A00 = B00 + B07 + A01 = B01 + B06 + A02 = B02 + B05 + A03 = B03 + B04 + A04 = (B00 - B07) * 0.5097956061 + A05 = (B01 - B06) * 0.6013448834 + A06 = (B02 - B05) * 0.8999761939 + A07 = (B03 - B04) * 2.5629155636 + A08 = B08 + B15 + A09 = B09 + B14 + A10 = B10 + B13 + A11 = B11 + B12 + A12 = (B08 - B15) * 0.5097956061 + A13 = (B09 - B14) * 0.6013448834 + A14 = (B10 - B13) * 0.8999761939 + A15 = (B11 - B12) * 2.5629155636 + B00 = A00 + A03 + B01 = A01 + A02 + B02 = (A00 - A03) * 0.5411961079 + B03 = (A01 - A02) * 1.3065630198 + B04 = A04 + A07 + B05 = A05 + A06 + B06 = (A04 - A07) * 0.5411961079 + B07 = (A05 - A06) * 1.3065630198 + B08 = A08 + A11 + B09 = A09 + A10 + B10 = (A08 - A11) * 0.5411961079 + B11 = (A09 - A10) * 1.3065630198 + B12 = A12 + A15 + B13 = A13 + A14 + B14 = (A12 - A15) * 0.5411961079 + B15 = (A13 - A14) * 1.3065630198 + A00 = (B00 + B01) + A01 = (B00 - B01) * 0.7071067691 + A02 = (B02 + B03) + A03 = (B02 - B03) * 0.7071067691 + A04 = (B04 + B05) + A05 = (B04 - B05) * 0.7071067691 + A06 = (B06 + B07) + A07 = (B06 - B07) * 0.7071067691 + A08 = (B08 + B09) + A09 = (B08 - B09) * 0.7071067691 + A10 = (B10 + B11) + A11 = (B10 - B11) * 0.7071067691 + A12 = (B12 + B13) + A13 = (B12 - B13) * 0.7071067691 + A14 = (B14 + B15) + A15 = (B14 - B15) * 0.7071067691 + V[o + 15] = A15 + t = A07 + A15 + V[o + 13] = t + t += A11 + V[o + 11] = t + V[o + 5] = t + A05 + A13 + t = A03 + A11 + A15 + V[o + 9] = t + V[o + 7] = t + A13 + t = A01 + A09 + A13 + A15 + V[o + 1] = t + V[o + 33] = -t - A14 + t = A05 + A07 + A09 + A13 + A15 + V[o + 3] = t + V[o + 35] = -t - A06 - A14 + t = -(A10 + A11 + A13 + A14 + A15) + V[o + 37] = t - A05 - A06 - A07 + V[o + 39] = t - A02 - A03 + t += A13 - A12 + V[o + 41] = t - A02 - A03 + V[o + 43] = t - A04 - A06 - A07 + t = -(A08 + A12 + A14 + A15) + V[o + 47] = t - A00 + V[o + 45] = t - A04 - A06 - A07 + for i = 0, 15 do + V[o + 32 - i] = -V[o + i] + end + for i = 33, 47 do + V[o + 96 - i] = V[o + i] + end +end +-- ------------------------------------------------------------------------------------------------ state +export type State = { + version: number, -- 7 | 8 + maxBand: number, -- the highest band index (0 .. 31) + ms: boolean, + channels: number, + resL: { number }, -- [band + 1] + resR: { number }, + scfL: { number }, -- [band * 3 + m + 1] + scfR: { number }, + scfiL: { number }, + scfiR: { number }, + dscfL: { boolean }, + dscfR: { boolean }, + msf: { boolean }, + qL: { number }, -- [band * 36 + k + 1] + qR: { number }, + yL: { number }, -- [n * 32 + band + 1], n = 0 .. 35 + yR: { number }, + vL: { number }, -- synthesis history, 2304 + 960 + vR: { number }, + r1: number, + r2: number, + lastMaxBand: number, +} + +function Decode.state(version: number, maxBand: number, ms: boolean, channels: number): State + local st: State = { + version = version, + maxBand = maxBand, + ms = ms, + channels = channels, + resL = table.create(33, 0), + resR = table.create(33, 0), + scfL = table.create(99, 0), + scfR = table.create(99, 0), + scfiL = table.create(33, 0), + scfiR = table.create(33, 0), + dscfL = table.create(33, false), + dscfR = table.create(33, false), + msf = table.create(33, false), + qL = table.create(32 * 36, 0), + qR = table.create(32 * 36, 0), + yL = table.create(36 * 32, 0), + yR = table.create(36 * 32, 0), + vL = table.create(2304 + 960, 0), + vR = table.create(2304 + 960, 0), + r1 = 1, + r2 = 1, + lastMaxBand = 0, + } + return st +end + +-- reset(st, scf): forget the history (before a seek); scf = the scalefactor indices to assume (libmpcdec: 0 at the +-- start of the stream, 0x01010101 in the middle of an SV7 stream). The noise generator restarts too, so a seek +-- decodes like libmpcdec seeking in a freshly opened stream. +function Decode.reset(st: State, scf: number) + for i = 1, 99 do + st.scfL[i] = scf + st.scfR[i] = scf + end + for i = 1, 33 do + st.resL[i], st.resR[i] = 0, 0 + st.dscfL[i], st.dscfR[i] = false, false + st.msf[i] = false + end + for i = 1, 2304 + 960 do + st.vL[i], st.vR[i] = 0, 0 + end + st.lastMaxBand = 0 + st.r1, st.r2 = 1, 1 +end + +local function noise(st: State, q: { number }, o: number) + local r1, r2 = st.r1, st.r2 + for k = 0, 35 do + local t1 = PARITY[band(r1, 0xF5) + 1] + local t2 = PARITY[band(rshift(r2, 25), 0x63) + 1] + r1 = bor(rshift(r1, 1), lshift(t1, 31)) + r2 = bor(band(lshift(r2, 1), 0xFFFFFFFF), t2) + local t = bxor(r1, r2) + q[o + k] = band(rshift(t, 24), 255) + band(rshift(t, 16), 255) + band(rshift(t, 8), 255) + band(t, 255) - 510 + end + st.r1, st.r2 = r1, r2 +end + +-- ------------------------------------------------------------------------------------------------ SV7 +-- mpc_decoder_read_bitstream_sv7 -> true | nil, message +local function readSv7(st: State, limit: number): (boolean?, string?) + local resL, resR, msf = st.resL, st.resR, st.msf + local maxUsed = 0 + local ms = st.ms + resL[1] = bits(4) + resR[1] = bits(4) + if resL[1] ~= 0 or resR[1] ~= 0 then + if ms then + msf[1] = bits(1) == 1 + end + maxUsed = 1 + end + for n = 1, st.maxBand do + local idx = huff(HDR) + resL[n + 1] = if idx ~= 4 then resL[n] + idx else bits(4) + idx = huff(HDR) + resR[n + 1] = if idx ~= 4 then resR[n] + idx else bits(4) + local l, r = resL[n + 1], resR[n + 1] + if l < -1 or l > 17 or r < -1 or r > 17 then + return nil, "bad band resolution" + end + if l ~= 0 or r ~= 0 then + if ms then + msf[n + 1] = bits(1) == 1 + end + maxUsed = n + 1 + end + end + if resL[1] > 17 or resR[1] > 17 then + return nil, "bad band resolution" + end + -- SCFI + local scfiL, scfiR = st.scfiL, st.scfiR + for n = 1, maxUsed do + if resL[n] ~= 0 then + scfiL[n] = huff(SCFI7) + end + if resR[n] ~= 0 then + scfiR[n] = huff(SCFI7) + end + end + if P > limit then + return nil, "truncated frame" + end + -- SCF / DSCF + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + if res ~= 0 then + local scf = if c == 1 then st.scfL else st.scfR + local scfi = if c == 1 then scfiL[n] else scfiR[n] + local o = (n - 1) * 3 + local idx = huff(DSCF7) + local s0 = if idx ~= 8 then scf[o + 3] + idx else bits(6) + local s1, s2 + if scfi == 1 then + idx = huff(DSCF7) + s1 = if idx ~= 8 then s0 + idx else bits(6) + s2 = s1 + elseif scfi == 3 then + s1, s2 = s0, s0 + elseif scfi == 2 then + s1 = s0 + idx = huff(DSCF7) + s2 = if idx ~= 8 then s1 + idx else bits(6) + else + idx = huff(DSCF7) + s1 = if idx ~= 8 then s0 + idx else bits(6) + idx = huff(DSCF7) + s2 = if idx ~= 8 then s1 + idx else bits(6) + end + scf[o + 1] = if s0 > 1024 then 0x8080 else s0 + scf[o + 2] = if s1 > 1024 then 0x8080 else s1 + scf[o + 3] = if s2 > 1024 then 0x8080 else s2 + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- samples + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + local q = if c == 1 then st.qL else st.qR + local o = (n - 1) * 36 + 1 + if res == -1 then + noise(st, q, o) + elseif res == 1 then + local tab = Q7[1][bits(1) + 1] + for k = 0, 35, 3 do + local idx = huff(tab) + q[o + k] = idx % 3 - 1 + q[o + k + 1] = (idx // 3) % 3 - 1 + q[o + k + 2] = idx // 9 - 1 + end + elseif res == 2 then + local tab = Q7[2][bits(1) + 1] + for k = 0, 35, 2 do + local idx = huff(tab) + q[o + k] = idx % 5 - 2 + q[o + k + 1] = idx // 5 - 2 + end + elseif res >= 3 and res <= 7 then + local tab = Q7[res][bits(1) + 1] + for k = 0, 35 do + q[o + k] = huff(tab) + end + elseif res >= 8 then + local nb, dc = RES_BIT[res], DC[res + 2] + for k = 0, 35 do + q[o + k] = bits(nb) - dc + end + end + if P > limit then + return nil, "truncated frame" + end + end + end + -- bands above maxUsed: silent + for n = maxUsed + 1, st.maxBand + 1 do + resL[n], resR[n] = 0, 0 + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ SV8 +local function readSv8(st: State, key: boolean, limit: number): (boolean?, string?) + local resL, resR, msf = st.resL, st.resR, st.msf + local maxBand = st.maxBand + local maxUsed + if key then + maxUsed = logDec(maxBand + 1) + else + maxUsed = st.lastMaxBand + huff(BANDS8) + if maxUsed > 32 then + maxUsed -= 33 + end + end + if maxUsed > maxBand + 1 then + return nil, "bad band count" + end + st.lastMaxBand = maxUsed + if maxUsed > 0 then + local l, r = huff(RES8[1]), huff(RES8[1]) + resL[maxUsed] = if l > 15 then l - 17 else l + resR[maxUsed] = if r > 15 then r - 17 else r + for n = maxUsed - 1, 1, -1 do + l = huff(RES8[if resL[n + 1] > 2 then 2 else 1]) + resL[n + 1] + resL[n] = if l > 15 then l - 17 else l + r = huff(RES8[if resR[n + 1] > 2 then 2 else 1]) + resR[n + 1] + resR[n] = if r > 15 then r - 17 else r + end + if st.ms then + local tot = 0 + for n = 1, maxUsed do + if resL[n] ~= 0 or resR[n] ~= 0 then + tot += 1 + end + end + local cnt = logDec(tot) + local tmp = 0 + if cnt ~= 0 and cnt ~= tot then + tmp = enumDec(math.min(cnt, tot - cnt), tot) + end + if cnt * 2 > tot then + tmp = bnot(tmp) + end + for n = maxUsed, 1, -1 do + if resL[n] ~= 0 or resR[n] ~= 0 then + msf[n] = band(tmp, 1) == 1 + tmp = rshift(tmp, 1) + end + end + end + end + for n = maxUsed + 1, maxBand + 1 do + resL[n], resR[n] = 0, 0 + end + -- SCFI + local dscfL, dscfR = st.dscfL, st.dscfR + if key then + for n = 1, 32 do + dscfL[n], dscfR[n] = true, true + end + end + local scfiL, scfiR = st.scfiL, st.scfiR + for n = 1, maxUsed do + local cnt = -1 + if resL[n] ~= 0 then + cnt += 1 + end + if resR[n] ~= 0 then + cnt += 1 + end + if cnt >= 0 then + local tmp = huff(SCFI8[cnt + 1]) + if resL[n] ~= 0 then + scfiL[n] = rshift(tmp, 2 * cnt) + end + if resR[n] ~= 0 then + scfiR[n] = band(tmp, 3) + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- SCF / DSCF + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + if res ~= 0 then + local scf = if c == 1 then st.scfL else st.scfR + local scfi = if c == 1 then scfiL[n] else scfiR[n] + local dscf = if c == 1 then dscfL else dscfR + local o = (n - 1) * 3 + if dscf[n] then + scf[o + 1] = bits(7) - 6 + dscf[n] = false + else + local tmp = huff(DSCF8[2]) + if tmp == 64 then + tmp += bits(6) + end + scf[o + 1] = band(scf[o + 3] - 25 + tmp, 127) - 6 + end + for m = 0, 1 do + if band(lshift(scfi, m), 2) == 0 then + local tmp = huff(DSCF8[1]) + if tmp == 31 then + tmp = 64 + bits(6) + end + scf[o + m + 2] = band(scf[o + m + 1] - 25 + tmp, 127) - 6 + else + scf[o + m + 2] = scf[o + m + 1] + end + end + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- samples + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + local q = if c == 1 then st.qL else st.qR + local o = (n - 1) * 36 + 1 + if res == 2 then + local tabs = Q8[2] + local thres = 3 + local idx = 6 + for k = 0, 35, 3 do + local tmp = huff(tabs[if idx > thres then 2 else 1]) + local a, b, cc = tmp % 5 - 2, (tmp // 5) % 5 - 2, tmp // 25 - 2 + q[o + k], q[o + k + 1], q[o + k + 2] = a, b, cc + idx = rshift(idx, 1) + abs(a) + abs(b) + abs(cc) + end + elseif res == 1 then + local k = 0 + while k < 36 do + local kmax = k + 18 + local cnt = huff(Q1_8) + local idx = 0 + if cnt > 0 and cnt < 18 then + idx = enumDec(if cnt <= 9 then cnt else 18 - cnt, 18) + end + if cnt > 9 then + idx = bnot(idx) + end + while k < kmax do + q[o + k] = 0 + if band(idx, 0x20000) ~= 0 then + q[o + k] = bits(1) * 2 - 1 + end + idx = lshift(idx, 1) + k += 1 + end + end + elseif res == -1 then + noise(st, q, o) + elseif res == 3 or res == 4 then + local tab = Q34[res - 2] + for k = 0, 35, 2 do + local s = band(huff(tab), 255) + local s1, s2 = band(s, 15), rshift(s, 4) + q[o + k] = if s1 >= 8 then s1 - 16 else s1 + q[o + k + 1] = if s2 >= 8 then s2 - 16 else s2 + end + elseif res >= 5 and res <= 8 then + local tabs = Q8[res] + local thres = THRES[res] + local idx = 2 * thres + for k = 0, 35 do + local v = huff(tabs[if idx > thres then 2 else 1]) + q[o + k] = v + idx = rshift(idx, 1) + abs(v) + end + elseif res >= 9 then + local sh = res - 9 + local dc = DC[res + 2] + for k = 0, 35 do + local v = band(huff(Q9UP), 255) + if sh > 0 then + v = v * 2 ^ sh + bits(sh) + end + q[o + k] = v - dc + end + elseif res < -1 then + return nil, "bad band resolution" + end + if P > limit then + return nil, "truncated frame" + end + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ requantisation +local function requant(st: State) + local resL, resR, msf = st.resL, st.resR, st.msf + local scfL, scfR, qL, qR, yL, yR = st.scfL, st.scfR, st.qL, st.qR, st.yL, st.yR + for b = 1, st.maxBand + 1 do + local rl, rr = resL[b], resR[b] + local ccl, ccr = CC[rl + 2] or 0, CC[rr + 2] or 0 + local ms = msf[b] + local o = (b - 1) * 36 + 1 + for part = 0, 2 do + local fl = if rl ~= 0 then f32(ccl * SCF[band(scfL[(b - 1) * 3 + part + 1], 255) + 1]) else 0 + local fr = if rr ~= 0 then f32(ccr * SCF[band(scfR[(b - 1) * 3 + part + 1], 255) + 1]) else 0 + local y = part * 12 * 32 + b + local qo = o + part * 12 + if ms then + for k = 0, 11 do + local l, r = fl * qL[qo + k], fr * qR[qo + k] + yL[y], yR[y] = l + r, l - r + y += 32 + end + else + for k = 0, 11 do + yL[y], yR[y] = fl * qL[qo + k], fr * qR[qo + k] + y += 32 + end + end + end + end +end + + +-- mpc_synthese_filter_float for one channel: 36 x 32 subband samples -> 1152 samples at out[base + i * step] +local function synth(V: { number }, Y: { number }, out: { number }, base: number, step: number) + table.move(V, 1, 960, 2305) + local o = 2304 + 1 + local dw = DW + local p = base + for n = 0, 35 do + o -= 64 + newV(Y, n * 32 + 1, V, o) + for k = 0, 31 do + local v = o + k + local d = k * 16 + 1 + out[p] = V[v] * dw[d] + V[v + 96] * dw[d + 1] + V[v + 128] * dw[d + 2] + V[v + 224] * dw[d + 3] + + V[v + 256] * dw[d + 4] + V[v + 352] * dw[d + 5] + V[v + 384] * dw[d + 6] + V[v + 480] * dw[d + 7] + + V[v + 512] * dw[d + 8] + V[v + 608] * dw[d + 9] + V[v + 640] * dw[d + 10] + V[v + 736] * dw[d + 11] + + V[v + 768] * dw[d + 12] + V[v + 864] * dw[d + 13] + V[v + 896] * dw[d + 14] + V[v + 992] * dw[d + 15] + p += step + end + end +end + +-- ------------------------------------------------------------------------------------------------ frames +-- frame(st, buf, bitPos, limitBits, key, out, base) -> the bit position after the frame | nil, message: decodes one +-- frame from buf (padded by PAD bytes past limitBits / 8) into out[base ..] (1152 * channels interleaved floats). +-- key: an SV8 key frame (the first of a block). bitPos < 0 decodes a silent frame (the synthesis tail). +function Decode.frame(st: State, buf: buffer, bitPos: number, limitBits: number, key: boolean, out: { number }, base: number): (number?, string?) + if bitPos >= 0 then + if rshift(limitBits, 3) + Decode.PAD > buffer.len(buf) or bitPos > limitBits then + return nil, "truncated frame" + end + B, P = buf, bitPos + local ok, err + if st.version == 8 then + ok, err = readSv8(st, key, limitBits) + else + ok, err = readSv7(st, limitBits) + end + B = buffer.create(0) + if not ok then + return nil, err + end + else + for b = 1, st.maxBand + 1 do + st.resL[b], st.resR[b] = 0, 0 + end + end + local pos = P + requant(st) + local ch = st.channels + synth(st.vL, st.yL, out, base, ch) + if ch > 1 then + synth(st.vR, st.yR, out, base + 1, ch) + end + return if bitPos >= 0 then pos else bitPos, nil +end + +-- bitsAt(buf, bitPos, n) -> n (1 .. 24) bits at bitPos (frame headers: the SV7 frame size); the caller keeps +-- bitPos / 8 + 4 inside buf +function Decode.bitsAt(buf: buffer, bitPos: number, n: number): number + local w = bswap(readu32(buf, rshift(bitPos, 3))) + return extract(w, 32 - band(bitPos, 7) - n, n) +end + +return Decode diff --git a/src/Formats/codecs/audio/Musepack/Tables.luau b/src/Formats/codecs/audio/Musepack/Tables.luau new file mode 100644 index 0000000..448ea85 --- /dev/null +++ b/src/Formats/codecs/audio/Musepack/Tables.luau @@ -0,0 +1,379 @@ +--!strict +-- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, the synthesis window and the requantisation +-- constants. Ported from libmpcdec (musepack_src_r475: huffman.c, synth_filter.c, requant.c, mpc_bits_reader.c; +-- BSD-3-Clause, (c) The Musepack Development Team, licenses/libmpcdec-BSD.txt); the tables are transcribed by script. +-- Each Huffman table is a flat { code, length, value, ... } list sorted by descending left-aligned 16-bit code; +-- canonical (SV8) tables map value - (code >> (16 - length)) through their symbol list. lut(table, sym?) builds the +-- 8-bit first-level lookup the decoder uses. +local T = {} + +T.HuffHdr = { + 32768, 1, 0, 24576, 3, 1, 24064, 7, -4, 23936, 9, 3, 23808, 9, 4, 23552, 8, -5, 22528, 6, 2, 20480, 5, -3, 16384, 4, -2, 0, 2, -1, +} +T.HuffSCFI = { + 32768, 1, 1, 24576, 3, 2, 16384, 3, 0, 0, 2, 3, +} +T.HuffDSCF = { + 63488, 5, 5, 61440, 5, -4, 57344, 4, 3, 53248, 4, -3, 49152, 4, 8, 40960, 3, 1, 36864, 4, 0, 34816, 5, -5, 33792, 6, 7, 32768, 6, -7, + 24576, 3, -1, 16384, 3, 2, 12288, 4, 4, 10240, 5, 6, 8192, 5, -6, 0, 3, -2, +} +T.HuffQ1_0 = { + 57344, 3, 13, 56320, 6, 26, 55296, 6, 0, 54272, 6, 20, 53248, 6, 6, 49152, 4, 14, 45056, 4, 12, 40960, 4, 4, 36864, 4, 22, 35840, 6, 8, + 34816, 6, 18, 33792, 6, 24, 32768, 6, 2, 28672, 4, 16, 24576, 4, 10, 22528, 5, 17, 20480, 5, 9, 18432, 5, 1, 16384, 5, 25, 14336, 5, 5, + 12288, 5, 21, 10240, 5, 3, 8192, 5, 11, 6144, 5, 15, 4096, 5, 23, 2048, 5, 19, 0, 5, 7, +} +T.HuffQ1_1 = { + 32768, 1, 13, 32256, 7, 15, 31744, 7, 1, 31232, 7, 11, 30720, 7, 7, 30208, 7, 17, 29696, 7, 25, 29184, 7, 19, 29056, 9, 8, 28928, 9, 18, + 28800, 9, 2, 28672, 9, 24, 28160, 7, 3, 27648, 7, 23, 27136, 7, 21, 26624, 7, 5, 26368, 8, 0, 26112, 8, 26, 25856, 8, 6, 25600, 8, 20, + 24576, 6, 9, 20480, 4, 14, 16384, 4, 12, 12288, 4, 4, 8192, 4, 22, 4096, 4, 16, 0, 4, 10, +} +T.HuffQ2_0 = { + 61440, 4, 13, 57344, 4, 17, 53248, 4, 7, 49152, 4, 11, 48128, 6, 1, 47104, 6, 23, 46592, 7, 4, 46080, 7, 20, 45568, 7, 0, 45056, 7, 24, + 43008, 5, 22, 40960, 5, 10, 32768, 3, 12, 30720, 5, 2, 28672, 5, 14, 24576, 4, 6, 20480, 4, 18, 16384, 4, 8, 12288, 4, 16, 10240, 5, 9, + 8192, 5, 5, 6144, 5, 15, 4096, 5, 21, 2048, 5, 19, 0, 5, 3, +} +T.HuffQ2_1 = { + 63488, 5, 18, 61440, 5, 6, 59392, 5, 8, 59136, 8, 3, 59072, 10, 24, 59008, 10, 4, 58944, 10, 0, 58880, 10, 20, 58368, 7, 23, 57856, 7, 1, + 57344, 7, 19, 55296, 5, 16, 54784, 7, 15, 54272, 7, 21, 53760, 7, 9, 53248, 7, 5, 52224, 6, 2, 51200, 6, 10, 50176, 6, 14, 49152, 6, 22, + 32768, 2, 12, 24576, 3, 13, 16384, 3, 17, 8192, 3, 11, 0, 3, 7, +} +T.HuffQ3_0 = { + 57344, 3, 1, 53248, 4, 3, 49152, 4, -3, 40960, 3, 2, 32768, 3, -2, 16384, 2, 0, 0, 2, -1, +} +T.HuffQ3_1 = { + 49152, 2, 0, 32768, 2, -1, 16384, 2, 1, 12288, 4, -2, 10240, 5, 3, 8192, 5, -3, 0, 3, 2, +} +T.HuffQ4_0 = { + 57344, 3, 0, 49152, 3, -1, 40960, 3, 1, 32768, 3, -2, 24576, 3, 2, 20480, 4, -4, 16384, 4, 4, 8192, 3, 3, 0, 3, -3, +} +T.HuffQ4_1 = { + 57344, 3, 1, 53248, 4, 2, 49152, 4, -3, 32768, 2, 0, 24576, 3, -2, 20480, 4, 3, 18432, 5, -4, 16384, 5, 4, 0, 2, -1, +} +T.HuffQ5_0 = { + 61440, 4, 2, 59392, 5, 5, 58368, 6, -7, 57344, 6, 7, 53248, 4, -3, 49152, 4, 3, 47104, 5, -6, 45056, 5, 6, 40960, 4, -4, 36864, 4, 4, + 32768, 4, -5, 24576, 3, 0, 16384, 3, -1, 8192, 3, 1, 0, 3, -2, +} +T.HuffQ5_1 = { + 61440, 4, 3, 59392, 5, 4, 58880, 7, 6, 58624, 8, -7, 58368, 8, 7, 57344, 6, -6, 49152, 3, 0, 40960, 3, -1, 32768, 3, 1, 24576, 3, -2, + 16384, 3, 2, 14336, 5, -5, 12288, 5, 5, 8192, 4, -4, 0, 3, -3, +} +T.HuffQ6_0 = { + 63488, 5, 3, 61440, 5, -4, 60416, 6, -11, 59392, 6, 12, 57344, 5, 4, 55296, 5, 6, 53248, 5, -5, 51200, 5, 5, 49152, 5, 7, 47104, 5, -7, + 46080, 6, -12, 45056, 6, -13, 43008, 5, -6, 40960, 5, 8, 38912, 5, -8, 36864, 5, 9, 34816, 5, -9, 33792, 6, 13, 33280, 7, -15, 32768, 7, 15, + 28672, 4, 0, 26624, 5, -10, 24576, 5, 10, 20480, 4, -1, 16384, 4, 2, 12288, 4, 1, 8192, 4, -2, 7168, 6, 14, 6144, 6, -14, 4096, 5, 11, + 0, 4, -3, +} +T.HuffQ6_1 = { + 63488, 5, -6, 61440, 5, 6, 57344, 4, 1, 53248, 4, -1, 52736, 7, 10, 52224, 7, -10, 51968, 8, -11, 51840, 9, -12, 51808, 11, 13, 51800, 13, 15, + 51792, 13, -14, 51784, 13, 14, 51776, 13, -15, 51712, 10, -13, 51456, 8, 11, 51200, 8, 12, 50176, 6, -9, 49152, 6, 9, 45056, 4, -2, 40960, 4, 2, + 36864, 4, 3, 32768, 4, -3, 30720, 5, -7, 28672, 5, 7, 24576, 4, -4, 20480, 4, 4, 18432, 5, -8, 16384, 5, 8, 12288, 4, 5, 8192, 4, -5, + 0, 3, 0, +} +T.HuffQ7_0 = { + 64512, 6, 7, 63488, 6, 8, 62464, 6, 9, 61440, 6, -8, 60416, 6, 11, 59904, 7, 21, 59648, 8, -28, 59392, 8, 28, 58368, 6, -9, 57856, 7, -22, + 57344, 7, -21, 56320, 6, -10, 55296, 6, -11, 54272, 6, 10, 53248, 6, 12, 52224, 6, -13, 51712, 7, 22, 51200, 7, 23, 50176, 6, -12, 49152, 6, 13, + 48128, 6, 14, 47104, 6, -14, 46592, 7, -23, 46336, 8, -29, 46080, 8, 29, 45056, 6, -15, 44032, 6, 15, 43008, 6, 16, 41984, 6, -16, 41472, 7, -24, + 40960, 7, 24, 39936, 6, 17, 39424, 7, -25, 39168, 8, -30, 38912, 8, 30, 37888, 6, -17, 36864, 6, 18, 35840, 6, -18, 35328, 7, 25, 34816, 7, 26, + 33792, 6, 19, 33280, 7, -26, 32768, 7, -27, 30720, 5, 2, 29696, 6, -19, 28672, 6, 20, 26624, 5, -1, 26368, 8, -31, 26112, 8, 31, 25600, 7, 27, + 24576, 6, -20, 22528, 5, 1, 20480, 5, -5, 18432, 5, -3, 16384, 5, 3, 14336, 5, 0, 12288, 5, -2, 10240, 5, -4, 8192, 5, 4, 6144, 5, 5, + 4096, 5, -6, 2048, 5, 6, 0, 5, -7, +} +T.HuffQ7_1 = { + 63488, 5, -1, 61440, 5, 2, 59392, 5, -2, 57344, 5, 3, 57088, 8, -20, 57024, 10, 24, 57020, 14, 28, 57016, 14, -28, 57012, 14, -30, 57008, 14, 30, + 56992, 12, -27, 56988, 14, 29, 56984, 14, -29, 56980, 14, 31, 56976, 14, -31, 56960, 12, 27, 56832, 9, -22, 56320, 7, -17, 55296, 6, -11, 53248, 5, -3, + 51200, 5, 4, 49152, 5, -4, 48640, 7, 17, 48384, 8, 20, 48256, 9, 22, 48192, 10, -25, 48128, 10, -26, 47104, 6, 12, 45056, 5, 5, 43008, 5, -5, + 40960, 5, 6, 38912, 5, -6, 37888, 6, -12, 37376, 7, -18, 36864, 7, 18, 35840, 6, 13, 34816, 6, -13, 32768, 5, -7, 31744, 6, 14, 31488, 8, 21, + 31232, 8, -21, 30720, 7, -19, 28672, 5, 7, 26624, 5, 8, 25600, 6, -14, 24576, 6, -15, 22528, 5, -8, 21504, 6, 15, 20992, 7, 19, 20928, 10, 25, + 20864, 10, 26, 20736, 9, -23, 20608, 9, 23, 20480, 9, -24, 18432, 5, -9, 16384, 5, 9, 15360, 6, 16, 14336, 6, -16, 12288, 5, 10, 8192, 4, 0, + 6144, 5, -10, 4096, 5, 11, 0, 4, 1, +} +T.H_SCFI_1 = { + 32768, 1, 1, 16384, 2, 2, 0, 3, 3, +} +T.H_SCFI_2 = { + 32768, 2, 3, 16384, 3, 5, 6144, 5, 11, 1024, 6, 14, 0, 7, 15, +} +T.H_DSCF_1 = { + 40960, 3, 7, 16384, 4, 12, 10240, 5, 16, 6144, 6, 21, 3584, 7, 27, 1792, 8, 34, 896, 9, 41, 320, 10, 48, 128, 11, 53, 48, 12, 57, + 24, 13, 60, 0, 14, 63, +} +T.H_DSCF_2 = { + 24576, 3, 7, 12288, 4, 10, 6144, 5, 13, 4096, 6, 16, 2560, 7, 20, 1536, 8, 25, 896, 9, 31, 448, 10, 38, 224, 11, 45, 80, 12, 52, + 32, 13, 57, 12, 14, 61, 0, 15, 64, +} +T.H_Bands = { + 32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 5, 6, 2048, 6, 8, 1536, 7, 10, 768, 8, 13, 512, 9, 16, 320, 10, 20, 192, 11, 25, + 16, 12, 31, 0, 13, 32, +} +T.H_Res_1 = { + 32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 4, 4, 2048, 5, 5, 1024, 6, 6, 512, 7, 7, 256, 8, 8, 128, 9, 9, 64, 10, 10, + 32, 11, 11, 16, 12, 12, 8, 13, 13, 4, 14, 14, 2, 15, 15, 0, 16, 16, +} +T.H_Res_2 = { + 16384, 2, 3, 8192, 3, 4, 4096, 4, 5, 2048, 5, 6, 1024, 6, 7, 512, 7, 8, 256, 8, 9, 128, 9, 10, 64, 10, 11, 32, 11, 12, + 16, 12, 13, 0, 14, 16, +} +T.H_Q1 = { + 24576, 3, 7, 4096, 4, 10, 2048, 5, 11, 1024, 6, 12, 512, 7, 13, 256, 8, 14, 128, 9, 15, 64, 10, 16, 32, 11, 17, 0, 12, 18, +} +T.H_Q2_1 = { + 57344, 3, 7, 32768, 4, 14, 15360, 6, 38, 10752, 7, 53, 4608, 8, 74, 1536, 9, 92, 960, 10, 104, 96, 11, 119, 32, 12, 122, 0, 13, 124, +} +T.H_Q2_2 = { + 61440, 4, 15, 28672, 5, 30, 18432, 6, 44, 15360, 7, 62, 3072, 8, 92, 1920, 9, 104, 192, 10, 119, 64, 11, 122, 0, 12, 124, +} +T.H_Q3 = { + 57344, 3, 7, 32768, 4, 14, 20480, 5, 22, 9216, 6, 32, 2560, 7, 41, 512, 8, 46, 0, 9, 48, +} +T.H_Q4 = { + 61440, 4, 15, 36864, 5, 30, 13312, 6, 48, 6144, 7, 61, 1280, 8, 73, 256, 9, 78, 0, 10, 80, 0, 0, 90, +} +T.H_Q5_1 = { + 49152, 2, 3, 16384, 3, 6, 8192, 4, 8, 4096, 5, 10, 2048, 6, 12, 0, 7, 14, +} +T.H_Q5_2 = { + 24576, 3, 7, 8192, 4, 10, 4096, 5, 12, 0, 6, 14, +} +T.H_Q6_1 = { + 49152, 2, 3, 32768, 3, 6, 16384, 4, 10, 10240, 5, 14, 3072, 6, 19, 2048, 7, 22, 1024, 8, 26, 0, 9, 30, +} +T.H_Q6_2 = { + 20480, 4, 15, 8192, 5, 20, 4096, 6, 24, 1024, 7, 28, 0, 8, 30, +} +T.H_Q7_1 = { + 49152, 2, 3, 32768, 3, 6, 24576, 4, 10, 16384, 5, 16, 10240, 6, 24, 5120, 7, 34, 2560, 8, 44, 1024, 9, 54, 0, 10, 62, +} +T.H_Q7_2 = { + 24576, 5, 31, 9216, 6, 43, 4096, 7, 52, 512, 8, 60, 0, 9, 62, +} +T.H_Q8_1 = { + 49152, 2, 3, 32768, 3, 6, 28672, 4, 10, 22528, 5, 17, 14336, 6, 28, 10240, 7, 42, 6400, 8, 62, 3328, 9, 87, 640, 10, 113, 96, 11, 123, + 0, 12, 126, +} +T.H_Q8_2 = { + 38912, 6, 63, 10752, 7, 101, 1024, 8, 122, 0, 9, 126, +} +T.H_Q9up = { + 63488, 6, 63, 44032, 7, 125, 9728, 8, -45, 640, 9, -7, 64, 10, -2, 0, 11, -1, +} +T.S_SCFI_1 = { + 2, 3, 1, 0, +} +T.S_SCFI_2 = { + 15, 10, 14, 11, 13, 9, 7, 6, 5, 12, 8, 3, 2, 0, 4, 1, +} +T.S_DSCF_1 = { + 35, 34, 33, 36, 32, 30, 29, 27, 26, 37, 28, 25, 39, 38, 24, 23, 40, 22, 21, 20, 19, 43, 42, 41, 18, 17, 16, 15, 46, 45, 44, 14, + 13, 12, 11, 49, 48, 47, 31, 10, 9, 8, 7, 6, 52, 51, 50, 5, 4, 3, 54, 53, 2, 1, 0, 57, 56, 55, 63, 62, 61, 60, 59, 58, +} +T.S_DSCF_2 = { + 33, 32, 31, 30, 29, 34, 28, 27, 36, 35, 26, 37, 25, 38, 24, 23, 40, 39, 22, 21, 42, 41, 20, 19, 18, 45, 44, 43, 17, 16, 15, 14, + 48, 47, 46, 13, 12, 11, 10, 64, 52, 51, 50, 49, 9, 8, 7, 6, 55, 54, 53, 5, 4, 3, 58, 57, 56, 2, 1, 63, 62, 61, 60, 59, + 0, +} +T.S_Bands = { + 0, 32, 1, 31, 2, 30, 3, 4, 29, 6, 5, 28, 7, 27, 26, 8, 25, 24, 23, 9, 22, 21, 20, 18, 17, 16, 15, 14, 12, 11, 10, 19, + 13, +} +T.S_Res_1 = { + 0, 1, 16, 2, 3, 4, 5, 15, 6, 7, 8, 9, 10, 11, 12, 14, 13, +} +T.S_Res_2 = { + 16, 1, 0, 2, 15, 3, 14, 4, 5, 13, 6, 12, 7, 11, 10, 9, 8, +} +T.S_Q1 = { + 7, 6, 5, 4, 3, 10, 9, 8, 2, 1, 11, 0, 12, 13, 14, 15, 16, 18, 17, +} +T.S_Q2_1 = { + 62, 87, 67, 63, 61, 57, 37, 93, 92, 88, 86, 83, 82, 81, 68, 66, 58, 56, 42, 41, 38, 36, 32, 31, 112, 91, 72, 64, 60, 52, 43, 33, + 12, 117, 113, 111, 107, 97, 89, 85, 77, 73, 71, 69, 65, 59, 55, 53, 51, 47, 39, 35, 27, 17, 13, 11, 7, 118, 116, 108, 106, 98, 96, 94, + 90, 84, 80, 78, 76, 48, 46, 44, 40, 34, 30, 28, 26, 18, 16, 8, 6, 122, 110, 102, 74, 70, 54, 50, 22, 2, 123, 121, 119, 115, 114, 109, + 105, 103, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 14, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4, +} +T.S_Q2_2 = { + 62, 92, 87, 86, 82, 68, 67, 66, 63, 61, 58, 57, 56, 42, 38, 37, 32, 93, 91, 88, 83, 81, 43, 41, 36, 33, 31, 112, 72, 64, 60, 52, + 12, 118, 117, 116, 113, 111, 108, 107, 106, 98, 97, 96, 94, 90, 89, 85, 84, 80, 78, 77, 76, 73, 71, 69, 65, 59, 55, 53, 51, 48, 47, 46, + 44, 40, 39, 35, 34, 30, 28, 27, 26, 18, 17, 16, 13, 11, 8, 7, 6, 122, 110, 74, 70, 54, 50, 22, 14, 2, 123, 121, 119, 115, 114, 109, + 105, 103, 102, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4, +} +T.S_Q3 = { + 0, 17, 16, 1, 15, -16, -1, 32, 31, 2, 14, -15, -32, 34, 33, 47, 46, 18, 30, -14, -2, -31, -17, -18, 49, 48, 63, 19, 29, 3, 13, -13, + -3, -30, -47, -48, -33, 50, 62, 35, 45, -29, -19, -46, -34, 51, 61, -45, -35, +} +T.S_Q4 = { + 0, 32, 17, 16, 31, 2, 1, 15, 14, -15, -16, -1, -32, 49, 48, 34, 33, 47, 46, 19, 18, 30, 29, 3, 13, -13, -14, -2, -3, -30, -31, -17, + -18, -47, -48, -33, 64, 50, 63, 62, 35, 45, 4, 12, -29, -19, -46, -34, -64, -49, 66, 65, 79, 78, 51, 61, 36, 44, 20, 28, -12, -4, -28, -20, + -45, -35, -62, -63, -50, 67, 77, 52, 60, -44, -36, -61, -51, 68, 76, -60, -52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +} +T.S_Q5_1 = { + 0, 2, 1, -1, -2, 3, -3, 4, -4, 5, -5, 7, 6, -6, -7, +} +T.S_Q5_2 = { + 2, 1, 0, -1, -2, 4, 3, -3, -4, 5, -5, 7, 6, -6, -7, +} +T.S_Q6_1 = { + 0, 1, -1, 3, 2, -2, -3, 4, -4, -5, 8, 7, 6, 5, -6, -7, -8, 9, -9, 11, 10, -10, -11, 15, 14, 13, 12, -12, -13, -14, -15, +} +T.S_Q6_2 = { + 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, 8, 7, 6, -6, -7, -8, 10, 9, -9, -10, 13, 12, 11, -11, -12, -13, 15, 14, -14, -15, +} +T.S_Q7_1 = { + 0, 1, -1, 2, -2, 4, 3, -3, -4, 7, 6, 5, -5, -6, -7, 13, 11, 10, 9, 8, -8, -9, -10, -11, -12, 17, 16, 15, 14, 12, -13, -14, + -15, -16, -17, 28, 27, 21, 20, 19, 18, -18, -19, -20, -21, -27, -28, 31, 30, 29, 26, 25, 24, 23, 22, -22, -23, -24, -25, -26, -29, -30, -31, +} +T.S_Q7_2 = { + 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, 17, 16, 15, 14, 13, 12, 11, -10, -11, -12, -13, -14, + -15, -16, -17, 22, 21, 20, 19, 18, -18, -19, -20, -21, -22, 29, 28, 27, 26, 25, 24, 23, -23, -24, -25, -26, -27, -28, -29, 31, 30, -30, -31, +} +T.S_Q8_1 = { + 0, 1, -1, -2, 3, 2, -3, 7, 6, 5, 4, -4, -5, -6, -7, 11, 10, 9, 8, -8, -9, -10, -11, 19, 18, 17, 16, 15, 14, 13, 12, -12, + -13, -14, -15, -16, -17, -19, 56, 55, 31, 28, 27, 26, 25, 24, 23, 22, 21, 20, -18, -20, -21, -22, -23, -24, -25, -26, -27, -33, -54, -56, 63, 62, + 61, 60, 59, 58, 57, 54, 53, 43, 40, 39, 38, 37, 36, 35, 34, 33, 32, 30, 29, -28, -29, -30, -31, -32, -34, -35, -36, -37, -38, -39, -40, -41, + -43, -53, -55, -57, -58, -59, -60, -61, 49, 47, 46, 45, 44, 42, 41, -42, -44, -45, -46, -47, -48, -49, -50, -62, -63, 52, 51, 50, 48, -51, -52, +} +T.S_Q8_2 = { + 13, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, 39, 38, 37, 36, 35, 34, + 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 12, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, + -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, + 44, 43, 42, 41, 40, -42, -43, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, 63, 62, 61, 60, -60, -61, -62, -63, +} +T.S_Q9up = { + -128, 127, -108, -110, -111, -112, -113, -114, -115, -116, -117, -118, -119, -120, -121, -122, -123, -124, -125, -126, -127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, + 115, 114, 113, 112, 111, 110, 109, 108, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, -60, -61, -62, -63, -64, -65, -66, -67, + -68, -69, -70, -71, -72, -73, -74, -75, -76, -77, -78, -79, -80, -81, -82, -83, -84, -85, -86, -87, -88, -89, -90, -91, -92, -93, -94, -95, -96, -97, -98, -99, + -100, -101, -102, -103, -104, -105, -106, -107, -109, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, + 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, + 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 40, 20, 19, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, + -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, -42, -43, 41, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, + 27, 26, 25, 24, 23, 22, 21, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, -3, -4, -5, -6, 4, 3, 2, 1, 0, -1, -2, +} + +-- Di_opt[32][16] (times 65536) +T.DI = { + 0, -29, 213, -459, 2037, -5153, 6574, -37489, 75038, 37489, 6574, 5153, 2037, 459, 213, 29, + -1, -31, 218, -519, 2000, -5517, 5959, -39336, 74992, 35640, 7134, 4788, 2063, 401, 208, 26, + -1, -35, 222, -581, 1952, -5879, 5288, -41176, 74856, 33791, 7640, 4425, 2080, 347, 202, 24, + -1, -38, 225, -645, 1893, -6237, 4561, -43006, 74630, 31947, 8092, 4063, 2087, 294, 196, 21, + -1, -41, 227, -711, 1822, -6589, 3776, -44821, 74313, 30112, 8492, 3705, 2085, 244, 190, 19, + -1, -45, 228, -779, 1739, -6935, 2935, -46617, 73908, 28289, 8840, 3351, 2075, 197, 183, 17, + -1, -49, 228, -848, 1644, -7271, 2037, -48390, 73415, 26482, 9139, 3004, 2057, 153, 176, 16, + -2, -53, 227, -919, 1535, -7597, 1082, -50137, 72835, 24694, 9389, 2663, 2032, 111, 169, 14, + -2, -58, 224, -991, 1414, -7910, 70, -51853, 72169, 22929, 9592, 2330, 2001, 72, 161, 13, + -2, -63, 221, -1064, 1280, -8209, -998, -53534, 71420, 21189, 9750, 2006, 1962, 36, 154, 11, + -2, -68, 215, -1137, 1131, -8491, -2122, -55178, 70590, 19478, 9863, 1692, 1919, 2, 147, 10, + -3, -73, 208, -1210, 970, -8755, -3300, -56778, 69679, 17799, 9935, 1388, 1870, -29, 139, 9, + -3, -79, 200, -1283, 794, -8998, -4533, -58333, 68692, 16155, 9966, 1095, 1817, -57, 132, 8, + -4, -85, 189, -1356, 605, -9219, -5818, -59838, 67629, 14548, 9959, 814, 1759, -83, 125, 7, + -4, -91, 177, -1428, 402, -9416, -7154, -61289, 66494, 12980, 9916, 545, 1698, -106, 117, 7, + -5, -97, 163, -1498, 185, -9585, -8540, -62684, 65290, 11455, 9838, 288, 1634, -127, 111, 6, + -5, -104, 146, -1567, -45, -9727, -9975, -64019, 64019, 9975, 9727, 45, 1567, -146, 104, 5, + -6, -111, 127, -1634, -288, -9838, -11455, -65290, 62684, 8540, 9585, -185, 1498, -163, 97, 5, + -7, -117, 106, -1698, -545, -9916, -12980, -66494, 61289, 7154, 9416, -402, 1428, -177, 91, 4, + -7, -125, 83, -1759, -814, -9959, -14548, -67629, 59838, 5818, 9219, -605, 1356, -189, 85, 4, + -8, -132, 57, -1817, -1095, -9966, -16155, -68692, 58333, 4533, 8998, -794, 1283, -200, 79, 3, + -9, -139, 29, -1870, -1388, -9935, -17799, -69679, 56778, 3300, 8755, -970, 1210, -208, 73, 3, + -10, -147, -2, -1919, -1692, -9863, -19478, -70590, 55178, 2122, 8491, -1131, 1137, -215, 68, 2, + -11, -154, -36, -1962, -2006, -9750, -21189, -71420, 53534, 998, 8209, -1280, 1064, -221, 63, 2, + -13, -161, -72, -2001, -2330, -9592, -22929, -72169, 51853, -70, 7910, -1414, 991, -224, 58, 2, + -14, -169, -111, -2032, -2663, -9389, -24694, -72835, 50137, -1082, 7597, -1535, 919, -227, 53, 2, + -16, -176, -153, -2057, -3004, -9139, -26482, -73415, 48390, -2037, 7271, -1644, 848, -228, 49, 1, + -17, -183, -197, -2075, -3351, -8840, -28289, -73908, 46617, -2935, 6935, -1739, 779, -228, 45, 1, + -19, -190, -244, -2085, -3705, -8492, -30112, -74313, 44821, -3776, 6589, -1822, 711, -227, 41, 1, + -21, -196, -294, -2087, -4063, -8092, -31947, -74630, 43006, -4561, 6237, -1893, 645, -225, 38, 1, + -24, -202, -347, -2080, -4425, -7640, -33791, -74856, 41176, -5288, 5879, -1952, 581, -222, 35, 1, + -26, -208, -401, -2063, -4788, -7134, -35640, -74992, 39336, -5959, 5517, -2000, 519, -218, 31, 1, +} + +-- requantisation: Cc[res] = 65536 / steps (res -1 .. 17, stored at res + 2), Dc[res] = (steps - 1) / 2, bits per +-- sample of the plain quantisers (res 8 .. 17) +T.CC = { + 111.285962475327, 65536.000000000000, 21845.333333333332, 13107.200000000001, 9362.285714285713, + 7281.777777777777, 4369.066666666666, 2114.064516129032, 1040.253968253968, 516.031496062992, 257.003921568627, + 128.250489236790, 64.062561094819, 32.015632633121, 16.003907203907, 8.000976681723, 4.000244155527, + 2.000061037018, 1.000015259021, +} +T.DC = { 2, 0, 1, 2, 3, 4, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767 } +T.RES_BIT = { [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 13, [15] = 14, [16] = 15, [17] = 16 } + +-- log_dec(max): ceil(log2(max + 2)) bits and the unused codes (index max + 1, max = 0 .. 31) +T.LOG2 = { 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6 } +T.LOG2_LOST = { 0, 1, 0, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 31 } + +-- enum_dec: CNK[k][n + 1] = C(n, k) (k = 1 .. 16, n = 0 .. 31), the code length ceil(log2 C(n, k)) and the unused +-- codes 2^len - C(n, k) (computed: libmpcdec's tables, whose last entry is 0) +T.CNK, T.CNK_LEN, T.CNK_LOST = {}, {}, {} +do + for k = 1, 16 do + local c, l, lost = table.create(32, 0), table.create(32, 0), table.create(32, 0) + for n = 0, 32 do + local v = 0 + if n >= k then + v = 1 + for i = 1, k do + v = v * (n - k + i) / i + end + v = math.floor(v + 0.5) + end + if n <= 31 then + c[n + 1] = v + end + if n >= 1 then + local bits = 0 + while 2 ^ bits < v do + bits += 1 + end + l[n] = bits + lost[n] = if v > 0 then 2 ^ bits - v else 0 + end + end + T.CNK[k], T.CNK_LEN[k], T.CNK_LOST[k] = c, l, lost + end + T.CNK_LOST[16][32] = 0 +end + +export type Lut = { + len: { number }, -- 256 entries: code length when the 8-bit prefix decides the symbol, else 0 + val: { number }, -- the symbol, or the 1-based table entry to scan from + codes: { number }, + lens: { number }, + vals: { number }, + sym: { number }?, +} + +-- lut(table, sym?) -> Lut +function T.lut(tab: { number }, sym: { number }?): Lut + local codes, lens, vals = {}, {}, {} + for i = 1, #tab, 3 do + table.insert(codes, tab[i]) + table.insert(lens, tab[i + 1]) + table.insert(vals, tab[i + 2]) + end + local function find(code: number): number + local j = 1 + while code < codes[j] do + j += 1 + end + return j + end + local function symbol(j: number, code: number): number + if sym then + local idx = bit32.band(vals[j] - bit32.rshift(code, 16 - lens[j]), 255) + return sym[idx + 1] or 0 + end + return vals[j] + end + local len, val = table.create(256, 0), table.create(256, 0) + for p = 0, 255 do + local lo, hi = find(p * 256), find(p * 256 + 255) + if lo == hi and lens[lo] <= 8 then + len[p + 1] = lens[lo] + val[p + 1] = symbol(lo, p * 256) + else + len[p + 1] = 0 + val[p + 1] = hi + end + end + return { len = len, val = val, codes = codes, lens = lens, vals = vals, sym = sym } +end + +return T diff --git a/src/Formats/codecs/audio/Musepack/init.luau b/src/Formats/codecs/audio/Musepack/init.luau new file mode 100644 index 0000000..3e29f0b --- /dev/null +++ b/src/Formats/codecs/audio/Musepack/init.luau @@ -0,0 +1,359 @@ +--!strict +-- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped +-- header, SV8's key / size packets: SH with its CRC, RG, EI, AP, SE), the frame / audio packet index, and the +-- decoder (codecs/audio/Musepack/Decode: subband bitstream, requantisation, polyphase synthesis). A port of libmpcdec +-- (musepack_src_r475: mpc_demux.c, streaminfo.c, mpc_decoder.c; BSD-3-Clause, (c) The Musepack Development Team, +-- licenses/libmpcdec-BSD.txt), gapless like libmpcdec (the 481-sample synthesis delay and SV8's leading silence are +-- dropped, the length is exact). Not supported: SV4 - SV6 (UNSUPPORTED), the SV8 seek table (the packets are indexed +-- instead), chapters. +-- +-- local s, err = Musepack.open(buf, start, limit) -- start: the "MP+" / "MPCK" magic (after an ID3v2 tag) +-- -- s: { version, sampleRate, channels, frames, maxBand, ms, profile, encoder, gapless, gain, ... } plus the +-- -- codecs/audio/Stream spec: count, start(i), decode(i), pcm(), reset(), skip, stop, preroll +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Crc32 = require("@formats/core/Crc32") +local Decode = require("@formats/codecs/audio/Musepack/Decode") + +local Musepack = {} + +local RATES = { 44100, 48000, 37800, 32000 } +local FRAME, DELAY, PAD = Decode.FRAME, Decode.DELAY, Decode.PAD +local readu8 = buffer.readu8 + +export type Stream = { + version: number, + sampleRate: number, + channels: number, + frames: number, -- output sample frames (gapless) + maxBand: number, + ms: boolean, + profile: number, -- SV7: the profile index (7 telephone .. 13 braindead); SV8: the quality (0 .. 15.875) + encoder: number, -- encoder version (SV7: one byte; SV8: major * 2^24 + minor * 2^16 + build * 2^8) + gapless: boolean, + pns: boolean?, + gain: { titleGain: number, titlePeak: number, albumGain: number, albumPeak: number }?, + blockFrames: number, -- frames per packet (SV7: 1; SV8: 2^block_pwr) + bytes: number, -- the stream's size in bytes (for the bitrate) + -- the codecs/audio/Stream spec + count: number, + start: (i: number) -> number, + decode: (i: number) -> (number?, Err.Err?), + pcm: () -> { number }, + reset: () -> (), + skip: number, + stop: number, + preroll: number, +} + +-- ------------------------------------------------------------------------------------------------ SV7 +-- SV7 reads the stream as little-endian 32-bit words, most significant bit first: swap them into a padded copy +local function swapped(buf: buffer, p: number, limit: number): buffer + local n = limit - p + local words = (n + 3) // 4 + local out = buffer.create(words * 4 + PAD) + buffer.copy(out, 0, buf, p, n) + for i = 0, words - 1 do + buffer.writeu32(out, i * 4, bit32.byteswap(buffer.readu32(out, i * 4))) + end + return out +end + +local function sv7(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) + if limit - start < 32 then + return nil, Err.new(Err.TRUNCATED, "SV7 header", start) + end + local ver = bit32.band(readu8(buf, start + 3), 15) + if ver ~= 7 then + return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. ver .. " (SV7 and SV8 only)", start) + end + local s = swapped(buf, start + 4, limit) + local totalBits = (limit - start - 4) * 8 + local at = Decode.bitsAt + local frames = at(s, 0, 16) * 65536 + at(s, 16, 16) + local ms = at(s, 33, 1) == 1 + local maxBand = at(s, 34, 6) + local profile = at(s, 40, 4) + local rate = RATES[at(s, 46, 2) + 1] + local gainTitle, peakTitle = at(s, 64, 16), at(s, 80, 16) + local gainAlbum, peakAlbum = at(s, 96, 16), at(s, 112, 16) + local gapless = at(s, 128, 1) == 1 + local last = at(s, 129, 11) + local encoder = at(s, 160, 8) + if maxBand == 0 or maxBand >= 32 then + return nil, Err.new(Err.CORRUPT, "bad band count " .. maxBand, start) + end + if last == 0 then + last = FRAME + elseif last > FRAME then + return nil, Err.new(Err.CORRUPT, "bad last frame length", start) + end + if frames == 0 then + return nil, Err.new(Err.CORRUPT, "no frames", start) + end + if frames > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, "more than 2^24 frames", start) + end + local samples = frames * FRAME - (if gapless then FRAME - last else DELAY) + -- the frame index: a 20-bit size in front of each frame (the last one has 11 more bits: its length) + local offs: { number }, sizes: { number } = {}, {} + local pos = 168 + for i = 1, frames do + if pos + 20 > totalBits then + break + end + local size = at(s, pos, 20) + local stop = pos + 20 + size + (if i == frames then 11 else 0) + if stop > totalBits then + break -- a truncated last frame + end + offs[i], sizes[i] = pos + 20, size + pos = stop + end + local have = #offs + if have == 0 then + return nil, Err.new(Err.TRUNCATED, "no complete frame", start) + end + -- frames past the stream (a truncated file, or the synthesis tail of a gapless stream) decode as silence + local need = math.min((samples + DELAY + FRAME - 1) // FRAME, have + 1) + local stopAt = math.min(samples + DELAY, have * FRAME + (if have < frames then 0 else FRAME)) + local st = Decode.state(7, maxBand, ms, 2) + local pcm = table.create(FRAME * 2, 0) + local prev = 0 + local out: Stream = { + version = 7, + sampleRate = rate, + channels = 2, + frames = math.max(0, stopAt - DELAY), + maxBand = maxBand, + ms = ms, + profile = profile, + encoder = encoder, + gapless = gapless, + gain = { titleGain = gainTitle, titlePeak = peakTitle, albumGain = gainAlbum, albumPeak = peakAlbum }, + blockFrames = 1, + bytes = limit - start, + count = need, + start = function(i: number): number + return (i - 1) * FRAME + end, + decode = function(i: number): (number?, Err.Err?) + if i ~= prev + 1 then + Decode.reset(st, if i == 1 then 0 else 0x01010101) + end + prev = i + local o: number? = offs[i] + if o == nil then + Decode.frame(st, s, -1, 0, false, pcm, 1) + return FRAME, nil + end + local e, msg = Decode.frame(st, s, o, o + sizes[i], false, pcm, 1) + if not e then + return nil, Err.from(msg, start + 4 + o // 8) + end + if e ~= o + sizes[i] then + return nil, Err.new(Err.CORRUPT, "frame " .. i .. " has the wrong size", start + 4 + o // 8) + end + return FRAME, nil + end, + pcm = function(): { number } + return pcm + end, + reset = function() + prev = -1 + end, + skip = DELAY, + stop = stopAt, + preroll = 32, + } + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ SV8 +-- a packet size: 7 bits per byte, most significant first, bit 7 = more +local function varint(buf: buffer, p: number, limit: number): (number, number) + local v = 0 + for k = 0, 7 do + if p + k >= limit then + return -1, p + end + local b = readu8(buf, p + k) + v = v * 128 + bit32.band(b, 127) + if b < 128 then + return v, p + k + 1 + end + end + return -1, p +end + +local function sv8(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) + local p = start + 4 + local sh: { [string]: any }? = nil + local gain, pns, profile, encoder = nil, nil, 0, 0 + local apOff: { number }, apSize: { number } = {}, {} + while p + 2 < limit do + local k1, k2 = readu8(buf, p), readu8(buf, p + 1) + if k1 < 65 or k1 > 90 or k2 < 65 or k2 > 90 then + return nil, Err.new(Err.CORRUPT, "bad packet key", p) + end + local key = buffer.readstring(buf, p, 2) + local size, body = varint(buf, p + 2, limit) + if size < 0 or size < body - p then + return nil, Err.new(Err.CORRUPT, "bad packet size", p) + end + local stop = p + size + if stop > limit then + if key == "AP" then + break -- a truncated last packet + end + return nil, Err.new(Err.TRUNCATED, key .. " packet", p) + end + if key == "SH" then + if stop - body < 6 then + return nil, Err.new(Err.CORRUPT, "short stream header", p) + end + local crc = buffer.readu32(buf, body) + crc = bit32.byteswap(crc) + if Crc32.of(buf, body + 4, stop - body - 4) ~= crc then + return nil, Err.new(Err.CHECKSUM, "stream header CRC", p) + end + if readu8(buf, body + 4) ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. readu8(buf, body + 4), p) + end + local samples, q = varint(buf, body + 5, stop) + local silence, q2 = varint(buf, q, stop) + if samples < 0 or silence < 0 or q2 + 2 > stop then + return nil, Err.new(Err.CORRUPT, "bad stream header", p) + end + local b0, b1 = readu8(buf, q2), readu8(buf, q2 + 1) + sh = { + samples = samples, + silence = silence, + rate = RATES[bit32.rshift(b0, 5) + 1], + maxBand = bit32.band(b0, 31) + 1, + channels = bit32.rshift(b1, 4) + 1, + ms = bit32.band(b1, 8) ~= 0, + blockPwr = bit32.band(b1, 7) * 2, + } + elseif key == "RG" and stop - body >= 9 and readu8(buf, body) == 1 then + local function u16(o: number): number + return readu8(buf, body + o) * 256 + readu8(buf, body + o + 1) + end + gain = { titleGain = u16(1), titlePeak = u16(3), albumGain = u16(5), albumPeak = u16(7) } + elseif key == "EI" and stop - body >= 4 then + local b = readu8(buf, body) + profile = bit32.rshift(b, 1) / 8 + pns = bit32.band(b, 1) == 1 + encoder = readu8(buf, body + 1) * 2 ^ 24 + readu8(buf, body + 2) * 2 ^ 16 + readu8(buf, body + 3) * 2 ^ 8 + elseif key == "AP" then + table.insert(apOff, body) + table.insert(apSize, stop - body) + elseif key == "SE" then + break + end + p = stop + end + if not sh then + return nil, Err.new(Err.CORRUPT, "no stream header", start) + end + local h = sh :: { [string]: any } + local samples, silence, maxBand, channels = h.samples, h.silence, h.maxBand, h.channels + if maxBand >= 32 or channels > 2 or silence > samples then + return nil, Err.new(Err.UNSUPPORTED, string.format("%d bands, %d channels", maxBand, channels), start) + end + if samples > 2 ^ 34 then + return nil, Err.new(Err.LIMIT, "too many samples", start) + end + if #apOff == 0 then + return nil, Err.new(Err.CORRUPT, "no audio packet", start) + end + local per = 2 ^ h.blockPwr + if per * FRAME * channels > 2 ^ 22 then + return nil, Err.new(Err.LIMIT, per .. " frames per audio packet", start) + end + local needFrames = (samples + DELAY + FRAME - 1) // FRAME + local count = math.min(#apOff, (needFrames + per - 1) // per) + local stopAt = math.min(samples + DELAY, count * per * FRAME) + local st = Decode.state(8, maxBand, h.ms, channels) + local pcm = table.create(per * FRAME * channels, 0) + local scratch = buffer.create(0) + local out: Stream = { + version = 8, + sampleRate = h.rate, + channels = channels, + frames = math.max(0, stopAt - DELAY - silence), + maxBand = maxBand, + ms = h.ms, + profile = profile, + encoder = encoder, + gapless = true, + pns = pns, + gain = gain, + blockFrames = per, + bytes = limit - start, + count = count, + start = function(i: number): number + return (i - 1) * per * FRAME + end, + decode = function(i: number): (number?, Err.Err?) + local o: number, size: number = apOff[i], apSize[i] + if buffer.len(scratch) < size + PAD then + scratch = buffer.create(size + PAD) + end + buffer.copy(scratch, 0, buf, o, size) + local nf = math.min(per, needFrames - (i - 1) * per) + local pos = 0 + for f = 1, nf do + local e, msg = Decode.frame(st, scratch, pos, size * 8, f == 1, pcm, (f - 1) * FRAME * channels + 1) + if not e then + return nil, Err.from(msg, o) + end + pos = e + end + if nf == per and size * 8 - pos > 7 then + return nil, Err.new(Err.CORRUPT, "audio packet " .. i .. " has unused data", o) + end + return nf * FRAME, nil + end, + pcm = function(): { number } + return pcm + end, + reset = function() + Decode.reset(st, 0) + end, + skip = DELAY + silence, + stop = stopAt, + preroll = 1, + } + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- magic(buf, p, limit) -> 7 | 8 | 0 (other: "MP+" with another version is 7's family, reported by open) +function Musepack.magic(buf: buffer, p: number, limit: number): number + if p + 4 > limit then + return 0 + end + local m = buffer.readstring(buf, p, 4) + if m == "MPCK" then + return 8 + end + if string.sub(m, 1, 3) == "MP+" then + return 7 + end + return 0 +end + +-- open(buf, start, limit) -> Stream | nil, Err +function Musepack.open(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) + local v = Musepack.magic(buf, start, limit) + if v == 8 then + return sv8(buf, start, limit) + elseif v == 7 then + return sv7(buf, start, limit) + end + return nil, Err.new(Err.CORRUPT, "not a Musepack stream", start) +end + +return Musepack diff --git a/tests/audio/mpc.luau b/tests/audio/mpc.luau new file mode 100644 index 0000000..bc29eb2 --- /dev/null +++ b/tests/audio/mpc.luau @@ -0,0 +1,145 @@ +-- audio/mpc tests: Musepack SV8 (mpcenc 1.30: stereo / mono, 32 / 44.1 / 48 kHz, quality 1 .. 9, 1 / 4 / 16 / 64 +-- frames per packet) and SV7 (mppenc 1.16, quality 2 / 5 / 8) against libmpcdec's float output (mpcf32: gapless +-- length, near bit-exact) and ffmpeg's decode (SNR); APEv2 tags; seeking (SV8 exact, SV7 like libmpcdec); a leading +-- ID3v2 tag; truncated files; error codes; the fuzz no-throw pass. Fixtures: tools/fixtures/mpc.py. +local T = require("@tests/T") +local Mpc = require("@formats/audio/mpc") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/mpc_cases") +local Seek = require("@tests/gen/mpc_seek") + +local t = T.suite("mpc") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- SNR (dB) and the largest difference of frames [from, to) of got against a f32le reference (frames from 0) +local function compare(got: buffer, gotFrom: number, ref: string, ch: number, frames: number): (number, number) + local rb = buffer.fromstring(ref) + local n = math.min(frames * ch, #ref // 4) + local sig, err, maxd = 0, 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(got, (gotFrom * ch + i) * 4) - r + sig += r * r + err += d * d + maxd = math.max(maxd, math.abs(d)) + end + return if err == 0 then math.huge else 10 * math.log10(sig / err), maxd +end + +t:eq(Mpc.name, "mpc", "name") +t:check(Mpc.caps.decode and not Mpc.caps.encode and Mpc.encode == nil, "caps: decode only") + +local byName = {} +for _, c in Fx do + byName[c.name] = c + local r = reader(c.data) + t:check(Mpc.sniff(r) >= 0.9, c.name .. ": sniff") + local a, err = Mpc.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + if not a then + continue + end + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": gapless length") + t:eq(a.meta.source.version, c.version, c.name .. ": stream version") + local s, maxd = compare(a.samples, 0, c.ref, c.channels, c.exact) + t:check(s > 120 and maxd < 1e-5, string.format("%s: SNR %.1f dB, max diff %g vs libmpcdec", c.name, s, maxd)) + local all = compare(a.samples, 0, c.ref, c.channels, c.frames) + t:check(all > 60, string.format("%s: whole SNR %.1f dB", c.name, all)) + local line = string.format("%s: SV%d %d ch %d Hz, %d frames, SNR %.1f dB (max diff %.2g) vs libmpcdec", c.name, c.version, c.channels, c.rate, a.frames, s, maxd) + if c.ff then + local f = compare(a.samples, 0, c.ff, c.channels, c.frames) + t:check(f > 80, string.format("%s: SNR %.1f dB vs ffmpeg", c.name, f)) + line ..= string.format(", %.1f dB vs ffmpeg (s16)", f) + end + t:note("%s", line) + if c.tags then + for k, v in c.tags do + t:eq(a.tags[k], v, c.name .. ": tag " .. k) + end + end +end + +-- seeking: SV8 is exact (one packet of pre-roll); SV7 decodes like libmpcdec's seek (32 frames of pre-roll from reset +-- scalefactors) +for _, sk in Seek do + local c = byName[sk.name] + local whole = Mpc.decode(reader(c.data)) :: any + local dec = Mpc.open(reader(c.data)) :: any + local _ = dec:read(5000) -- decode a little first: the seek must forget the state + dec:seek(sk.at / c.rate) + t:check(math.abs(dec:position() - sk.at / c.rate) < 1e-9, sk.name .. ": position after seek") + local b, n = dec:read(4096) + t:eq(n, 4096, sk.name .. ": read after seek") + if c.version == 8 then + local _, own = compare(b, 0, string.sub(buffer.tostring(whole.samples), sk.at * 8 + 1, (sk.at + 4096) * 8), 2, 4096) + t:check(own < 1e-6, string.format("%s: seek to %d is exact (max diff %g)", sk.name, sk.at, own)) + -- libmpcdec seeks without warming the synthesis up: compare after its first frame + local _, lib = compare(b, 1152, string.sub(sk.ref, 1152 * 8 + 1), 2, 4096 - 1152) + t:check(lib < 1e-5, string.format("%s: seek matches libmpcdec past 1152 frames (max diff %g)", sk.name, lib)) + else + local s, lib = compare(b, 0, sk.ref, 2, 4096) + t:check(lib < 1e-5, string.format("%s: seek to %d matches libmpcdec's (max diff %g)", sk.name, sk.at, lib)) + local own = compare(b, 0, string.sub(buffer.tostring(whole.samples), sk.at * 8 + 1, (sk.at + 4096) * 8), 2, 4096) + t:note("%s: seek %d: SNR %.1f dB vs the continuous decode (SV7 seeks restart the scalefactors: not always exact)", sk.name, sk.at, own) + local _ = s + end + dec:seek(0) + local b0, n0 = dec:read(1000) + local _, d0 = compare(b0, 0, c.ref, 2, n0) + t:check(n0 == 1000 and d0 < 1e-5, sk.name .. ": seek back to 0") +end + +-- an ID3v2 tag in front; truncated files +do + local c = byName.sv8_q5_stereo + local id3 = "ID3\3\0\0\0\0\0\20" .. string.rep("\0", 20) + local a = Mpc.decode(reader(id3 .. c.data)) :: any + t:check(a and a.frames == c.frames, "ID3v2 in front") + t:check(Mpc.sniff(reader(id3 .. c.data)) == 1, "ID3v2 in front: sniff") + for _, name in { "sv8_q5_stereo", "sv7_q5_stereo" } do + local d = byName[name] + local cut = Mpc.decode(reader(string.sub(d.data, 1, #d.data * 2 // 3))) :: any + t:check(cut and cut.frames > 0 and cut.frames < d.frames, name .. ": truncated file decodes its start") + if cut then + local _, m = compare(cut.samples, 0, d.ref, 2, math.min(cut.frames - 1152, d.exact)) + t:check(m < 1e-5, name .. ": truncated file: same start") + end + end +end + +-- errors +do + local c8, c7 = byName.sv8_q5_stereo.data, byName.sv7_q5_stereo.data + t:eq(Mpc.sniff(reader("RIFF....WAVE")), 0, "sniff a WAV") + local _, e = Mpc.decode(reader("MPCX" .. string.rep("\0", 64))) + t:check(e and e.code == Err.CORRUPT, "bad magic: " .. tostring(e)) + -- the stream header's CRC (SH is the first packet: "SH", size, CRC, version ...) + local p = string.find(c8, "SH", 5, true) :: number + local bad = string.sub(c8, 1, p + 7) .. string.char((string.byte(c8, p + 8) + 1) % 256) .. string.sub(c8, p + 9) + _, e = Mpc.decode(reader(bad)) + t:check(e and e.code == Err.CHECKSUM, "SH CRC: " .. tostring(e)) + _, e = Mpc.decode(reader("MP+\6" .. string.sub(c7, 5))) + t:check(e and e.code == Err.UNSUPPORTED, "SV6: " .. tostring(e)) + _, e = Mpc.decode(reader(string.sub(c7, 1, 20))) + t:check(e and e.code == Err.TRUNCATED, "short SV7 header: " .. tostring(e)) + _, e = Mpc.decode(reader(c8), { maxFrames = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxFrames: " .. tostring(e)) +end + +-- fuzz +do + local samples = {} + for _, c in Fx do + table.insert(samples, string.sub(c.data, 1, 3000)) + end + t:fuzz("decode", function(b: buffer) + return Mpc.decode(Bytes.reader(b)) + end, samples, { mutations = 25, keepHeader = 4 }) +end + +t:done() diff --git a/tools/fixtures/mpc.py b/tools/fixtures/mpc.py new file mode 100644 index 0000000..8aee074 --- /dev/null +++ b/tools/fixtures/mpc.py @@ -0,0 +1,130 @@ +# Musepack fixtures (tools/fixtures.py). There is no Musepack encoder in nixpkgs, so the reference tools are built +# here from the official sources through nix (fetchurl with pinned hashes): mpcenc / libmpcdec from musepack_src_r475 +# (SV8, BSD / LGPL tools), mppenc 1.16 (SV7), and `mpcf32`, a 20-line C program linked against r475's libmpcdec that +# writes its float output (gapless, the reference) as f32le, optionally after mpc_demux_seek_sample. +# tests/gen/mpc_cases.luau { name, data, version, channels, rate, frames, exact (frames that match libmpcdec +# exactly), ref (mpcf32's f32le, the first REF frames), ff? (ffmpeg's s16 decode as f32le, +# aligned: ffmpeg is not gapless), tags? } +# tests/gen/mpc_seek.luau { name (a case), at (sample), ref (mpcf32 after seeking to `at`, SEEK_REF stereo frames) } +import importlib.util, os, subprocess, tempfile, shutil + +_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 = ["tools/fixtures/_audio.py"] + +NIX = r''' +with import {}; +let + flags = "-fcommon -Wno-error -Wno-implicit-function-declaration -Wno-incompatible-pointer-types -Wno-int-conversion"; + f32 = writeText "mpcf32.c" '' + #include + #include + #include + int main(int argc, char **argv) { + mpc_reader r; mpc_streaminfo si; MPC_SAMPLE_FORMAT b[MPC_DECODER_BUFFER_LENGTH]; + if (argc < 2 || mpc_reader_init_stdio(&r, argv[1]) < 0) return 1; + mpc_demux *d = mpc_demux_init(&r); if (!d) return 2; + mpc_demux_get_info(d, &si); + if (argc > 2) mpc_demux_seek_sample(d, (mpc_uint64_t) atoll(argv[2])); + for (;;) { mpc_frame_info f; f.buffer = b; + if (mpc_demux_decode(d, &f) != MPC_STATUS_OK) { fprintf(stderr, "error\n"); return 3; } + if (f.bits == -1) break; + fwrite(b, sizeof(float), f.samples * si.channels, stdout); } + return 0; } + ''; +in symlinkJoin { name = "musepack-tools"; paths = [ + (stdenv.mkDerivation { + pname = "musepack"; version = "r475"; + src = fetchurl { url = "https://files.musepack.net/source/musepack_src_r475.tar.gz"; sha256 = "a4b1742f997f83e1056142d556a8c20845ba764b70365ff9ccf2e3f81c427b2b"; }; + nativeBuildInputs = [ cmake ]; + NIX_CFLAGS_COMPILE = flags; + postPatch = "sed -i -e /mpcgain/d -e /mpcchap/d -e /wavcmp/d -e /mpccut/d CMakeLists.txt"; + cmakeFlags = [ "-DCMAKE_POLICY_VERSION_MINIMUM=3.5" "-DSHARED=OFF" ]; + postBuild = "$CC -O2 -I../include ${f32} libmpcdec/libmpcdec_static.a -lm -o mpcf32"; + installPhase = "mkdir -p $out/bin; cp mpcenc/mpcenc mpcdec/mpcdec mpcf32 $out/bin/"; + }) + (stdenv.mkDerivation { + pname = "mppenc"; version = "1.16"; + src = fetchurl { url = "https://files.musepack.net/source/mppenc-1.16.tar.bz2"; sha256 = "f90781856ca7b6ce1ec7033321fadbcd04fe264d0349c20b49ad05f7cb2655ad"; }; + nativeBuildInputs = [ cmake ]; + NIX_CFLAGS_COMPILE = flags; + cmakeFlags = [ "-DCMAKE_POLICY_VERSION_MINIMUM=3.5" ]; + installPhase = "mkdir -p $out/bin; cp src/mppenc $out/bin/"; + }) +]; } +''' + +# name, encoder (mpcenc = SV8, mppenc = SV7), signal, rate, channels, seconds, extra options +CASES = [ + ("sv8_q5_stereo", "mpcenc", "music", 44100, 2, 1.2, ["--quality", "5", "--num_frames", "1"]), + ("sv8_q3_mono32k", "mpcenc", "sweep", 32000, 1, 0.5, ["--quality", "3"]), + ("sv8_q9_noise48k", "mpcenc", "noise", 48000, 2, 0.4, ["--quality", "9", "--num_frames", "2"]), + ("sv8_q1_sine", "mpcenc", "sine", 44100, 2, 0.3, ["--quality", "1", "--num_frames", "0", + "--artist", "Some One", "--tag", "Title=Mpc Tone", "--tag", "Year=2026"]), + ("sv7_q5_stereo", "mppenc", "music", 44100, 2, 1.2, ["--quality", "5"]), + ("sv7_q8_noise", "mppenc", "noise", 44100, 2, 0.3, ["--quality", "8"]), + ("sv7_q2_sweep", "mppenc", "sweep", 48000, 2, 0.5, ["--quality", "2"]), +] +REF = 22050 # frames of reference output kept per case (the fixture module stays small) +FF = ("sv8_q5_stereo", "sv7_q5_stereo") # cases also compared with ffmpeg +SEEKS = [("sv8_q5_stereo", 30000), ("sv8_q9_noise48k", 9000), ("sv7_q5_stereo", 40000)] +SEEK_REF = 4096 + + +def tools(): + out = subprocess.run(["nix", "build", "--impure", "--no-link", "--print-out-paths", "--expr", NIX], + capture_output=True, check=True).stdout.decode().strip().split("\n")[-1] + return os.path.join(out, "bin") + + +def generate(ctx): + bin_ = tools() + d = tempfile.mkdtemp(prefix="fmt-mpc-") + cases, seeks, files = [], [], {} + try: + for name, enc, kind, rate, ch, secs, extra in CASES: + frames = int(rate * secs) + sig = A.signal(kind, rate, ch, frames, seed=len(name)) + wav = os.path.join(d, name + ".wav") + mpc = os.path.join(d, name + ".mpc") + with open(wav, "wb") as f: + f.write(A.wav(sig, rate, ch)) + subprocess.run([os.path.join(bin_, enc)] + extra + ["--silent", "--overwrite", wav, mpc], capture_output=True, check=True) + with open(mpc, "rb") as f: + data = f.read() + files[name] = mpc + ref = subprocess.run([os.path.join(bin_, "mpcf32"), mpc], capture_output=True, check=True).stdout + got = len(ref) // (4 * ch) + assert got == frames, (name, got, frames) + # SV7: libmpcdec decodes the zero-filled data past the last frame for the synthesis tail (reading past + # its tables); we decode silence there, so only the frames before it compare exactly + exact = frames + if enc == "mppenc": + exact = min(frames, int.from_bytes(data[4:8], "little") * 1152 - 481) + c = {"name": name, "data": data, "version": 8 if enc == "mpcenc" else 7, "channels": ch, "rate": rate, + "frames": frames, "exact": exact, "ref": ref[:REF * ch * 4]} + if name in FF: + _, _, ff = A.ffdecode(ctx, data, ext="mpc") + # ffmpeg decodes without the gapless trimming: find the lag of the reference inside its output + refl = A.from_f32le(ref) + best = None + for lag in range(0, 2400): + if (lag + 200) * ch > len(ff): + break + e = sum((ff[(lag + i) * ch] - refl[i * ch]) ** 2 for i in range(100, 200)) + if best is None or e < best[0]: + best = (e, lag) + c["ff"] = A.f32le(ff[best[1] * ch:(best[1] + REF) * ch]) + if "--artist" in extra: + c["tags"] = {"artist": "Some One", "title": "Mpc Tone", "date": "2026"} + cases.append(c) + for name, at in SEEKS: + ref = subprocess.run([os.path.join(bin_, "mpcf32"), files[name], str(at)], capture_output=True, check=True).stdout + data = next(c["data"] for c in cases if c["name"] == name) + seeks.append({"name": name, "at": at, "ref": ref[:SEEK_REF * 8]}) + finally: + shutil.rmtree(d, ignore_errors=True) + ctx.emit("mpc_cases", cases) + ctx.emit("mpc_seek", seeks) From 5b8f7cba3918176a80cead66e6297f1b2d92fd75 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:26:34 -0500 Subject: [PATCH 3/7] ws-audio2: regenerate docs/FORMATS.md after merging master --- docs/FORMATS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index b36bd82..d17d956 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -88,6 +88,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **audio** - codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program + - codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the - codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). - codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and - codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim, From 41b72d9b8a99b0f1dc5a3385f39d03e8009308a0 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:45:23 -0500 Subject: [PATCH 4/7] ws-audio2: audio/ac3 + codecs/audio/Ac3: AC-3 decoding from ATSC A/52, AC-3 tracks of MKV / MP4 / TS / AVI Written from the A/52:2018 specification (tables transcribed from it; no liba52 / ffmpeg code): every acmod with LFE, coupling + phase flags, rematrixing, block switching, delta bit allocation, dither, CRC check, dynamic range off by default (drc = 0 .. 1). E-AC-3 and bsid 9 / 10 are UNSUPPORTED. 101.8 - 108.6 dB SNR vs ffmpeg's float decode (liba52's for block-switched streams: the packaged ffmpeg mis-decodes the first short transform). Outside the folders: containers/AudioWrap passes ac3 tracks to audio/ac3 (one branch); a comment in src/Formats/init.luau mentions it. The fixture clears the encoders' dithflags (positions from the new Ac3 decoder field dec.blocks) so reference and decoder decode the same numbers. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/audio/ac3/init.luau | 146 ++++ src/Formats/codecs/audio/Ac3/Decode.luau | 916 +++++++++++++++++++++++ src/Formats/codecs/audio/Ac3/Tables.luau | 102 +++ src/Formats/codecs/audio/Ac3/init.luau | 172 +++++ src/Formats/containers/AudioWrap.luau | 6 +- src/Formats/init.luau | 2 +- tests/audio/ac3.luau | 153 ++++ tools/fixtures/ac3.py | 233 ++++++ 10 files changed, 1741 insertions(+), 2 deletions(-) create mode 100644 src/Formats/audio/ac3/init.luau create mode 100644 src/Formats/codecs/audio/Ac3/Decode.luau create mode 100644 src/Formats/codecs/audio/Ac3/Tables.luau create mode 100644 src/Formats/codecs/audio/Ac3/init.luau create mode 100644 tests/audio/ac3.luau create mode 100644 tools/fixtures/ac3.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index d17d956..c68c2af 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -17,6 +17,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` | | image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` | | audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.luau` | +| audio | ac3 | .ac3 .a52 | yes | - | codecs: "ac3", channels: 6, streaming: true, lossy: true | `tests/audio/ac3.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 | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 2b94be5..9450fdd 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -158,6 +158,18 @@ local list: { Entry } = { return require("@formats/audio/aac") end, }, + { + name = "ac3", + category = "audio", + path = "audio/ac3", + extensions = { "ac3", "a52" }, + mime = { "audio/ac3", "audio/x-ac3" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, + caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, + load = function() + return require("@formats/audio/ac3") + end, + }, { name = "aiff", category = "audio", diff --git a/src/Formats/audio/ac3/init.luau b/src/Formats/audio/ac3/init.luau new file mode 100644 index 0000000..4f69ea9 --- /dev/null +++ b/src/Formats/audio/ac3/init.luau @@ -0,0 +1,146 @@ +--!strict +-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) elementary streams, the .ac3 files of DVD / broadcast rips, through +-- codecs/audio/Ac3 (written from the A/52 specification). Supports: every channel layout (1+1, 1/0 .. 3/2, LFE) +-- output in WAVE order without downmixing, 32 / 44.1 / 48 kHz, every bit rate, coupling, rematrixing, block +-- switching, delta bit allocation, the CRC check, resync over garbage, a truncated last frame (dropped), streaming and +-- exact seeking (one frame of pre-roll for the overlap). Dynamic range control is off by default (`drc` = 0 .. 1). +-- Not supported: writing, E-AC-3 / Dolby Digital Plus (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Stream = require("@formats/codecs/audio/Stream") +local Ac3 = require("@formats/codecs/audio/Ac3") + +-- ------------------------------------------------------------------------------------------------ contract +local Ac3Format = { + name = "ac3", + category = "audio", + extensions = { "ac3", "a52" }, + mime = { "audio/ac3", "audio/x-ac3" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, + caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFrames: number?, -- refuse streams with more syncframes (default 2^22) + drc: number?, -- dynamic range control scale: 0 = off (default), 1 = full + crc: boolean?, -- check every syncframe's CRC (default true; a bad frame ends the stream with Err.CHECKSUM) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ac3Format.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + local h = Ac3.header(b, p, limit) + if not h or h.bsid > 10 then + return 0 + end + local h2 = Ac3.header(b, p + h.frameSize, limit) + if h2 and h2.sampleRate == h.sampleRate then + return 0.9 + end + return if p + h.frameSize >= limit then 0.6 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the syncframe index (resyncing over garbage: a header counts when the next one follows it, or the data ends) +local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Ac3.Header?, Err.Err?) + local b, limit = r.buf, r.limit + local p = r.base + local offs, sizes = {}, {} + local first: Ac3.Header? = nil + while p + 8 <= limit do + local h = Ac3.header(b, p, limit) + if h and first and (h.sampleRate ~= first.sampleRate or h.bsid > 10) then + h = nil + end + if h and not first and p + h.frameSize + 8 <= limit then + local h2 = Ac3.header(b, p + h.frameSize, limit) + if not h2 then + h = nil -- a false sync word + end + end + if not h then + p += 1 + continue + end + if not first then + first = h + if h.bsid > 10 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "E-AC-3 (Dolby Digital Plus)", p) + elseif h.bsid > 8 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "reduced sample rate AC-3 (bsid " .. h.bsid .. ")", p) + end + end + if p + h.frameSize > limit then + break -- a truncated last frame + end + table.insert(offs, p) + table.insert(sizes, h.frameSize) + if #offs > maxFrames then + return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") + end + p += h.frameSize + end + return offs, sizes, first, nil +end + +function Ac3Format.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) + if ierr then + return nil, ierr + end + if not first or #offs == 0 then + return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", r.base) + end + local h = first :: Ac3.Header + local d = Ac3.decoder({ drc = o.drc, crc = o.crc }) + local buf = r.buf + local n = #offs + local out = { + sampleRate = h.sampleRate, + channels = h.channels, + frames = n * 1536, + duration = n * 1536 / h.sampleRate, + bitrate = h.bitrate, + tags = {}, + codec = "ac3", + acmod = h.acmod, + lfe = h.lfeon, + } + return Stream.packets(out, { + count = n, + start = function(i: number): number + return (i - 1) * 1536 + end, + decode = function(i: number): (number?, Err.Err?) + local frames, err = d:decode(buf, offs[i], sizes[i]) + if frames and d.channels ~= h.channels then + return nil, Err.new(Err.UNSUPPORTED, "channel layout change inside the stream", offs[i]) + end + return frames, err + end, + pcm = function(): { number } + return d.pcm + end, + reset = function() + d:reset() + end, + preroll = 1, + }) +end + +function Ac3Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Ac3Format.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "ac3", codec = "ac3", acmod = d.acmod, lfe = d.lfe, bitrate = d.bitrate }) +end + +return Ac3Format diff --git a/src/Formats/codecs/audio/Ac3/Decode.luau b/src/Formats/codecs/audio/Ac3/Decode.luau new file mode 100644 index 0000000..830de4a --- /dev/null +++ b/src/Formats/codecs/audio/Ac3/Decode.luau @@ -0,0 +1,916 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/Ac3/Decode: one AC-3 syncframe (6 audio blocks of 256 samples) -> PCM. Written from ATSC A/52:2018 +-- (section 5.3 syntax, 7.1 exponents, 7.2 parametric bit allocation with delta bit allocation, 7.3 mantissas with +-- grouping and dither, 7.4 coupling with phase flags, 7.5 rematrixing, 7.7.1 dynamic range, 7.9 the 512 / 2 x 256 +-- inverse transforms with block switching) on codecs/audio/Mdct; no third-party code. The bit reader is module state +-- over a frame the caller pads by PAD bytes; every section stops when the position passes the frame. No error / +-- assert: failures return nil, "message". +local T = require("@formats/codecs/audio/Ac3/Tables") +local Mdct = require("@formats/codecs/audio/Mdct") + +local readu32, bswap, extract, band, rshift = buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.rshift +local max, min = math.max, math.min + +local Decode = {} +Decode.PAD = 2048 + +local CPL, LFE = 7, 6 -- channel slots: 1 .. 5 full bandwidth, 6 LFE, 7 the coupling channel +local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } + +local SLOWDEC, FASTDEC, SLOWGAIN, DBPBTAB, FLOORTAB, FASTGAIN = T.SLOWDEC, T.FASTDEC, T.SLOWGAIN, T.DBPBTAB, T.FLOORTAB, T.FASTGAIN +local BNDTAB, BNDSZ, MASKTAB, LATAB, HTH, BAPTAB = T.BNDTAB, T.BNDSZ, T.MASKTAB, T.LATAB, T.HTH, T.BAPTAB + +-- 2^-e for the exponents 0 .. 24 +local POW2 = table.create(32, 0) +for e = 0, 31 do + POW2[e + 1] = 2 ^ -e +end +-- symmetric quantiser values (Tables 7.19 - 7.23): Q1[code + 1] etc. +local function levels(n: number): { number } + local t = {} + for c = 0, n - 1 do + t[c + 1] = (2 * c - (n - 1)) / n + end + return t +end +local Q1, Q2, Q3, Q4, Q5 = levels(3), levels(5), levels(7), levels(11), levels(15) +-- bits of the asymmetric quantisers (bap 6 .. 15) +local QBITS = { [6] = 5, [7] = 6, [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 14, [15] = 16 } + +local WINDOW = Mdct.window("kbd", 512, 5) :: { number } +local PLAN512 = Mdct.new(512) :: Mdct.Plan +local PLAN256 = Mdct.new(256) :: Mdct.Plan + +-- ------------------------------------------------------------------------------------------------ bit reader +local B: buffer = buffer.create(0) +local P = 0 + +local function bits(n: number): number + if n <= 0 then + return 0 + end + if n > 24 then + local hi = bits(n - 16) + return hi * 65536 + bits(16) + end + local w = bswap(readu32(B, rshift(P, 3))) + local v = extract(w, 32 - band(P, 7) - n, n) + P += n + return v +end + +-- ------------------------------------------------------------------------------------------------ state +export type State = { + -- the frame header + fscod: number, + acmod: number, + lfeon: boolean, + nfchans: number, + channels: number, -- output channels + map: { number }, -- output index of slots 1 .. 6 + drc: number, -- the dynamic range scale (0 = off) + -- per channel slot (1 .. 7) + exp: { { number } }, + bap: { { number } }, + coef: { { number } }, + delay: { { number } }, + endmant: { number }, + chexpstr: { number }, + blksw: { boolean }, + dithflag: { boolean }, + fsnroffst: { number }, + fgaincod: { number }, + dbaOn: { boolean }, + dbaOffst: { { number } }, + dbaLen: { { number } }, + dbaBa: { { number } }, + -- coupling + cplinu: boolean, + chincpl: { boolean }, + phsflginu: boolean, + cplbegf: number, + cplendf: number, + cplbndstrc: { boolean }, -- [sbnd + 1], sbnd = 0 .. 17 (absolute sub-band) + cplco: { { number } }, -- [ch][sbnd + 1] + phsflg: { boolean }, -- [sbnd + 1] + cplfleak: number, + cplsleak: number, + rematflg: { boolean }, + -- bit allocation parameters + sdcycod: number, + fdcycod: number, + sgaincod: number, + dbpbcod: number, + floorcod: number, + csnroffst: number, + dynrng: { number }, -- gain for Ch1 / Ch2 + seed: number, -- dither generator + -- scratch + psd: { number }, + bndpsd: { number }, + excite: { number }, + mask: { number }, + y: { number }, + pcm: { number }, + blocks: { number }, -- the bit offset of each audio block in the last frame (for tools) +} + +local function arrays(n: number, size: number, v: any): { any } + local t = {} + for i = 1, n do + t[i] = table.create(size, v) + end + return t +end + +function Decode.state(): State + return { + fscod = 0, + acmod = 2, + lfeon = false, + nfchans = 2, + channels = 2, + map = { 1, 2, 3, 4, 5, 6 }, + drc = 0, + exp = arrays(7, 264, 0), + bap = arrays(7, 264, 0), + coef = arrays(7, 256, 0), + delay = arrays(6, 256, 0), + endmant = table.create(7, 0), + chexpstr = table.create(7, 0), + blksw = table.create(7, false), + dithflag = table.create(7, false), + fsnroffst = table.create(7, 0), + fgaincod = table.create(7, 0), + dbaOn = table.create(7, false), + dbaOffst = arrays(7, 8, 0), + dbaLen = arrays(7, 8, 0), + dbaBa = arrays(7, 8, 0), + cplinu = false, + chincpl = table.create(7, false), + phsflginu = false, + cplbegf = 0, + cplendf = 0, + cplbndstrc = table.create(18, false), + cplco = arrays(5, 18, 0), + phsflg = table.create(18, false), + cplfleak = 0, + cplsleak = 0, + rematflg = table.create(4, false), + sdcycod = 0, + fdcycod = 0, + sgaincod = 0, + dbpbcod = 0, + floorcod = 0, + csnroffst = 0, + dynrng = { 1, 1 }, + seed = 1, + psd = table.create(256, 0), + bndpsd = table.create(50, 0), + excite = table.create(50, 0), + mask = table.create(50, 0), + y = table.create(512, 0), + pcm = table.create(1536 * 2, 0), + blocks = table.create(6, 0), + } +end + +-- reset(st): forget the overlap (before a seek) +function Decode.reset(st: State) + for _, d in st.delay do + for i = 1, 256 do + d[i] = 0 + end + end +end + +-- ------------------------------------------------------------------------------------------------ exponents +-- read ngrps grouped exponents (7 bits = 3 deltas each) after absexp into e[first + 1 ..] (bins first ..), grpsize +-- bins per delta; false when an exponent leaves 0 .. 24 +local function exponents(e: { number }, absexp: number, ngrps: number, grpsize: number, first: number): boolean + local prev = absexp + local k = first + 1 + for _ = 1, ngrps do + local g = bits(7) + if g >= 125 then + return false + end + local d1 = g // 25 + local d2 = (g % 25) // 5 + local d3 = g % 5 + for m = 1, 3 do + local d = if m == 1 then d1 elseif m == 2 then d2 else d3 + prev += d - 2 + if prev < 0 or prev > 24 then + return false + end + for _ = 1, grpsize do + e[k] = prev + k += 1 + end + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ bit allocation +local function logadd(a: number, b: number): number + local c = a - b + local adr = min(rshift(if c >= 0 then c else -c, 1), 255) + return if c >= 0 then a + LATAB[adr + 1] else b + LATAB[adr + 1] +end + +local function lowcomp(a: number, b0: number, b1: number, bin: number): number + if bin < 7 then + if b0 + 256 == b1 then + a = 384 + elseif b0 > b1 then + a = max(0, a - 64) + end + elseif bin < 20 then + if b0 + 256 == b1 then + a = 320 + elseif b0 > b1 then + a = max(0, a - 64) + end + else + a = max(0, a - 128) + end + return a +end + +-- section 7.2.2: the bap of bins [start, stop) of channel slot ch +local function allocate(st: State, ch: number, start: number, stop: number, fgain: number, snroffset: number, isLfe: boolean) + local e, bap = st.exp[ch], st.bap[ch] + local psd, bndpsd, excite, mask = st.psd, st.bndpsd, st.excite, st.mask + local sdecay, fdecay = SLOWDEC[st.sdcycod + 1], FASTDEC[st.fdcycod + 1] + local sgain, dbknee, floor = SLOWGAIN[st.sgaincod + 1], DBPBTAB[st.dbpbcod + 1], FLOORTAB[st.floorcod + 1] + if floor >= 0x8000 then + floor -= 0x10000 -- 0xf800: a negative 16-bit value + end + for bin = start, stop - 1 do + psd[bin + 1] = 3072 - e[bin + 1] * 128 + end + -- PSD integration + local j = start + local k = MASKTAB[start + 1] + local lastbin + repeat + lastbin = min(BNDTAB[k + 1] + BNDSZ[k + 1], stop) + local v = psd[j + 1] + j += 1 + while j < lastbin do + v = logadd(v, psd[j + 1]) + j += 1 + end + bndpsd[k + 1] = v + k += 1 + until stop <= lastbin + -- excitation + local bndstrt = MASKTAB[start + 1] + local bndend = MASKTAB[stop] + 1 + local fastleak, slowleak = 0, 0 + local begin + if bndstrt == 0 then + local lc = 0 + lc = lowcomp(lc, bndpsd[1], bndpsd[2], 0) + excite[1] = bndpsd[1] - fgain - lc + lc = lowcomp(lc, bndpsd[2], bndpsd[3], 1) + excite[2] = bndpsd[2] - fgain - lc + begin = 7 + for bin = 2, 6 do + local last = isLfe and bin == 6 + if not last then + lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) + end + fastleak = bndpsd[bin + 1] - fgain + slowleak = bndpsd[bin + 1] - sgain + excite[bin + 1] = fastleak - lc + if not last and bndpsd[bin + 1] <= bndpsd[bin + 2] then + begin = bin + 1 + break + end + end + for bin = begin, min(bndend, 22) - 1 do + if not (isLfe and bin == 6) then + lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) + end + fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) + slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) + excite[bin + 1] = max(fastleak - lc, slowleak) + end + begin = 22 + else + begin = bndstrt + fastleak = st.cplfleak * 256 + 768 + slowleak = st.cplsleak * 256 + 768 + end + for bin = begin, bndend - 1 do + fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) + slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) + excite[bin + 1] = max(fastleak, slowleak) + end + -- masking curve + local hth = HTH[st.fscod + 1] + for bin = bndstrt, bndend - 1 do + local x = excite[bin + 1] + local p = bndpsd[bin + 1] + if p < dbknee then + x += (dbknee - p) // 4 + end + mask[bin + 1] = max(x, hth[bin + 1]) + end + -- delta bit allocation + if st.dbaOn[ch] then + local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] + local b = 0 + for seg = 1, #offs do + b += offs[seg] + local ba = bas[seg] + local delta = if ba >= 4 then (ba - 3) * 128 else (ba - 4) * 128 + for _ = 1, lens[seg] do + if b < 50 then + mask[b + 1] += delta + end + b += 1 + end + end + end + -- bit allocation pointers + local i = start + j = MASKTAB[start + 1] + repeat + lastbin = min(BNDTAB[j + 1] + BNDSZ[j + 1], stop) + local m = mask[j + 1] - snroffset - floor + if m < 0 then + m = 0 + end + m = band(m, 0x1fe0) + floor + while i < lastbin do + local adr = (psd[i + 1] - m) // 32 + bap[i + 1] = BAPTAB[min(63, max(0, adr)) + 1] + i += 1 + end + j += 1 + until stop <= lastbin +end + +-- ------------------------------------------------------------------------------------------------ mantissas +-- grouped mantissa state (bap 1, 2, 4 share groups across channels within a block) +local G1, G2, G4 = table.create(3, 0), table.create(3, 0), table.create(2, 0) +local n1, n2, n4 = 0, 0, 0 + +local function dither(st: State): number + local s = (st.seed * 1664525 + 1013904223) % 4294967296 + st.seed = s + return (s / 2147483648 - 1) * 0.707 +end + +-- the mantissas of bins [start, stop) of slot ch into out[], scaled by their exponents (bap 0: dither when asked) +local function mantissas(st: State, ch: number, start: number, stop: number, out: { number }, dith: boolean) + local e, bap = st.exp[ch], st.bap[ch] + for bin = start, stop - 1 do + local b = bap[bin + 1] + local v + if b == 0 then + v = if dith then dither(st) else 0 + elseif b == 1 then + if n1 == 0 then + local g = bits(5) + if g > 26 then + g = 26 + end + G1[1], G1[2], G1[3] = Q1[g // 9 + 1], Q1[(g % 9) // 3 + 1], Q1[g % 3 + 1] + n1 = 3 + end + v = G1[4 - n1] + n1 -= 1 + elseif b == 2 then + if n2 == 0 then + local g = bits(7) + if g > 124 then + g = 124 + end + G2[1], G2[2], G2[3] = Q2[g // 25 + 1], Q2[(g % 25) // 5 + 1], Q2[g % 5 + 1] + n2 = 3 + end + v = G2[4 - n2] + n2 -= 1 + elseif b == 3 then + v = Q3[min(bits(3), 6) + 1] + elseif b == 4 then + if n4 == 0 then + local g = bits(7) + if g > 120 then + g = 120 + end + G4[1], G4[2] = Q4[g // 11 + 1], Q4[g % 11 + 1] + n4 = 2 + end + v = G4[3 - n4] + n4 -= 1 + elseif b == 5 then + v = Q5[min(bits(4), 14) + 1] + else + local nb = QBITS[b] + local m = bits(nb) + local half = 2 ^ (nb - 1) + if m >= half then + m -= 2 * half + end + v = m / half + end + out[bin + 1] = v * POW2[e[bin + 1] + 1] + end +end + +-- ------------------------------------------------------------------------------------------------ audio block +local function readDba(st: State, ch: number) + local nseg = bits(3) + 1 + local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] + table.clear(offs) + table.clear(lens) + table.clear(bas) + for seg = 1, nseg do + offs[seg] = bits(5) + lens[seg] = bits(4) + bas[seg] = bits(3) + end +end + +local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D25 / D45) + +local function audblk(st: State, blk: number, limit: number): (boolean?, string?) + local nf, acmod = st.nfchans, st.acmod + for ch = 1, nf do + st.blksw[ch] = bits(1) == 1 + end + for ch = 1, nf do + st.dithflag[ch] = bits(1) == 1 + end + for i = 1, if acmod == 0 then 2 else 1 do + if bits(1) == 1 then + local v = bits(8) + local x = rshift(v, 5) + if x >= 4 then + x -= 8 + end + local g = 2 ^ (x + 1) * (32 + band(v, 31)) / 64 + st.dynrng[i] = if st.drc == 1 then g else g ^ st.drc + elseif blk == 0 then + st.dynrng[i] = 1 + end + end + -- coupling strategy + if bits(1) == 1 then + st.cplinu = bits(1) == 1 + if st.cplinu then + if acmod < 2 then + return nil, "coupling in a mono / dual mono stream" + end + for ch = 1, nf do + st.chincpl[ch] = bits(1) == 1 + end + st.phsflginu = if acmod == 2 then bits(1) == 1 else false + st.cplbegf = bits(4) + st.cplendf = bits(4) + if st.cplendf + 3 <= st.cplbegf then + return nil, "bad coupling range" + end + st.cplbndstrc[st.cplbegf + 1] = false + for sbnd = st.cplbegf + 1, st.cplendf + 2 do + st.cplbndstrc[sbnd + 1] = bits(1) == 1 + end + else + for ch = 1, nf do + st.chincpl[ch] = false + end + st.phsflginu = false + end + elseif blk == 0 then + return nil, "no coupling strategy in block 0" + end + local cplinu = st.cplinu + local cplbegf, cplendf = st.cplbegf, st.cplendf + local cplstrt = 37 + 12 * cplbegf + local cplend = 37 + 12 * (cplendf + 3) + -- coupling coordinates (per sub-band, duplicated over each coupling band) + if cplinu then + local anyNew = false + for ch = 1, nf do + if st.chincpl[ch] then + if bits(1) == 1 then + anyNew = true + local mstr = bits(2) * 3 + local co = st.cplco[ch] + local v = 0 + for sbnd = cplbegf, cplendf + 2 do + if not st.cplbndstrc[sbnd + 1] then + local ex, mant = bits(4), bits(4) + local m = if ex == 15 then mant / 16 else (mant + 16) / 32 + v = m * 2 ^ -(ex + mstr) + end + co[sbnd + 1] = v + end + end + end + end + if acmod == 2 and st.phsflginu and anyNew then + local f = false + for sbnd = cplbegf, cplendf + 2 do + if not st.cplbndstrc[sbnd + 1] then + f = bits(1) == 1 + end + st.phsflg[sbnd + 1] = f + end + end + end + -- rematrixing + if acmod == 2 then + if bits(1) == 1 then + local n = if not cplinu or cplbegf > 2 then 4 elseif cplbegf > 0 then 3 else 2 + for r = 1, 4 do + st.rematflg[r] = if r <= n then bits(1) == 1 else false + end + elseif blk == 0 then + for r = 1, 4 do + st.rematflg[r] = false + end + end + end + -- exponent strategies + local chexpstr = st.chexpstr + chexpstr[CPL] = if cplinu then bits(2) else 0 + for ch = 1, nf do + chexpstr[ch] = bits(2) + end + chexpstr[LFE] = if st.lfeon then bits(1) else 0 + if blk == 0 then + for ch = 1, nf do + if chexpstr[ch] == 0 then + return nil, "exponent reuse in block 0" + end + end + if (cplinu and chexpstr[CPL] == 0) or (st.lfeon and chexpstr[LFE] == 0) then + return nil, "exponent reuse in block 0" + end + end + local endmant = st.endmant + for ch = 1, nf do + if chexpstr[ch] ~= 0 then + if st.chincpl[ch] then + endmant[ch] = cplstrt + else + local bw = bits(6) + if bw > 60 then + return nil, "bad channel bandwidth code" + end + endmant[ch] = 37 + 3 * (bw + 12) + end + end + end + endmant[LFE] = 7 + -- exponents + if cplinu and chexpstr[CPL] ~= 0 then + local abs = bits(4) * 2 + local grp = EXPGRP[chexpstr[CPL]] + if not exponents(st.exp[CPL], abs, (cplend - cplstrt) // grp, grp // 3, cplstrt) then + return nil, "bad coupling exponents" + end + end + for ch = 1, nf do + local s = chexpstr[ch] + if s ~= 0 then + local grp = EXPGRP[s] + local ngrps + if s == 1 then + ngrps = (endmant[ch] - 1) // 3 + elseif s == 2 then + ngrps = (endmant[ch] - 1 + 3) // 6 + else + ngrps = (endmant[ch] - 1 + 9) // 12 + end + local e = st.exp[ch] + e[1] = bits(4) + if not exponents(e, e[1], ngrps, grp // 3, 1) then + return nil, "bad exponents" + end + bits(2) -- gainrng + end + end + if st.lfeon and chexpstr[LFE] ~= 0 then + local e = st.exp[LFE] + e[1] = bits(4) + if not exponents(e, e[1], 2, 1, 1) then + return nil, "bad LFE exponents" + end + end + if P > limit then + return nil, "truncated block" + end + -- bit allocation parameters + if bits(1) == 1 then + st.sdcycod, st.fdcycod, st.sgaincod, st.dbpbcod, st.floorcod = bits(2), bits(2), bits(2), bits(2), bits(3) + elseif blk == 0 then + return nil, "no bit allocation parameters in block 0" + end + if bits(1) == 1 then + st.csnroffst = bits(6) + if cplinu then + st.fsnroffst[CPL], st.fgaincod[CPL] = bits(4), bits(3) + end + for ch = 1, nf do + st.fsnroffst[ch], st.fgaincod[ch] = bits(4), bits(3) + end + if st.lfeon then + st.fsnroffst[LFE], st.fgaincod[LFE] = bits(4), bits(3) + end + elseif blk == 0 then + return nil, "no SNR offsets in block 0" + end + if cplinu then + if bits(1) == 1 then + st.cplfleak, st.cplsleak = bits(3), bits(3) + end + end + -- delta bit allocation + if bits(1) == 1 then + local modes = table.create(7, 0) + if cplinu then + modes[CPL] = bits(2) + end + for ch = 1, nf do + modes[ch] = bits(2) + end + if cplinu and modes[CPL] == 1 then + readDba(st, CPL) + end + for ch = 1, nf do + if modes[ch] == 1 then + readDba(st, ch) + end + end + for _, ch in { 1, 2, 3, 4, 5, CPL } do + if modes[ch] == 1 then + st.dbaOn[ch] = true + elseif modes[ch] == 2 or modes[ch] == 3 then + st.dbaOn[ch] = false + end + end + elseif blk == 0 then + for ch = 1, 7 do + st.dbaOn[ch] = false + end + end + -- skip field + if bits(1) == 1 then + P += bits(9) * 8 + end + if P > limit then + return nil, "truncated block" + end + -- bit allocation + local zero = st.csnroffst == 0 + if zero then + for ch = 1, nf do + if st.fsnroffst[ch] ~= 0 then + zero = false + end + end + if (cplinu and st.fsnroffst[CPL] ~= 0) or (st.lfeon and st.fsnroffst[LFE] ~= 0) then + zero = false + end + end + local function alloc(ch: number, start: number, stop: number, isLfe: boolean) + if zero then + for i = start + 1, stop do + st.bap[ch][i] = 0 + end + else + local snr = ((st.csnroffst - 15) * 16 + st.fsnroffst[ch]) * 4 + allocate(st, ch, start, stop, FASTGAIN[st.fgaincod[ch] + 1], snr, isLfe) + end + end + if cplinu then + alloc(CPL, cplstrt, cplend, false) + end + for ch = 1, nf do + alloc(ch, 0, endmant[ch], false) + end + if st.lfeon then + alloc(LFE, 0, 7, true) + end + -- mantissas + n1, n2, n4 = 0, 0, 0 + local gotCpl = false + local coef = st.coef + for ch = 1, nf do + local c = coef[ch] + mantissas(st, ch, 0, endmant[ch], c, st.dithflag[ch]) + for i = endmant[ch] + 1, 256 do + c[i] = 0 + end + if cplinu and st.chincpl[ch] and not gotCpl then + mantissas(st, CPL, cplstrt, cplend, coef[CPL], false) + gotCpl = true + end + if P > limit then + return nil, "truncated block" + end + end + if st.lfeon then + local c = coef[LFE] + mantissas(st, LFE, 0, 7, c, false) + for i = 8, 256 do + c[i] = 0 + end + end + if P > limit then + return nil, "truncated block" + end + -- decoupling (section 7.4): dither the coupling channel's zero-bit mantissas per channel + if cplinu then + local cc, cbap, cexp = coef[CPL], st.bap[CPL], st.exp[CPL] + for ch = 1, nf do + if st.chincpl[ch] then + local c, co = coef[ch], st.cplco[ch] + local dith = st.dithflag[ch] + local flip = acmod == 2 and ch == 2 and st.phsflginu + for sbnd = cplbegf, cplendf + 2 do + local f = co[sbnd + 1] * 8 + if flip and st.phsflg[sbnd + 1] then + f = -f + end + for k = 37 + 12 * sbnd + 1, 37 + 12 * sbnd + 12 do + local v = cc[k] + if cbap[k] == 0 then + v = if dith then dither(st) * POW2[cexp[k] + 1] else 0 + end + c[k] = v * f + end + end + for k = cplend + 1, 256 do + c[k] = 0 + end + end + end + end + -- rematrixing (section 7.5) + if acmod == 2 then + local stop = if cplinu then cplstrt else min(endmant[1], endmant[2]) + local l, r = coef[1], coef[2] + local edges = { 13, 25, 37, 61, 253 } + for rb = 1, 4 do + if st.rematflg[rb] then + for k = edges[rb] + 1, min(edges[rb + 1], stop) do + local a, b = l[k], r[k] + l[k], r[k] = a + b, a - b + end + end + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ transform +-- the inverse transform of slot ch (long or two short), windowed, overlap-added into out[base + i * step] +local function synth(st: State, ch: number, short: boolean, gain: number, out: { number }, base: number, step: number) + local x, y, d, w = st.coef[ch], st.y, st.delay[ch], WINDOW + if short then + -- two 256-point transforms of the interleaved coefficients, phases alpha = -1 (n0 = 0) and +1 (n0 = N / 2) + local z = st.psd -- 256 scratch + Mdct.inverse(PLAN256, x, 1, 2, z, 1, -2 * gain) + for n = 0, 63 do + y[n + 1] = -z[n + 193] + end + for n = 64, 255 do + y[n + 1] = z[n - 63] + end + Mdct.inverse(PLAN256, x, 2, 2, z, 1, -2 * gain) + for n = 0, 191 do + y[257 + n] = z[n + 65] + end + for n = 192, 255 do + y[257 + n] = -z[n - 191] + end + else + Mdct.inverse(PLAN512, x, 1, 1, y, 1, -2 * gain) + end + local p = base + for n = 1, 256 do + out[p] = y[n] * w[n] + d[n] + d[n] = y[n + 256] * w[n + 256] + p += step + end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- the output index of each slot (1 .. 5 full bandwidth, 6 LFE) in WAVE order: L R C LFE surrounds +local ORDER: { [number]: { number } } = { + [0] = { 1, 2 }, + { 1 }, + { 1, 2 }, + { 1, 3, 2 }, + { 1, 2, 3 }, + { 1, 3, 2, 4 }, + { 1, 2, 3, 4 }, + { 1, 3, 2, 4, 5 }, +} +local HAS_C = { [0] = false, true, false, true, false, true, false, true } + +-- frame(st, buf, len, drc) -> 1536 | nil, message: decodes the syncframe at buf[0 .. len) (padded by PAD bytes) +-- into st.pcm (1536 * st.channels interleaved floats, WAVE order). drc: the dynamic range scale (0 = off, 1 = full). +function Decode.frame(st: State, buf: buffer, len: number, drc: number): (number?, string?) + if len < 8 or buffer.len(buf) < len + Decode.PAD then + return nil, "truncated frame" + end + B, P = buf, 32 + local fscod = bits(2) + bits(6) + local bsid = bits(5) + if bsid > 8 then + B = buffer.create(0) + return nil, "unsupported: bsid " .. bsid .. (if bsid > 10 then " (E-AC-3)" else " (reduced sample rate)") + end + if fscod == 3 then + B = buffer.create(0) + return nil, "bad sample rate code" + end + bits(3) -- bsmod + local acmod = bits(3) + if band(acmod, 1) == 1 and acmod ~= 1 then + bits(2) + end + if band(acmod, 4) ~= 0 then + bits(2) + end + if acmod == 2 then + bits(2) + end + local lfeon = bits(1) == 1 + for _ = 1, if acmod == 0 then 2 else 1 do + bits(5) + if bits(1) == 1 then + bits(8) + end + if bits(1) == 1 then + bits(8) + end + if bits(1) == 1 then + bits(7) + end + end + bits(2) + if bits(1) == 1 then + bits(14) + end + if bits(1) == 1 then + bits(14) + end + if bits(1) == 1 then + P += (bits(6) + 1) * 8 + end + local nf = NFCHANS[acmod] + local channels = nf + (if lfeon then 1 else 0) + if st.acmod ~= acmod or st.lfeon ~= lfeon then + -- a new channel layout: build the output map and forget the overlap + local order = ORDER[acmod] + local map = table.create(6, 0) + local nfront = if HAS_C[acmod] then 3 elseif acmod == 1 then 1 else 2 + for ch = 1, nf do + local o = order[ch] + map[ch] = if lfeon and o > nfront then o + 1 else o + end + if lfeon then + map[LFE] = nfront + 1 + end + st.map = map + st.pcm = table.create(1536 * channels, 0) + Decode.reset(st) + end + st.fscod, st.acmod, st.lfeon, st.nfchans, st.channels, st.drc = fscod, acmod, lfeon, nf, channels, drc + local pcm = st.pcm + local limit = len * 8 - 16 -- crc2 + for blk = 0, 5 do + st.blocks[blk + 1] = P + local ok, err = audblk(st, blk, limit) + if not ok then + B = buffer.create(0) + return nil, err + end + local base = blk * 256 * channels + for ch = 1, nf do + local g = st.dynrng[if acmod == 0 and ch == 2 then 2 else 1] + synth(st, ch, st.blksw[ch], g, pcm, base + st.map[ch], channels) + end + if lfeon then + synth(st, LFE, false, st.dynrng[1], pcm, base + st.map[LFE], channels) + end + end + B = buffer.create(0) + return 1536, nil +end + +return Decode diff --git a/src/Formats/codecs/audio/Ac3/Tables.luau b/src/Formats/codecs/audio/Ac3/Tables.luau new file mode 100644 index 0000000..3eec9e3 --- /dev/null +++ b/src/Formats/codecs/audio/Ac3/Tables.luau @@ -0,0 +1,102 @@ +--!strict +-- codecs/audio/Ac3/Tables: the AC-3 constant tables, transcribed from ATSC A/52:2018 (Digital Audio Compression +-- Standard) section 7.2.3 (bit allocation: slowdec, fastdec, slowgain, dbpbtab, floortab, fastgain, bndtab / bndsz, +-- latab, hth, baptab) and section 5.4 (frame sizes). masktab is derived from bndtab / bndsz, the transform window +-- (Table 7.33) is the Kaiser-Bessel-derived window with alpha 5 (codecs/audio/Mdct), which Table 7.33 rounds to five +-- decimals. No third-party code. +local T = {} + +T.SLOWDEC = { 0x0f, 0x11, 0x13, 0x15 } +T.FASTDEC = { 0x3f, 0x53, 0x67, 0x7b } +T.SLOWGAIN = { 0x540, 0x4d8, 0x478, 0x410 } +T.DBPBTAB = { 0x000, 0x700, 0x900, 0xb00 } +T.FLOORTAB = { 0x2f0, 0x2b0, 0x270, 0x230, 0x1f0, 0x170, 0x0f0, 0xf800 } +T.FASTGAIN = { 0x080, 0x100, 0x180, 0x200, 0x280, 0x300, 0x380, 0x400 } + +-- the 50 bit allocation bands: first bin and width (Table 7.12) +T.BNDTAB = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 31, 34, 37, 40, 43, 46, 49, 55, 61, 67, 73, 79, 85, 97, 109, 121, 133, 157, 181, 205, 229, +} +T.BNDSZ = { + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 24, 24, 24, 24, 24, +} +-- masktab[bin + 1]: the band of each bin (Table 7.13; bins 253 .. 255 map to 0) +T.MASKTAB = table.create(256, 0) +for b = 1, 50 do + for k = T.BNDTAB[b], T.BNDTAB[b] + T.BNDSZ[b] - 1 do + T.MASKTAB[k + 1] = b - 1 + end +end + +-- log-addition table (Table 7.14) +T.LATAB = { + 0x0040, 0x003f, 0x003e, 0x003d, 0x003c, 0x003b, 0x003a, 0x0039, 0x0038, 0x0037, 0x0036, 0x0035, 0x0034, 0x0034, 0x0033, 0x0032, + 0x0031, 0x0030, 0x002f, 0x002f, 0x002e, 0x002d, 0x002c, 0x002c, 0x002b, 0x002a, 0x0029, 0x0029, 0x0028, 0x0027, 0x0026, 0x0026, + 0x0025, 0x0024, 0x0024, 0x0023, 0x0023, 0x0022, 0x0021, 0x0021, 0x0020, 0x0020, 0x001f, 0x001e, 0x001e, 0x001d, 0x001d, 0x001c, + 0x001c, 0x001b, 0x001b, 0x001a, 0x001a, 0x0019, 0x0019, 0x0018, 0x0018, 0x0017, 0x0017, 0x0016, 0x0016, 0x0015, 0x0015, 0x0015, + 0x0014, 0x0014, 0x0013, 0x0013, 0x0013, 0x0012, 0x0012, 0x0012, 0x0011, 0x0011, 0x0011, 0x0010, 0x0010, 0x0010, 0x000f, 0x000f, + 0x000f, 0x000e, 0x000e, 0x000e, 0x000d, 0x000d, 0x000d, 0x000d, 0x000c, 0x000c, 0x000c, 0x000c, 0x000b, 0x000b, 0x000b, 0x000b, + 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x0009, 0x0009, 0x0009, 0x0009, 0x0009, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, + 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0005, 0x0005, + 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, + 0x0004, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0002, + 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, + 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, +} + +-- hearing threshold per band (Table 7.15): HTH[fscod + 1][band + 1] +T.HTH = { + { + 0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, + 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0370, 0x0370, + 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, + 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, 0x0340, 0x0390, 0x03e0, 0x0420, + 0x0460, 0x0490, 0x04a0, 0x0460, 0x0440, 0x0440, 0x0520, 0x0800, 0x0840, 0x0840, + }, + { + 0x04f0, 0x04f0, 0x0460, 0x0410, 0x03e0, 0x03d0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, + 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, + 0x0370, 0x0370, 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0320, 0x0310, + 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0320, 0x0350, 0x0390, 0x03e0, + 0x0420, 0x0450, 0x04a0, 0x0490, 0x0460, 0x0440, 0x0480, 0x0630, 0x0840, 0x0840, + }, + { + 0x0580, 0x0580, 0x04b0, 0x0450, 0x0420, 0x03f0, 0x03e0, 0x03d0, 0x03c0, 0x03b0, + 0x03b0, 0x03b0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, + 0x0390, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, 0x0370, 0x0360, 0x0350, + 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, + 0x0330, 0x0350, 0x03c0, 0x0410, 0x0470, 0x04a0, 0x0460, 0x0440, 0x0450, 0x04e0, + }, +} + +-- bit allocation pointers (Table 7.16) +T.BAPTAB = { + 0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, + 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, +} + +-- words per syncframe (Table 5.18) for frmsizecod // 2 (the nominal bit rate in kbps) and fscod: 48 kHz = 2 x rate, +-- 32 kHz = 3 x rate, 44.1 kHz = floor(rate x 1536000 / 705600) + (frmsizecod & 1) +T.BITRATES = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640 } +T.RATES = { 48000, 44100, 32000 } + +function T.frameWords(fscod: number, frmsizecod: number): number + local kbps = T.BITRATES[frmsizecod // 2 + 1] + if not kbps or fscod > 2 then + return 0 + end + if fscod == 0 then + return 2 * kbps + elseif fscod == 2 then + return 3 * kbps + end + return kbps * 1536000 // 705600 + frmsizecod % 2 +end + +return T diff --git a/src/Formats/codecs/audio/Ac3/init.luau b/src/Formats/codecs/audio/Ac3/init.luau new file mode 100644 index 0000000..16bf136 --- /dev/null +++ b/src/Formats/codecs/audio/Ac3/init.luau @@ -0,0 +1,172 @@ +--!strict +-- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the +-- decoder (codecs/audio/Ac3/Decode). Written from ATSC A/52:2018; no third-party code. A codec (layer 3): audio/ac3 +-- (raw .ac3 files) builds on it, and the AC-3 tracks of MKV / MP4 / MPEG-TS / AVI reach it through +-- containers/AudioWrap. +-- Supports: every acmod (1+1, 1/0 .. 3/2) with or without LFE, 32 / 44.1 / 48 kHz, all bit rates, coupling with phase +-- flags, rematrixing, block switching, delta bit allocation, dither, dynamic range control (off by default, +-- `drc` = 0 .. 1 scales it). Output: every channel in WAVE order (L R C LFE surrounds), no downmix. Not supported: +-- E-AC-3 (bsid 11 .. 16) and the reduced-rate bsid 9 / 10 streams (UNSUPPORTED). +-- +-- local h = Ac3.header(buf, offset, limit) -- { sampleRate, frameSize, channels, acmod, lfeon, bsid, bitrate } +-- local dec = Ac3.decoder({ drc = 0 }) -- dec:decode(buf, offset, length) -> 1536, dec.pcm (interleaved) +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local T = require("@formats/codecs/audio/Ac3/Tables") +local Decode = require("@formats/codecs/audio/Ac3/Decode") + +local Ac3 = {} + +local readu8 = buffer.readu8 +local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } + +export type Header = { + sampleRate: number, + frameSize: number, -- bytes + bitrate: number, -- bits per second + channels: number, + acmod: number, + lfeon: boolean, + bsid: number, +} + +-- header(buf, o, limit) -> Header | nil (not an AC-3 / E-AC-3 syncframe header at o). E-AC-3 headers (bsid > 10) +-- come back with frameSize from their own frmsiz field so a scanner can step over them. +function Ac3.header(b: buffer, o: number, limit: number): Header? + if o < 0 or o + 8 > limit or o + 8 > buffer.len(b) then + return nil + end + if readu8(b, o) ~= 0x0B or readu8(b, o + 1) ~= 0x77 then + return nil + end + local bsid = bit32.rshift(readu8(b, o + 5), 3) + if bsid > 10 then + if bsid > 16 then + return nil + end + -- E-AC-3: strmtyp(2) substreamid(3) frmsiz(11) fscod(2) ... + local words = bit32.band(readu8(b, o + 2), 7) * 256 + readu8(b, o + 3) + 1 + local fs = bit32.rshift(readu8(b, o + 4), 6) + return { + sampleRate = if fs < 3 then T.RATES[fs + 1] else 0, + frameSize = words * 2, + bitrate = 0, + channels = 0, + acmod = bit32.band(bit32.rshift(readu8(b, o + 4), 1), 7), + lfeon = false, + bsid = bsid, + } + end + local b4 = readu8(b, o + 4) + local fscod, frmsizecod = bit32.rshift(b4, 6), bit32.band(b4, 63) + local words = T.frameWords(fscod, frmsizecod) + if words == 0 then + return nil + end + local acmod = bit32.rshift(readu8(b, o + 6), 5) + -- lfeon: after acmod and the optional cmixlev / surmixlev / dsurmod fields + local skip = 0 + if bit32.band(acmod, 1) == 1 and acmod ~= 1 then + skip += 2 + end + if bit32.band(acmod, 4) ~= 0 then + skip += 2 + end + if acmod == 2 then + skip += 2 + end + local w = readu8(b, o + 6) * 256 + readu8(b, o + 7) + local lfeon = bit32.extract(w, 12 - skip, 1) == 1 + local shift = if bsid > 8 then bsid - 8 else 0 + return { + sampleRate = T.RATES[fscod + 1] // 2 ^ shift, + frameSize = words * 2, + bitrate = T.BITRATES[frmsizecod // 2 + 1] * 1000 // 2 ^ shift, + channels = NFCHANS[acmod] + (if lfeon then 1 else 0), + acmod = acmod, + lfeon = lfeon, + bsid = bsid, + } +end + +-- the CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): a syncframe checks when the CRC of +-- everything after the sync word is 0 +local CRC = table.create(256, 0) +for i = 0, 255 do + local c = i * 256 + for _ = 1, 8 do + c = if c >= 0x8000 then bit32.bxor(bit32.band(c * 2, 0xFFFF), 0x8005) else c * 2 + end + CRC[i + 1] = c +end + +function Ac3.crc(b: buffer, o: number, n: number): number + local c = 0 + for i = o, o + n - 1 do + c = bit32.bxor(bit32.band(c * 256, 0xFFFF), CRC[bit32.bxor(bit32.rshift(c, 8), readu8(b, i)) + 1]) + end + return c +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Options = { + drc: number?, -- dynamic range control: 0 = off (default, like ffmpeg -drc_scale 0), 1 = as the stream says + crc: boolean?, -- check crc2 (default true): a mismatch is Err.CHECKSUM +} + +export type Decoder = { + pcm: { number }, -- the last frame: 1536 * channels interleaved floats, WAVE order + channels: number, + sampleRate: number, + blocks: { number }, -- the bit offset of each audio block in the last frame (tools: stream editing, analysis) + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + reset: (self: Decoder) -> (), +} + +function Ac3.decoder(opts: Options?): Decoder + local o: Options = opts or {} + local drc = math.max(0, o.drc or 0) + local checkCrc = o.crc ~= false + local st = Decode.state() + local scratch = buffer.create(3840 + Decode.PAD) + local dec: Decoder + dec = { + pcm = st.pcm, + channels = 0, + sampleRate = 0, + blocks = st.blocks, + decode = function(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local off = offset or 0 + if type(buf) ~= "buffer" or off < 0 or off >= buffer.len(buf) then + return nil, Err.new(Err.ARG, "frame range out of the buffer") + end + local h = Ac3.header(buf, off, buffer.len(buf)) + if not h then + return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", off) + end + local n = h.frameSize + if length and length < n or off + n > buffer.len(buf) then + return nil, Err.new(Err.TRUNCATED, "truncated syncframe", off) + end + if checkCrc and Ac3.crc(buf, off + 2, n - 2) ~= 0 then + return nil, Err.new(Err.CHECKSUM, "syncframe CRC", off) + end + buffer.copy(scratch, 0, buf, off, n) + local frames, msg = Decode.frame(st, scratch, n, drc) + if not frames then + return nil, Err.from(msg, off) + end + self.pcm = st.pcm + self.channels = st.channels + self.sampleRate = h.sampleRate + return frames, nil + end, + reset = function(_self: Decoder) + Decode.reset(st) + end, + } + return dec +end + +return Ac3 diff --git a/src/Formats/containers/AudioWrap.luau b/src/Formats/containers/AudioWrap.luau index ac51aee..4a0f3da 100644 --- a/src/Formats/containers/AudioWrap.luau +++ b/src/Formats/containers/AudioWrap.luau @@ -8,7 +8,8 @@ -- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames; -- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations); -- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout); --- aac -> ADTS (from the AudioSpecificConfig) for audio/aac. +-- aac -> ADTS (from the AudioSpecificConfig) for audio/aac; +-- ac3 -> the syncframes back to back (format "ac3"; E-AC-3 tracks stay UNSUPPORTED). -- -- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format }) local Err = require("@formats/core/Err") @@ -407,6 +408,9 @@ function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Er if codec == "mp3" or codec == "mp2" or codec == "mp1" then return concat(packets), "mp3", nil end + if codec == "ac3" then + return concat(packets), "ac3", nil + end if codec == "flac" then local c = track.config local prefix: buffer? = nil diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 5774bf3..927a7d4 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -278,7 +278,7 @@ end -- -- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets -- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / --- FLAC as they are), opened through F.open with that format. +-- FLAC / AC-3 as they are), opened through F.open with that format. local function openAudio(demuxer: any, track: any): (any, Err.Err?) local buf, fmt, err = AudioWrap.wrap(demuxer, track) if not buf then diff --git a/tests/audio/ac3.luau b/tests/audio/ac3.luau new file mode 100644 index 0000000..6f00ebd --- /dev/null +++ b/tests/audio/ac3.luau @@ -0,0 +1,153 @@ +-- audio/ac3 tests: AC-3 streams from ffmpeg (every acmod with and without LFE, coupling incl. cplbegf 0, rematrixing, +-- 32 / 44.1 / 48 kHz) and aften (block switching, 1+1 dual mono, dynamic range profiles, the alternate BSI) against +-- ffmpeg's float decode, or liba52's for block-switched streams (SNR, max difference; dithflags cleared in the +-- fixture step so both sides decode the same numbers); dynamic range on; the encoders' dithered originals; AC-3 tracks +-- of MKV / MP4 / MPEG-TS through the api's audio hook; exact seeking; resync and truncation; error codes (E-AC-3, +-- CRC); the fuzz no-throw pass. Fixtures: tools/fixtures/ac3.py. +local T = require("@tests/T") +local F = require("@formats") +local Ac3F = require("@formats/audio/ac3") +local Ac3 = require("@formats/codecs/audio/Ac3") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/ac3_cases") +local Tracks = require("@tests/gen/ac3_tracks") + +local t = T.suite("ac3") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- SNR (dB) and the largest difference of interleaved f32 `got` against the f32le reference `ref` +local function compare(got: buffer, ref: string, count: number): (number, number) + local rb = buffer.fromstring(ref) + local n = math.min(count, #ref // 4, buffer.len(got) // 4) + local sig, err, maxd = 0, 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(got, i * 4) - r + sig += r * r + err += d * d + maxd = math.max(maxd, math.abs(d)) + end + return if err == 0 then math.huge else 10 * math.log10(sig / err), maxd +end + +t:eq(Ac3F.name, "ac3", "name") +t:check(Ac3F.caps.decode and not Ac3F.caps.encode and Ac3F.encode == nil, "caps: decode only") + +local byName = {} +for _, c in Fx do + byName[c.name] = c + local r = reader(c.data) + t:check(Ac3F.sniff(r) >= 0.9, c.name .. ": sniff") + local a, err = Ac3F.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + if not a then + continue + end + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + -- liba52's 6-channel output is 16-bit + local min = if c.refTool == "a52dec" and c.channels > 2 then 80 else 95 + local s, maxd = compare(a.samples, c.ref, a.frames * a.channels) + t:check(s > min, string.format("%s: SNR %.1f dB vs %s", c.name, s, c.refTool)) + t:note("%s: %d ch %d Hz, %d frames: SNR %.1f dB, max diff %.1e vs %s", c.name, a.channels, a.sampleRate, a.frames, s, maxd, c.refTool) + if c.refDrc then + local d = Ac3F.decode(r, { drc = 1 }) :: any + local sd = compare(d.samples, c.refDrc, d.frames * d.channels) + t:check(sd > min, string.format("%s: dynamic range on: SNR %.1f dB vs %s", c.name, sd, c.refTool)) + local off = compare(d.samples, c.ref, d.frames * d.channels) + t:check(off < 40, c.name .. ": the dynamic range gains change the output") + end + if c.dithered then + -- the encoder's own stream (dithflag set): our dither against the reference's undithered decode + local dd = Ac3F.decode(reader(c.dithered)) :: any + local sd = compare(dd.samples, c.ref, dd.frames * dd.channels) + t:check(dd and sd > 10, string.format("%s: dithered original decodes (SNR %.1f dB, the dither noise)", c.name, sd)) + end +end + +-- AC-3 tracks of video containers, through the api's audio hook (containers/AudioWrap -> audio/ac3) +for _, c in Tracks do + local v, err = F.video.open(buffer.fromstring(c.data)) + t:check(v, c.name .. ": open: " .. tostring(err)) + if not v then + continue + end + t:check(v.audio, c.name .. ": audio track opens: " .. tostring(v.audioError)) + if v.audio then + local a = assert(F.ops.audio.toAudio(v.audio)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": audio format") + local s = compare(a.samples, c.ref, a.frames * a.channels) + t:check(s > 95, string.format("%s: AC-3 track SNR %.1f dB vs ffmpeg", c.name, s)) + t:note("%s: AC-3 track, %d ch, %d frames, SNR %.1f dB", c.name, a.channels, a.frames, s) + end +end + +-- streaming + exact seeking (one frame of pre-roll for the overlap) +do + local c = byName["5.1_448"] + local whole = Ac3F.decode(reader(c.data)) :: any + local dec = Ac3F.open(reader(c.data)) :: any + local _ = dec:read(3000) + for _, at in { 0.1, 0.0, 0.0517 } do + dec:seek(at) + local b, n = dec:read(700) + local f0 = math.floor(at * c.rate + 0.5) + local maxd = 0 + for i = 0, n * 6 - 1 do + maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * 6 + i) * 4))) + end + t:check(n == 700 and maxd < 1e-6, string.format("seek %.4f s (max diff %g)", at, maxd)) + end +end + +-- resync over garbage, a truncated last frame, the raw codec API +do + local c = byName.stereo_44k + local a = Ac3F.decode(reader("\0\11\119garbage" .. c.data)) :: any + t:check(a and a.frames == c.frames, "garbage in front: same frames") + local h = Ac3.header(buffer.fromstring(c.data), 0, #c.data) :: Ac3.Header + t:check(h.sampleRate == 44100 and h.channels == 2 and h.acmod == 2 and h.bitrate == 192000, "header fields") + local cut = Ac3F.decode(reader(string.sub(c.data, 1, #c.data - 10))) :: any + t:check(cut and cut.frames == c.frames - 1536, "truncated last frame dropped") + local d = Ac3.decoder() + local n = d:decode(buffer.fromstring(c.data), 0, h.frameSize) + t:check(n == 1536 and d.channels == 2 and #d.pcm == 1536 * 2, "decoder: one syncframe") +end + +-- errors +do + local c = byName.stereo_44k.data + t:eq(Ac3F.sniff(reader("RIFF....WAVE")), 0, "sniff a WAV") + local _, e = Ac3F.decode(reader(string.rep("\0", 100))) + t:check(e and e.code == Err.CORRUPT, "no frames: " .. tostring(e)) + -- an E-AC-3 header: bsid 16, frmsiz 255 (512 bytes), then the same again + local eac3 = "\11\119\0\255\128\128" .. string.rep("\0", 506) + _, e = Ac3F.decode(reader(eac3 .. eac3)) + t:check(e and e.code == Err.UNSUPPORTED, "E-AC-3: " .. tostring(e)) + -- a flipped bit in the middle of the first frame: the CRC catches it + local bad = string.sub(c, 1, 300) .. string.char(bit32.bxor(string.byte(c, 301), 4)) .. string.sub(c, 302) + _, e = Ac3F.decode(reader(bad)) + t:check(e and e.code == Err.CHECKSUM, "CRC: " .. tostring(e)) + _, e = Ac3F.decode(reader(c), { maxFrames = 2 }) + t:check(e and e.code == Err.LIMIT, "maxFrames: " .. tostring(e)) +end + +-- fuzz (without the CRC check, so mutations reach the decoder) +do + local samples = {} + for _, c in Fx do + table.insert(samples, string.sub(c.data, 1, 4000)) + end + t:fuzz("decode", function(b: buffer) + return Ac3F.decode(Bytes.reader(b), { crc = false }) + end, samples, { mutations = 25 }) + t:fuzz("decode (crc)", function(b: buffer) + return Ac3F.decode(Bytes.reader(b)) + end, samples, { mutations = 4, garbage = 20 }) +end + +t:done() diff --git a/tools/fixtures/ac3.py b/tools/fixtures/ac3.py new file mode 100644 index 0000000..f7cba37 --- /dev/null +++ b/tools/fixtures/ac3.py @@ -0,0 +1,233 @@ +# AC-3 fixtures (tools/fixtures.py). Encoders: ffmpeg (every channel layout, coupling, rematrixing, 32 / 44.1 / +# 48 kHz) and aften (block switching, dual mono 1+1, dynamic range profiles, the alternate bit stream syntax). +# References: ffmpeg's float decode with -drc_scale 0 (dynamic range off, our default), except for block-switched +# streams: ffmpeg (as packaged) mis-decodes the first of the two short transforms, so those use liba52's a52dec +# (-r -a: no dynamic range, no level adjustment; float for stereo, 16-bit wav6 for more channels), which agrees with +# the A/52 transform equations. AC-3 tracks in Matroska / MP4 / MPEG-TS (remuxed by ffmpeg) for the api's audio hook. +# +# Both encoders set dithflag, and decoders draw their own random dither for the zero-bit mantissas, so two correct +# decoders differ by about the coding noise. The reference streams therefore have their dithflags cleared (the bit +# positions come from our decoder's dec.blocks, the CRCs are recomputed): the reference and we decode the same +# numbers. `dithered` keeps the encoder's original stream for a few cases. +# tests/gen/ac3_cases.luau { name, data, channels, rate, frames, ref (f32le, WAVE order), refTool, refDrc?, +# dithered? } +# tests/gen/ac3_tracks.luau { name, data (the container), channels, rate, ref (ffmpeg's decode of the AC-3) } +import importlib.util, math, os, random, shutil, struct, subprocess, tempfile + +_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 = ["tools/fixtures/_audio.py", "src/Formats/codecs/audio/Ac3"] +SECONDS = 0.15 +DITHERED = ("stereo_44k", "aften_5.1_blksw") +NFCHANS = [2, 1, 2, 3, 3, 4, 4, 5] + + +def _lit(b): + return '"' + "".join("\\x%02x" % x for x in b) + '"' + + + +def crc16(data, crc=0): + """A/52 section 7.10.1: x^16 + x^15 + x^2 + 1, MSB first, zero start""" + for b in data: + crc ^= b << 8 + for _ in range(8): + crc = ((crc << 1) ^ 0x8005) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF + return crc + + +def fix_crcs(f): + """recompute crc1 (the CRC of the first 5/8 of the frame after the sync word is 0) and crc2 (all of it)""" + words = len(f) // 2 + n58 = ((words >> 1) + (words >> 3)) * 2 + # crc1 is the first word of the span: solve the linear map W -> crc(W || 0...) for crc(W || rest) == 0 + rest = crc16(bytes(2) + bytes(f[4:n58])) + basis = [crc16(bytes([(1 << i) >> 8, (1 << i) & 255]) + bytes(n58 - 4)) for i in range(16)] + rows = [(basis[i], 1 << i) for i in range(16)] + pivots = {} + for v, m in rows: + for bit in range(15, -1, -1): + if not v >> bit & 1: + continue + if bit in pivots: + pv, pm = pivots[bit] + v, m = v ^ pv, m ^ pm + else: + pivots[bit] = (v, m) + break + w, target = 0, rest + for bit in range(15, -1, -1): + if target >> bit & 1: + pv, pm = pivots[bit] + target ^= pv + w ^= pm + f[2], f[3] = w >> 8, w & 255 + assert crc16(bytes(f[2:n58])) == 0 + c2 = crc16(bytes(f[2:-2])) + f[-2], f[-1] = c2 >> 8, c2 & 255 + assert crc16(bytes(f[2:])) == 0 + + +def undither(ctx, data): + """clear every dithflag (after the blksw flags at each audio block's start) and fix the CRCs""" + code = """ +local Ac3 = require("@formats/codecs/audio/Ac3") +local b = buffer.fromstring(%s) +local dec = Ac3.decoder() +local o, n = 0, buffer.len(b) +while o + 8 <= n do + local h = Ac3.header(b, o, n) + if not h then break end + assert(dec:decode(b, o, h.frameSize)) + print(o, h.frameSize, h.acmod, table.concat(dec.blocks, " ")) + o += h.frameSize +end +""" % _lit(data) + out = bytearray(data) + for line in A.luau(ctx, code).decode().strip().split("\n"): + v = [int(x) for x in line.split()] + o, size, acmod, blocks = v[0], v[1], v[2], v[3:] + nf = NFCHANS[acmod] + f = out[o:o + size] + for p in blocks: + for k in range(nf): + bit = p + nf + k + f[bit >> 3] &= ~(0x80 >> (bit & 7)) & 255 + fix_crcs(f) + out[o:o + size] = f + return bytes(out) + +# Both encoders set dithflag, and decoders draw their own random dither for the zero-bit mantissas, so two correct +# decoders differ by about the coding noise. The reference streams therefore have their dithflags cleared (the bit +# positions come from our decoder's dec.blocks, the CRCs are recomputed): ffmpeg and we then decode the same numbers. +# `dithered` keeps the encoder's original stream for a few cases. +# +# name, encoder, layout (ffmpeg) or (acmod, lfe) (aften), rate, kbps, extra options +CASES = [ + ("mono_48k", "ffmpeg", "mono", 48000, 96, []), + ("stereo_44k", "ffmpeg", "stereo", 44100, 192, []), + ("stereo_cpl_48k", "ffmpeg", "stereo", 48000, 96, ["-channel_coupling", "1", "-cpl_start_band", "1"]), + ("stereo_cpl0_48k", "ffmpeg", "stereo", 48000, 64, ["-channel_coupling", "1", "-cpl_start_band", "0"]), + ("stereo_32k", "ffmpeg", "stereo", 32000, 64, []), + ("3.0_48k", "ffmpeg", "3.0", 48000, 256, []), + ("2.1_48k", "ffmpeg", "2.1", 48000, 192, []), + ("3.0back_48k", "ffmpeg", "3.0(back)", 48000, 192, []), + ("4.0_48k", "ffmpeg", "4.0", 48000, 256, []), + ("4.1_44k", "ffmpeg", "4.1", 44100, 320, []), + ("quad_side_48k", "ffmpeg", "quad(side)", 48000, 256, []), + ("5.0_side_32k", "ffmpeg", "5.0(side)", 32000, 320, []), + ("5.1_448", "ffmpeg", "5.1(side)", 48000, 448, []), + ("5.1_cpl_256", "ffmpeg", "5.1(side)", 48000, 256, ["-channel_coupling", "1"]), + ("aften_blksw_stereo", "aften", (2, 0), 48000, 192, ["-s", "1"]), + ("aften_dualmono", "aften", (0, 0), 48000, 128, []), + ("aften_5.1_blksw", "aften", (7, 1), 48000, 384, ["-s", "1"]), + ("aften_5.1_drc", "aften", (7, 1), 48000, 384, ["-dynrng", "1"]), + ("aften_xbsi_2.2", "aften", (6, 0), 44100, 256, ["-xbsi1", "1", "-xbsi2", "1", "-s", "1"]), +] +CHANNELS = {"mono": 1, "stereo": 2, "3.0": 3, "2.1": 3, "3.0(back)": 3, "4.0": 4, "4.1": 5, "quad(side)": 4, + "5.0(side)": 5, "5.1(side)": 6} +ACMOD_CH = {0: 2, 1: 1, 2: 2, 3: 3, 4: 3, 5: 4, 6: 4, 7: 5} + + +def signal(frames, ch, rate, seed): + """per-channel tones with vibrato, noise bursts and clicks (transients for block switching)""" + rng = random.Random(seed) + out = [0.0] * (frames * ch) + for c in range(ch): + f = 110.0 * (c + 2) * (1.0 + 0.07 * c) + for i in range(frames): + t = i / rate + v = 0.2 * math.sin(2 * math.pi * f * t + 2 * math.sin(2 * math.pi * 4 * t)) + v += 0.06 * math.sin(2 * math.pi * (2500 + 700 * c) * t) + if (i // (rate // 10) + c) % 4 == 1: + v += 0.12 * (rng.random() * 2 - 1) + k = i % (rate // 7) + if k < 60: + v += 0.5 * (1 - k / 60) * (1 if (i // 5) % 2 else -1) + out[i * ch + c] = v + return out + + +def raw(samples): + return struct.pack("<%df" % len(samples), *samples) + + +def a52dec(run, d, name, ch): + """liba52's decode: float (planar per 256-sample block) for stereo, 16-bit wav6 otherwise -> f32le, WAVE order""" + flags = "-a -r" + if ch == 2: + raw_ = run("a52dec -o float %s %s 2>/dev/null" % (flags, name)) + v = struct.unpack("<%df" % (len(raw_) // 4), raw_) + out = [0.0] * len(v) + for b in range(len(v) // 512): + for i in range(256): + out[(b * 256 + i) * 2] = v[b * 512 + i] + out[(b * 256 + i) * 2 + 1] = v[b * 512 + 256 + i] + return raw(out) + wav = run("a52dec -o wav6 %s %s 2>/dev/null" % (flags, name)) + p = wav.index(b"data") + 8 + pcm = struct.unpack("<%dh" % ((len(wav) - p) // 2), wav[p:p + (len(wav) - p) // 2 * 2]) + return raw([x / 32768 for x in pcm]) + + +def generate(ctx): + d = tempfile.mkdtemp(prefix="fmt-ac3-") + cases, tracks = [], [] + try: + def run(cmd): + return ctx.nix(["ffmpeg", "aften", "a52dec"], ["sh", "-c", "cd '%s' && %s" % (d, cmd)]) + + for name, enc, layout, rate, kbps, extra in CASES: + ch = CHANNELS[layout] if enc == "ffmpeg" else ACMOD_CH[layout[0]] + layout[1] + frames = int(rate * SECONDS) + sig = signal(frames, ch, rate, len(name)) + with open(os.path.join(d, name + ".raw"), "wb") as f: + f.write(raw(sig)) + out = name + ".ac3" + if enc == "ffmpeg": + run("ffmpeg -v error -y -f f32le -ar %d -ch_layout '%s' -i %s.raw -c:a ac3 -b:a %dk %s %s" + % (rate, layout, name, kbps, " ".join(extra), out)) + else: + with open(os.path.join(d, name + ".wav"), "wb") as f: + f.write(A.wav(sig, rate, ch)) + run("aften -v 0 -threads 1 -b %d -acmod %d -lfe %d %s %s.wav %s" % (kbps, layout[0], layout[1], " ".join(extra), name, out)) + with open(os.path.join(d, out), "rb") as f: + orig = f.read() + data = undither(ctx, orig) + with open(os.path.join(d, "u_" + out), "wb") as f: + f.write(data) + c = {"name": name, "data": data, "channels": ch, "rate": rate} + if "-s" in extra: + c["ref"], c["refTool"] = a52dec(run, d, "u_" + out, ch), "a52dec" + else: + c["ref"], c["refTool"] = run("ffmpeg -v error -drc_scale 0 -i u_%s -f f32le -" % out), "ffmpeg" + if "-dynrng" in extra: + c["refDrc"] = run("ffmpeg -v error -drc_scale 1 -i u_%s -f f32le -" % out) + c["frames"] = len(c["ref"]) // (4 * ch) + if name in DITHERED: + c["dithered"] = orig + cases.append(c) + # AC-3 tracks in containers: the (undithered) AC-3 remuxed with a tiny Motion-JPEG / MPEG-1 picture track + sig = signal(int(48000 * 0.3), 6, 48000, 7) + with open(os.path.join(d, "t.raw"), "wb") as f: + f.write(raw(sig)) + for name, video, layout in (("ac3.mkv", "-c:v mjpeg -pix_fmt yuvj420p", "5.1(side)"), + ("ac3.mp4", "-c:v mjpeg -pix_fmt yuvj420p", "stereo"), ("ac3.ts", "-c:v mpeg1video", "stereo")): + run("ffmpeg -v error -y -f f32le -ar 48000 -ch_layout '5.1(side)' -i t.raw -af aformat=channel_layouts='%s' " + "-c:a ac3 -b:a 192k t.ac3" % layout) + with open(os.path.join(d, "t.ac3"), "rb") as f: + es = undither(ctx, f.read()) + with open(os.path.join(d, "u.ac3"), "wb") as f: + f.write(es) + run("ffmpeg -v error -y -f lavfi -i testsrc=size=64x48:rate=25:duration=0.3 -i u.ac3 %s -c:a copy -shortest %s" + % (video, name)) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + ref = run("ffmpeg -v error -drc_scale 0 -i u.ac3 -f f32le -") + tracks.append({"name": name, "data": data, "channels": CHANNELS[layout], "rate": 48000, "ref": ref}) + finally: + shutil.rmtree(d, ignore_errors=True) + ctx.emit("ac3_cases", cases) + ctx.emit("ac3_tracks", tracks) From 2d99b9924afaad304c2969e509295d7afe82b886 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:48:22 -0500 Subject: [PATCH 5/7] ws-audio2: Musepack / AC-3 bench lines, docs/guide/audio.md section (+ tools/fixtures/docs_lossy.py inputs), AVI AC-3 track test --- docs/guide/audio.md | 26 ++++++++++++++++++++++-- tests/audio/ac3.luau | 2 +- tools/bench.luau | 28 ++++++++++++++++++++++++++ tools/fixtures/ac3.py | 5 +++-- tools/fixtures/docs_lossy.py | 39 ++++++++++++++++++++++++++++++++++++ 5 files changed, 95 insertions(+), 5 deletions(-) create mode 100644 tools/fixtures/docs_lossy.py diff --git a/docs/guide/audio.md b/docs/guide/audio.md index 94271f6..8af0240 100644 --- a/docs/guide/audio.md +++ b/docs/guide/audio.md @@ -99,7 +99,8 @@ the guide's [README](README.md#inputs)). Options: | Option | Formats | Meaning | |---|---|---| | `format` | all | decode as this format (`"mp3"`, `"wav"`, ...) and skip detection | -| `maxFrames` | wav, flac, mp3, aiff, au, voc, aac | `Err.LIMIT` past this many frames | +| `maxFrames` | wav, flac, mp3, aiff, au, voc, aac, mpc, ac3 | `Err.LIMIT` past this many frames | +| `drc` | ac3 | dynamic range control: 0 = off (default), 1 = as the stream says | | `stereo` | opus | downmix surround streams to stereo | ```luau @@ -189,7 +190,7 @@ Tags are written from `audio.tags`, or from the Decoder's `tags`, wherever the f | Read and write | Read only | |---|---| -| wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC) | aac (ADTS), m4a / caf AAC | +| wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC) | aac (ADTS), m4a / caf AAC, mpc (Musepack SV7 / SV8), ac3 (Dolby Digital) | Each format's capabilities are listed in [FORMATS.md](../FORMATS.md). The audio tracks of video files open as Decoders too: see `v.audio` in [video.md](video.md). Music files (MOD, MIDI, ...) render to a Decoder: see @@ -243,6 +244,27 @@ end Roblox has no API to play raw samples, so on Roblox the decoded samples are data only, for example for analysis or visualisers. +### Musepack and AC-3 + +Musepack (`.mpc`, stream versions 7 and 8) decodes gapless, with its APEv2 tags. AC-3 (`.ac3`, Dolby Digital) decodes +every channel layout up to 5.1 without downmixing, in WAVE order (FL FR FC LFE SL SR), with dynamic range control off +unless `drc` asks for it. The AC-3 tracks of MKV, MP4, MPEG-TS and AVI files open as `v.audio` the same way. Both +seek exactly (Musepack SV7 like libmpcdec: 32 frames of pre-roll). E-AC-3 (Dolby Digital Plus) is `Err.UNSUPPORTED`. + +```luau +local mpc = assert(F.audio.load(mpcBytes)) -- Musepack: tags, exact length +assert(F.detect(mpcBytes) == "mpc" and mpc.tags.title == "Docs Tone") +assert(mpc.frames == 44100 and mpc.meta.source.version == 8) +local dd = assert(F.audio.open(ac3Bytes)) -- AC-3 5.1: a Decoder like any other +assert(dd.channels == 6 and dd.sampleRate == 48000) +dd:seek(0.25) +local _, n = dd:read(256) +assert(n == 256) +local stereo = assert(F.ops.audio.downmix(F.audio.load(ac3Bytes))) -- 2 channels, ITU-R BS.775 +local night = assert(F.audio.load(ac3Bytes, { drc = 1 })) -- the stream's dynamic range gains applied +assert(stereo.channels == 2 and night.channels == 6) +``` + ## Gotchas - `F.ops.audio.downmix(a)` defaults to **2** channels, so a stereo input stays stereo. Use `downmix(a, 1)` for mono. diff --git a/tests/audio/ac3.luau b/tests/audio/ac3.luau index 6f00ebd..447c959 100644 --- a/tests/audio/ac3.luau +++ b/tests/audio/ac3.luau @@ -2,7 +2,7 @@ -- 32 / 44.1 / 48 kHz) and aften (block switching, 1+1 dual mono, dynamic range profiles, the alternate BSI) against -- ffmpeg's float decode, or liba52's for block-switched streams (SNR, max difference; dithflags cleared in the -- fixture step so both sides decode the same numbers); dynamic range on; the encoders' dithered originals; AC-3 tracks --- of MKV / MP4 / MPEG-TS through the api's audio hook; exact seeking; resync and truncation; error codes (E-AC-3, +-- of MKV / MP4 / MPEG-TS / AVI through the api's audio hook; exact seeking; resync and truncation; error codes (E-AC-3, -- CRC); the fuzz no-throw pass. Fixtures: tools/fixtures/ac3.py. local T = require("@tests/T") local F = require("@formats") diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..bacd38a 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1078,3 +1078,31 @@ do jitTune(false) end end +-- ws-audio2: lossy +do + -- Musepack (codecs/audio/Musepack) SV8 / SV7 and AC-3 5.1 (codecs/audio/Ac3): whole-file decodes, MB/s of f32 output + -- (tools/fixtures/mpc.py: 1.2 s of 44.1 kHz stereo at quality 5; tools/fixtures/ac3.py: 0.16 s of 48 kHz 5.1 at + -- 448 kbps, decoded 4 times per run) + local Mpc = require("@formats/audio/mpc") + local MpcFx = require("@tests/gen/mpc_cases") + local Ac3F = require("@formats/audio/ac3") + local Ac3Fx = require("@tests/gen/ac3_cases") + for _, c in MpcFx do + if c.name == "sv8_q5_stereo" or c.name == "sv7_q5_stereo" then + local b = buffer.fromstring(c.data) + bench("mpc " .. c.name, 5, c.frames * c.channels * 4, function() + assert(Mpc.decode(Bytes.reader(b))) + end) + end + end + for _, c in Ac3Fx do + if c.name == "5.1_448" then + local b = buffer.fromstring(c.data) + bench("ac3 5.1 448 kbps", 5, c.frames * c.channels * 4 * 4, function() + for _ = 1, 4 do + assert(Ac3F.decode(Bytes.reader(b))) + end + end) + end + end +end diff --git a/tools/fixtures/ac3.py b/tools/fixtures/ac3.py index f7cba37..a0c394e 100644 --- a/tools/fixtures/ac3.py +++ b/tools/fixtures/ac3.py @@ -3,7 +3,7 @@ # References: ffmpeg's float decode with -drc_scale 0 (dynamic range off, our default), except for block-switched # streams: ffmpeg (as packaged) mis-decodes the first of the two short transforms, so those use liba52's a52dec # (-r -a: no dynamic range, no level adjustment; float for stereo, 16-bit wav6 for more channels), which agrees with -# the A/52 transform equations. AC-3 tracks in Matroska / MP4 / MPEG-TS (remuxed by ffmpeg) for the api's audio hook. +# the A/52 transform equations. AC-3 tracks in Matroska / MP4 / MPEG-TS / AVI (remuxed by ffmpeg) for the api's audio hook. # # Both encoders set dithflag, and decoders draw their own random dither for the zero-bit mantissas, so two correct # decoders differ by about the coding noise. The reference streams therefore have their dithflags cleared (the bit @@ -214,7 +214,8 @@ def generate(ctx): with open(os.path.join(d, "t.raw"), "wb") as f: f.write(raw(sig)) for name, video, layout in (("ac3.mkv", "-c:v mjpeg -pix_fmt yuvj420p", "5.1(side)"), - ("ac3.mp4", "-c:v mjpeg -pix_fmt yuvj420p", "stereo"), ("ac3.ts", "-c:v mpeg1video", "stereo")): + ("ac3.mp4", "-c:v mjpeg -pix_fmt yuvj420p", "stereo"), ("ac3.ts", "-c:v mpeg1video", "stereo"), + ("ac3.avi", "-c:v mjpeg -pix_fmt yuvj420p", "stereo")): run("ffmpeg -v error -y -f f32le -ar 48000 -ch_layout '5.1(side)' -i t.raw -af aformat=channel_layouts='%s' " "-c:a ac3 -b:a 192k t.ac3" % layout) with open(os.path.join(d, "t.ac3"), "rb") as f: diff --git a/tools/fixtures/docs_lossy.py b/tools/fixtures/docs_lossy.py new file mode 100644 index 0000000..42f6f50 --- /dev/null +++ b/tools/fixtures/docs_lossy.py @@ -0,0 +1,39 @@ +# Docs inputs for the Musepack / AC-3 section of docs/guide/audio.md (tools/docs_check.py): a tagged stereo tone as +# Musepack SV8 (mpcenc, built by tools/fixtures/mpc.py's nix expression) and a 5.1 tone as AC-3 (ffmpeg). +# tests/gen/docs_lossy.luau { files = { [name] = bytes }, vars = { mpcBytes = "tone.mpc", ac3Bytes = "tone.ac3" } } +import importlib.util, math, os, shutil, struct, subprocess, tempfile + +INPUTS = ["tools/docs_check.py", "tools/fixtures/mpc.py"] + + +def load(ctx, rel, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, rel)) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + dc = load(ctx, "tools/docs_check.py", "docs_check") + mpc = load(ctx, "tools/fixtures/mpc.py", "docs_lossy_mpc") + d = tempfile.mkdtemp(prefix="fmt-docs-lossy-") + try: + rate, n = 44100, 44100 + st = [0.3 * math.sin(2 * math.pi * f * i / rate) for i in range(n) for f in (440, 660)] + with open(os.path.join(d, "tone.wav"), "wb") as f: + f.write(mpc.A.wav(st, rate, 2)) + subprocess.run([os.path.join(mpc.tools(), "mpcenc"), "--silent", "--overwrite", "--quality", "4", + "--tag", "Title=Docs Tone", "--artist", "formats-luau", os.path.join(d, "tone.wav"), + os.path.join(d, "tone.mpc")], capture_output=True, check=True) + six = [0.2 * math.sin(2 * math.pi * (200 + 100 * c) * i / 48000) for i in range(24000) for c in range(6)] + with open(os.path.join(d, "six.raw"), "wb") as f: + f.write(struct.pack("<%df" % len(six), *six)) + ctx.nix("ffmpeg", ["sh", "-c", "cd '%s' && ffmpeg -v error -y -f f32le -ar 48000 -ch_layout '5.1(side)' -i six.raw " + "-c:a ac3 -b:a 384k tone.ac3" % d]) + files = {} + for name in ("tone.mpc", "tone.ac3"): + with open(os.path.join(d, name), "rb") as f: + files[name] = f.read() + finally: + shutil.rmtree(d, ignore_errors=True) + dc.emit_inputs(ctx, files, {"mpcBytes": "tone.mpc", "ac3Bytes": "tone.ac3"}) From 62aded60c08f6a8a15ee4eac883620b0128a8bd1 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:52:41 -0500 Subject: [PATCH 6/7] ws-audio2: audio/ac3 sniffs E-AC-3 too (loading one says UNSUPPORTED, not an unknown format); fixture tidy --- src/Formats/audio/ac3/init.luau | 3 ++- tests/audio/ac3.luau | 2 ++ tools/fixtures/ac3.py | 9 ++------- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/Formats/audio/ac3/init.luau b/src/Formats/audio/ac3/init.luau index 4f69ea9..c481523 100644 --- a/src/Formats/audio/ac3/init.luau +++ b/src/Formats/audio/ac3/init.luau @@ -32,10 +32,11 @@ export type DecodeOptions = { } -- ------------------------------------------------------------------------------------------------ sniff +-- (E-AC-3 streams sniff too, so loading one says UNSUPPORTED instead of an unknown format) function Ac3Format.sniff(r: Bytes.Reader): number local b, p, limit = r.buf, r.pos, r.limit local h = Ac3.header(b, p, limit) - if not h or h.bsid > 10 then + if not h then return 0 end local h2 = Ac3.header(b, p + h.frameSize, limit) diff --git a/tests/audio/ac3.luau b/tests/audio/ac3.luau index 447c959..7b67ca4 100644 --- a/tests/audio/ac3.luau +++ b/tests/audio/ac3.luau @@ -128,6 +128,8 @@ do local eac3 = "\11\119\0\255\128\128" .. string.rep("\0", 506) _, e = Ac3F.decode(reader(eac3 .. eac3)) t:check(e and e.code == Err.UNSUPPORTED, "E-AC-3: " .. tostring(e)) + local _, fe = F.audio.load(buffer.fromstring(eac3 .. eac3)) + t:check(fe and fe.code == Err.UNSUPPORTED, "E-AC-3 through the api: " .. tostring(fe)) -- a flipped bit in the middle of the first frame: the CRC catches it local bad = string.sub(c, 1, 300) .. string.char(bit32.bxor(string.byte(c, 301), 4)) .. string.sub(c, 302) _, e = Ac3F.decode(reader(bad)) diff --git a/tools/fixtures/ac3.py b/tools/fixtures/ac3.py index a0c394e..4e8f26f 100644 --- a/tools/fixtures/ac3.py +++ b/tools/fixtures/ac3.py @@ -12,7 +12,7 @@ # tests/gen/ac3_cases.luau { name, data, channels, rate, frames, ref (f32le, WAVE order), refTool, refDrc?, # dithered? } # tests/gen/ac3_tracks.luau { name, data (the container), channels, rate, ref (ffmpeg's decode of the AC-3) } -import importlib.util, math, os, random, shutil, struct, subprocess, tempfile +import importlib.util, math, os, random, shutil, struct, tempfile _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) @@ -28,7 +28,6 @@ def _lit(b): return '"' + "".join("\\x%02x" % x for x in b) + '"' - def crc16(data, crc=0): """A/52 section 7.10.1: x^16 + x^15 + x^2 + 1, MSB first, zero start""" for b in data: @@ -99,11 +98,7 @@ end out[o:o + size] = f return bytes(out) -# Both encoders set dithflag, and decoders draw their own random dither for the zero-bit mantissas, so two correct -# decoders differ by about the coding noise. The reference streams therefore have their dithflags cleared (the bit -# positions come from our decoder's dec.blocks, the CRCs are recomputed): ffmpeg and we then decode the same numbers. -# `dithered` keeps the encoder's original stream for a few cases. -# + # name, encoder, layout (ffmpeg) or (acmod, lfe) (aften), rate, kbps, extra options CASES = [ ("mono_48k", "ffmpeg", "mono", 48000, 96, []), From e7c6f4e2af13b741d99021992fd065c8cf1f9ef5 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:55:37 -0500 Subject: [PATCH 7/7] ws-audio2: tests/codecs/ac3 + tests/codecs/musepack (the codec APIs, frame-by-frame decodes, fuzz) --- tests/codecs/ac3.luau | 57 +++++++++++++++++++++++++++++++++++++ tests/codecs/musepack.luau | 58 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 tests/codecs/ac3.luau create mode 100644 tests/codecs/musepack.luau diff --git a/tests/codecs/ac3.luau b/tests/codecs/ac3.luau new file mode 100644 index 0000000..dbac64a --- /dev/null +++ b/tests/codecs/ac3.luau @@ -0,0 +1,57 @@ +-- codecs/audio/Ac3 tests: the codec API under audio/ac3 and the container hook: header fields of every fixture layout, +-- the CRC (a syncframe checks to 0), one-frame decodes against the reference (frame by frame, as a container feeds +-- them), the block offsets, reset, argument / data errors, and a fuzz pass over single frames (CRC off). +-- Fixtures: tools/fixtures/ac3.py. +local T = require("@tests/T") +local Ac3 = require("@formats/codecs/audio/Ac3") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/ac3_cases") + +local t = T.suite("codecs/ac3") + +local ACMOD_CH = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } +local frames = {} +for _, c in Fx do + local b = buffer.fromstring(c.data) + local h = Ac3.header(b, 0, buffer.len(b)) + t:check(h, c.name .. ": header") + if not h then + continue + end + t:check(h.sampleRate == c.rate and h.channels == c.channels, c.name .. ": header rate / channels") + t:eq(ACMOD_CH[h.acmod] + (if h.lfeon then 1 else 0), c.channels, c.name .. ": acmod + lfe") + t:eq(Ac3.crc(b, 2, h.frameSize - 2), 0, c.name .. ": crc2 checks") + -- frame by frame, fresh decoder: the second frame against the reference + local d = Ac3.decoder() + local n1 = d:decode(b, 0, h.frameSize) + local h2 = Ac3.header(b, h.frameSize, buffer.len(b)) :: Ac3.Header + local n2, err = d:decode(b, h.frameSize, h2.frameSize) + t:check(n1 == 1536 and n2 == 1536, c.name .. ": two frames: " .. tostring(err)) + local rb = buffer.fromstring(c.ref) + local maxd = 0 + for i = 1, 1536 * c.channels do + maxd = math.max(maxd, math.abs(d.pcm[i] - buffer.readf32(rb, (1536 * c.channels + i - 1) * 4))) + end + t:check(maxd < 1e-4, string.format("%s: frame 2 (max diff %g)", c.name, maxd)) + t:check(#d.blocks == 6 and d.blocks[1] > 40 and d.blocks[6] < h2.frameSize * 8, c.name .. ": block offsets") + d:reset() + table.insert(frames, buffer.readstring(b, 0, h.frameSize)) +end + +-- errors +do + local d = Ac3.decoder() + local _, e = d:decode(buffer.create(10), 20) + t:check(e and e.code == Err.ARG, "offset past the buffer: " .. tostring(e)) + _, e = d:decode(buffer.fromstring(string.rep("\0", 64)), 0) + t:check(e and e.code == Err.CORRUPT, "no sync: " .. tostring(e)) + _, e = d:decode(buffer.fromstring(string.sub(frames[1], 1, 100)), 0) + t:check(e and e.code == Err.TRUNCATED, "short frame: " .. tostring(e)) + t:check(Ac3.header(buffer.fromstring("\11\119\0\0\255\0\0\0"), 0, 8) == nil, "frmsizecod 63 / fscod 3: no header") +end + +t:fuzz("decode one frame (crc off)", function(b: buffer) + return Ac3.decoder({ crc = false }):decode(b, 0) +end, frames, { mutations = 30, keepHeader = 6 }) + +t:done() diff --git a/tests/codecs/musepack.luau b/tests/codecs/musepack.luau new file mode 100644 index 0000000..1deb78b --- /dev/null +++ b/tests/codecs/musepack.luau @@ -0,0 +1,58 @@ +-- codecs/audio/Musepack tests: the codec API under audio/mpc: magic, the stream fields of SV7 / SV8 fixtures (version, +-- rate, channels, band count, packet layout, gapless length), packets decoded by hand against libmpcdec (the +-- synthesis delay at the front), out-of-order decodes, and a fuzz pass over open + every packet. Fixtures: +-- tools/fixtures/mpc.py. +local T = require("@tests/T") +local Musepack = require("@formats/codecs/audio/Musepack") +local Fx = require("@tests/gen/mpc_cases") + +local t = T.suite("codecs/musepack") + +for _, c in Fx do + local b = buffer.fromstring(c.data) + t:eq(Musepack.magic(b, 0, buffer.len(b)), c.version, c.name .. ": magic") + local s, err = Musepack.open(b, 0, buffer.len(b)) + t:check(s, c.name .. ": open: " .. tostring(err)) + if not s then + continue + end + t:check(s.version == c.version and s.sampleRate == c.rate and s.channels == c.channels, c.name .. ": fields") + t:eq(s.frames, c.frames, c.name .. ": gapless length") + t:check(s.maxBand >= 1 and s.maxBand <= 31 and s.count >= 1 and s.skip >= 481, c.name .. ": bands / packets") + t:eq(s.stop - s.skip, c.frames, c.name .. ": stop - skip = length") + -- the first packet by hand: output frame k is raw frame skip + k + local n = s.decode(1) + t:check(n and n > 0 and n % 1152 == 0 and n <= s.blockFrames * 1152, c.name .. ": first packet length") + local pcm = s.pcm() + local rb = buffer.fromstring(c.ref) + local ch = c.channels + local maxd = 0 + for k = 0, math.min(500, (n :: number) - s.skip - 1) do + for j = 1, ch do + maxd = math.max(maxd, math.abs(pcm[(s.skip + k) * ch + j] - buffer.readf32(rb, (k * ch + j - 1) * 4))) + end + end + t:check(maxd < 1e-5, string.format("%s: first packet matches libmpcdec (max diff %g)", c.name, maxd)) + if s.count >= 3 then + s.reset() + t:check(s.decode(3) ~= nil and s.decode(1) ~= nil, c.name .. ": decodes out of order after reset") + end +end + +local samples = {} +for _, c in Fx do + table.insert(samples, string.sub(c.data, 1, 2500)) +end +t:fuzz("open + every packet", function(b: buffer) + local s = Musepack.open(b, 0, buffer.len(b)) + if s then + for i = 1, math.min(s.count, 40) do + if not s.decode(i) then + break + end + end + end + return s +end, samples, { mutations = 25, keepHeader = 4 }) + +t:done()