diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 539efa1..48aaa98 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -17,11 +17,15 @@ 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 | 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` | -| audio | flac | .flac .oga | yes | - | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | +| 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 | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | +| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt" | `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` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | @@ -83,6 +87,7 @@ Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and - codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point - codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks +- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. - codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette - codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine - codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index bc49697..8c75fce 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -12,10 +12,12 @@ | `src/Formats/audio/mp3/` | mp3-luau c755bbf (same author), a port of minimp3 by lieff (https://github.com/lieff/minimp3) | minimp3: CC0 1.0, [minimp3-CC0.txt](minimp3-CC0.txt) | | `tests/fixtures/mp3/` | made by ffmpeg (libmp3lame / mp2) from a synthetic signal; `*.ref` are minimp3 decodes of them | test data, no third-party content | | `src/Formats/audio/opus/` (Decoder, Celt, Silk, Mdct, RangeDecoder, Packet, CeltTables, SilkTables) | opus-luau dd2b4e5 (same author): a port of the libopus 1.6 decoder (git bafd40dcbd50; tables generated from its sources); the stereo downmix weights follow opusfile | libopus BSD 3-clause (Xiph.Org, Skype, Octasic, J.-M. Valin, T. B. Terriberry, CSIRO, G. Maxwell, M. Borgerding, E. de Castro Lopo, Mozilla, Amazon), opusfile BSD 3-clause: [libopus-BSD.txt](libopus-BSD.txt) | +| `src/Formats/audio/vorbis/` (Setup, Codebook, Packet, Tables) | a Luau port of stb_vorbis 1.22 by Sean Barrett (https://github.com/nothings/stb): setup parsing, codebooks, floor 1, residues, coupling (the IMDCT is codecs/Mdct; the timing follows libvorbis / the spec) | public domain or MIT (dual): [stb_vorbis-LICENSE.txt](stb_vorbis-LICENSE.txt) | | `src/Formats/audio/flac/` | flac-luau 7083d0d (same author), written from RFC 9639 | no licence chosen yet; no third-party code | | `src/Formats/image/bmp/` | bmp-luau b86aed6 (same author), written from the Microsoft BMP documentation | no licence chosen yet; no third-party code | | `tests/fixtures/bmpsuite/` | BMP Suite 2.8 by Jason Summers (generated images) | public domain: [bmpsuite-NOTICE.txt](bmpsuite-NOTICE.txt) | | `src/Formats/containers/Zip/` (the reader), `src/Formats/archive/zip/` | zip-luau 121d4b0 (same author), written from PKWARE's APPNOTE.TXT 6.3 | no licence chosen yet; no third-party code | +| `src/Formats/audio/mp3/EncTables.luau` (ws-audio encoders) | PDMP3 by Krister Lagerström et al. (https://github.com/technosaurus/PDMP3): the ISO/IEC 11172-3 synthesis window and layer III Huffman trees | public domain (unlicense): [PDMP3-UNLICENSE.txt](PDMP3-UNLICENSE.txt) | | `src/Formats/playlist/` (m3u, pls; xspf is new), `src/Formats/codecs/Url/`, `src/Formats/codecs/Text/` | playlist-luau 3fc7fd3 (same author), written from RFC 3986 / RFC 8216 | no licence chosen yet; no third-party code | | `src/Formats/image/jpeg/` (Decode, Scan, Color), `src/Formats/codecs/Dct/` (inverse DCTs) | jpeg-luau 1.0 (same author); the IDCTs, upsampling, colour conversion and IDCT-size choice are Luau translations of libjpeg / libjpeg-turbo (jidctint.c, jidctred.c, jdsample.c, jdcolor.c, jdmaster.c) | IJG licence + libjpeg-turbo BSD: [libjpeg-turbo-LICENSE.md](libjpeg-turbo-LICENSE.md), [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. | | `src/Formats/image/jpeg/Arith.luau`, `src/Formats/image/jpeg/Encode.luau`, `src/Formats/codecs/Dct/` (forward DCT) | new; Luau translations of libjpeg-turbo 3.2 jdarith.c / jaricom.c (Guido Vollbeding), jccolor.c, jcsample.c, jccoefct.c, jfdctint.c, jcdctmgr.c, jchuff.c, jcphuff.c, jcparam.c | as above | diff --git a/licenses/PDMP3-UNLICENSE.txt b/licenses/PDMP3-UNLICENSE.txt new file mode 100644 index 0000000..abdbb5f --- /dev/null +++ b/licenses/PDMP3-UNLICENSE.txt @@ -0,0 +1,27 @@ +PDMP3 (https://github.com/technosaurus/PDMP3), public domain decoder by Krister Lagerstrom et al. +Tables used in src/Formats/audio/mp3/EncTables.luau. + +Public Domain (www.unlicense.org) + This is free and unencumbered software released into the public domain. + Anyone is free to copy, modify, publish, use, compile, sell, or distribute this + software, either in source code form or as a compiled binary, for any purpose, + commercial or non-commercial, and by any means. + In jurisdictions that recognize copyright laws, the author or authors of this + software dedicate any and all copyright interest in the software to the public + domain. We make this dedication for the benefit of the public at large and to + the detriment of our heirs and successors. We intend this dedication to be an + overt act of relinquishment in perpetuity of all present and future rights to + this software under copyright law. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + Original version written by Krister Lagerström(krister@kmlager.com) + Website: https://sites.google.com/a/kmlager.com/www/projects + + Contributors: + technosaurus + Erik Hofman (added a subset of the libmpg123 compatible streaming API) diff --git a/licenses/stb_vorbis-LICENSE.txt b/licenses/stb_vorbis-LICENSE.txt new file mode 100644 index 0000000..6e4b8d2 --- /dev/null +++ b/licenses/stb_vorbis-LICENSE.txt @@ -0,0 +1,41 @@ +stb_vorbis.c v1.22 (https://github.com/nothings/stb), by Sean Barrett and contributors. +Ported to Luau in src/Formats/audio/vorbis/ (decoder). + +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ab394ee..8d7b29c 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -158,6 +158,30 @@ local list: { Entry } = { return require("@formats/audio/aac") end, }, + { + name = "aiff", + category = "audio", + path = "audio/aiff", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, + load = function() + return require("@formats/audio/aiff") + end, + }, + { + name = "au", + category = "audio", + path = "audio/au", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, + load = function() + return require("@formats/audio/au") + end, + }, { name = "caf", category = "audio", @@ -176,8 +200,8 @@ local list: { Entry } = { path = "audio/flac", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, - caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, load = function() return require("@formats/audio/flac") end, @@ -200,8 +224,8 @@ local list: { Entry } = { path = "audio/mp3", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "Types" }, - caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, load = function() return require("@formats/audio/mp3") end, @@ -218,6 +242,30 @@ local list: { Entry } = { return require("@formats/audio/opus") end, }, + { + name = "voc", + category = "audio", + path = "audio/voc", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, + load = function() + return require("@formats/audio/voc") + end, + }, + { + name = "vorbis", + category = "audio", + path = "audio/vorbis", + extensions = { "ogg", "oga" }, + mime = { "audio/ogg", "audio/vorbis" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, + load = function() + return require("@formats/audio/vorbis") + end, + }, { name = "wav", category = "audio", diff --git a/src/Formats/audio/aiff/init.luau b/src/Formats/audio/aiff/init.luau new file mode 100644 index 0000000..94b02c2 --- /dev/null +++ b/src/Formats/audio/aiff/init.luau @@ -0,0 +1,384 @@ +--!strict +-- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs. +-- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw +-- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated +-- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 / +-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. Not supported: compressed AIFF-C codecs (ima4, MAC3 / +-- MAC6, Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Aiff = { + name = "aiff", + category = "audio", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, +} + +export type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +export type EncodeOptions = { + sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" + littleEndian: boolean?, -- 16-bit samples as AIFF-C "sowt" (default false: big endian; readers such as ffmpeg only + -- take 16-bit sowt, so other formats return Err.ARG) + aifc: boolean?, -- always write AIFF-C (default: only when the sample format needs it) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" } +local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } } +local AIFC_VERSION = 0xA2805140 + +-- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian) +local function ext80(b: buffer, o: number): number + local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) + local hi = bit32.byteswap(buffer.readu32(b, o + 2)) + local lo = bit32.byteswap(buffer.readu32(b, o + 6)) + local e = bit32.band(se, 0x7FFF) + if e == 0 and hi == 0 and lo == 0 then + return 0 + end + if e == 0x7FFF then + return math.huge + end + local v = (hi * 4294967296 + lo) * 2 ^ (e - 16383 - 63) + return if se >= 0x8000 then -v else v +end + +-- the 10 bytes of x (> 0) as an 80-bit extended float +local function writeExt80(w: Bytes.Writer, x: number) + if x <= 0 or x ~= x then + w:fill(0, 10) + return + end + local e = 0 + while x >= 2 ^ (e + 1) do + e += 1 + end + while x < 2 ^ e do + e -= 1 + end + local m = x * 2 ^ (63 - e) -- in [2^63, 2^64) + local hi = math.floor(m / 4294967296) + local lo = m - hi * 4294967296 + w:u16be(e + 16383) + w:u32be(hi) + w:u32be(math.floor(lo)) +end + +-- the sample format of a COMM chunk: Pcm format name | nil, message +local function sampleFormat(comp: string, bits: number): (string?, string?) + if comp == "NONE" or comp == "twos" or comp == "" then + if bits >= 1 and bits <= 8 then + return "s8" + elseif bits <= 16 then + return "s16be" + elseif bits <= 24 then + return "s24be" + elseif bits <= 32 then + return "s32be" + end + return nil, "bad sample size " .. bits + elseif comp == "sowt" then + if bits >= 1 and bits <= 8 then + return "s8" + elseif bits <= 16 then + return "s16le" + elseif bits <= 24 then + return "s24le" + elseif bits <= 32 then + return "s32le" + end + return nil, "bad sample size " .. bits + elseif comp == "raw " then + return "u8" + elseif comp == "in24" then + return "s24be" + elseif comp == "in32" then + return "s32be" + elseif comp == "42ni" then + return "s32le" + elseif comp == "fl32" or comp == "FL32" then + return "f32be" + elseif comp == "fl64" or comp == "FL64" then + return "f64be" + elseif comp == "ulaw" or comp == "ULAW" then + return "ulaw" + elseif comp == "alaw" or comp == "ALAW" then + return "alaw" + end + return nil, "compression " .. string.format("%q", comp) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Aiff.sniff(r: Bytes.Reader): number + if r:remaining() < 12 or r:peek(4) ~= "FORM" then + return 0 + end + local form = buffer.readstring(r.buf, r.pos + 8, 4) + return if form == "AIFF" or form == "AIFC" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Info = { + channels: number, + frames: number, + sampleRate: number, + bits: number, + format: string, + compression: string, + aifc: boolean, + dataOffset: number, -- absolute in r.buf + truncated: boolean, + tags: Types.Tags, +} + +-- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples) +local function parse(r: Bytes.Reader): (Info?, Err.Err?) + local b = r.buf + local base, limit = r.base, r.limit + if limit - base < 12 or buffer.readstring(b, base, 4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not a FORM file", base) + end + local form = buffer.readstring(b, base + 8, 4) + if form ~= "AIFF" and form ~= "AIFC" then + return nil, Err.new(Err.CORRUPT, "FORM type " .. string.format("%q", form) .. " is not AIFF / AIFC", base + 8) + end + local aifc = form == "AIFC" + local formEnd = math.min(limit, base + 8 + bit32.byteswap(buffer.readu32(b, base + 4))) + local info: Info? = nil + local comm = false + local ssnd: number? = nil + local ssndLen = 0 + local tags: Types.Tags = {} + local p = base + 12 + while p + 8 <= formEnd do + local id = buffer.readstring(b, p, 4) + local len = bit32.byteswap(buffer.readu32(b, p + 4)) + local d = p + 8 + local avail = math.min(len, limit - d) + if id == "COMM" then + if avail < 18 or (aifc and avail < 22) then + return nil, Err.new(Err.TRUNCATED, "COMM chunk too short", p) + end + local ch = buffer.readu8(b, d) * 256 + buffer.readu8(b, d + 1) + local frames = bit32.byteswap(buffer.readu32(b, d + 2)) + local bits = buffer.readu8(b, d + 6) * 256 + buffer.readu8(b, d + 7) + local rate = ext80(b, d + 8) + local comp = if aifc then buffer.readstring(b, d + 18, 4) else "NONE" + if ch < 1 then + return nil, Err.new(Err.CORRUPT, "no channels", d) + end + if not (rate > 0 and rate < 2 ^ 31) then + return nil, Err.new(Err.CORRUPT, "bad sample rate", d + 8) + end + local fmt, why = sampleFormat(comp, bits) + if not fmt then + return nil, Err.new(if comp == "NONE" or comp == "twos" or comp == "sowt" then Err.CORRUPT else Err.UNSUPPORTED, why :: string, d + 18) + end + info = { + channels = ch, + frames = frames, + sampleRate = rate, + bits = bits, + format = fmt, + compression = comp, + aifc = aifc, + dataOffset = 0, + truncated = false, + tags = tags, + } + comm = true + elseif id == "SSND" then + if avail < 8 then + return nil, Err.new(Err.TRUNCATED, "SSND chunk too short", p) + end + local off = bit32.byteswap(buffer.readu32(b, d)) + ssnd = d + 8 + off + ssndLen = math.max(0, avail - 8 - off) + if len >= 8 + off then + ssndLen = math.min(ssndLen, len - 8 - off) + end + elseif TEXT_TAGS[id] then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + local key = TEXT_TAGS[id] + tags[key] = if tags[key] then tags[key] .. "\n" .. s else s + end + if len > formEnd - d then + break + end + p = d + len + len % 2 + end + if not comm or not info then + return nil, Err.new(Err.CORRUPT, "no COMM chunk", base) + end + local fi = info :: Info + if fi.frames > 0 and not ssnd then + return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base) + end + local frameBytes = fi.channels * Pcm.Convert.SIZE[fi.format] + local present = if ssnd then ssndLen // frameBytes else 0 + if present < fi.frames then + fi.frames = present + fi.truncated = true + end + fi.dataOffset = ssnd or base + return fi, nil +end + +-- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err +function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?) + return parse(r) +end + +function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Aiff.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local a = Types.Audio.new(d.sampleRate, d.channels, d.frames) + d:read(d.frames, a.samples) + a.tags = d.tags + a.meta.source = d.source + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local FORMATS = { + s8 = { "s8", 8, "NONE" }, + s16 = { "s16be", 16, "NONE" }, + s24 = { "s24be", 24, "NONE" }, + s32 = { "s32be", 32, "NONE" }, + f32 = { "f32be", 32, "fl32" }, + f64 = { "f64be", 64, "fl64" }, + ulaw = { "ulaw", 16, "ulaw" }, + alaw = { "alaw", 16, "alaw" }, +} +local LE = { s16be = "s16le" } +local COMP_NAMES = { NONE = "not compressed", sowt = "", fl32 = "32-bit floating point", fl64 = "64-bit floating point", ulaw = "\181Law 2:1", alaw = "ALaw 2:1" } + +function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = FORMATS[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + local fmt, bits, comp = spec[1], spec[2], spec[3] + if o.littleEndian then + if not LE[fmt] then + return nil, Err.new(Err.ARG, "littleEndian needs 16-bit samples") + end + fmt, comp = LE[fmt], "sowt" + end + if src.channels > 65535 then + return nil, Err.new(Err.ARG, "too many channels") + end + local aifc = o.aifc or comp ~= "NONE" + local w = Bytes.writer(65536) + w:string("FORM") + w:u32be(0) -- patched + w:string(if aifc then "AIFC" else "AIFF") + if aifc then + w:string("FVER") + w:u32be(4) + w:u32be(AIFC_VERSION) + end + -- text chunks from the tags + for _, pair in TEXT_ORDER do + local id, key = pair[1], pair[2] + local s = src.tags[key] + if type(s) == "string" and #s > 0 then + w:string(id) + w:u32be(#s) + w:string(s) + if #s % 2 == 1 then + w:u8(0) + end + end + end + local commAt = w:tell() + w:string("COMM") + if aifc then + local name = COMP_NAMES[comp] or "" + local plen = 1 + #name + plen += plen % 2 + w:u32be(22 + plen) + else + w:u32be(18) + end + w:u16be(src.channels) + w:u32be(0) -- frames, patched + w:u16be(bits) + writeExt80(w, src.sampleRate) + if aifc then + w:string(comp) + local name = COMP_NAMES[comp] or "" + w:u8(#name) + w:string(name) + if (1 + #name) % 2 == 1 then + w:u8(0) + end + end + local ssndAt = w:tell() + w:string("SSND") + w:u32be(0) -- patched + w:u32be(0) -- offset + w:u32be(0) -- block size + local frames, perr = Pcm.encode(src, fmt, w) + if not frames then + return nil, perr + end + local dataLen = w:tell() - ssndAt - 16 + if dataLen % 2 == 1 then + w:u8(0) + end + w:setU32be(ssndAt + 4, dataLen + 8) + w:setU32be(commAt + 10, frames) + w:setU32be(4, w:tell() - 8) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local info, err = parse(r) + if not info then + return nil, err + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if info.frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames)) + end + local dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags) + if not dec then + return nil, derr + end + local d = dec :: any + d.source = { + format = "aiff", + aifc = info.aifc, + compression = info.compression, + bitDepth = info.bits, + sampleFormat = info.format, + truncated = info.truncated or nil, + } + return dec, nil +end + +return Aiff diff --git a/src/Formats/audio/au/init.luau b/src/Formats/audio/au/init.luau new file mode 100644 index 0000000..0215799 --- /dev/null +++ b/src/Formats/audio/au/init.luau @@ -0,0 +1,166 @@ +--!strict +-- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description. +-- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear), +-- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file); +-- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit). +-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Au = { + name = "au", + category = "audio", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, +} + +export type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +export type EncodeOptions = { + sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" +} + +-- ------------------------------------------------------------------------------------------------ constants +local ENCODINGS: { [number]: string } = { + [1] = "ulaw", + [2] = "s8", + [3] = "s16be", + [4] = "s24be", + [5] = "s32be", + [6] = "f32be", + [7] = "f64be", + [27] = "alaw", +} +local WRITE = { + ulaw = { 1, "ulaw" }, + s8 = { 2, "s8" }, + s16 = { 3, "s16be" }, + s24 = { 4, "s24be" }, + s32 = { 5, "s32be" }, + f32 = { 6, "f32be" }, + f64 = { 7, "f64be" }, + alaw = { 27, "alaw" }, +} +local BITS = { ulaw = 8, alaw = 8, s8 = 8, s16be = 16, s24be = 24, s32be = 32, f32be = 32, f64be = 64 } + +local function be32(b: buffer, o: number): number + return bit32.byteswap(buffer.readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Au.sniff(r: Bytes.Reader): number + return if r:peek(4) == ".snd" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Au.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local a = Types.Audio.new(d.sampleRate, d.channels, d.frames) + d:read(d.frames, a.samples) + a.tags = d.tags + a.meta.source = d.source + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + -- annotation: the comment tag, NUL-terminated, padded to a multiple of 8 (at least 4 bytes, as Sun requires) + local note = if type(src.tags.comment) == "string" then src.tags.comment else "" + local alen = #note + 1 + alen = math.max(8, alen + (8 - alen % 8) % 8) + local w = Bytes.writer(65536) + w:string(".snd") + w:u32be(24 + alen) + w:u32be(0xFFFFFFFF) -- patched + w:u32be(spec[1]) + w:u32be(src.sampleRate) + w:u32be(src.channels) + w:string(note) + w:fill(0, alen - #note) + local frames, perr = Pcm.encode(src, spec[2], w) + if not frames then + return nil, perr + end + w:setU32be(8, w:tell() - 24 - alen) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Au.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 24 or buffer.readstring(b, base, 4) ~= ".snd" then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local off, size, enc, rate, ch = be32(b, base + 4), be32(b, base + 8), be32(b, base + 12), be32(b, base + 16), be32(b, base + 20) + local fmt = ENCODINGS[enc] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "encoding " .. enc, base + 12) + end + if ch < 1 or ch > 65535 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch, base + 20) + end + if rate < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate", base + 16) + end + if off < 24 or off > limit - base then + return nil, Err.new(Err.CORRUPT, "bad data offset", base + 4) + end + local tags: Types.Tags = {} + if off > 24 then + local s = buffer.readstring(b, base + 24, off - 24) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + if #s > 0 then + tags.comment = s + end + end + local avail = limit - base - off + local truncated = false + if size == 0xFFFFFFFF then + size = avail + elseif size > avail then + size = avail + truncated = true + end + local frameBytes = ch * Pcm.Convert.SIZE[fmt] + local frames = size // frameBytes + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", frames, maxFrames)) + end + local dec, derr = Pcm.rawDecoder(b, base + off, frames, ch, rate, fmt, tags) + if not dec then + return nil, derr + end + local d = dec :: any + d.source = { format = "au", encoding = enc, sampleFormat = fmt, bitDepth = BITS[fmt], truncated = truncated or nil } + return dec, nil +end + +return Au diff --git a/src/Formats/audio/flac/Encode.luau b/src/Formats/audio/flac/Encode.luau new file mode 100644 index 0000000..499f4c0 --- /dev/null +++ b/src/Formats/audio/flac/Encode.luau @@ -0,0 +1,1038 @@ +--!strict +--!native +--!optimize 2 +-- audio/flac/Encode: the FLAC encoder (RFC 9639). New code, written from the RFC; the presets mirror libFLAC's -0 .. -8 +-- (block size 1152 / 4096, max LPC order 0 / 6 / 8 / 12, Rice partition order 3 .. 6, independent / adaptive / +-- exhaustive stereo decorrelation). Subframes: CONSTANT, VERBATIM, FIXED (order 0..4, chosen by the residual sum), +-- LPC (Levinson-Durbin on the tukey(0.5)-windowed autocorrelation, error-feedback coefficient quantization with +-- libFLAC's precision table, the order estimated from the prediction error or searched exhaustively at -8), wasted +-- bits; Rice / Rice2 partitions with the partition order and parameters searched per subframe. Frames carry CRC-8 / +-- CRC-16; STREAMINFO carries the sizes, total samples and the MD5 of the PCM; VORBIS_COMMENT from the tags; an optional +-- SEEKTABLE. Streams: input blocks are pulled from a codecs/Pcm Source, so a Decoder is encoded without decoding it +-- whole. Never throws: bad options are rejected by audio/flac before calling in. +local Md5 = require("@formats/core/Md5") + +local Encode = {} + +local floor, abs, log = math.floor, math.abs, math.log +local readf32, writeu8 = buffer.readf32, buffer.writeu8 + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ CRCs +local CRC8 = table.create(256, 0) +local CRC16 = table.create(256, 0) +for i = 0, 255 do + local c = i + for _ = 1, 8 do + c = if c >= 128 then bit32.bxor((c * 2) % 256, 0x07) else c * 2 + end + CRC8[i + 1] = c + local d = i * 256 + for _ = 1, 8 do + d = if d >= 32768 then bit32.bxor((d * 2) % 65536, 0x8005) else d * 2 + end + CRC16[i + 1] = d +end +local function crc8(b: buffer, o: number, n: number): number + local c = 0 + for i = o, o + n - 1 do + c = CRC8[bit32.bxor(c, buffer.readu8(b, i)) + 1] + end + return c +end +local function crc16(b: buffer, o: number, n: number): number + local c = 0 + for i = o, o + n - 1 do + c = bit32.bxor((c * 256) % 65536, CRC16[bit32.bxor(c // 256, buffer.readu8(b, i)) + 1]) + end + return c +end +Encode.crc8, Encode.crc16 = crc8, crc16 + +-- ------------------------------------------------------------------------------------------------ bit writer (MSB first) +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +local function ensure(w: W, n: number) + local need = w.pos + n + 16 + local cap = buffer.len(w.buf) + if need > cap then + local nb = buffer.create(math.max(cap * 2, need)) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end +end + +-- put(w, v, n): the low n bits (n <= 32) of the non-negative integer v +local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc * POW[n + 1] + v + local cnt = w.cnt + n + local b, p = w.buf, w.pos + while cnt >= 8 do + cnt -= 8 + local m = POW[cnt + 1] + local byte = floor(acc / m) + writeu8(b, p, byte) + p += 1 + acc -= byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +local function putSigned(w: W, v: number, n: number) + put(w, if v < 0 then v + POW[n + 1] else v, n) +end + +local function alignByte(w: W) + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end +end + +local function putUtf8(w: W, v: number) + if v < 0x80 then + put(w, v, 8) + return + end + local n = if v < 0x800 then 2 elseif v < 0x10000 then 3 elseif v < 0x200000 then 4 elseif v < 0x4000000 then 5 elseif v < 0x80000000 then 6 else 7 + local first = if n == 7 then 0xFE else (0xFF00 // POW[n + 1]) % 256 -- n leading ones + local shift = 6 * (n - 1) + put(w, first + floor(v / POW[shift + 1]), 8) + for k = n - 2, 0, -1 do + put(w, 0x80 + floor(v / POW[6 * k + 1]) % 64, 8) + end +end + +-- ------------------------------------------------------------------------------------------------ presets +export type Config = { + blockSize: number, + maxLpcOrder: number, + maxPartitionOrder: number, + stereo: string, -- "independent" | "adaptive" | "exhaustive" + exhaustiveOrder: boolean, +} +local PRESETS: { Config } = { + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "independent", exhaustiveOrder = false }, + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "adaptive", exhaustiveOrder = false }, + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 6, maxPartitionOrder = 4, stereo = "independent", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 4, stereo = "adaptive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 5, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = true }, +} +Encode.PRESETS = PRESETS + +-- ------------------------------------------------------------------------------------------------ analysis +-- a subframe plan for one channel signal +type Plan = { + kind: number, -- 0 constant, 1 verbatim, 2 fixed, 3 lpc + bits: number, -- estimated size in bits (with the subframe header) + order: number, + wasted: number, + bps: number, -- sample size after removing wasted bits + res: { number }, -- residual (fixed / lpc), indices 1..n + porder: number, + params: { number }, + method: number, -- 0 Rice (4-bit params), 1 Rice2 (5-bit) + qlp: { number }, + shift: number, + precision: number, + x: { number }, -- the (shifted) samples +} + +local function newPlan(n: number): Plan + return { + kind = 1, + bits = 0, + order = 0, + wasted = 0, + bps = 16, + res = table.create(n, 0), + porder = 0, + params = table.create(64, 0), + method = 0, + qlp = table.create(32, 0), + shift = 0, + precision = 0, + x = table.create(n, 0), + } +end + +-- scratch per encoder +type Scratch = { + sums: { number }, + counts: { number }, + ks: { number }, + bestKs: { number }, + tmpRes: { number }, + win: { number }, + winN: number, + wx: { number }, + autoc: { number }, + lpc: { { number } }, + err: { number }, + qlp: { number }, +} + +-- rice(res, n, order, maxP, plan?) -> bits, porder, method (fills scratch.bestKs with the parameters) +local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP: number): (number, number, number) + -- the finest usable partition order + local p = maxP + while p > 0 and (n % POW[p + 1] ~= 0 or n // POW[p + 1] <= order) do + p -= 1 + end + local sums, counts = sc.sums, sc.counts + local parts = POW[p + 1] + local ps = n // parts + -- sums of zig-zag values at the finest order + for j = 0, parts - 1 do + local s = 0 + local a = if j == 0 then order + 1 else j * ps + 1 + local e = (j + 1) * ps + for i = a, e do + local r = res[i] + s += if r >= 0 then 2 * r else -2 * r - 1 + end + sums[j + 1] = s + counts[j + 1] = e - a + 1 + end + local bestBits, bestP, bestMethod = math.huge, 0, 0 + local ks, bestKs = sc.ks, sc.bestKs + local q = p + while true do + local np = POW[q + 1] + local total = 0 + local maxk = 0 + for j = 1, np do + local s, c = sums[j], counts[j] + local k = 0 + local cost = s + c -- k = 0: unary s, plus one stop bit per sample + if c > 0 and s > c then + local k0 = floor(log(s / c) / 0.6931471805599453) + for kk = math.max(0, k0 - 1), math.min(30, k0 + 1) do + local cc = c * (kk + 1) + floor(s / POW[kk + 1]) + if cc < cost then + cost, k = cc, kk + end + end + end + ks[j] = k + if k > maxk then + maxk = k + end + total += cost + end + local method = if maxk > 14 then 1 else 0 + total += np * (if method == 1 then 5 else 4) + 2 + 4 + if total < bestBits then + bestBits, bestP, bestMethod = total, q, method + for j = 1, np do + bestKs[j] = ks[j] + end + end + if q == 0 then + break + end + -- merge pairs into the next coarser order + for j = 1, np // 2 do + sums[j] = sums[2 * j - 1] + sums[2 * j] + counts[j] = counts[2 * j - 1] + counts[2 * j] + end + q -= 1 + end + return bestBits, bestP, bestMethod +end + +local function keepRice(sc: Scratch, plan: Plan, porder: number, method: number) + plan.porder, plan.method = porder, method + local params = plan.params + for j = 1, POW[porder + 1] do + params[j] = sc.bestKs[j] + end +end + +-- fixed predictor residuals +local function fixedResidual(x: { number }, n: number, order: number, res: { number }) + for i = 1, order do + res[i] = 0 + end + if order == 0 then + for i = 1, n do + res[i] = x[i] + end + elseif order == 1 then + for i = 2, n do + res[i] = x[i] - x[i - 1] + end + elseif order == 2 then + for i = 3, n do + res[i] = x[i] - 2 * x[i - 1] + x[i - 2] + end + elseif order == 3 then + for i = 4, n do + res[i] = x[i] - 3 * x[i - 1] + 3 * x[i - 2] - x[i - 3] + end + else + for i = 5, n do + res[i] = x[i] - 4 * x[i - 1] + 6 * x[i - 2] - 4 * x[i - 3] + x[i - 4] + end + end +end + +-- the fixed order with the smallest residual magnitude (libFLAC's estimate) +local function bestFixedOrder(x: { number }, n: number): (number, number) + if n <= 4 then + return 0, 0 + end + local s0, s1, s2, s3, s4 = 0, 0, 0, 0, 0 + local a, b, c, d = x[4], x[4] - x[3], x[4] - 2 * x[3] + x[2], x[4] - 3 * x[3] + 3 * x[2] - x[1] + for i = 5, n do + local e0 = x[i] + local e1 = e0 - a + local e2 = e1 - b + local e3 = e2 - c + local e4 = e3 - d + s0 += abs(e0) + s1 += abs(e1) + s2 += abs(e2) + s3 += abs(e3) + s4 += abs(e4) + a, b, c, d = e0, e1, e2, e3 + end + local best, bs = 0, s0 + if s1 < bs then + best, bs = 1, s1 + end + if s2 < bs then + best, bs = 2, s2 + end + if s3 < bs then + best, bs = 3, s3 + end + if s4 < bs then + best, bs = 4, s4 + end + return best, bs +end +Encode.bestFixedOrder = bestFixedOrder + +-- libFLAC's default QLP coefficient precision for a block size +local function qlpPrecision(bps: number, n: number): number + if bps > 16 then + return 15 + end + if n <= 192 then + return 7 + elseif n <= 384 then + return 8 + elseif n <= 576 then + return 9 + elseif n <= 1152 then + return 10 + elseif n <= 2304 then + return 11 + elseif n <= 4608 then + return 12 + end + return 13 +end + +-- quantize coefficients lp[1..order] to precision bits: qlp[1..order], shift | nil +local function quantize(lp: { number }, order: number, precision: number, qlp: { number }): number? + local cmax = 0 + for i = 1, order do + local a = abs(lp[i]) + if a > cmax then + cmax = a + end + end + if cmax <= 0 or cmax ~= cmax or cmax == math.huge then + return nil + end + local log2cmax = 0 + while cmax >= 1 do + cmax /= 2 + log2cmax += 1 + end + while cmax < 0.5 do + cmax *= 2 + log2cmax -= 1 + end + -- frexp: cmax = m * 2^log2cmax with m in [0.5, 1) + log2cmax -= 1 + local p = precision - 1 + local qmax = POW[p + 1] - 1 + local qmin = -POW[p + 1] + local shift = p - log2cmax - 1 + if shift > 15 then + shift = 15 + elseif shift < 0 then + return nil + end + local err = 0 + local scale = POW[shift + 1] + for i = 1, order do + err += lp[i] * scale + local q = floor(err + 0.5) + if q > qmax then + q = qmax + elseif q < qmin then + q = qmin + end + err -= q + qlp[i] = q + end + return shift +end + +local function lpcResidual(x: { number }, n: number, order: number, qlp: { number }, shift: number, res: { number }) + local d = POW[shift + 1] + for i = 1, order do + res[i] = 0 + end + for i = order + 1, n do + local s = 0 + for j = 1, order do + s += qlp[j] * x[i - j] + end + res[i] = x[i] - floor(s / d) + end +end + +-- Levinson-Durbin: sc.lpc[o][1..o] and sc.err[o] for o = 1 .. maxOrder; returns the highest usable order +local function levinson(sc: Scratch, maxOrder: number): number + local r = sc.autoc + local e = r[1] + if e <= 0 then + return 0 + end + local a = table.create(maxOrder + 1, 0) + local tmp = table.create(maxOrder + 1, 0) + for o = 1, maxOrder do + local acc = r[o + 1] + for j = 1, o - 1 do + acc -= a[j] * r[o - j + 1] + end + local k = acc / e + for j = 1, o - 1 do + tmp[j] = a[j] - k * a[o - j] + end + for j = 1, o - 1 do + a[j] = tmp[j] + end + a[o] = k + e *= (1 - k * k) + local row = sc.lpc[o] + for j = 1, o do + row[j] = a[j] + end + sc.err[o] = e + if e <= 0 then + return o + end + end + return maxOrder +end + +-- choose the subframe for signal x (n samples, bps bits) into plan (reusing its arrays) +local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps: number, plan: Plan) + local x = plan.x + -- constant? + local first = src[1] + local constant = true + for i = 1, n do + local v = src[i] + if v ~= first then + constant = false + end + end + if constant then + plan.kind, plan.bits, plan.wasted, plan.bps = 0, 8 + bps, 0, bps + plan.res[1] = first + return + end + -- wasted bits: the common trailing zeros + local wasted = 0 + do + local w = 0 + while w < bps - 1 do + local m = POW[w + 2] + local all = true + for i = 1, n do + if src[i] % m ~= 0 then + all = false + break + end + end + if not all then + break + end + w += 1 + end + wasted = w + end + local d = POW[wasted + 1] + for i = 1, n do + x[i] = src[i] / d + end + local b = bps - wasted + local hdr = 8 + wasted + plan.wasted, plan.bps = wasted, b + -- verbatim + plan.kind, plan.bits = 1, hdr + n * b + -- fixed + local fo = bestFixedOrder(x, n) + if n > fo then + local tmp = sc.tmpRes + fixedResidual(x, n, fo, tmp) + local rb, po, me = rice(sc, tmp, n, fo, cfg.maxPartitionOrder) + local bits = hdr + fo * b + rb + if bits < plan.bits then + plan.kind, plan.bits, plan.order = 2, bits, fo + sc.tmpRes, plan.res = plan.res, tmp + keepRice(sc, plan, po, me) + end + end + -- lpc + local maxOrder = math.min(cfg.maxLpcOrder, n - 1, 32) + if maxOrder > 0 then + -- windowed autocorrelation + local win = sc.win + if sc.winN ~= n then + -- tukey(0.5) + local np = floor(0.25 * n) + for i = 1, n do + win[i] = 1 + end + if np > 0 then + for i = 0, np - 1 do + local v = 0.5 - 0.5 * math.cos(math.pi * i / np) + win[i + 1] = v + win[n - i] = v + end + end + sc.winN = n + end + local wx = sc.wx + for i = 1, n do + wx[i] = x[i] * win[i] + end + local ac = sc.autoc + for lag = 0, maxOrder do + local s = 0 + for i = lag + 1, n do + s += wx[i] * wx[i - lag] + end + ac[lag + 1] = s + end + local top = levinson(sc, maxOrder) + if top > 0 then + local precision = qlpPrecision(b, n) + local orders = {} + if cfg.exhaustiveOrder then + for o = 1, top do + table.insert(orders, o) + end + else + -- estimated bits: (n - o) * 0.5 * log2(err_o / n) + o * precision + local bestO, bestE = 1, math.huge + for o = 1, top do + local e = sc.err[o] + local est = if e > 0 then (n - o) * 0.5 * log(e / n) / 0.6931471805599453 + o * (precision + b) else -math.huge + if est < bestE then + bestO, bestE = o, est + end + end + orders[1] = bestO + end + local qlp = sc.qlp + for _, o in orders do + local prec = precision + local shift = quantize(sc.lpc[o], o, prec, qlp) + if shift then + local tmp = sc.tmpRes + lpcResidual(x, n, o, qlp, shift, tmp) + local rb, po, me = rice(sc, tmp, n, o, cfg.maxPartitionOrder) + local bits = hdr + o * b + 4 + 5 + o * prec + rb + if bits < plan.bits then + plan.kind, plan.bits, plan.order = 3, bits, o + plan.shift, plan.precision = shift, prec + for j = 1, o do + plan.qlp[j] = qlp[j] + end + sc.tmpRes, plan.res = plan.res, tmp + keepRice(sc, plan, po, me) + end + end + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ writing +local function writeResidual(w: W, plan: Plan, n: number) + local method = plan.method + put(w, method, 2) + local porder = plan.porder + put(w, porder, 4) + local parts = POW[porder + 1] + local ps = n // parts + local res = plan.res + local pbits = if method == 1 then 5 else 4 + for j = 0, parts - 1 do + local k = plan.params[j + 1] + put(w, k, pbits) + local a = if j == 0 then plan.order + 1 else j * ps + 1 + local e = (j + 1) * ps + local mk = POW[k + 1] + for i = a, e do + local r = res[i] + local u = if r >= 0 then 2 * r else -2 * r - 1 + local hi = floor(u / mk) + local lo = u - hi * mk + if hi + 1 + k <= 32 then + put(w, mk + lo, hi + 1 + k) + else + local q = hi + while q > 24 do + put(w, 0, 24) + q -= 24 + end + put(w, 1, q + 1) + put(w, lo, k) + end + end + end +end + +local function writeSubframe(w: W, plan: Plan, n: number) + local kind = plan.kind + local typ = if kind == 0 then 0 elseif kind == 1 then 1 elseif kind == 2 then 8 + plan.order else 32 + plan.order - 1 + put(w, 0, 1) + put(w, typ, 6) + if kind ~= 0 and plan.wasted > 0 then + put(w, 1, 1) + put(w, 1, plan.wasted) -- k - 1 zeros, then a one + else + put(w, 0, 1) + end + local b = plan.bps + if kind == 0 then + putSigned(w, plan.res[1], b) + return + end + local x = plan.x + if kind == 1 then + for i = 1, n do + putSigned(w, x[i], b) + end + return + end + for i = 1, plan.order do + putSigned(w, x[i], b) + end + if kind == 3 then + put(w, plan.precision - 1, 4) + put(w, plan.shift, 5) + for j = 1, plan.order do + putSigned(w, plan.qlp[j], plan.precision) + end + end + writeResidual(w, plan, n) +end + +local RATE_CODES: { [number]: number } = { + [88200] = 1, + [176400] = 2, + [192000] = 3, + [8000] = 4, + [16000] = 5, + [22050] = 6, + [24000] = 7, + [32000] = 8, + [44100] = 9, + [48000] = 10, + [96000] = 11, +} +local SIZE_CODES: { [number]: number } = { [8] = 1, [12] = 2, [16] = 4, [20] = 5, [24] = 6, [32] = 7 } + +local function blockCode(n: number): (number, number) -- code, extra bits (0, 8, 16) + if n == 192 then + return 1, 0 + end + for k = 2, 5 do + if n == 576 * POW[k - 1] then + return k, 0 + end + end + for k = 8, 15 do + if n == 256 * POW[k - 7] then + return k, 0 + end + end + if n <= 256 then + return 6, 8 + end + return 7, 16 +end + +-- ------------------------------------------------------------------------------------------------ encoder +export type Source = { + sampleRate: number, + channels: number, + frames: number, + tags: { [string]: string }, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +export type Options = { + level: number, + bits: number, + blockSize: number?, + seekInterval: number, -- seconds between seek points (0 = no SEEKTABLE) + padding: number, -- bytes of PADDING + vendor: string, +} + +local TAG_NAMES = { track = "TRACKNUMBER" } + +-- encode(src, opts) -> buffer | nil, message +function Encode.encode(src: Source, opts: Options): (buffer?, string?) + local cfg = PRESETS[opts.level + 1] + local ch, rate, bps = src.channels, src.sampleRate, opts.bits + local bs = opts.blockSize or cfg.blockSize + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + -- metadata + put(w, 0x664C6143, 32) -- "fLaC" + put(w, 0, 1) + put(w, 0, 7) + put(w, 34, 24) + local siData = w.pos + for _ = 1, 34 do + put(w, 0, 8) + end + -- seek table placeholders (when the length is known) + local seekPoints = 0 + local seekAt = 0 + local interval = floor(opts.seekInterval * rate) + if interval > 0 and src.frames > 0 then + seekPoints = (src.frames - 1) // interval + 1 + if seekPoints > 65535 // 18 * 18 then + seekPoints = 0 + end + end + -- vorbis comment + local comments = {} + local keys = {} + for k in src.tags do + if type(k) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + for _, k in keys do + local v = src.tags[k] + if type(v) == "string" then + table.insert(comments, (TAG_NAMES[k] or string.upper(k)) .. "=" .. v) + end + end + local vendor = opts.vendor + local vcLen = 4 + #vendor + 4 + for _, c in comments do + vcLen += 4 + #c + end + -- SEEKTABLE + if seekPoints > 0 then + put(w, 0, 1) + put(w, 3, 7) + put(w, seekPoints * 18, 24) + seekAt = w.pos + ensure(w, seekPoints * 18) + for _ = 1, seekPoints do + put(w, 0xFFFFFFFF, 32) -- sample number: a placeholder until a frame fills it + put(w, 0xFFFFFFFF, 32) + put(w, 0, 32) -- byte offset + put(w, 0, 32) + put(w, 0, 16) -- frame samples + end + end + -- VORBIS_COMMENT (little-endian lengths) + local function le32(v: number) + put(w, v % 256, 8) + put(w, (v // 256) % 256, 8) + put(w, (v // 65536) % 256, 8) + put(w, v // 16777216, 8) + end + ensure(w, vcLen + 8) + put(w, if opts.padding > 0 then 0 else 1, 1) -- the last metadata block unless PADDING follows + put(w, 4, 7) + put(w, vcLen, 24) + le32(#vendor) + for i = 1, #vendor do + put(w, string.byte(vendor, i), 8) + end + le32(#comments) + for _, c in comments do + ensure(w, #c + 8) + le32(#c) + for i = 1, #c do + put(w, string.byte(c, i), 8) + end + end + if opts.padding > 0 then + ensure(w, opts.padding + 8) + put(w, 1, 1) + put(w, 1, 7) + put(w, opts.padding, 24) + for _ = 1, opts.padding do + put(w, 0, 8) + end + end + local audioStart = w.pos + -- frames + local md5 = Md5.new() + local mbytes = (bps + 7) // 8 + local mbuf = buffer.create(bs * ch * mbytes) + local scale = POW[bps] + local maxv, minv = scale - 1, -scale + local X = table.create(ch) + for c = 1, ch do + X[c] = table.create(bs, 0) + end + local side = table.create(bs, 0) + local mid = table.create(bs, 0) + local plans = {} + for i = 1, 4 do + plans[i] = newPlan(bs) + end + for c = 1, ch do + plans[4 + c] = newPlan(bs) + end + local lpcRows = {} + for o = 1, 32 do + lpcRows[o] = table.create(o, 0) + end + local sc: Scratch = { + sums = table.create(64, 0), + counts = table.create(64, 0), + ks = table.create(64, 0), + bestKs = table.create(64, 0), + tmpRes = table.create(bs, 0), + win = table.create(bs, 0), + winN = 0, + wx = table.create(bs, 0), + autoc = table.create(33, 0), + lpc = lpcRows, + err = table.create(32, 0), + qlp = table.create(32, 0), + } + local frameNo = 0 + local total = 0 + local minFrame, maxFrame = math.huge, 0 + local seekNext = 0 + local seekIdx = 0 + local rateCode = RATE_CODES[rate] or 0 + local sizeCode = SIZE_CODES[bps] or 0 + local tmp: buffer? = nil + local pendingBuf: buffer? = nil + local pendingN, pendingOff = 0, 0 + -- read exactly bs frames (fewer only at the end) + local function readBlock(): (buffer?, number) + local out = buffer.create(bs * ch * 4) + local got = 0 + while got < bs do + if pendingN == 0 then + local b, n = src:read(math.max(bs, 4096), tmp) + if n <= 0 then + break + end + tmp = b + pendingBuf, pendingN, pendingOff = b, n, 0 + end + local take = math.min(bs - got, pendingN) + buffer.copy(out, got * ch * 4, pendingBuf :: buffer, pendingOff * ch * 4, take * ch * 4) + got += take + pendingN -= take + pendingOff += take + end + return out, got + end + while true do + local fb, n = readBlock() + if n <= 0 or fb == nil then + break + end + -- to integers (+ the MD5 bytes, signed little endian) + local mo = 0 + for i = 0, n - 1 do + for c = 1, ch do + local v = floor(readf32(fb, (i * ch + c - 1) * 4) * scale + 0.5) + if v ~= v then + v = 0 + elseif v > maxv then + v = maxv + elseif v < minv then + v = minv + end + X[c][i + 1] = v + local u = if v < 0 then v + 4294967296 else v + for k = 0, mbytes - 1 do + writeu8(mbuf, mo, floor(u / POW[8 * k + 1]) % 256) + mo += 1 + end + end + end + md5:update(mbuf, 0, mo) + -- channel decorrelation + local assign = ch - 1 + local chosen: { Plan } = {} + if ch == 2 and cfg.stereo ~= "independent" then + local L, R = X[1], X[2] + for i = 1, n do + local l, r = L[i], R[i] + side[i] = l - r + mid[i] = floor((l + r) / 2) + end + local pl, pr, pm, ps = plans[1], plans[2], plans[3], plans[4] + if cfg.stereo == "adaptive" then + local _, el = bestFixedOrder(L, n) + local _, er = bestFixedOrder(R, n) + local _, em = bestFixedOrder(mid, n) + local _, es = bestFixedOrder(side, n) + -- the estimate picks one decorrelated pair; it is kept only if it beats left / right for real + local best = math.min(el + es, er + es, em + es) + analyze(sc, cfg, L, n, bps, pl) + analyze(sc, cfg, R, n, bps, pr) + chosen, assign = { pl, pr }, 1 + if best < el + er then + analyze(sc, cfg, side, n, bps + 1, ps) + if best == em + es then + analyze(sc, cfg, mid, n, bps, pm) + if pm.bits + ps.bits < pl.bits + pr.bits then + chosen, assign = { pm, ps }, 10 + end + elseif best == el + es then + if pl.bits + ps.bits < pl.bits + pr.bits then + chosen, assign = { pl, ps }, 8 + end + elseif ps.bits + pr.bits < pl.bits + pr.bits then + chosen, assign = { ps, pr }, 9 + end + end + else + analyze(sc, cfg, L, n, bps, pl) + analyze(sc, cfg, R, n, bps, pr) + analyze(sc, cfg, mid, n, bps, pm) + analyze(sc, cfg, side, n, bps + 1, ps) + local lr, ls, rs, msb = pl.bits + pr.bits, pl.bits + ps.bits, ps.bits + pr.bits, pm.bits + ps.bits + local best = math.min(lr, ls, rs, msb) + if best == lr then + chosen, assign = { pl, pr }, 1 + elseif best == msb then + chosen, assign = { pm, ps }, 10 + elseif best == ls then + chosen, assign = { pl, ps }, 8 + else + chosen, assign = { ps, pr }, 9 + end + end + else + for c = 1, ch do + analyze(sc, cfg, X[c], n, bps, plans[4 + c]) + chosen[c] = plans[4 + c] + end + end + -- the frame + local need = n * ch * 4 + 64 + for _, p in chosen do + need += (p.bits // 8) + 8 + end + ensure(w, need) + local start = w.pos + -- seek points: the first frame at or after each multiple of the interval + while seekIdx < seekPoints and total >= seekNext do + local at = seekAt + seekIdx * 18 + local sn, off = total, start - audioStart + local tb = w.buf + for k = 0, 7 do + writeu8(tb, at + k, floor(sn / POW[8 * (7 - k) + 1]) % 256) + writeu8(tb, at + 8 + k, floor(off / POW[8 * (7 - k) + 1]) % 256) + end + writeu8(tb, at + 16, n // 256) + writeu8(tb, at + 17, n % 256) + seekIdx += 1 + seekNext = seekIdx * interval + end + put(w, 0x3FFE, 14) + put(w, 0, 1) + put(w, 0, 1) -- fixed block size + local bcode, bextra = blockCode(n) + put(w, bcode, 4) + put(w, rateCode, 4) + put(w, assign, 4) + put(w, sizeCode, 3) + put(w, 0, 1) + putUtf8(w, frameNo) + if bextra > 0 then + put(w, n - 1, bextra) + end + put(w, crc8(w.buf, start, w.pos - start), 8) + for _, p in chosen do + writeSubframe(w, p, n) + end + alignByte(w) + local c16 = crc16(w.buf, start, w.pos - start) + put(w, c16, 16) + local fsize = w.pos - start + if fsize < minFrame then + minFrame = fsize + end + if fsize > maxFrame then + maxFrame = fsize + end + frameNo += 1 + total += n + if n < bs then + break + end + end + if src.err then + return nil, tostring(src.err) + end + -- unused seek points stay placeholders; STREAMINFO + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + local si = Encode.streaminfo(bs, if frameNo > 0 then minFrame else 0, maxFrame, rate, ch, bps, total, md5:digest()) + buffer.copy(out, siData, si, 0, 34) + return out, nil +end + +-- streaminfo(...) -> the 34-byte STREAMINFO body +function Encode.streaminfo(bs: number, minFrame: number, maxFrame: number, rate: number, ch: number, bps: number, total: number, md5: string): buffer + local w: W = { buf = buffer.create(64), pos = 0, acc = 0, cnt = 0 } + put(w, bs, 16) + put(w, bs, 16) + put(w, minFrame, 24) + put(w, maxFrame, 24) + put(w, rate, 20) + put(w, ch - 1, 3) + put(w, bps - 1, 5) + put(w, floor(total / 2 ^ 32), 4) + put(w, total % 2 ^ 32, 32) + for i = 1, 16 do + put(w, string.byte(md5, i), 8) + end + local out = buffer.create(34) + buffer.copy(out, 0, w.buf, 0, 34) + return out +end + +return Encode diff --git a/src/Formats/audio/flac/init.luau b/src/Formats/audio/flac/init.luau index bcf2578..88e5f22 100644 --- a/src/Formats/audio/flac/init.luau +++ b/src/Formats/audio/flac/init.luau @@ -5,7 +5,9 @@ -- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame -- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in -- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when --- STREAMINFO has none. Not supported: encoding (ws-audio), MD5 verification, chained Ogg streams. +-- STREAMINFO has none. Encode (audio/flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels +-- 0-8 like libFLAC's presets, 4-24 bits, 1-8 channels, MD5, VORBIS_COMMENT, SEEKTABLE. Not supported: MD5 +-- verification on decode, chained Ogg streams, Ogg FLAC output. -- -- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...) -- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end @@ -18,6 +20,8 @@ local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Ogg = require("@formats/containers/Ogg") local Stream = require("@formats/audio/flac/Stream") +local Encode = require("@formats/audio/flac/Encode") +local Pcm = require("@formats/codecs/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Flac = { @@ -25,8 +29,8 @@ local Flac = { category = "audio", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, - caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, } -- ------------------------------------------------------------------------------------------------ types @@ -35,6 +39,13 @@ export type OpenOptions = { crc16: boolean?, -- check every frame's CRC-16 (default true; a bad frame is skipped by resyncing) maxFrames: number?, -- decode(): refuse streams longer than this many sample frames (default 2^28) } +export type EncodeOptions = { + level: number?, -- 0..8 like libFLAC's -0 .. -8 (default 5) + bits: number?, -- bits per sample 4..24 (default: the source's meta.source.bitDepth / bitsPerSample if 4..24, else 16) + blockSize: number?, -- 16..65535 (default: the level's, 1152 or 4096) + seekInterval: number?, -- seconds between SEEKTABLE points when the length is known (default 10; 0 = none) + padding: number?, -- bytes of PADDING after the metadata (default 0) +} -- ------------------------------------------------------------------------------------------------ sniff function Flac.sniff(r: Bytes.Reader): number @@ -108,6 +119,51 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er return a, nil end +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audioOrDecoder, opts?) -> FLAC file buffer | nil, Err +function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local level = o.level or 5 + if type(level) ~= "number" or level ~= math.floor(level) or level < 0 or level > 8 then + return nil, Err.new(Err.ARG, "level must be 0..8") + end + local bits = o.bits + if bits == nil then + local v = value :: any + local sb = (type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.bitDepth) or v.bitsPerSample + bits = if type(sb) == "number" and sb >= 4 and sb <= 24 then sb else 16 + end + if type(bits) ~= "number" or bits ~= math.floor(bits) or bits < 4 or bits > 24 then + return nil, Err.new(Err.ARG, "bits must be 4..24") + end + local bs = o.blockSize + if bs ~= nil and (type(bs) ~= "number" or bs ~= math.floor(bs) or bs < 16 or bs > 65535) then + return nil, Err.new(Err.ARG, "blockSize must be 16..65535") + end + if src.channels > 8 then + return nil, Err.new(Err.ARG, "FLAC holds at most 8 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 20 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer below 2^20") + end + local out, msg = Encode.encode(src :: any, { + level = level, + bits = bits :: number, + blockSize = bs, + seekInterval = math.max(0, o.seekInterval or 10), + padding = math.clamp(math.floor(o.padding or 0), 0, 0xFFFFFF), + vendor = "formats-luau", + }) + if not out then + return nil, Err.new(Err.CORRUPT, tostring(msg)) + end + return out, nil +end + -- ------------------------------------------------------------------------------------------------ open -- open(r, opts?) -> Decoder | nil, Err function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) diff --git a/src/Formats/audio/mp3/Analysis.luau b/src/Formats/audio/mp3/Analysis.luau new file mode 100644 index 0000000..782b023 --- /dev/null +++ b/src/Formats/audio/mp3/Analysis.luau @@ -0,0 +1,63 @@ +--!strict +--!native +--!optimize 2 +-- audio/mp3/Analysis: the MPEG audio polyphase analysis filterbank (ISO/IEC 11172-3 section C.1.3, figure C.4): 32 +-- input samples -> one sample in each of the 32 subbands, with the standard's 512-tap window C = D / 32 (D from +-- audio/mp3/EncTables) and the matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). Shared by the layer II and layer III +-- encoders. New code from the standard's flow chart. Never throws. +-- +-- local st = Analysis.new() +-- Analysis.run(st, samples, start, out, outStart) -- samples[start .. start + 31] -> out[outStart .. outStart + 31] +local E = require("@formats/audio/mp3/EncTables") + +local Analysis = {} + +local C = table.create(512, 0) +for i = 1, 512 do + C[i] = E.D[i] / 32 +end +local M = table.create(32 * 64, 0) -- M[k * 64 + i + 1] +for k = 0, 31 do + for i = 0, 63 do + M[k * 64 + i + 1] = math.cos((2 * k + 1) * (i - 16) * math.pi / 64) + end +end + +export type State = { x: { number }, off: number, y: { number } } + +function Analysis.new(): State + return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) } +end + +-- run(st, s, si, out, oi): s[si .. si + 31] (oldest first) -> out[oi .. oi + 31] (subbands 0 .. 31) +function Analysis.run(st: State, s: { number }, si: number, out: { number }, oi: number) + -- the window X is kept twice (x[p] and x[p + 512]) so X[i] = x[off + i + 1] without a modulo + local x = st.x + local off = (st.off - 32) % 512 + st.off = off + for j = 0, 31 do + local v = s[si + j] + local p = (off + 31 - j) % 512 + 1 -- X[31 - j]: the first new sample goes to X[31], the newest to X[0] + x[p] = v + x[p + 512] = v + end + local y = st.y + for i = 0, 63 do + local acc = 0 + local b = off + i + 1 + for j = 0, 7 do + acc += C[i + 64 * j + 1] * x[b + 64 * j] + end + y[i + 1] = acc + end + for k = 0, 31 do + local acc = 0 + local mb = k * 64 + for i = 1, 64 do + acc += M[mb + i] * y[i] + end + out[oi + k] = acc + end +end + +return Analysis diff --git a/src/Formats/audio/mp3/EncTables.luau b/src/Formats/audio/mp3/EncTables.luau new file mode 100644 index 0000000..e730723 --- /dev/null +++ b/src/Formats/audio/mp3/EncTables.luau @@ -0,0 +1,292 @@ +--!strict +-- audio/mp3/EncTables: tables for the MPEG audio encoders, from PDMP3 (public domain / unlicense, by Krister +-- Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt), which transcribes ISO/IEC 11172-3: the synthesis window D +-- (the analysis window is C = D / 32) and the layer III Huffman code trees (the encoders derive codeword tables from +-- them). Trees use the standard's decoder layout: an entry with a high byte is a node (high byte: left offset, low +-- byte: right offset), otherwise a leaf (x << 4 | y; count1 tables: v w x y bits). +local E = {} +E.D = { + 0.000000000, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000030518, + -0.000030518, -0.000030518, -0.000030518, -0.000045776, -0.000045776, -0.000061035, -0.000061035, -0.000076294, + -0.000076294, -0.000091553, -0.000106812, -0.000106812, -0.000122070, -0.000137329, -0.000152588, -0.000167847, + -0.000198364, -0.000213623, -0.000244141, -0.000259399, -0.000289917, -0.000320435, -0.000366211, -0.000396729, + -0.000442505, -0.000473022, -0.000534058, -0.000579834, -0.000625610, -0.000686646, -0.000747681, -0.000808716, + -0.000885010, -0.000961304, -0.001037598, -0.001113892, -0.001205444, -0.001296997, -0.001388550, -0.001480103, + -0.001586914, -0.001693726, -0.001785278, -0.001907349, -0.002014160, -0.002120972, -0.002243042, -0.002349854, + -0.002456665, -0.002578735, -0.002685547, -0.002792358, -0.002899170, -0.002990723, -0.003082275, -0.003173828, + 0.003250122, 0.003326416, 0.003387451, 0.003433228, 0.003463745, 0.003479004, 0.003479004, 0.003463745, + 0.003417969, 0.003372192, 0.003280640, 0.003173828, 0.003051758, 0.002883911, 0.002700806, 0.002487183, + 0.002227783, 0.001937866, 0.001617432, 0.001266479, 0.000869751, 0.000442505, -0.000030518, -0.000549316, + -0.001098633, -0.001693726, -0.002334595, -0.003005981, -0.003723145, -0.004486084, -0.005294800, -0.006118774, + -0.007003784, -0.007919312, -0.008865356, -0.009841919, -0.010848999, -0.011886597, -0.012939453, -0.014022827, + -0.015121460, -0.016235352, -0.017349243, -0.018463135, -0.019577026, -0.020690918, -0.021789551, -0.022857666, + -0.023910522, -0.024932861, -0.025909424, -0.026840210, -0.027725220, -0.028533936, -0.029281616, -0.029937744, + -0.030532837, -0.031005859, -0.031387329, -0.031661987, -0.031814575, -0.031845093, -0.031738281, -0.031478882, + 0.031082153, 0.030517578, 0.029785156, 0.028884888, 0.027801514, 0.026535034, 0.025085449, 0.023422241, + 0.021575928, 0.019531250, 0.017257690, 0.014801025, 0.012115479, 0.009231567, 0.006134033, 0.002822876, + -0.000686646, -0.004394531, -0.008316040, -0.012420654, -0.016708374, -0.021179199, -0.025817871, -0.030609131, + -0.035552979, -0.040634155, -0.045837402, -0.051132202, -0.056533813, -0.061996460, -0.067520142, -0.073059082, + -0.078628540, -0.084182739, -0.089706421, -0.095169067, -0.100540161, -0.105819702, -0.110946655, -0.115921021, + -0.120697021, -0.125259399, -0.129562378, -0.133590698, -0.137298584, -0.140670776, -0.143676758, -0.146255493, + -0.148422241, -0.150115967, -0.151306152, -0.151962280, -0.152069092, -0.151596069, -0.150497437, -0.148773193, + -0.146362305, -0.143264771, -0.139450073, -0.134887695, -0.129577637, -0.123474121, -0.116577148, -0.108856201, + 0.100311279, 0.090927124, 0.080688477, 0.069595337, 0.057617188, 0.044784546, 0.031082153, 0.016510010, + 0.001068115, -0.015228271, -0.032379150, -0.050354004, -0.069168091, -0.088775635, -0.109161377, -0.130310059, + -0.152206421, -0.174789429, -0.198059082, -0.221984863, -0.246505737, -0.271591187, -0.297210693, -0.323318481, + -0.349868774, -0.376800537, -0.404083252, -0.431655884, -0.459472656, -0.487472534, -0.515609741, -0.543823242, + -0.572036743, -0.600219727, -0.628295898, -0.656219482, -0.683914185, -0.711318970, -0.738372803, -0.765029907, + -0.791213989, -0.816864014, -0.841949463, -0.866363525, -0.890090942, -0.913055420, -0.935195923, -0.956481934, + -0.976852417, -0.996246338, -1.014617920, -1.031936646, -1.048156738, -1.063217163, -1.077117920, -1.089782715, + -1.101211548, -1.111373901, -1.120223999, -1.127746582, -1.133926392, -1.138763428, -1.142211914, -1.144287109, + 1.144989014, 1.144287109, 1.142211914, 1.138763428, 1.133926392, 1.127746582, 1.120223999, 1.111373901, + 1.101211548, 1.089782715, 1.077117920, 1.063217163, 1.048156738, 1.031936646, 1.014617920, 0.996246338, + 0.976852417, 0.956481934, 0.935195923, 0.913055420, 0.890090942, 0.866363525, 0.841949463, 0.816864014, + 0.791213989, 0.765029907, 0.738372803, 0.711318970, 0.683914185, 0.656219482, 0.628295898, 0.600219727, + 0.572036743, 0.543823242, 0.515609741, 0.487472534, 0.459472656, 0.431655884, 0.404083252, 0.376800537, + 0.349868774, 0.323318481, 0.297210693, 0.271591187, 0.246505737, 0.221984863, 0.198059082, 0.174789429, + 0.152206421, 0.130310059, 0.109161377, 0.088775635, 0.069168091, 0.050354004, 0.032379150, 0.015228271, + -0.001068115, -0.016510010, -0.031082153, -0.044784546, -0.057617188, -0.069595337, -0.080688477, -0.090927124, + 0.100311279, 0.108856201, 0.116577148, 0.123474121, 0.129577637, 0.134887695, 0.139450073, 0.143264771, + 0.146362305, 0.148773193, 0.150497437, 0.151596069, 0.152069092, 0.151962280, 0.151306152, 0.150115967, + 0.148422241, 0.146255493, 0.143676758, 0.140670776, 0.137298584, 0.133590698, 0.129562378, 0.125259399, + 0.120697021, 0.115921021, 0.110946655, 0.105819702, 0.100540161, 0.095169067, 0.089706421, 0.084182739, + 0.078628540, 0.073059082, 0.067520142, 0.061996460, 0.056533813, 0.051132202, 0.045837402, 0.040634155, + 0.035552979, 0.030609131, 0.025817871, 0.021179199, 0.016708374, 0.012420654, 0.008316040, 0.004394531, + 0.000686646, -0.002822876, -0.006134033, -0.009231567, -0.012115479, -0.014801025, -0.017257690, -0.019531250, + -0.021575928, -0.023422241, -0.025085449, -0.026535034, -0.027801514, -0.028884888, -0.029785156, -0.030517578, + 0.031082153, 0.031478882, 0.031738281, 0.031845093, 0.031814575, 0.031661987, 0.031387329, 0.031005859, + 0.030532837, 0.029937744, 0.029281616, 0.028533936, 0.027725220, 0.026840210, 0.025909424, 0.024932861, + 0.023910522, 0.022857666, 0.021789551, 0.020690918, 0.019577026, 0.018463135, 0.017349243, 0.016235352, + 0.015121460, 0.014022827, 0.012939453, 0.011886597, 0.010848999, 0.009841919, 0.008865356, 0.007919312, + 0.007003784, 0.006118774, 0.005294800, 0.004486084, 0.003723145, 0.003005981, 0.002334595, 0.001693726, + 0.001098633, 0.000549316, 0.000030518, -0.000442505, -0.000869751, -0.001266479, -0.001617432, -0.001937866, + -0.002227783, -0.002487183, -0.002700806, -0.002883911, -0.003051758, -0.003173828, -0.003280640, -0.003372192, + -0.003417969, -0.003463745, -0.003479004, -0.003479004, -0.003463745, -0.003433228, -0.003387451, -0.003326416, + 0.003250122, 0.003173828, 0.003082275, 0.002990723, 0.002899170, 0.002792358, 0.002685547, 0.002578735, + 0.002456665, 0.002349854, 0.002243042, 0.002120972, 0.002014160, 0.001907349, 0.001785278, 0.001693726, + 0.001586914, 0.001480103, 0.001388550, 0.001296997, 0.001205444, 0.001113892, 0.001037598, 0.000961304, + 0.000885010, 0.000808716, 0.000747681, 0.000686646, 0.000625610, 0.000579834, 0.000534058, 0.000473022, + 0.000442505, 0.000396729, 0.000366211, 0.000320435, 0.000289917, 0.000259399, 0.000244141, 0.000213623, + 0.000198364, 0.000167847, 0.000152588, 0.000137329, 0.000122070, 0.000106812, 0.000106812, 0.000091553, + 0.000076294, 0.000076294, 0.000061035, 0.000061035, 0.000045776, 0.000045776, 0.000030518, 0.000030518, + 0.000030518, 0.000030518, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, +} +E.LINBITS = { [0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, 5, 6, 7, 8, 9, 11, 13, 0, 0 } +-- trees by table number (tables 16..23 share 16's tree, 24..31 share 24's) +E.TREES = { + [1] = { + 0x0201, 0x0000, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, + }, + [2] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, + 0x0022, + }, + [3] = { + 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0011, 0x0201, 0x0010, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, + 0x0022, + }, + [5] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0013, 0x0201, 0x0031, 0x0201, 0x0032, 0x0201, 0x0023, 0x0033, + }, + [6] = { + 0x0601, 0x0401, 0x0201, 0x0000, 0x0010, 0x0011, 0x0601, 0x0201, 0x0001, 0x0201, 0x0020, 0x0021, 0x0601, 0x0201, 0x0012, 0x0201, + 0x0002, 0x0022, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0030, 0x0032, 0x0201, 0x0023, 0x0201, 0x0003, 0x0033, + }, + [7] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, 0x1201, 0x0601, + 0x0201, 0x0012, 0x0201, 0x0022, 0x0030, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, 0x0004, + 0x0a01, 0x0401, 0x0201, 0x0040, 0x0041, 0x0201, 0x0014, 0x0201, 0x0042, 0x0024, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0033, 0x0043, + 0x0050, 0x0401, 0x0201, 0x0034, 0x0005, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, 0x0035, + 0x0401, 0x0201, 0x0053, 0x0054, 0x0201, 0x0045, 0x0055, + }, + [8] = { + 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0021, 0x0012, 0x0e01, 0x0401, 0x0201, 0x0020, + 0x0002, 0x0201, 0x0022, 0x0401, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0201, 0x0014, 0x0042, 0x0c01, 0x0601, 0x0201, 0x0024, 0x0201, 0x0033, 0x0050, 0x0401, + 0x0201, 0x0043, 0x0034, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0005, 0x0052, 0x0601, 0x0201, 0x0025, 0x0201, 0x0044, 0x0035, + 0x0201, 0x0053, 0x0201, 0x0045, 0x0201, 0x0054, 0x0055, + }, + [9] = { + 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0a01, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, + 0x0002, 0x0022, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0030, 0x0003, 0x0031, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0c01, 0x0401, + 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0040, 0x0033, 0x0201, 0x0042, 0x0024, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0050, + 0x0043, 0x0201, 0x0034, 0x0051, 0x0801, 0x0401, 0x0201, 0x0015, 0x0052, 0x0201, 0x0025, 0x0044, 0x0601, 0x0401, 0x0201, 0x0005, + 0x0054, 0x0053, 0x0201, 0x0035, 0x0201, 0x0045, 0x0055, + }, + [10] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0a01, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x1c01, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0031, 0x0013, 0x0801, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, + 0x0040, 0x0401, 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0004, 0x0033, 0x0201, 0x0042, 0x0024, 0x1c01, 0x0a01, 0x0601, 0x0401, + 0x0201, 0x0050, 0x0005, 0x0060, 0x0201, 0x0061, 0x0016, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0043, 0x0034, 0x0051, 0x0201, 0x0015, + 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0026, 0x0036, 0x0071, 0x1401, 0x0801, 0x0201, 0x0017, 0x0401, 0x0201, 0x0044, 0x0053, + 0x0006, 0x0601, 0x0401, 0x0201, 0x0035, 0x0045, 0x0062, 0x0201, 0x0070, 0x0201, 0x0007, 0x0064, 0x0e01, 0x0401, 0x0201, 0x0072, + 0x0027, 0x0601, 0x0201, 0x0063, 0x0201, 0x0054, 0x0055, 0x0201, 0x0046, 0x0073, 0x0801, 0x0401, 0x0201, 0x0037, 0x0065, 0x0201, + 0x0056, 0x0074, 0x0601, 0x0201, 0x0047, 0x0201, 0x0066, 0x0075, 0x0401, 0x0201, 0x0057, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [11] = { + 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0012, 0x1801, 0x0801, + 0x0201, 0x0021, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, 0x0401, + 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0014, 0x1e01, 0x1001, 0x0a01, 0x0401, 0x0201, 0x0042, 0x0024, 0x0401, 0x0201, 0x0033, + 0x0043, 0x0050, 0x0401, 0x0201, 0x0034, 0x0051, 0x0061, 0x0601, 0x0201, 0x0016, 0x0201, 0x0006, 0x0026, 0x0201, 0x0062, 0x0201, + 0x0015, 0x0201, 0x0005, 0x0052, 0x1001, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0025, 0x0044, 0x0060, 0x0201, 0x0063, 0x0036, 0x0401, + 0x0201, 0x0070, 0x0017, 0x0071, 0x1001, 0x0601, 0x0401, 0x0201, 0x0007, 0x0064, 0x0072, 0x0201, 0x0027, 0x0401, 0x0201, 0x0053, + 0x0035, 0x0201, 0x0054, 0x0045, 0x0a01, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, 0x0201, 0x0065, 0x0056, 0x0a01, 0x0601, + 0x0401, 0x0201, 0x0055, 0x0057, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [12] = { + 0x0c01, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0201, 0x0000, 0x0201, 0x0020, 0x0002, 0x1001, 0x0401, 0x0201, 0x0021, + 0x0012, 0x0401, 0x0201, 0x0022, 0x0031, 0x0201, 0x0013, 0x0201, 0x0030, 0x0201, 0x0003, 0x0040, 0x1a01, 0x0801, 0x0401, 0x0201, + 0x0032, 0x0023, 0x0201, 0x0041, 0x0033, 0x0a01, 0x0401, 0x0201, 0x0014, 0x0042, 0x0201, 0x0024, 0x0201, 0x0004, 0x0050, 0x0401, + 0x0201, 0x0043, 0x0034, 0x0201, 0x0051, 0x0015, 0x1c01, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0052, 0x0025, 0x0201, 0x0053, 0x0035, + 0x0401, 0x0201, 0x0060, 0x0016, 0x0061, 0x0401, 0x0201, 0x0062, 0x0026, 0x0601, 0x0401, 0x0201, 0x0005, 0x0006, 0x0044, 0x0201, + 0x0054, 0x0045, 0x1201, 0x0a01, 0x0401, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0070, 0x0007, 0x0071, 0x0401, 0x0201, 0x0017, + 0x0064, 0x0201, 0x0046, 0x0072, 0x0a01, 0x0601, 0x0201, 0x0027, 0x0201, 0x0055, 0x0073, 0x0201, 0x0037, 0x0056, 0x0801, 0x0401, + 0x0201, 0x0065, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [13] = { + 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x1c01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, + 0x0012, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0401, + 0x0201, 0x0040, 0x0004, 0x0041, 0x4601, 0x1c01, 0x0e01, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, + 0x0050, 0x0201, 0x0043, 0x0034, 0x0401, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0005, 0x0052, 0x0201, 0x0025, 0x0201, 0x0044, + 0x0053, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0060, 0x0006, 0x0201, 0x0061, 0x0016, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x1001, + 0x0801, 0x0401, 0x0201, 0x0035, 0x0062, 0x0201, 0x0026, 0x0054, 0x0401, 0x0201, 0x0045, 0x0063, 0x0201, 0x0036, 0x0070, 0x0601, + 0x0401, 0x0201, 0x0007, 0x0055, 0x0071, 0x0201, 0x0017, 0x0201, 0x0027, 0x0037, 0x4801, 0x1801, 0x0c01, 0x0401, 0x0201, 0x0018, + 0x0082, 0x0201, 0x0028, 0x0401, 0x0201, 0x0064, 0x0046, 0x0072, 0x0801, 0x0401, 0x0201, 0x0084, 0x0048, 0x0201, 0x0090, 0x0009, + 0x0201, 0x0091, 0x0019, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0073, 0x0065, 0x0201, 0x0056, 0x0074, 0x0401, 0x0201, 0x0047, + 0x0066, 0x0083, 0x0601, 0x0201, 0x0038, 0x0201, 0x0075, 0x0057, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0067, + 0x0085, 0x0201, 0x0058, 0x0039, 0x0201, 0x0093, 0x0201, 0x0049, 0x0086, 0x0601, 0x0201, 0x00a0, 0x0201, 0x0068, 0x000a, 0x0201, + 0x00a1, 0x001a, 0x4401, 0x1801, 0x0c01, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0401, 0x0201, 0x0095, 0x0059, 0x0201, 0x00a3, 0x003a, + 0x0801, 0x0401, 0x0201, 0x004a, 0x0096, 0x0201, 0x00b0, 0x000b, 0x0201, 0x00b1, 0x001b, 0x1401, 0x0801, 0x0201, 0x00b2, 0x0401, + 0x0201, 0x0076, 0x0077, 0x0094, 0x0601, 0x0401, 0x0201, 0x0087, 0x0078, 0x00a4, 0x0401, 0x0201, 0x0069, 0x00a5, 0x002b, 0x0c01, + 0x0601, 0x0401, 0x0201, 0x005a, 0x0088, 0x00b3, 0x0201, 0x003b, 0x0201, 0x0079, 0x00a6, 0x0601, 0x0401, 0x0201, 0x006a, 0x00b4, + 0x00c0, 0x0401, 0x0201, 0x000c, 0x0098, 0x00c1, 0x3c01, 0x1601, 0x0a01, 0x0601, 0x0201, 0x001c, 0x0201, 0x0089, 0x00b5, 0x0201, + 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x003c, 0x0401, 0x0201, 0x00b6, 0x006b, 0x0201, 0x00c4, 0x004c, 0x1001, 0x0801, 0x0401, + 0x0201, 0x00a8, 0x008a, 0x0201, 0x00d0, 0x000d, 0x0201, 0x00d1, 0x0201, 0x004b, 0x0201, 0x0097, 0x00a7, 0x0c01, 0x0601, 0x0201, + 0x00c3, 0x0201, 0x007a, 0x0099, 0x0401, 0x0201, 0x00c5, 0x005c, 0x00b7, 0x0401, 0x0201, 0x001d, 0x00d2, 0x0201, 0x002d, 0x0201, + 0x007b, 0x00d3, 0x3401, 0x1c01, 0x0c01, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, + 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e0, 0x0a01, + 0x0401, 0x0201, 0x00e1, 0x001e, 0x0401, 0x0201, 0x000e, 0x002e, 0x00e2, 0x0801, 0x0401, 0x0201, 0x00e3, 0x006d, 0x0201, 0x008c, + 0x00e4, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x00f0, 0x2601, 0x1001, 0x0401, 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00aa, + 0x009b, 0x00b9, 0x0201, 0x003e, 0x0201, 0x00d6, 0x00c8, 0x0c01, 0x0601, 0x0201, 0x004e, 0x0201, 0x00d7, 0x007d, 0x0201, 0x00ab, + 0x0201, 0x005e, 0x00c9, 0x0601, 0x0201, 0x000f, 0x0201, 0x009c, 0x006e, 0x0201, 0x00f2, 0x002f, 0x2001, 0x1001, 0x0601, 0x0401, + 0x0201, 0x00d8, 0x008d, 0x003f, 0x0601, 0x0201, 0x00f3, 0x0201, 0x00e6, 0x00ca, 0x0201, 0x00f4, 0x004f, 0x0801, 0x0401, 0x0201, + 0x00bb, 0x00ac, 0x0201, 0x00e7, 0x00f5, 0x0401, 0x0201, 0x00d9, 0x009d, 0x0201, 0x005f, 0x00e8, 0x1e01, 0x0c01, 0x0601, 0x0201, + 0x006f, 0x0201, 0x00f6, 0x00cb, 0x0401, 0x0201, 0x00bc, 0x00ad, 0x00da, 0x0801, 0x0201, 0x00f7, 0x0401, 0x0201, 0x007e, 0x007f, + 0x008e, 0x0601, 0x0401, 0x0201, 0x009e, 0x00ae, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00db, 0x00bd, + 0x0201, 0x00ea, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00eb, 0x0201, 0x00be, 0x0201, 0x00cd, 0x00fa, 0x0e01, 0x0401, 0x0201, 0x00dd, + 0x00ec, 0x0601, 0x0401, 0x0201, 0x00e9, 0x00af, 0x00dc, 0x0201, 0x00ce, 0x00fb, 0x0801, 0x0401, 0x0201, 0x00bf, 0x00de, 0x0201, + 0x00cf, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00ef, 0x0201, 0x00ff, 0x0201, 0x00ed, 0x0201, 0x00fd, 0x0201, 0x00fc, 0x00fe, + }, + [15] = { + 0x1001, 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x3201, 0x1001, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0003, 0x0040, 0x0201, 0x0032, + 0x0023, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0014, 0x0041, 0x0401, 0x0201, 0x0033, 0x0042, 0x0201, 0x0024, 0x0043, 0x0a01, + 0x0601, 0x0201, 0x0034, 0x0201, 0x0050, 0x0005, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, + 0x0053, 0x0061, 0x5a01, 0x2401, 0x1201, 0x0a01, 0x0601, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0201, 0x0016, 0x0062, 0x0401, + 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0a01, 0x0601, 0x0201, 0x0036, 0x0201, 0x0070, 0x0007, 0x0201, 0x0071, 0x0055, + 0x0401, 0x0201, 0x0017, 0x0064, 0x0201, 0x0072, 0x0027, 0x1801, 0x1001, 0x0801, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, + 0x0065, 0x0401, 0x0201, 0x0056, 0x0080, 0x0201, 0x0008, 0x0074, 0x0401, 0x0201, 0x0081, 0x0018, 0x0201, 0x0082, 0x0028, 0x1001, + 0x0801, 0x0401, 0x0201, 0x0047, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, 0x0601, + 0x0401, 0x0201, 0x0090, 0x0019, 0x0091, 0x0401, 0x0201, 0x0092, 0x0076, 0x0201, 0x0067, 0x0029, 0x5c01, 0x2401, 0x1201, 0x0a01, + 0x0401, 0x0201, 0x0085, 0x0058, 0x0401, 0x0201, 0x0009, 0x0077, 0x0093, 0x0401, 0x0201, 0x0039, 0x0094, 0x0201, 0x0049, 0x0086, + 0x0a01, 0x0601, 0x0201, 0x0068, 0x0201, 0x00a0, 0x000a, 0x0201, 0x00a1, 0x001a, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, + 0x0059, 0x1a01, 0x0e01, 0x0601, 0x0201, 0x00a3, 0x0201, 0x003a, 0x0087, 0x0401, 0x0201, 0x0078, 0x00a4, 0x0201, 0x004a, 0x0096, + 0x0601, 0x0401, 0x0201, 0x0069, 0x00b0, 0x00b1, 0x0401, 0x0201, 0x001b, 0x00a5, 0x00b2, 0x0e01, 0x0801, 0x0401, 0x0201, 0x005a, + 0x002b, 0x0201, 0x0088, 0x0097, 0x0201, 0x00b3, 0x0201, 0x0079, 0x003b, 0x0801, 0x0401, 0x0201, 0x006a, 0x00b4, 0x0201, 0x004b, + 0x00c1, 0x0401, 0x0201, 0x0098, 0x0089, 0x0201, 0x001c, 0x00b5, 0x5001, 0x2201, 0x1001, 0x0601, 0x0401, 0x0201, 0x005b, 0x002c, + 0x00c2, 0x0601, 0x0401, 0x0201, 0x000b, 0x00c0, 0x00a6, 0x0201, 0x00a7, 0x007a, 0x0a01, 0x0401, 0x0201, 0x00c3, 0x003c, 0x0401, + 0x0201, 0x000c, 0x0099, 0x00b6, 0x0401, 0x0201, 0x006b, 0x00c4, 0x0201, 0x004c, 0x00a8, 0x1401, 0x0a01, 0x0401, 0x0201, 0x008a, + 0x00c5, 0x0401, 0x0201, 0x00d0, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x0201, 0x000d, 0x002d, 0x0c01, + 0x0401, 0x0201, 0x00d2, 0x00d3, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x00a9, 0x0601, 0x0401, 0x0201, 0x009a, 0x00b8, + 0x00d4, 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x4401, 0x2201, 0x1201, 0x0a01, 0x0401, 0x0201, 0x00d5, 0x005d, + 0x0401, 0x0201, 0x00e0, 0x000e, 0x00e1, 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x002e, 0x0801, 0x0401, 0x0201, 0x00b9, + 0x009b, 0x0201, 0x00e3, 0x00d6, 0x0401, 0x0201, 0x006d, 0x003e, 0x0201, 0x00c8, 0x008c, 0x1001, 0x0801, 0x0401, 0x0201, 0x00e4, + 0x004e, 0x0201, 0x00d7, 0x007d, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x0201, 0x00ab, 0x005e, 0x0801, 0x0401, 0x0201, 0x00c9, 0x009c, + 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00f0, 0x006e, 0x00f2, 0x0201, 0x002f, 0x00e6, 0x2601, 0x1201, 0x0801, 0x0401, + 0x0201, 0x00d8, 0x00f3, 0x0201, 0x003f, 0x00f4, 0x0601, 0x0201, 0x004f, 0x0201, 0x008d, 0x00d9, 0x0201, 0x00bb, 0x00ca, 0x0801, + 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00f5, 0x0801, 0x0401, 0x0201, 0x009d, 0x005f, 0x0201, 0x00e8, 0x008e, 0x0201, + 0x00f6, 0x00cb, 0x2201, 0x1201, 0x0a01, 0x0601, 0x0401, 0x0201, 0x000f, 0x00ae, 0x006f, 0x0201, 0x00bc, 0x00da, 0x0401, 0x0201, + 0x00ad, 0x00f7, 0x0201, 0x007f, 0x00e9, 0x0801, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x0401, 0x0201, 0x00db, + 0x00bd, 0x0201, 0x00ea, 0x00f9, 0x1001, 0x0801, 0x0401, 0x0201, 0x009f, 0x00dc, 0x0201, 0x00cd, 0x00eb, 0x0401, 0x0201, 0x00be, + 0x00fa, 0x0201, 0x00af, 0x00dd, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00ec, 0x00ce, 0x00fb, 0x0401, 0x0201, 0x00bf, 0x00ed, 0x0201, + 0x00de, 0x00fc, 0x0601, 0x0401, 0x0201, 0x00cf, 0x00fd, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00fe, 0x0201, 0x00ef, 0x00ff, + }, + [16] = { + 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x2a01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, + 0x0012, 0x0a01, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0a01, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, 0x0050, 0x0201, + 0x0043, 0x0034, 0x8a01, 0x2801, 0x1001, 0x0601, 0x0401, 0x0201, 0x0005, 0x0015, 0x0051, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, + 0x0201, 0x0044, 0x0035, 0x0053, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0060, 0x0006, 0x0061, 0x0201, 0x0016, 0x0062, 0x0801, 0x0401, + 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0401, 0x0201, 0x0036, 0x0070, 0x0071, 0x2801, 0x1201, 0x0801, 0x0201, 0x0017, + 0x0201, 0x0007, 0x0201, 0x0055, 0x0064, 0x0401, 0x0201, 0x0072, 0x0027, 0x0401, 0x0201, 0x0046, 0x0065, 0x0073, 0x0a01, 0x0601, + 0x0201, 0x0037, 0x0201, 0x0056, 0x0008, 0x0201, 0x0080, 0x0081, 0x0601, 0x0201, 0x0018, 0x0201, 0x0074, 0x0047, 0x0201, 0x0082, + 0x0201, 0x0028, 0x0066, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0083, 0x0038, 0x0201, 0x0075, 0x0084, 0x0401, 0x0201, 0x0048, + 0x0090, 0x0091, 0x0601, 0x0201, 0x0019, 0x0201, 0x0009, 0x0076, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0085, + 0x0058, 0x0201, 0x0093, 0x0039, 0x0401, 0x0201, 0x00a0, 0x000a, 0x001a, 0x0801, 0x0201, 0x00a2, 0x0201, 0x0067, 0x0201, 0x0057, + 0x0049, 0x0601, 0x0201, 0x0094, 0x0201, 0x0077, 0x0086, 0x0201, 0x00a1, 0x0201, 0x0068, 0x0095, 0xdc01, 0x7e01, 0x3201, 0x1a01, + 0x0c01, 0x0601, 0x0201, 0x002a, 0x0201, 0x0059, 0x003a, 0x0201, 0x00a3, 0x0201, 0x0087, 0x0078, 0x0801, 0x0401, 0x0201, 0x00a4, + 0x004a, 0x0201, 0x0096, 0x0069, 0x0401, 0x0201, 0x00b0, 0x000b, 0x00b1, 0x0a01, 0x0401, 0x0201, 0x001b, 0x00b2, 0x0201, 0x002b, + 0x0201, 0x00a5, 0x005a, 0x0601, 0x0201, 0x00b3, 0x0201, 0x00a6, 0x006a, 0x0401, 0x0201, 0x00b4, 0x004b, 0x0201, 0x000c, 0x00c1, + 0x1e01, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00b5, 0x00c2, 0x002c, 0x0401, 0x0201, 0x00a7, 0x00c3, 0x0201, 0x006b, 0x00c4, 0x0801, + 0x0201, 0x001d, 0x0401, 0x0201, 0x0088, 0x0097, 0x003b, 0x0401, 0x0201, 0x00d1, 0x00d2, 0x0201, 0x002d, 0x00d3, 0x1201, 0x0601, + 0x0401, 0x0201, 0x001e, 0x002e, 0x00e2, 0x0601, 0x0401, 0x0201, 0x0079, 0x0098, 0x00c0, 0x0201, 0x001c, 0x0201, 0x0089, 0x005b, + 0x0e01, 0x0601, 0x0201, 0x003c, 0x0201, 0x007a, 0x00b6, 0x0401, 0x0201, 0x004c, 0x0099, 0x0201, 0x00a8, 0x008a, 0x0601, 0x0201, + 0x000d, 0x0201, 0x00c5, 0x005c, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x009a, 0x5801, 0x5601, 0x2401, 0x1001, 0x0801, + 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x0401, 0x0201, 0x00d5, 0x005d, 0x0201, 0x00e0, 0x000e, 0x0801, 0x0201, + 0x00e3, 0x0401, 0x0201, 0x00d0, 0x00b7, 0x007b, 0x0601, 0x0401, 0x0201, 0x00a9, 0x00b8, 0x00d4, 0x0201, 0x00e1, 0x0201, 0x00aa, + 0x00b9, 0x1801, 0x0a01, 0x0601, 0x0401, 0x0201, 0x009b, 0x00d6, 0x006d, 0x0201, 0x003e, 0x00c8, 0x0601, 0x0401, 0x0201, 0x008c, + 0x00e4, 0x004e, 0x0401, 0x0201, 0x00d7, 0x00e5, 0x0201, 0x00ba, 0x00ab, 0x0c01, 0x0401, 0x0201, 0x009c, 0x00e6, 0x0401, 0x0201, + 0x006e, 0x00d8, 0x0201, 0x008d, 0x00bb, 0x0801, 0x0401, 0x0201, 0x00e7, 0x009d, 0x0201, 0x00e8, 0x008e, 0x0401, 0x0201, 0x00cb, + 0x00bc, 0x009e, 0x00f1, 0x0201, 0x001f, 0x0201, 0x000f, 0x002f, 0x4201, 0x3801, 0x0201, 0x00f2, 0x3401, 0x3201, 0x1401, 0x0801, + 0x0201, 0x00bd, 0x0201, 0x005e, 0x0201, 0x007d, 0x00c9, 0x0601, 0x0201, 0x00ca, 0x0201, 0x00ac, 0x007e, 0x0401, 0x0201, 0x00da, + 0x00ad, 0x00cc, 0x0a01, 0x0601, 0x0201, 0x00ae, 0x0201, 0x00db, 0x00dc, 0x0201, 0x00cd, 0x00be, 0x0601, 0x0401, 0x0201, 0x00eb, + 0x00ed, 0x00ee, 0x0601, 0x0401, 0x0201, 0x00d9, 0x00ea, 0x00e9, 0x0201, 0x00de, 0x0401, 0x0201, 0x00dd, 0x00ec, 0x00ce, 0x003f, + 0x00f0, 0x0401, 0x0201, 0x00f3, 0x00f4, 0x0201, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0a01, 0x0201, 0x00ff, 0x0401, 0x0201, 0x00f6, + 0x006f, 0x0201, 0x00f7, 0x007f, 0x0c01, 0x0601, 0x0201, 0x008f, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00fa, 0x00af, + 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, + }, + [24] = { + 0x3c01, 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, + 0x0201, 0x0012, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0e01, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0801, 0x0401, 0x0201, 0x0014, 0x0033, 0x0201, 0x0042, 0x0024, 0x0601, 0x0401, 0x0201, + 0x0043, 0x0034, 0x0051, 0x0601, 0x0401, 0x0201, 0x0050, 0x0005, 0x0015, 0x0201, 0x0052, 0x0025, 0xfa01, 0x6201, 0x2201, 0x1201, + 0x0a01, 0x0401, 0x0201, 0x0044, 0x0053, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0401, 0x0201, 0x0061, 0x0016, 0x0201, 0x0062, + 0x0026, 0x0801, 0x0401, 0x0201, 0x0054, 0x0045, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0071, 0x0055, 0x0201, 0x0064, 0x0046, + 0x2001, 0x0e01, 0x0601, 0x0201, 0x0072, 0x0201, 0x0027, 0x0037, 0x0201, 0x0073, 0x0401, 0x0201, 0x0070, 0x0007, 0x0017, 0x0a01, + 0x0401, 0x0201, 0x0065, 0x0056, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x0401, 0x0201, 0x0074, 0x0047, 0x0201, 0x0018, 0x0082, + 0x1001, 0x0801, 0x0401, 0x0201, 0x0028, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, + 0x0801, 0x0401, 0x0201, 0x0091, 0x0019, 0x0201, 0x0092, 0x0076, 0x0401, 0x0201, 0x0067, 0x0029, 0x0201, 0x0085, 0x0058, 0x5c01, + 0x2201, 0x1001, 0x0801, 0x0401, 0x0201, 0x0093, 0x0039, 0x0201, 0x0094, 0x0049, 0x0401, 0x0201, 0x0077, 0x0086, 0x0201, 0x0068, + 0x00a1, 0x0801, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, 0x0059, 0x0401, 0x0201, 0x00a3, 0x003a, 0x0201, 0x0087, 0x0201, + 0x0078, 0x004a, 0x1601, 0x0c01, 0x0401, 0x0201, 0x00a4, 0x0096, 0x0401, 0x0201, 0x0069, 0x00b1, 0x0201, 0x001b, 0x00a5, 0x0601, + 0x0201, 0x00b2, 0x0201, 0x005a, 0x002b, 0x0201, 0x0088, 0x00b3, 0x1001, 0x0a01, 0x0601, 0x0201, 0x0090, 0x0201, 0x0009, 0x00a0, + 0x0201, 0x0097, 0x0079, 0x0401, 0x0201, 0x00a6, 0x006a, 0x00b4, 0x0c01, 0x0601, 0x0201, 0x001a, 0x0201, 0x000a, 0x00b0, 0x0201, + 0x003b, 0x0201, 0x000b, 0x00c0, 0x0401, 0x0201, 0x004b, 0x00c1, 0x0201, 0x0098, 0x0089, 0x4301, 0x2201, 0x1001, 0x0801, 0x0401, + 0x0201, 0x001c, 0x00b5, 0x0201, 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x00a7, 0x0201, 0x007a, 0x00c3, 0x0a01, 0x0601, 0x0201, + 0x003c, 0x0201, 0x000c, 0x00d0, 0x0201, 0x00b6, 0x006b, 0x0401, 0x0201, 0x00c4, 0x004c, 0x0201, 0x0099, 0x00a8, 0x1001, 0x0801, + 0x0401, 0x0201, 0x008a, 0x00c5, 0x0201, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x00d2, 0x0901, 0x0401, + 0x0201, 0x002d, 0x00d3, 0x0201, 0x003d, 0x00c6, 0x55fa, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, 0x2001, 0x1001, + 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e1, 0x0801, + 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x00b9, 0x0401, 0x0201, 0x009b, 0x00e3, 0x0201, 0x00d6, 0x006d, 0x1401, 0x0a01, + 0x0601, 0x0201, 0x003e, 0x0201, 0x002e, 0x004e, 0x0201, 0x00c8, 0x008c, 0x0401, 0x0201, 0x00e4, 0x00d7, 0x0401, 0x0201, 0x007d, + 0x00ab, 0x00e5, 0x0a01, 0x0401, 0x0201, 0x00ba, 0x005e, 0x0201, 0x00c9, 0x0201, 0x009c, 0x006e, 0x0801, 0x0201, 0x00e6, 0x0201, + 0x000d, 0x0201, 0x00e0, 0x000e, 0x0401, 0x0201, 0x00d8, 0x008d, 0x0201, 0x00bb, 0x00ca, 0x4a01, 0x0201, 0x00ff, 0x4001, 0x3a01, + 0x2001, 0x1001, 0x0801, 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00d9, 0x0401, 0x0201, 0x009d, 0x00e8, 0x0201, 0x008e, + 0x00cb, 0x0801, 0x0401, 0x0201, 0x00bc, 0x00da, 0x0201, 0x00ad, 0x00e9, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00db, 0x00bd, + 0x1001, 0x0801, 0x0401, 0x0201, 0x00ea, 0x00ae, 0x0201, 0x00dc, 0x00cd, 0x0401, 0x0201, 0x00eb, 0x00be, 0x0201, 0x00dd, 0x00ec, + 0x0801, 0x0401, 0x0201, 0x00ce, 0x00ed, 0x0201, 0x00de, 0x00ee, 0x000f, 0x0401, 0x0201, 0x00f0, 0x001f, 0x00f1, 0x0401, 0x0201, + 0x00f2, 0x002f, 0x0201, 0x00f3, 0x003f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00f4, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0401, 0x0201, + 0x00f6, 0x006f, 0x0201, 0x00f7, 0x0201, 0x007f, 0x008f, 0x0a01, 0x0401, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00af, + 0x00fa, 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, + }, + [32] = { + 0x0201, 0x0000, 0x0801, 0x0401, 0x0201, 0x0008, 0x0004, 0x0201, 0x0001, 0x0002, 0x0801, 0x0401, 0x0201, 0x000c, 0x000a, 0x0201, + 0x0003, 0x0006, 0x0601, 0x0201, 0x0009, 0x0201, 0x0005, 0x0007, 0x0401, 0x0201, 0x000e, 0x000d, 0x0201, 0x000f, 0x000b, + }, + [33] = { + 0x1001, 0x0801, 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0002, 0x0003, 0x0401, 0x0201, 0x0004, 0x0005, 0x0201, 0x0006, 0x0007, + 0x0801, 0x0401, 0x0201, 0x0008, 0x0009, 0x0201, 0x000a, 0x000b, 0x0401, 0x0201, 0x000c, 0x000d, 0x0201, 0x000e, 0x000f, + }, +} +return E diff --git a/src/Formats/audio/mp3/Encode2.luau b/src/Formats/audio/mp3/Encode2.luau new file mode 100644 index 0000000..0a6af36 --- /dev/null +++ b/src/Formats/audio/mp3/Encode2.luau @@ -0,0 +1,407 @@ +--!strict +--!native +--!optimize 2 +-- audio/mp3/Encode2: an MPEG audio layer II (MP2) encoder: constant bit rate, MPEG-1 (32 / 44.1 / 48 kHz) and MPEG-2 +-- low sampling frequencies (16 / 22.05 / 24 kHz), mono or stereo. New code written from ISO/IEC 11172-3 (2.4.2.3, +-- C.1.5.2): the polyphase analysis (audio/mp3/Analysis), one scalefactor per 12-sample part (scfsi 0: all three are +-- sent), the standard bit allocation tables (in minimp3's compact form, CC0: licenses/minimp3-CC0.txt, as the decoder +-- in this folder reads them), a greedy allocation that always gives the next step to the band with the most noise +-- (signal level minus the quantizer's SNR; no psychoacoustic model), uniform midtread quantization and grouping of +-- 3 / 5 / 9-level samples. Never throws. +local T = require("@formats/audio/mp3/Tables") +local Analysis = require("@formats/audio/mp3/Analysis") + +local Encode2 = {} + +local floor, log = math.floor, math.log +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +-- the allocation tables: { bit-allocation-code offset into g_bitalloc_code_tab, bits, band count } runs (minimp3) +local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } +local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } +local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } +local CODE = T.g_bitalloc_code_tab + +-- quantizer classes (minimp3's ba): 1..16 -> 2^ba - 1 levels in ba bits; 17 / 18 / 19 -> 3 / 5 / 9 levels grouped +local function levels(ba: number): number + if ba >= 17 then + return if ba == 17 then 3 elseif ba == 18 then 5 else 9 + end + return POW[ba + 1] - 1 +end +-- bits for the 3 samples of one granule +local function tripleBits(ba: number): number + if ba >= 17 then + return if ba == 17 then 5 elseif ba == 18 then 7 else 10 + end + return 3 * ba +end +-- the quantizer's signal-to-noise ratio in dB (ISO 11172-3 table C.5) +local SNR: { [number]: number } = {} +do + local byLevels = { + [3] = 7.00, + [5] = 11.00, + [7] = 16.00, + [9] = 20.84, + [15] = 25.28, + [31] = 31.59, + [63] = 37.75, + [127] = 43.84, + [255] = 49.89, + [511] = 55.93, + [1023] = 61.96, + [2047] = 67.98, + [4095] = 74.01, + [8191] = 80.03, + [16383] = 86.05, + [32767] = 92.01, + [65535] = 98.01, + } + for ba = 1, 19 do + SNR[ba] = byLevels[levels(ba)] or (6.02 * ba) + end +end + +-- scalefactors 2^(1 - i/3), i = 0 .. 62 +local SCF = table.create(63, 0) +for i = 0, 62 do + SCF[i + 1] = 2 ^ (1 - i / 3) +end + +local RATES = { + [44100] = { 3, 0 }, + [48000] = { 3, 1 }, + [32000] = { 3, 2 }, + [22050] = { 2, 0 }, + [24000] = { 2, 1 }, + [16000] = { 2, 2 }, +} +Encode2.RATES = RATES +local BITRATES_V1 = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 } +local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 } +Encode2.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } + +type W = { buf: buffer, pos: number, acc: number, cnt: number } +local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc * POW[n + 1] + v + local cnt = w.cnt + n + local b, p = w.buf, w.pos + while cnt >= 8 do + cnt -= 8 + local m = POW[cnt + 1] + local byte = floor(acc / m) + writeu8(b, p, byte) + p += 1 + acc -= byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +export type Source = { + sampleRate: number, + channels: number, + frames: number, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +export type Options = { bitrate: number, mode: string, prefix: buffer? } + +-- encode(src, opts) -> buffer | nil, message +function Encode2.encode(src: Source, opts: Options): (buffer?, string?) + local rate = src.sampleRate + local info = RATES[rate] + if not info then + return nil, "unsupported sample rate" + end + local version, srIndex = info[1], info[2] + local mpeg1 = version == 3 + local inCh = src.channels + local nch = if opts.mode == "mono" then 1 else 2 + local kbps = opts.bitrate + local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 + local brIndex = table.find(list, kbps) + if not brIndex then + return nil, "unsupported bit rate" + end + -- the allocation table (the decoder's choice from the header) + local alloc, nbands + if not mpeg1 then + alloc, nbands = ALLOC_L2M2, 30 + else + local perCh = if nch == 2 then kbps // 2 else kbps + alloc, nbands = ALLOC_L2M1, 27 + if perCh < 56 then + alloc, nbands = ALLOC_L2M1_LOW, if srIndex == 2 then 12 else 8 + elseif perCh >= 96 and srIndex ~= 1 then + nbands = 30 + end + end + local bandOff, bandBits = table.create(nbands, 0), table.create(nbands, 0) + do + local k, ai = 0, 1 + local off, bits = 0, 0 + for i = 0, nbands - 1 do + if i == k then + off, bits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] + ai += 3 + end + bandOff[i + 1], bandBits[i + 1] = off, bits + end + end + -- per band: the classes it can take, in increasing order (index into the code table = the value written) + local steps: { { { number } } } = {} + for i = 1, nbands do + local s = {} + for v = 1, POW[bandBits[i] + 1] - 1 do + local ba = CODE[bandOff[i] + v] + if ba and ba > 0 then + table.insert(s, { v, ba }) + end + end + steps[i] = s + end + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + if opts.prefix then + local pf = opts.prefix :: buffer + if buffer.len(pf) > buffer.len(w.buf) - 16 then + w.buf = buffer.create(buffer.len(pf) + 65536) + end + buffer.copy(w.buf, 0, pf, 0, buffer.len(pf)) + w.pos = buffer.len(pf) + end + local ana = { Analysis.new(), Analysis.new() } + local pcm = { table.create(1152, 0), table.create(1152, 0) } + -- subband samples: sb[c][band * 36 + t + 1], t = 0 .. 35 + local sbs = { table.create(32 * 36, 0), table.create(32 * 36, 0) } + local sub = table.create(32, 0) + local scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) } -- scalefactor index per band and part + local bal = { table.create(32, 0), table.create(32, 0) } -- allocation step (0 = none) per band + local slot = 144000 * kbps + local rest = 0 + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local srcDone, flushed = false, false + while true do + local got = 0 + while got < 1152 and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(1152 - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * inCh * 4 + local l = buffer.readf32(pb, base) + local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l + if nch == 1 then + pcm[1][got + i + 1] = if inCh > 1 then (l + r) * 0.5 else l + else + pcm[1][got + i + 1] = l + pcm[2][got + i + 1] = r + end + end + got += take + pendN -= take + pendOff += take + end + if got == 0 then + if flushed then + break + end + flushed = true + end + for c = 1, nch do + local s = pcm[c] + for i = got + 1, 1152 do + s[i] = 0 + end + local sb = sbs[c] + for t = 0, 35 do + Analysis.run(ana[c], s, t * 32 + 1, sub, 1) + for b = 0, 31 do + sb[b * 36 + t + 1] = sub[b + 1] + end + end + -- scalefactors: the smallest scalefactor (largest index) still >= the part's peak + local sc = scf[c] + for b = 0, nbands - 1 do + for part = 0, 2 do + local m = 0 + local o = b * 36 + part * 12 + for t = 1, 12 do + local v = math.abs(sb[o + t]) + if v > m then + m = v + end + end + local idx = 62 + if m > 0 then + idx = math.clamp(floor(3 * (1 - log(m) / log(2))), 0, 62) + while idx > 0 and SCF[idx + 1] < m do + idx -= 1 + end + while idx < 62 and SCF[idx + 2] >= m do + idx += 1 + end + end + sc[b * 3 + part + 1] = idx + end + end + end + -- the frame size and the bits left for scalefactors and samples + local frameBytes = slot // rate + rest += slot % rate + local padding = 0 + if rest >= rate then + rest -= rate + padding = 1 + frameBytes += 1 + end + local avail = frameBytes * 8 - 32 + for b = 1, nbands do + avail -= bandBits[b] * nch + end + -- greedy allocation: the band with the most noise gets its next step while it fits + local level = { table.create(nbands, 0), table.create(nbands, 0) } -- signal level (dB) per band + for c = 1, nch do + local sc = scf[c] + for b = 1, nbands do + local best = math.min(sc[(b - 1) * 3 + 1], sc[(b - 1) * 3 + 2], sc[(b - 1) * 3 + 3]) + level[c][b] = 20 * math.log10(SCF[best + 1]) + bal[c][b] = 0 + end + end + while true do + local bestC, bestB, bestNoise, bestCost = 0, 0, -math.huge, 0 + for c = 1, nch do + for b = 1, nbands do + local st = bal[c][b] + local s = steps[b] + if st < #s and level[c][b] > -110 then + local cur = if st == 0 then 0 else s[st][2] + local nxt = s[st + 1][2] + local noise = level[c][b] - (if st == 0 then 0 else SNR[cur]) + local cost = 12 * tripleBits(nxt) - (if st == 0 then 0 else 12 * tripleBits(cur)) + if st == 0 then + cost += 2 + 18 -- scfsi + three scalefactors + end + if cost <= avail and noise > bestNoise then + bestC, bestB, bestNoise, bestCost = c, b, noise, cost + end + end + end + end + if bestC == 0 then + break + end + bal[bestC][bestB] += 1 + avail -= bestCost + end + -- write the frame + if w.pos + frameBytes + 64 > buffer.len(w.buf) then + local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end + local start = w.pos + put(w, 0x7FF, 11) + put(w, version, 2) + put(w, 2, 2) -- layer II + put(w, 1, 1) -- no CRC + put(w, brIndex, 4) + put(w, srIndex, 2) + put(w, padding, 1) + put(w, 0, 1) + put(w, if nch == 1 then 3 else 0, 2) + put(w, 0, 2) + put(w, 0, 1) + put(w, 1, 1) + put(w, 0, 2) + -- bit allocation + for b = 1, nbands do + for c = 1, nch do + local st = bal[c][b] + put(w, if st == 0 then 0 else steps[b][st][1], bandBits[b]) + end + end + -- scfsi (0: three scalefactors) and the scalefactors + for b = 1, nbands do + for c = 1, nch do + if bal[c][b] > 0 then + put(w, 0, 2) + end + end + end + for b = 1, nbands do + for c = 1, nch do + if bal[c][b] > 0 then + for part = 1, 3 do + put(w, scf[c][(b - 1) * 3 + part], 6) + end + end + end + end + -- samples: 12 granules of 3, band by band, channel by channel + for gr = 0, 11 do + local part = gr // 4 + for b = 1, nbands do + for c = 1, nch do + local st = bal[c][b] + if st > 0 then + local ba = steps[b][st][2] + local L = levels(ba) + local inv = 1 / SCF[scf[c][(b - 1) * 3 + part + 1] + 1] + local o = (b - 1) * 36 + gr * 3 + local sb = sbs[c] + local q0, q1, q2 + do + local function quant(x: number): number + local q = floor((x * inv + 1) * L / 2) + return if q < 0 then 0 elseif q > L - 1 then L - 1 else q + end + q0, q1, q2 = quant(sb[o + 1]), quant(sb[o + 2]), quant(sb[o + 3]) + end + if ba >= 17 then + put(w, q0 + L * (q1 + L * q2), tripleBits(ba)) + else + put(w, q0, ba) + put(w, q1, ba) + put(w, q2, ba) + end + end + end + end + end + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + while w.pos < start + frameBytes do + writeu8(w.buf, w.pos, 0) + w.pos += 1 + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Encode2 diff --git a/src/Formats/audio/mp3/Encode3.luau b/src/Formats/audio/mp3/Encode3.luau new file mode 100644 index 0000000..39e6dbf --- /dev/null +++ b/src/Formats/audio/mp3/Encode3.luau @@ -0,0 +1,680 @@ +--!strict +--!native +--!optimize 2 +-- audio/mp3/Encode3: an MPEG audio layer III encoder in the spirit of shine: constant bit rate, long blocks only, +-- global-gain rate control (no psychoacoustic model, scalefactors all zero), no bit reservoir (main_data_begin = 0), +-- MPEG-1 (32 / 44.1 / 48 kHz, two granules), MPEG-2 (16 / 22.05 / 24 kHz) and MPEG-2.5 (8 / 11.025 / 12 kHz), mono, +-- stereo or joint (mid / side) stereo. New code written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code): the +-- analysis filterbank (audio/mp3/Analysis), the 36-point MDCT with the sine window, the alias-reduction butterflies, +-- the x^(3/4) quantizer, big_values / count1 partitioning with per-region Huffman table choice; the Huffman codes are +-- derived from the standard's decoder trees (audio/mp3/EncTables, from PDMP3, public domain). Never throws. +local E = require("@formats/audio/mp3/EncTables") +local T = require("@formats/audio/mp3/Tables") +local Analysis = require("@formats/audio/mp3/Analysis") + +local Encode3 = {} + +local floor, sqrt, cos, pi = math.floor, math.sqrt, math.cos, math.pi +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ Huffman codes +-- CODE[t][x * 16 + y + 1], LEN[t][...] for the pair tables 1..31 (16..23 and 24..31 share a tree); count1 tables A +-- (32) and B (33) indexed by v * 8 + w * 4 + x * 2 + y + 1 +local CODE: { [number]: { number } } = {} +local LEN: { [number]: { number } } = {} +local XLEN: { [number]: number } = {} + +local function walk(tree: { number }, codes: { number }, lens: { number }, p: number, code: number, len: number) + local v = tree[p + 1] + if bit32.band(v, 0xFF00) == 0 then + local idx = bit32.band(v, 0xFF) + 1 + if lens[idx] == 0 then + codes[idx], lens[idx] = code, len + end + return + end + -- left (bit 0): offsets of 250+ chain + local q = p + while bit32.rshift(tree[q + 1], 8) >= 250 do + q += bit32.rshift(tree[q + 1], 8) + end + q += bit32.rshift(tree[q + 1], 8) + walk(tree, codes, lens, q, code * 2, len + 1) + q = p + while bit32.band(tree[q + 1], 0xFF) >= 250 do + q += bit32.band(tree[q + 1], 0xFF) + end + q += bit32.band(tree[q + 1], 0xFF) + walk(tree, codes, lens, q, code * 2 + 1, len + 1) +end + +for t = 1, 33 do + local src = if t >= 16 and t <= 23 then 16 elseif t >= 24 and t <= 31 then 24 else t + local tree = E.TREES[src] + if tree then + local codes, lens = table.create(256, 0), table.create(256, 0) + walk(tree, codes, lens, 0, 0, 0) + -- the leaf value of pair tables is x << 4 | y: index x * 16 + y + 1 (count1: the 4-bit vwxy) + CODE[t], LEN[t] = codes, lens + local xl = 0 + for idx = 1, 256 do + if lens[idx] > 0 then + local x = (idx - 1) // 16 + if x + 1 > xl then + xl = x + 1 + end + end + end + XLEN[t] = xl + end +end +local LINBITS = E.LINBITS +-- the tables that hold values up to m (m <= 15), smallest first +local SMALL: { [number]: { number } } = {} +for m = 0, 15 do + local list = {} + for _, t in { 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 } do + if XLEN[t] and XLEN[t] - 1 >= m then + table.insert(list, t) + end + end + SMALL[m] = list +end + +-- ------------------------------------------------------------------------------------------------ bit writer +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc * POW[n + 1] + v + local cnt = w.cnt + n + local b, p = w.buf, w.pos + while cnt >= 8 do + cnt -= 8 + local m = POW[cnt + 1] + local byte = floor(acc / m) + writeu8(b, p, byte) + p += 1 + acc -= byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end +Encode3.put = put + +-- ------------------------------------------------------------------------------------------------ constants +local RATES = { + -- rate -> version bits (3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5), sample rate index, scalefactor band group (g_scf_long) + [44100] = { 3, 0, 5 }, + [48000] = { 3, 1, 6 }, + [32000] = { 3, 2, 7 }, + [22050] = { 2, 0, 2 }, + [24000] = { 2, 1, 3 }, + [16000] = { 2, 2, 4 }, + [11025] = { 0, 0, 0 }, + [12000] = { 0, 1, 0 }, + [8000] = { 0, 2, 1 }, +} +Encode3.RATES = RATES +local BITRATES_V1 = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 } +local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 } +Encode3.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } + +-- the 36-point MDCT (long blocks): X[k] = 1/9 sum_i w_i z_i cos(pi/72 (2i + 19)(2k + 1)), w_i = sin(pi/36 (i + 1/2)) +local MDCT = table.create(18 * 36, 0) +for k = 0, 17 do + for i = 0, 35 do + MDCT[k * 36 + i + 1] = math.sin(pi / 36 * (i + 0.5)) * cos(pi / 72 * (2 * i + 19) * (2 * k + 1)) / 9 + end +end +-- alias reduction coefficients +local CI = { -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037 } +local CS, CA = table.create(8, 0), table.create(8, 0) +for i = 1, 8 do + local s = sqrt(1 + CI[i] * CI[i]) + CS[i], CA[i] = 1 / s, CI[i] / s +end + +-- ------------------------------------------------------------------------------------------------ Huffman planning +type Plan = { + bits: number, + bigValues: number, -- pairs + count1: number, -- quadruples + tables: { number }, -- 3 region tables + region0: number, + region1: number, + c1table: number, -- 0 = A (table 32), 1 = B (33) + addr1: number, -- coefficient index where region 1 starts + addr2: number, +} + +local function newPlan(): Plan + return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 } +end + +-- bits of the pairs ix[a .. b) with table t (ix 1-based: ix[i + 1] is coefficient i) +local function pairBits(ix: { number }, a: number, b: number, t: number): number + if t == 0 then + return 0 + end + local lens = LEN[t] + local lb = LINBITS[t] + local bits = 0 + for i = a, b - 1, 2 do + local x, y = ix[i + 1], ix[i + 2] + local extra = 0 + if x > 14 then + x = 15 + extra += lb + end + if y > 14 then + y = 15 + extra += lb + end + bits += lens[x * 16 + y + 1] + extra + if x ~= 0 then + bits += 1 + end + if y ~= 0 then + bits += 1 + end + end + return bits +end + +-- the best table for the pairs ix[a .. b): table, bits +local function chooseTable(ix: { number }, a: number, b: number): (number, number) + if b <= a then + return 0, 0 + end + local m = 0 + for i = a + 1, b do + local v = ix[i] + if v > m then + m = v + end + end + if m == 0 then + return 0, 0 + end + if m <= 15 then + local best, bestBits = 0, math.huge + for _, t in SMALL[m] do + local bits = pairBits(ix, a, b, t) + if bits < bestBits then + best, bestBits = t, bits + end + end + return best, bestBits + end + local need = m - 15 + local best, bestBits = 0, math.huge + for _, group in { 16, 24 } do + for t = group, group + 7 do + if POW[LINBITS[t] + 1] - 1 >= need then + local bits = pairBits(ix, a, b, t) + if bits < bestBits then + best, bestBits = t, bits + end + break + end + end + end + return best, bestBits +end + +-- plan the Huffman coding of ix (576 values, max <= 8206) into p; bounds = scalefactor band starts (1-based list) +local function plan(ix: { number }, bounds: { number }, p: Plan) + local i = 576 + while i > 1 and ix[i] == 0 and ix[i - 1] == 0 do + i -= 2 + end + -- count1 region: quadruples of values <= 1 + local c1 = 0 + while i > 3 and ix[i] <= 1 and ix[i - 1] <= 1 and ix[i - 2] <= 1 and ix[i - 3] <= 1 do + i -= 4 + c1 += 1 + end + local bv = i -- big_values * 2 coefficients + p.bigValues, p.count1 = bv // 2, c1 + -- count1 bits, table A vs B + local ba, bb = 0, 0 + local lensA = LEN[32] + for q = 0, c1 - 1 do + local o = bv + q * 4 + local v, w, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] + local s = v + w + x + y + ba += lensA[v * 8 + w * 4 + x * 2 + y + 1] + s + bb += 4 + s + end + p.c1table = if bb < ba then 1 else 0 + local bits = if bb < ba then bb else ba + -- regions: region 0 / 1 / 2 split at scalefactor band boundaries + local j = 0 + while j + 1 < #bounds and bounds[j + 2] <= bv do + j += 1 + end + local r0 = math.clamp(floor((j + 1) / 3), 0, 15) + local r1 = math.clamp(floor((j + 1) / 3), 0, 7) + if r0 + r1 + 2 > 22 then + r1 = 22 - r0 - 2 + end + local a1 = math.min(bounds[r0 + 2] or 576, bv) + local a2 = math.min(bounds[r0 + r1 + 3] or 576, bv) + p.region0, p.region1, p.addr1, p.addr2 = r0, r1, a1, a2 + local t1, b1 = chooseTable(ix, 0, a1) + local t2, b2 = chooseTable(ix, a1, a2) + local t3, b3 = chooseTable(ix, a2, bv) + p.tables[1], p.tables[2], p.tables[3] = t1, t2, t3 + p.bits = bits + b1 + b2 + b3 +end + +local function writePairs(w: W, ix: { number }, sign: { boolean }, a: number, b: number, t: number) + if t == 0 then + return + end + local codes, lens = CODE[t], LEN[t] + local lb = LINBITS[t] + for i = a, b - 1, 2 do + local x, y = ix[i + 1], ix[i + 2] + local cx, cy = if x > 14 then 15 else x, if y > 14 then 15 else y + local idx = cx * 16 + cy + 1 + put(w, codes[idx], lens[idx]) + if cx == 15 then + put(w, x - 15, lb) + end + if x ~= 0 then + put(w, if sign[i + 1] then 1 else 0, 1) + end + if cy == 15 then + put(w, y - 15, lb) + end + if y ~= 0 then + put(w, if sign[i + 2] then 1 else 0, 1) + end + end +end + +local function writeHuffman(w: W, ix: { number }, sign: { boolean }, p: Plan) + local bv = p.bigValues * 2 + writePairs(w, ix, sign, 0, p.addr1, p.tables[1]) + writePairs(w, ix, sign, p.addr1, p.addr2, p.tables[2]) + writePairs(w, ix, sign, p.addr2, bv, p.tables[3]) + local codesA, lensA = CODE[32], LEN[32] + for q = 0, p.count1 - 1 do + local o = bv + q * 4 + local v, ww, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] + local idx = v * 8 + ww * 4 + x * 2 + y + if p.c1table == 1 then + put(w, 15 - idx, 4) -- table B: the 4 bits inverted + else + put(w, codesA[idx + 1], lensA[idx + 1]) + end + for k = 1, 4 do + if ix[o + k] ~= 0 then + put(w, if sign[o + k] then 1 else 0, 1) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ quantization +type Unit = { + xr: { number }, -- 576 MDCT coefficients + xa: { number }, -- |xr|^(3/4) + ix: { number }, + sign: { boolean }, + plan: Plan, + gain: number, +} + +local function newUnit(): Unit + return { + xr = table.create(576, 0), + xa = table.create(576, 0), + ix = table.create(576, 0), + sign = table.create(576, false), + plan = newPlan(), + gain = 210, + } +end + +-- quantize with global gain g: false when a value overflows 8206 +local function quantize(u: Unit, g: number): boolean + local step = 2 ^ (-(g - 210) * 3 / 16) + local xa, ix = u.xa, u.ix + for i = 1, 576 do + local v = floor(xa[i] * step + 0.4054) + if v > 8206 then + return false + end + ix[i] = v + end + return true +end + +-- the finest global gain whose Huffman size fits budget bits +local function rateLoop(u: Unit, budget: number, bounds: { number }) + local xr, xa, sign = u.xr, u.xa, u.sign + local maxa = 0 + for i = 1, 576 do + local v = xr[i] + sign[i] = v < 0 + local a = math.abs(v) ^ 0.75 + xa[i] = a + if a > maxa then + maxa = a + end + end + local p = u.plan + if maxa < 1e-12 then + for i = 1, 576 do + u.ix[i] = 0 + end + plan(u.ix, bounds, p) + u.gain = 0 + return + end + -- the gain where the largest value quantizes to 0: an upper bound + local lo, hi = 0, 255 + local best = -1 + while lo <= hi do + local mid = (lo + hi) // 2 + if quantize(u, mid) then + plan(u.ix, bounds, p) + if p.bits <= budget then + best = mid + hi = mid - 1 + else + lo = mid + 1 + end + else + lo = mid + 1 + end + end + if best < 0 then + best = 255 + end + quantize(u, best) + plan(u.ix, bounds, p) + if p.bits > budget then -- give up on this granule: silence fits any budget + for i = 1, 576 do + u.ix[i] = 0 + end + plan(u.ix, bounds, p) + end + u.gain = best +end + +-- ------------------------------------------------------------------------------------------------ encoder +export type Source = { + sampleRate: number, + channels: number, + frames: number, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +export type Options = { + bitrate: number, -- kbps, valid for the version + mode: string, -- "stereo" | "joint" | "mono" + prefix: buffer?, -- bytes written before the first frame (an ID3v2 tag) +} + +-- encode(src, opts) -> buffer | nil, message +function Encode3.encode(src: Source, opts: Options): (buffer?, string?) + local rate = src.sampleRate + local info = RATES[rate] + if not info then + return nil, "unsupported sample rate" + end + local version, srIndex, group = info[1], info[2], info[3] + local mpeg1 = version == 3 + local granules = if mpeg1 then 2 else 1 + local spf = 576 * granules + local inCh = src.channels + local mode = opts.mode + local nch = if mode == "mono" then 1 else 2 + local kbps = opts.bitrate + local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 + local brIndex = table.find(list, kbps) + if not brIndex then + return nil, "unsupported bit rate" + end + local sideBytes = if mpeg1 then (if nch == 1 then 17 else 32) else (if nch == 1 then 9 else 17) + local slotNum = (if mpeg1 then 144000 else 72000) * kbps -- frame bytes * rate + -- scalefactor band starts (long blocks) + local bounds = { 0 } + do + local acc = 0 + for k = 0, 21 do + acc += T.g_scf_long[group * 23 + k] + table.insert(bounds, acc) + end + end + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + if opts.prefix then + local pf = opts.prefix :: buffer + local need = buffer.len(pf) + if need > buffer.len(w.buf) - 16 then + w.buf = buffer.create(need + 65536) + end + buffer.copy(w.buf, 0, pf, 0, need) + w.pos = need + end + local ana = { Analysis.new(), Analysis.new() } + local prev = { table.create(576, 0), table.create(576, 0) } -- previous granule's subband samples [sb * 18 + k + 1] + local cur = { table.create(576, 0), table.create(576, 0) } + local units = {} + for g = 1, 2 do + units[g] = { newUnit(), newUnit() } + end + local pcm = { table.create(spf, 0), table.create(spf, 0) } + local sub = table.create(32, 0) + local z = table.create(36, 0) + local rest = 0 + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local srcDone = false + local flushed = false + while true do + -- one frame of input (zero padded at the end; one more silent frame flushes the filterbank delay) + local got = 0 + while got < spf and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(spf - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * inCh * 4 + local l = buffer.readf32(pb, base) + local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l + if nch == 1 then + if inCh > 1 then + l = (l + r) * 0.5 + end + pcm[1][got + i + 1] = l + else + pcm[1][got + i + 1] = l + pcm[2][got + i + 1] = r + end + end + got += take + pendN -= take + pendOff += take + end + if got == 0 then + if flushed then + break + end + flushed = true -- one silent frame after the input pushes its tail through the filterbank delay + end + for c = 1, nch do + local s = pcm[c] + for i = got + 1, spf do + s[i] = 0 + end + end + -- analysis + MDCT per granule and channel + for g = 1, granules do + for c = 1, nch do + local cu, pv = cur[c], prev[c] + local s = pcm[c] + for k = 0, 17 do + Analysis.run(ana[c], s, (g - 1) * 576 + k * 32 + 1, sub, 1) + for sb = 0, 31 do + local v = sub[sb + 1] + if sb % 2 == 1 and k % 2 == 1 then + v = -v -- frequency inversion of the odd subbands + end + cu[sb * 18 + k + 1] = v + end + end + local xr = units[g][c].xr + for sb = 0, 31 do + local o = sb * 18 + for i = 1, 18 do + z[i] = pv[o + i] + z[i + 18] = cu[o + i] + end + for k = 0, 17 do + local acc = 0 + local mb = k * 36 + for i = 1, 36 do + acc += MDCT[mb + i] * z[i] + end + xr[o + k + 1] = acc + end + end + -- alias reduction butterflies (the inverse of the decoder's) + for sb = 1, 31 do + local o = sb * 18 + for i = 0, 7 do + local a, b = xr[o - i], xr[o + i + 1] + xr[o - i] = a * CS[i + 1] + b * CA[i + 1] + xr[o + i + 1] = b * CS[i + 1] - a * CA[i + 1] + end + end + prev[c], cur[c] = cu, pv + end + if mode == "joint" then + local x0, x1 = units[g][1].xr, units[g][2].xr + local r2 = sqrt(0.5) + for i = 1, 576 do + local l, r = x0[i], x1[i] + x0[i], x1[i] = (l + r) * r2, (l - r) * r2 + end + end + end + -- the frame size + local frameBytes = slotNum // rate + rest += slotNum % rate + local padding = 0 + if rest >= rate then + rest -= rate + padding = 1 + frameBytes += 1 + end + local avail = (frameBytes - 4 - sideBytes) * 8 + local left = avail + local nUnits = granules * nch + local done = 0 + for g = 1, granules do + for c = 1, nch do + local budget = math.min(4095, left // (nUnits - done)) + local u = units[g][c] + rateLoop(u, budget, bounds) + left -= u.plan.bits + done += 1 + end + end + -- header + if w.pos + frameBytes + 64 > buffer.len(w.buf) then + local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end + local start = w.pos + put(w, 0x7FF, 11) + put(w, version, 2) + put(w, 1, 2) -- layer III + put(w, 1, 1) -- no CRC + put(w, brIndex, 4) + put(w, srIndex, 2) + put(w, padding, 1) + put(w, 0, 1) + put(w, if mode == "mono" then 3 elseif mode == "joint" then 1 else 0, 2) + put(w, if mode == "joint" then 2 else 0, 2) -- mode extension: mid / side on, intensity off + put(w, 0, 1) + put(w, 1, 1) -- original + put(w, 0, 2) + -- side info + if mpeg1 then + put(w, 0, 9) -- main_data_begin + put(w, 0, if nch == 1 then 5 else 3) + for _ = 1, nch do + put(w, 0, 4) -- scfsi + end + else + put(w, 0, 8) + put(w, 0, if nch == 1 then 1 else 2) + end + for g = 1, granules do + for c = 1, nch do + local u = units[g][c] + local p = u.plan + put(w, p.bits, 12) -- part2_3_length (no scalefactor bits) + put(w, p.bigValues, 9) + put(w, u.gain, 8) + put(w, 0, if mpeg1 then 4 else 9) -- scalefac_compress + put(w, 0, 1) -- window switching off + put(w, p.tables[1], 5) + put(w, p.tables[2], 5) + put(w, p.tables[3], 5) + put(w, p.region0, 4) + put(w, p.region1, 3) + if mpeg1 then + put(w, 0, 1) -- preflag + end + put(w, 0, 1) -- scalefac_scale + put(w, p.c1table, 1) + end + end + -- main data + for g = 1, granules do + for c = 1, nch do + local u = units[g][c] + writeHuffman(w, u.ix, u.sign, u.plan) + end + end + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + -- ancillary padding to the frame size + while w.pos < start + frameBytes do + writeu8(w.buf, w.pos, 0) + w.pos += 1 + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Encode3 diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau index 649970d..e3bd87d 100644 --- a/src/Formats/audio/mp3/init.luau +++ b/src/Formats/audio/mp3/init.luau @@ -4,8 +4,9 @@ -- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing / -- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync -- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped). --- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Not supported: encoding (see the mp3 encoder in the --- audio workstream), MPEG-2 multichannel extension, CRC checks. +-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, audio/mp3/Encode3 + Encode2): layer III +-- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from +-- the tags. Not supported: MPEG-2 multichannel extension, CRC checks, VBR / Xing output, encoder resampling. -- -- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay, -- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll()) @@ -19,6 +20,9 @@ local Header = require("@formats/audio/mp3/Header") local Index = require("@formats/audio/mp3/Index") local Tags = require("@formats/audio/mp3/Tags") local Stream = require("@formats/audio/mp3/Stream") +local Encode3 = require("@formats/audio/mp3/Encode3") +local Encode2 = require("@formats/audio/mp3/Encode2") +local Pcm = require("@formats/codecs/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Mp3 = { @@ -26,8 +30,8 @@ local Mp3 = { category = "audio", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "Types" }, - caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, } -- ------------------------------------------------------------------------------------------------ types @@ -35,6 +39,13 @@ export type OpenOptions = { maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31) } export type Decoder = Stream.Decoder +export type EncodeOptions = { + layer: number?, -- 3 (MP3, default) or 2 (MP2) + bitrate: number?, -- kbps, constant (default 128 for layer III, 192 for layer II; MPEG-2 / 2.5 rates: 64 / 96) + mode: ("stereo" | "joint" | "mono")?, -- default "joint" (mid / side) for stereo layer III, "stereo" for layer II, + -- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo" + id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags) +} -- ------------------------------------------------------------------------------------------------ constants local MAX_FRAMES = 2 ^ 31 @@ -85,6 +96,115 @@ function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err return a, nil end +-- ------------------------------------------------------------------------------------------------ encode +local ID3_FRAMES = { + { "title", "TIT2" }, + { "artist", "TPE1" }, + { "album", "TALB" }, + { "albumArtist", "TPE2" }, + { "year", "TDRC" }, + { "date", "TDRC" }, + { "track", "TRCK" }, + { "genre", "TCON" }, + { "composer", "TCOM" }, +} + +-- an ID3v2.4 tag (UTF-8 text frames + a COMM frame) | nil when there is nothing to write +local function id3Tag(tags: { [string]: any }): buffer? + local w = Bytes.writer(256) + local seen: { [string]: boolean } = {} + local function syncsafe(v: number) + w:u8((v // 2097152) % 128) + w:u8((v // 16384) % 128) + w:u8((v // 128) % 128) + w:u8(v % 128) + end + for _, f in ID3_FRAMES do + local v = tags[f[1]] + if type(v) == "string" and #v > 0 and not seen[f[2]] then + seen[f[2]] = true + w:string(f[2]) + syncsafe(#v + 1) + w:u16be(0) + w:u8(3) -- UTF-8 + w:string(v) + end + end + if type(tags.comment) == "string" and #tags.comment > 0 then + local v = tags.comment + w:string("COMM") + syncsafe(#v + 5) + w:u16be(0) + w:u8(3) + w:string("eng") + w:u8(0) -- empty description + w:string(v) + end + local body = w:finish() + if buffer.len(body) == 0 then + return nil + end + local out = Bytes.writer(buffer.len(body) + 10) + out:string("ID3") + out:u8(4) + out:u8(0) + out:u8(0) + local n = buffer.len(body) + out:u8((n // 2097152) % 128) + out:u8((n // 16384) % 128) + out:u8((n // 128) % 128) + out:u8(n % 128) + out:bytes(body) + return out:finish() +end + +-- encode(audioOrDecoder, opts?) -> an MP3 (layer III) or MP2 (layer II) file | nil, Err +function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local layer = o.layer or 3 + if layer ~= 2 and layer ~= 3 then + return nil, Err.new(Err.ARG, "layer must be 2 or 3") + end + local Enc = if layer == 3 then Encode3 else Encode2 + local info = Enc.RATES[src.sampleRate] + if not info then + return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz (no resampling)", layer, tostring(src.sampleRate))) + end + local mpeg1 = info[1] == 3 + local mode = o.mode or (if src.channels == 1 then "mono" elseif layer == 3 then "joint" else "stereo") + if mode ~= "stereo" and mode ~= "joint" and mode ~= "mono" then + return nil, Err.new(Err.ARG, "mode must be stereo, joint or mono") + end + if src.channels > 2 then + return nil, Err.new(Err.ARG, "MPEG audio holds 1 or 2 channels") + end + if layer == 2 and mode == "joint" then + mode = "stereo" + end + local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96)) + if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then + return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, src.sampleRate)) + end + if layer == 2 and mpeg1 then + -- the standard's allowed bit rate / mode combinations + if mode == "mono" and bitrate > 192 then + return nil, Err.new(Err.ARG, "layer II mono is at most 192 kbps") + elseif mode ~= "mono" and (bitrate == 32 or bitrate == 48 or bitrate == 56 or bitrate == 80) then + return nil, Err.new(Err.ARG, "layer II stereo needs 64 kbps or more (and not 80)") + end + end + local prefix = if o.id3 == false then nil else id3Tag(src.tags) + local out, msg = Enc.encode(src :: any, { bitrate = bitrate, mode = mode, prefix = prefix }) + if not out then + return nil, Err.new(Err.ARG, tostring(msg)) + end + return out, nil +end + -- ------------------------------------------------------------------------------------------------ open -- the string-valued tag fields (title, artist, album, albumArtist, year, track, disc, genre, composer, comment) local function stringTags(t: any): { [string]: string } diff --git a/src/Formats/audio/voc/init.luau b/src/Formats/audio/voc/init.luau new file mode 100644 index 0000000..3feca49 --- /dev/null +++ b/src/Formats/audio/voc/init.luau @@ -0,0 +1,278 @@ +--!strict +-- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description. +-- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence), +-- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit +-- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played +-- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version +-- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM +-- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Voc = { + name = "voc", + category = "audio", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, +} + +export type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +export type EncodeOptions = { + sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16" +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "Creative Voice File\26" +local T9_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le", [6] = "alaw", [7] = "ulaw" } +local T1_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le" } +local WRITE = { u8 = { 0, "u8", 8 }, s16 = { 4, "s16le", 16 }, alaw = { 6, "alaw", 8 }, ulaw = { 7, "ulaw", 8 } } +local MAX_BLOCK = 0xFFFFFF - 12 -- payload bytes of one type 9 block (a 24-bit size, 12 header bytes) + +local readu8 = buffer.readu8 +local function u16(b: buffer, o: number): number + return readu8(b, o) + readu8(b, o + 1) * 256 +end +local function u24(b: buffer, o: number): number + return readu8(b, o) + readu8(b, o + 1) * 256 + readu8(b, o + 2) * 65536 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Voc.sniff(r: Bytes.Reader): number + return if r:peek(20) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Segment = { at: number, frames: number, fmt: string? } -- fmt nil: silence + +function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 26 or buffer.readstring(b, base, 20) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local hsize = u16(b, base + 20) + local version = u16(b, base + 22) + if hsize < 26 or hsize > limit - base then + return nil, Err.new(Err.CORRUPT, "bad header size", base + 20) + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + local rate, channels = 0, 0 + local extRate, extChannels = 0, 0 -- a type 8 block's settings for the next type 1 block + local lastFmt: string? = nil + local codec = -1 + local segments: { Segment } = {} + local total = 0 + local truncated = false + local tags: Types.Tags = {} + local p = base + hsize + -- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames) + local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err? + if channels == 0 then + channels, rate = ch, sr + elseif ch ~= channels then + return Err.new(Err.UNSUPPORTED, "the channel count changes mid-file", at) + end + local frames = if fmt then bytes // (ch * Pcm.Convert.SIZE[fmt]) else bytes + if frames > 0 then + total += frames + if total > maxFrames then + return Err.new(Err.LIMIT, string.format("over the %d frame limit", maxFrames)) + end + table.insert(segments, { at = at, frames = frames, fmt = fmt }) + end + return nil + end + while p < limit do + local t = readu8(b, p) + if t == 0 then + break + end + if p + 4 > limit then + truncated = true + break + end + local size = u24(b, p + 1) + local d = p + 4 + local avail = math.min(size, limit - d) + if avail < size then + truncated = true + end + local err: Err.Err? = nil + if t == 1 then + if avail < 2 then + break + end + local div, c = readu8(b, d), readu8(b, d + 1) + local fmt = T1_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "Creative ADPCM (codec " .. c .. ")", d + 1) + end + local ch, sr = 1, 1000000 // (256 - div) + if extChannels > 0 then + ch, sr = extChannels, extRate + extChannels = 0 + end + lastFmt, codec = fmt, c + err = add(d + 2, avail - 2, fmt, ch, sr) + elseif t == 2 then + if lastFmt == nil then + return nil, Err.new(Err.CORRUPT, "continuation block before any sound data", p) + end + err = add(d, avail, lastFmt, channels, rate) + elseif t == 3 then + if avail < 3 then + break + end + local len, div = u16(b, d) + 1, readu8(b, d + 2) + err = add(d, len, nil, if channels > 0 then channels else 1, if rate > 0 then rate else 1000000 // (256 - div)) + elseif t == 5 then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + tags.comment = if tags.comment then tags.comment .. "\n" .. s else s + elseif t == 8 then + if avail < 4 then + break + end + local tc, mode = u16(b, d), readu8(b, d + 3) + extChannels = mode + 1 + extRate = 256000000 // (extChannels * (65536 - tc)) + elseif t == 9 then + if avail < 12 then + break + end + local sr = readu8(b, d) + readu8(b, d + 1) * 256 + readu8(b, d + 2) * 65536 + readu8(b, d + 3) * 16777216 + local ch, c = readu8(b, d + 5), u16(b, d + 6) + local fmt = T9_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "codec " .. c, d + 6) + end + if ch < 1 or sr < 1 then + return nil, Err.new(Err.CORRUPT, "bad channels or sample rate", d) + end + lastFmt, codec = fmt, c + err = add(d + 12, avail - 12, fmt, ch, sr) + end + if err then + return nil, err + end + p = d + size + end + if channels == 0 then + return nil, Err.new(if truncated then Err.TRUNCATED else Err.CORRUPT, "no sound data", p) + end + local a = Types.Audio.new(rate, channels, total) + local o = 0 + for _, s in segments do + local n = s.frames * channels + if s.fmt then + Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o) + end -- silence: the buffer is already zero + o += n * 4 + end + a.tags = tags + a.meta.source = { + format = "voc", + version = string.format("%d.%02d", version // 256, version % 256), + codec = codec, + sampleFormat = lastFmt, + bitDepth = if lastFmt == "s16le" then 16 else 8, + truncated = truncated or nil, + } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + w:u16le(26) + w:u16le(0x0114) + w:u16le((0xFFFF - 0x0114 + 0x1234 + 1) % 65536) -- ~version + 0x1234 + if type(src.tags.comment) == "string" and #src.tags.comment > 0 then + local s = string.sub(src.tags.comment, 1, 0xFFFFFE) + w:u8(5) + w:u24le(#s + 1) + w:string(s) + w:u8(0) + end + local size = Pcm.Convert.SIZE[spec[2]] + local frameBytes = size * src.channels + local framesPerBlock = MAX_BLOCK // frameBytes + local blockAt, blockFrames = -1, 0 + local tmp: buffer? = nil + while true do + local bf, n = src:read(math.min(8192, framesPerBlock), tmp) + if n <= 0 then + break + end + tmp = bf + local i = 0 + while i < n do + if blockAt < 0 or blockFrames == framesPerBlock then + blockAt = w:tell() + blockFrames = 0 + w:u8(9) + w:u24le(0) -- patched + w:u32le(src.sampleRate) + w:u8(spec[3]) + w:u8(src.channels) + w:u16le(spec[1]) + w:u32le(0) + end + local take = math.min(n - i, framesPerBlock - blockFrames) + local at = w:reserve(take * frameBytes) + Pcm.Convert.encode(bf, i * src.channels * 4, take * src.channels, spec[2], w.buf, at) + w.pos = at + take * frameBytes + blockFrames += take + i += take + local len = blockFrames * frameBytes + 12 + w:setU8(blockAt + 1, len % 256) + w:setU8(blockAt + 2, (len // 256) % 256) + w:setU8(blockAt + 3, len // 65536) + end + end + if src.err then + return nil, src.err + end + w:u8(0) -- terminator + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Voc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local a, err = Voc.decode(r, opts) + if not a then + return nil, err + end + local dec = Pcm.audioDecoder(a) :: any + dec.source = a.meta.source + return dec, nil +end + +return Voc diff --git a/src/Formats/audio/vorbis/Codebook.luau b/src/Formats/audio/vorbis/Codebook.luau new file mode 100644 index 0000000..19c0da5 --- /dev/null +++ b/src/Formats/audio/vorbis/Codebook.luau @@ -0,0 +1,394 @@ +--!strict +--!native +--!optimize 2 +-- audio/vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3): +-- reading a codebook from the setup header (ordered / sparse length lists, lookup types 1 and 2, float32_unpack), +-- the codeword assignment, and Huffman / VQ decoding. Ported from stb_vorbis 1.22 (public domain / MIT; see +-- licenses/stb_vorbis-LICENSE.txt): compute_codewords' lowest-free-leaf assignment, lookup1_values; the decode side +-- is a fast table (up to 10 bits) plus a binary tree for longer codes instead of stb's sorted binary search. +-- +-- Never throws. Reading past the packet end gives zero bits and sets br.eop (the spec's end-of-packet condition); +-- an invalid codeword also sets eop and decodes to -1. +local Codebook = {} + +local readu8 = buffer.readu8 +local floor = math.floor + +local POW = table.create(41, 0) +for i = 0, 40 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ bit reader +export type Br = { + buf: buffer, + pos: number, -- next byte to load + limit: number, + acc: number, -- loaded, unread bits (LSB first) + cnt: number, + pad: number, -- how many of the top bits of acc are past the end of the packet + eop: boolean, -- read past the end of the packet +} + +function Codebook.reader(buf: buffer, offset: number, size: number): Br + return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false } +end + +-- bits(br, n) -> the next n (0..32) bits as an unsigned number +local function bits(br: Br, n: number): number + if n == 0 then + return 0 + end + local acc, cnt = br.acc, br.cnt + if cnt < n then + local b, p, lim = br.buf, br.pos, br.limit + repeat + if p < lim then + acc += readu8(b, p) * POW[cnt + 1] + p += 1 + else + br.pad += 8 + end + cnt += 8 + until cnt >= n + br.pos = p + end + local m = POW[n + 1] + local v = acc % m + br.acc = (acc - v) / m + cnt -= n + br.cnt = cnt + if cnt < br.pad then + br.eop = true + br.pad = cnt + end + return v +end +Codebook.bits = bits + +-- ilog(x): the number of bits needed to hold x (0 for x <= 0) +local function ilog(x: number): number + local n = 0 + while x > 0 do + n += 1 + x = floor(x / 2) + end + return n +end +Codebook.ilog = ilog + +-- float32_unpack (spec 9.2.2) +local function float32Unpack(x: number): number + local mantissa = x % 2097152 + local sign = x >= 2147483648 + local exp = floor((x % 2147483648) / 2097152) + local v = mantissa * 2 ^ (exp - 788) + return if sign then -v else v +end + +-- ------------------------------------------------------------------------------------------------ codebooks +export type Book = { + dims: number, + entries: number, + fastBits: number, + fastLen: { number }, -- per fastBits-bit prefix: code length (> 0), 0 = continue in the tree, -1 = invalid + fastSym: { number }, -- symbol, or the tree node to continue from + c0: { number }, -- tree: child for bit 0 / 1: > 0 node, < 0 leaf (-symbol - 1), 0 none + c1: { number }, + lookup: number, -- 0, 1, 2 + vq: { number }?, -- entries * dims values (lookup 1 / 2, expanded) + used: number, -- entries with a codeword +} + +local MAX_ENTRIES = 2 ^ 20 +local MAX_VQ = 2 ^ 22 + +-- lookup1_values(entries, dims): the largest r with r^dims <= entries +local function lookup1Values(entries: number, dims: number): number + local r = floor(math.exp(math.log(entries) / dims)) + if floor((r + 1) ^ dims) <= entries then + r += 1 + end + if (r + 1) ^ dims <= entries then + return -1 + end + if floor(r ^ dims) > entries then + return -1 + end + return r +end + +-- assign codewords (spec 3.2.1: in entry order, the lowest free leaf) and build the decode tree + fast table +local function build(book: Book, lengths: { number }): string? + local n = book.entries + local c0, c1 = book.c0, book.c1 + local nodes = 1 + c0[1], c1[1] = 0, 0 + local available = table.create(33, 0) -- available[l]: the free code at depth l, as a 32-bit left-aligned value + 1 (0 = none) + local first = true + local used = 0 + local maxLen = 0 + for i = 0, n - 1 do + local len = lengths[i + 1] + if len > 0 then + local code: number + if first then + first = false + code = 0 + for l = 1, len do + available[l + 1] = POW[33 - l] + 1 + end + else + local z = len + while z > 0 and available[z + 1] == 0 do + z -= 1 + end + if z == 0 then + return "over-subscribed codebook" + end + code = available[z + 1] - 1 + available[z + 1] = 0 + for y = len, z + 1, -1 do + available[y + 1] = code + POW[33 - y] + 1 + end + end + -- walk the MSB-first code into the tree + local node = 1 + for d = 1, len do + local bit = floor(code / POW[33 - d]) % 2 + local child = if bit == 0 then c0[node] else c1[node] + if d == len then + if child ~= 0 then + return "ambiguous codeword" + end + if bit == 0 then + c0[node] = -(i + 1) + else + c1[node] = -(i + 1) + end + else + if child < 0 then + return "ambiguous codeword" + elseif child == 0 then + nodes += 1 + c0[nodes], c1[nodes] = 0, 0 + child = nodes + if bit == 0 then + c0[node] = child + else + c1[node] = child + end + end + node = child + end + end + used += 1 + if len > maxLen then + maxLen = len + end + end + end + book.used = used + -- the fast table: every fastBits-bit prefix (read LSB first) walked down the tree + local fb = math.clamp(maxLen, 1, 10) + book.fastBits = fb + local size = POW[fb + 1] + local fl, fs = table.create(size, -1), table.create(size, 0) + for idx = 0, size - 1 do + local node = 1 + local v = idx + for d = 1, fb do + local bit = v % 2 + v = (v - bit) / 2 + local child = if bit == 0 then c0[node] else c1[node] + if child < 0 then + fl[idx + 1], fs[idx + 1] = d, -child - 1 + break + elseif child == 0 then + break -- invalid (-1) + end + node = child + if d == fb then + fl[idx + 1], fs[idx + 1] = 0, node + end + end + end + book.fastLen, book.fastSym = fl, fs + return nil +end + +-- read(br) -> Book | nil, message: one codebook from the setup header +function Codebook.read(br: Br): (Book?, string?) + if bits(br, 24) ~= 0x564342 then + return nil, "bad codebook sync" + end + local dims = bits(br, 16) + local entries = bits(br, 24) + local ordered = bits(br, 1) + if br.eop then + return nil, "setup header ends in a codebook" + end + if dims == 0 and entries ~= 0 then + return nil, "codebook with 0 dimensions" + end + if entries > MAX_ENTRIES then + return nil, "codebook with " .. entries .. " entries" + end + local lengths = table.create(entries, 0) + if ordered == 1 then + local cur = 0 + local len = bits(br, 5) + 1 + while cur < entries do + local num = bits(br, ilog(entries - cur)) + if len >= 32 or cur + num > entries or br.eop then + return nil, "bad ordered codebook lengths" + end + for k = cur + 1, cur + num do + lengths[k] = len + end + cur += num + len += 1 + end + else + local sparse = bits(br, 1) + for j = 1, entries do + if sparse == 0 or bits(br, 1) == 1 then + local l = bits(br, 5) + 1 + if l == 32 then + return nil, "codeword length 32" + end + lengths[j] = l + end + end + end + if br.eop then + return nil, "setup header ends in a codebook" + end + local book: Book = { + dims = dims, + entries = entries, + fastBits = 1, + fastLen = {}, + fastSym = {}, + c0 = {}, + c1 = {}, + lookup = 0, + vq = nil, + used = 0, + } + local err = build(book, lengths) + if err then + return nil, err + end + local lookup = bits(br, 4) + if lookup > 2 then + return nil, "lookup type " .. lookup + end + book.lookup = lookup + if lookup > 0 then + local minimum = float32Unpack(bits(br, 32)) + local delta = float32Unpack(bits(br, 32)) + local valueBits = bits(br, 4) + 1 + local seq = bits(br, 1) == 1 + local nvalues + if lookup == 1 then + nvalues = lookup1Values(entries, dims) + if nvalues < 0 then + return nil, "bad lookup1 size" + end + else + nvalues = entries * dims + end + if nvalues == 0 then + return nil, "empty lookup table" + end + if entries * dims > MAX_VQ or nvalues > MAX_VQ then + return nil, "lookup table too large" + end + local mults = table.create(nvalues, 0) + for j = 1, nvalues do + mults[j] = bits(br, valueBits) + end + if br.eop then + return nil, "setup header ends in a lookup table" + end + -- expand to one vector per entry (spec 3.2.1, "VQ lookup table vector representation") + local vq = table.create(entries * dims, 0) + for e = 0, entries - 1 do + local last = 0 + local div = 1 + for k = 0, dims - 1 do + local off + if lookup == 1 then + off = floor(e / div) % nvalues + div *= nvalues + else + off = e * dims + k + end + local v = mults[off + 1] * delta + minimum + last + if seq then + last = v + end + vq[e * dims + k + 1] = v + end + end + book.vq = vq + end + return book, nil +end + +-- decode(br, book) -> entry number | -1 (end of packet / invalid codeword: br.eop is set) +local function decode(br: Br, book: Book): number + local fb = book.fastBits + local acc, cnt = br.acc, br.cnt + if cnt < fb then + local b, p, lim = br.buf, br.pos, br.limit + repeat + if p < lim then + acc += readu8(b, p) * POW[cnt + 1] + p += 1 + else + br.pad += 8 + end + cnt += 8 + until cnt >= fb + br.pos = p + br.acc, br.cnt = acc, cnt + end + local idx = acc % POW[fb + 1] + 1 + local l = book.fastLen[idx] + if l > 0 then + local m = POW[l + 1] + br.acc = (acc - acc % m) / m + cnt -= l + br.cnt = cnt + if cnt < br.pad then + br.eop = true + br.pad = cnt + return -1 + end + return book.fastSym[idx] + elseif l == 0 then + bits(br, fb) + local node = book.fastSym[idx] + local c0, c1 = book.c0, book.c1 + while true do + local child = if bits(br, 1) == 0 then c0[node] else c1[node] + if br.eop then + return -1 + end + if child < 0 then + return -child - 1 + elseif child == 0 then + br.eop = true + return -1 + end + node = child + end + end + br.eop = true + return -1 +end +Codebook.decode = decode + +return Codebook diff --git a/src/Formats/audio/vorbis/Encode.luau b/src/Formats/audio/vorbis/Encode.luau new file mode 100644 index 0000000..f15a212 --- /dev/null +++ b/src/Formats/audio/vorbis/Encode.luau @@ -0,0 +1,825 @@ +--!strict +--!native +--!optimize 2 +-- audio/vorbis/Encode: a basic but valid Vorbis I encoder in Ogg. New code written from the Vorbis I specification +-- (no libvorbis code). Design: long blocks only (2048 samples; blocksize 0 is declared as 256 but never used), the +-- Vorbis window, the MDCT (codecs/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a +-- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality- +-- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer +-- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then +-- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian +-- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact +-- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws. +local Mdct = require("@formats/codecs/Mdct") +local Ogg = require("@formats/containers/Ogg") +local Tables = require("@formats/audio/vorbis/Tables") + +local Encode = {} + +local floor, log, exp, abs = math.floor, math.log, math.exp, math.abs +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +local N = 2048 +local N2 = 1024 +local PSIZE_PER_CHANNEL = 16 -- residue partitions hold 16 values per channel (libvorbis needs a multiple of ch) +local MULT = 2 -- floor1 multiplier (range 128) +local RANGE = 128 +local NCLASS = 6 + +-- ------------------------------------------------------------------------------------------------ LSB-first bit writer +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +local function newW(size: number): W + return { buf = buffer.create(size), pos = 0, acc = 0, cnt = 0 } +end + +local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc + v * POW[w.cnt + 1] + local cnt = w.cnt + n + local b, p = w.buf, w.pos + if p + 8 > buffer.len(b) then + local nb = buffer.create(buffer.len(b) * 2 + 64) + buffer.copy(nb, 0, b, 0, p) + b = nb + w.buf = nb + end + while cnt >= 8 do + local byte = acc % 256 + writeu8(b, p, byte) + p += 1 + acc = (acc - byte) / 256 + cnt -= 8 + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +local function finish(w: W): buffer + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out +end + +local function putString(w: W, s: string) + for i = 1, #s do + put(w, string.byte(s, i), 8) + end +end + +local function ilog(x: number): number + local n = 0 + while x > 0 do + n += 1 + x = floor(x / 2) + end + return n +end + +-- ------------------------------------------------------------------------------------------------ codebooks +type Book = { + dims: number, + entries: number, + lengths: { number }, + codes: { number }, -- bit-reversed codewords (ready for the LSB-first writer) + lookup: number, -- 0 or 1 + minimum: number, + delta: number, + values: number, -- lookup1 values per dimension +} + +-- Huffman code lengths for weights w[1..n] (all > 0), at most 24 bits long (weights are floored to keep it so) +local function huffmanLengths(w: { number }): { number } + local n = #w + local total = 0 + for i = 1, n do + total += w[i] + end + local lens = table.create(n, 0) + if n == 1 then + lens[1] = 1 + return lens + end + local minw = total * 2 ^ -20 + -- nodes: leaves 1..n then internal; a simple O(n^2)-free approach with two sorted queues + local order = table.create(n, 0) + for i = 1, n do + order[i] = i + end + local weight = table.create(2 * n, 0) + local parent = table.create(2 * n, 0) + for i = 1, n do + weight[i] = math.max(w[i], minw) + end + table.sort(order, function(a: number, b: number): boolean + if weight[a] ~= weight[b] then + return weight[a] < weight[b] + end + return a < b + end) + local q1, h1 = order, 1 -- leaves, ascending + local q2, h2, t2 = table.create(n, 0), 1, 0 -- internal nodes, created in ascending weight order + local nextId = n + local function pop(): number + local a = if h1 <= n then q1[h1] else nil + local b = if h2 <= t2 then q2[h2] else nil + if a and (not b or weight[a] <= weight[b]) then + h1 += 1 + return a + end + h2 += 1 + return b :: number + end + for _ = 1, n - 1 do + local a = pop() + local b = pop() + nextId += 1 + weight[nextId] = weight[a] + weight[b] + parent[a], parent[b] = nextId, nextId + t2 += 1 + q2[t2] = nextId + end + for i = 1, n do + local d, x = 0, i + while parent[x] ~= 0 do + x = parent[x] + d += 1 + end + lens[i] = d + end + return lens +end + +-- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes +local function assign(lens: { number }): { number } + local codes = table.create(#lens, 0) + local available = table.create(33, 0) + local first = true + for i, len in lens do + if len > 0 then + local code + if first then + first = false + code = 0 + for l = 1, len do + available[l + 1] = POW[33 - l] + 1 + end + else + local z = len + while z > 0 and available[z + 1] == 0 do + z -= 1 + end + code = available[z + 1] - 1 + available[z + 1] = 0 + for y = len, z + 1, -1 do + available[y + 1] = code + POW[33 - y] + 1 + end + end + -- the top len bits of the 32-bit left-aligned code, MSB first, reversed for the LSB-first writer + local msb = floor(code / POW[33 - len]) + local rev = 0 + for _ = 1, len do + rev = rev * 2 + msb % 2 + msb = floor(msb / 2) + end + codes[i] = rev + end + end + return codes +end + +local function makeBook(dims: number, entries: number, weight: (number) -> number, lookup: number, minimum: number, delta: number, values: number): Book + local w = table.create(entries, 0) + for e = 0, entries - 1 do + w[e + 1] = weight(e) + end + local lens = huffmanLengths(w) + return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values } +end + +-- a VQ book of `dims` dimensions over integer values -h .. h times `scale`, Laplacian weights exp(-|v| / s) +local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book + local values = 2 * h + 1 + local entries = values ^ dims + return makeBook(dims, entries, function(e: number): number + local wt = 1 + local x = e + for _ = 1, dims do + local v = x % values - h + x = x // values + wt *= exp(-abs(v) / s) * (if v == 0 then zeroBoost else 1) + end + return wt + end, 1, -h * scale, scale, values) +end + +local BOOK_FLOOR = makeBook(1, RANGE, function(e: number): number + return exp(-e / 7) + 0.002 +end, 0, 0, 0, 0) +local CLASS_W = { 0.30, 0.30, 0.20, 0.12, 0.06, 0.02 } +local BOOK_CLASS = makeBook(2, NCLASS * NCLASS, function(e: number): number + return CLASS_W[e % NCLASS + 1] * CLASS_W[e // NCLASS + 1] +end, 0, 0, 0, 0) +local BOOK_A = vqBook(4, 1, 1, 0.6, 2.5) -- |v| <= 1, 4 at a time (mostly zeros) +local BOOK_B = vqBook(2, 4, 1, 1.4, 1) -- |v| <= 4 +local BOOK_C = vqBook(2, 15, 1, 4, 1) -- |v| <= 15 +local BOOK_D = vqBook(2, 15, 16, 3, 1) -- multiples of 16 up to 240 +local BOOK_E = vqBook(2, 15, 256, 3, 1) -- multiples of 256 up to 3840 +local BOOKS = { BOOK_FLOOR, BOOK_CLASS, BOOK_A, BOOK_B, BOOK_C, BOOK_D, BOOK_E } +local FLOOR_BOOK, CLASS_BOOK, A_BOOK, B_BOOK, C_BOOK, D_BOOK, E_BOOK = 0, 1, 2, 3, 4, 5, 6 +-- the books of each residue class per pass (book numbers; -1 = none) +local CLASS_BOOKS = { + { -1, -1, -1 }, + { A_BOOK, -1, -1 }, + { B_BOOK, -1, -1 }, + { C_BOOK, -1, -1 }, + { D_BOOK, C_BOOK, -1 }, + { E_BOOK, D_BOOK, C_BOOK }, +} +local CLASS_MAX = { 0, 1, 4, 15, 255, 4095 } + +-- float32_pack (spec 9.2.2) of an integer-valued x +local function float32Pack(x: number): number + local sign = if x < 0 then 2147483648 else 0 + local m = abs(x) + local e = 788 + while m >= 2097152 do + m /= 2 + e += 1 + end + return sign + e * 2097152 + floor(m) +end + +local function writeBook(w: W, b: Book) + put(w, 0x564342, 24) + put(w, b.dims, 16) + put(w, b.entries, 24) + put(w, 0, 1) -- not ordered + put(w, 0, 1) -- not sparse + for i = 1, b.entries do + put(w, b.lengths[i] - 1, 5) + end + put(w, b.lookup, 4) + if b.lookup == 1 then + put(w, float32Pack(b.minimum), 32) + put(w, float32Pack(b.delta), 32) + local vb = ilog(b.values - 1) + put(w, vb - 1, 4) + put(w, 0, 1) -- sequence_p + for j = 0, b.values - 1 do + put(w, j, vb) + end + end +end + +local function putEntry(w: W, b: Book, e: number) + put(w, b.codes[e + 1], b.lengths[e + 1]) +end + +-- ------------------------------------------------------------------------------------------------ floor posts +-- x positions: 0, 1024, then 28 log-spaced points in bisection order (coarse first) so predictions are good +local POSTS: { number } = { 0, N2 } +do + local xs = {} + local seen = { [0] = true, [N2] = true } + for j = 0, 27 do + local x = floor(3 + 957 * (j / 27) ^ 2.2 + 0.5) -- 3 .. 960, denser at low frequencies + while seen[x] do + x += 1 + end + seen[x] = true + table.insert(xs, x) + end + table.sort(xs) + -- bisection order over the sorted list + local queue = { { 1, #xs } } + local qh = 1 + while qh <= #queue do + local r = queue[qh] + qh += 1 + if r[1] <= r[2] then + local m = (r[1] + r[2]) // 2 + table.insert(POSTS, xs[m]) + table.insert(queue, { r[1], m - 1 }) + table.insert(queue, { m + 1, r[2] }) + end + end +end +local NPOSTS = #POSTS -- 30 +local FLOOR_PARTS = (NPOSTS - 2) // 4 -- 7 partitions of one class with 4 dimensions +local SORTED: { number } = table.create(NPOSTS, 0) -- post indices (1-based) by increasing x +for i = 1, NPOSTS do + SORTED[i] = i +end +table.sort(SORTED, function(a: number, b: number): boolean + return POSTS[a] < POSTS[b] +end) +local LOW, HIGH = table.create(NPOSTS, 0), table.create(NPOSTS, 0) +for j = 3, NPOSTS do + local lo, hi = -1, 65536 + local x = POSTS[j] + for k = 1, j - 1 do + local xv = POSTS[k] + if xv > lo and xv < x then + LOW[j], lo = k, xv + end + if xv < hi and xv > x then + HIGH[j], hi = k, xv + end + end +end +-- the floor value (0..127) closest to an amplitude, through the spec's inverse dB table +local DB = table.create(RANGE, 0) +for y = 0, RANGE - 1 do + DB[y + 1] = 20 * math.log10(Tables[y * MULT + 1]) +end +local function yOf(db: number): number + local y = floor((db - DB[1]) / (DB[RANGE] - DB[1]) * (RANGE - 1) + 0.5) + return math.clamp(y, 0, RANGE - 1) +end + +local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number + local dy = y1 - y0 + local adx = x1 - x0 + local off = (abs(dy) * (x - x0)) // adx + return if dy < 0 then y0 - off else y0 + off +end + +-- render the decoder's floor curve for final Y values into F[1..N2] (only the posts the decoder marks used) +local function renderFloor(Y: { number }, used: { boolean }, F: { number }) + local lx, ly = 0, Y[1] * MULT + for q = 2, NPOSTS do + local j = SORTED[q] + if not used[j] then + continue + end + local hx, hy = POSTS[j], Y[j] * MULT + -- draw_line(lx, ly, hx, hy) + local dy = hy - ly + local adx = hx - lx + local ady = abs(dy) + local base = if dy < 0 then -(ady // adx) else ady // adx + local sy = if dy < 0 then base - 1 else base + 1 + ady -= abs(base) * adx + local x, y, err = lx, ly, 0 + local x1 = math.min(hx, N2) + if x < x1 then + F[x + 1] = Tables[y % 256 + 1] + x += 1 + while x < x1 do + err += ady + if err >= adx then + err -= adx + y += sy + else + y += base + end + F[x + 1] = Tables[y % 256 + 1] + x += 1 + end + end + lx, ly = hx, hy + end + for x = lx + 1, N2 do + F[x] = Tables[ly % 256 + 1] + end +end + +-- the coded value for target t at post j given the final values of its neighbours (spec 7.2.4 step 1, inverted) +local function floorVal(Y: { number }, j: number): number + local lo, hi = LOW[j], HIGH[j] + local pred = predict(POSTS[j], POSTS[lo], POSTS[hi], Y[lo], Y[hi]) + local t = Y[j] + local d = t - pred + if d == 0 then + return 0 + end + local highroom = RANGE - pred + local lowroom = pred + local room = if highroom < lowroom then highroom * 2 else lowroom * 2 + local cands = { if d > 0 then 2 * d else -2 * d - 1, d + lowroom, -d + highroom - 1 } + for _, v in cands do + if v > 0 and v < RANGE then + local got + if v >= room then + got = if highroom > lowroom then v - lowroom + pred else pred - v + highroom - 1 + elseif v % 2 == 1 then + got = pred - (v + 1) // 2 + else + got = pred + v // 2 + end + if got == t then + return v + end + end + end + return 0 -- unreachable for t in range; fall back to the prediction +end + +-- ------------------------------------------------------------------------------------------------ headers +local function identHeader(ch: number, rate: number, nominal: number): buffer + local w = newW(64) + put(w, 1, 8) + putString(w, "vorbis") + put(w, 0, 32) + put(w, ch, 8) + put(w, rate, 32) + put(w, 0, 32) + put(w, nominal, 32) + put(w, 0, 32) + put(w, 8, 4) -- blocksize 0: 256 + put(w, 11, 4) -- blocksize 1: 2048 + put(w, 1, 1) + return finish(w) +end + +local function commentHeader(vendor: string, tags: { [string]: string }): buffer + local w = newW(256) + put(w, 3, 8) + putString(w, "vorbis") + put(w, #vendor, 32) + putString(w, vendor) + local keys = {} + for k, v in tags do + if type(k) == "string" and type(v) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + put(w, #keys, 32) + for _, k in keys do + local name = if k == "track" then "TRACKNUMBER" else string.upper(k) + local s = name .. "=" .. tags[k] + put(w, #s, 32) + putString(w, s) + end + put(w, 1, 1) + return finish(w) +end + +local function setupHeader(ch: number): buffer + local w = newW(8192) + put(w, 5, 8) + putString(w, "vorbis") + -- codebooks + put(w, #BOOKS - 1, 8) + for _, b in BOOKS do + writeBook(w, b) + end + -- time domain placeholders + put(w, 0, 6) + put(w, 0, 16) + -- one floor 1 + put(w, 0, 6) + put(w, 1, 16) + put(w, FLOOR_PARTS, 5) + for _ = 1, FLOOR_PARTS do + put(w, 0, 4) -- class 0 + end + put(w, 3, 3) -- class 0: 4 dimensions + put(w, 0, 2) -- no subclasses + put(w, FLOOR_BOOK + 1, 8) -- its one subclass book (+1) + put(w, MULT - 1, 2) + put(w, 10, 4) -- rangebits: x in 0 .. 1024 + for j = 3, NPOSTS do + put(w, POSTS[j], 10) + end + -- one residue 2 + put(w, 0, 6) + put(w, 2, 16) + put(w, 0, 24) -- begin + put(w, N2 * ch, 24) -- end + put(w, PSIZE_PER_CHANNEL * ch - 1, 24) + put(w, NCLASS - 1, 6) + put(w, CLASS_BOOK, 8) + for c = 1, NCLASS do + local bits = 0 + for pass = 1, 3 do + if CLASS_BOOKS[c][pass] >= 0 then + bits += POW[pass] + end + end + put(w, bits % 8, 3) + if bits >= 8 then + put(w, 1, 1) + put(w, bits // 8, 5) + else + put(w, 0, 1) + end + end + for c = 1, NCLASS do + for pass = 1, 3 do + local b = CLASS_BOOKS[c][pass] + if b >= 0 then + put(w, b, 8) + end + end + end + -- one mapping + put(w, 0, 6) + put(w, 0, 16) + put(w, 0, 1) -- one submap + if ch == 2 then + put(w, 1, 1) + put(w, 0, 8) -- one coupling step + put(w, 0, 1) -- magnitude: channel 0 + put(w, 1, 1) -- angle: channel 1 + else + put(w, 0, 1) + end + put(w, 0, 2) + put(w, 0, 8) -- submap 0: time (unused) + put(w, 0, 8) -- floor 0 + put(w, 0, 8) -- residue 0 + -- one mode: long blocks + put(w, 0, 6) + put(w, 1, 1) + put(w, 0, 16) + put(w, 0, 16) + put(w, 0, 8) + put(w, 1, 1) -- framing + return finish(w) +end + +-- ------------------------------------------------------------------------------------------------ encoder +export type Source = { + sampleRate: number, + channels: number, + frames: number, + tags: { [string]: string }, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +export type Options = { + quality: number, -- -1 .. 10 + vendor: string, + serial: number, +} + +-- the residue of one partition: vectors of each pass for class c +local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number) + local b = CLASS_BOOKS[c][pass] + if b < 0 then + return + end + local book = BOOKS[b + 1] + local dims, h = book.dims, (book.values - 1) // 2 + local scale = book.delta + local values = book.values + local i = 0 + while i < psize do + local e = 0 + local m = 1 + for k = 0, dims - 1 do + local x = v[o + i + k + 1] + -- the part of x this pass carries (coarse passes take the rounded multiple of their scale) + local q + if pass < 3 and CLASS_BOOKS[c][pass + 1] >= 0 then + q = math.clamp(floor(x / scale + 0.5), -h, h) + else + q = math.clamp(x // scale, -h, h) + end + v[o + i + k + 1] = x - q * scale + e += (q + h) * m + m *= values + end + putEntry(w, book, e) + i += dims + end +end + +function Encode.encode(src: Source, opts: Options): (buffer?, string?) + local ch, rate = src.channels, src.sampleRate + local q = math.clamp(opts.quality, -1, 10) + local snrDb = 2 * q - 1 -- floor level below the band energy (at low frequencies; 8 dB less at the top) + local mux = Ogg.muxer({ pageSize = 4096 }) + local stream = mux:stream(opts.serial) + local nominal = floor(math.clamp(rate * ch * (0.6 + 0.12 * q), 32000, 500000)) + stream:packet(identHeader(ch, rate, nominal), 0, { flush = true }) + stream:packet(commentHeader(opts.vendor, src.tags), 0) + stream:packet(setupHeader(ch), 0, { flush = true }) + local plan = Mdct.new(N) :: Mdct.Plan + local win = Mdct.window("vorbis", N) :: { number } + -- input ring: per channel the samples of the current frame [k*1024 - 1024, k*1024 + 1024) + local frame = table.create(ch) + for c = 1, ch do + frame[c] = table.create(N, 0) + end + local blk = table.create(N, 0) + local X = table.create(ch) + local R = table.create(ch) + for c = 1, ch do + X[c] = table.create(N2, 0) + R[c] = table.create(N2, 0) + end + local F = table.create(N2, 0) + local Y = table.create(NPOSTS, 0) + local vals = table.create(NPOSTS, 0) + local used = table.create(NPOSTS, false) + local inter = table.create(N2 * ch, 0) + local psize = PSIZE_PER_CHANNEL * ch + local npart = N2 * ch // psize + local classes = table.create(npart + 2, 0) + local total = 0 + local srcDone = false + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local k = 0 + local lastWanted = -1 -- the last packet index needed (known once the input ends) + while true do + -- shift in the next 1024 input samples (zeros past the end) + for c = 1, ch do + local fr = frame[c] + table.move(fr, N2 + 1, N, 1) + end + local got = 0 + while got < N2 and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(N2 - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * ch * 4 + for c = 1, ch do + frame[c][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4) + end + end + got += take + pendN -= take + pendOff += take + end + for c = 1, ch do + local fr = frame[c] + for i = N2 + got + 1, N do + fr[i] = 0 + end + end + total += got + if srcDone and lastWanted < 0 then + lastWanted = (total + N2 - 1) // N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024)) + end + -- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024) + -- (frame k holds input [(k - 1) * 1024, (k + 1) * 1024): the shift above moved the window by 1024) + -- MDCT per channel + local energy = 0 + for c = 1, ch do + local fr = frame[c] + for i = 1, N do + blk[i] = fr[i] * win[i] + end + Mdct.forward(plan, blk, 1, X[c], 1, 1, 4 / N) + local xc = X[c] + for i = 1, N2 do + energy += xc[i] * xc[i] + end + end + local w = newW(2048) + put(w, 0, 1) -- audio packet + -- (one mode: 0 bits) long block, previous and next long + put(w, 1, 1) + put(w, 1, 1) + local silent = energy < 1e-18 + if silent then + for _ = 1, ch do + put(w, 0, 1) -- no floor: the channel is zero + end + else + -- the floor from the loudest channel's band energies at each post + for j = 1, NPOSTS do + local x = POSTS[j] + -- the band around x: halfway to the neighbouring posts in x order + local idx = table.find(SORTED, j) :: number + local lo = if idx > 1 then (POSTS[SORTED[idx - 1]] + x) // 2 else 0 + local hi = if idx < NPOSTS then (POSTS[SORTED[idx + 1]] + x) // 2 else N2 - 1 + if hi < lo then + hi = lo + end + local e = 0 + for c = 1, ch do + local xc = X[c] + local s = 0 + for i = lo + 1, math.min(hi + 1, N2) do + s += xc[i] * xc[i] + end + s /= (hi - lo + 1) + if s > e then + e = s + end + end + local db = if e > 0 then 10 * math.log10(e) - snrDb + 8 * x / N2 else -200 + Y[j] = yOf(db) + end + -- the decoder's step 2 flags: a point is drawn when its value or a later neighbour's value is nonzero + used[1], used[2] = true, true + for j = 3, NPOSTS do + local v = floorVal(Y, j) + vals[j] = v + used[j] = v ~= 0 + if v ~= 0 then + used[LOW[j]], used[HIGH[j]] = true, true + end + end + renderFloor(Y, used, F) + -- residues: X / F rounded, then coupling, then interleaving + for c = 1, ch do + local xc, rc = X[c], R[c] + for i = 1, N2 do + local v = floor(xc[i] / F[i] + 0.5) + rc[i] = math.clamp(v, -4095, 4095) + end + end + if ch == 2 then + local l, r = R[1], R[2] + for i = 1, N2 do + local a, b = l[i], r[i] + local m, an + if abs(a) > abs(b) then + m = a + an = if a > 0 then a - b else b - a + else + m = b + an = if b > 0 then a - b else b - a + end + -- keep the angle inside the books' range + l[i], r[i] = m, math.clamp(an, -4095, 4095) + end + end + for c = 1, ch do + local rc = R[c] + for i = 1, N2 do + inter[(i - 1) * ch + c] = rc[i] + end + end + -- floors + for _ = 1, ch do + put(w, 1, 1) + put(w, Y[1], 7) + put(w, Y[2], 7) + for j = 3, NPOSTS do + putEntry(w, BOOK_FLOOR, vals[j]) + end + end + -- residue classes + for p = 0, npart - 1 do + local m = 0 + for i = 1, psize do + local a = abs(inter[p * psize + i]) + if a > m then + m = a + end + end + local c = 1 + while CLASS_MAX[c] < m do + c += 1 + end + classes[p + 1] = c + end + classes[npart + 1] = 1 + for pass = 1, 3 do + for p = 0, npart - 1, 2 do + if pass == 1 then + putEntry(w, BOOK_CLASS, (classes[p + 1] - 1) * NCLASS + (classes[p + 2] - 1)) -- first partition: the high digit + end + writePartition(w, inter, p * psize, psize, classes[p + 1], pass) + if p + 1 < npart then + writePartition(w, inter, (p + 1) * psize, psize, classes[p + 2], pass) + end + end + end + end + local pk = finish(w) + local last = lastWanted >= 0 and k >= lastWanted + local granule = if k == 0 then 0 else math.min(k * N2, if lastWanted >= 0 then total else math.huge) + stream:packet(pk, granule, if last then { eos = true } else nil) + if last then + break + end + k += 1 + end + if src.err then + return nil, tostring(src.err) + end + return mux:finish(), nil +end + +-- the codebooks (tests check the Huffman lengths are a valid prefix code) +Encode.BOOKS = BOOKS + +return Encode diff --git a/src/Formats/audio/vorbis/Packet.luau b/src/Formats/audio/vorbis/Packet.luau new file mode 100644 index 0000000..ca69d79 --- /dev/null +++ b/src/Formats/audio/vorbis/Packet.luau @@ -0,0 +1,586 @@ +--!strict +--!native +--!optimize 2 +-- audio/vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1 +-- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/Mdct), windowing and overlap-add. +-- Floors, residues and coupling are ported from stb_vorbis 1.22 vorbis_decode_packet_rest / decode_residue / +-- do_floor / draw_line (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). The overlap follows libvorbis: +-- each packet after the first returns the n_prev/4 + n_cur/4 samples between the centres of the two windows, so +-- granule positions count exactly the samples returned (the first packet returns none). +-- +-- local st = Packet.new(ident, setup) +-- local n = Packet.decode(st, buf, offset, size) -- frames now in st.out[ch][1 .. n]; -1 = not an audio packet +-- Packet.reset(st) -- forget the overlap (after a seek / a gap) +-- local bs = Packet.blocksize(st, buf, offset, size) -- the packet's block size (0 = not audio), header bits only +-- Never throws: a damaged packet decodes as far as its bits go (the spec's end-of-packet rule) or returns -1. +local Codebook = require("@formats/audio/vorbis/Codebook") +local Setup = require("@formats/audio/vorbis/Setup") +local Tables = require("@formats/audio/vorbis/Tables") +local Mdct = require("@formats/codecs/Mdct") + +local Packet = {} + +local bits, decode = Codebook.bits, Codebook.decode +local ilog = Codebook.ilog +local INV_DB = Tables +local RANGE = { 256, 128, 86, 64 } + +export type State = { + channels: number, + n0: number, + n1: number, + setup: Setup.Setup, + plans: { [number]: Mdct.Plan }, + slopes: { [number]: { number } }, -- rising half-window of overlap length L (= blocksize / 2) + spec: { { number } }, -- per channel: n/2 spectral values (residue, then times the floor) + frame: { { number } }, -- per channel: n windowed time samples + tail: { { number } }, -- per channel: the previous frame from its centre on + tailLen: number, + prevN: number, -- the previous block size, 0 = no previous frame + out: { { number } }, -- per channel: the returned samples + finalY: { { number } }, + step2: { number }, + inter: { number }, -- residue type 2 interleaved scratch + zero: { boolean }, + reallyZero: { boolean }, + partClass: { { { number } } }, +} + +function Packet.new(id: Setup.Ident, setup: Setup.Setup): State? + local n0, n1, ch = id.blocksize0, id.blocksize1, id.channels + local plans: { [number]: Mdct.Plan } = {} + local slopes: { [number]: { number } } = {} + for _, n in { n0, n1 } do + local p = Mdct.new(n) + if not p then + return nil + end + plans[n] = p + local w = Mdct.window("vorbis", n) :: { number } + local half = table.create(n // 2, 0) + for i = 1, n // 2 do + half[i] = w[i] + end + slopes[n // 2] = half + end + local function arrays(len: number): { { number } } + local t = table.create(ch) + for c = 1, ch do + t[c] = table.create(len, 0) + end + return t + end + local partClass = table.create(ch) + for c = 1, ch do + partClass[c] = {} + end + return { + channels = ch, + n0 = n0, + n1 = n1, + setup = setup, + plans = plans, + slopes = slopes, + spec = arrays(n1 // 2), + frame = arrays(n1), + tail = arrays(n1 // 2), + tailLen = 0, + prevN = 0, + out = arrays(n1), + finalY = arrays(math.max(2, setup.maxFloorValues)), + step2 = table.create(math.max(2, setup.maxFloorValues), 0), + inter = table.create(n1 // 2 * ch, 0), + zero = table.create(ch, false), + reallyZero = table.create(ch, false), + partClass = partClass, + } +end + +function Packet.reset(st: State) + st.prevN = 0 + st.tailLen = 0 +end + +-- blocksize(st, buf, off, size) -> the block size of an audio packet (0 if not audio) +function Packet.blocksize(st: State, b: buffer, off: number, size: number): number + if size < 1 then + return 0 + end + local br = Codebook.reader(b, off, size) + if bits(br, 1) ~= 0 then + return 0 + end + local m = bits(br, st.setup.modeBits) + local mode = st.setup.modes[m + 1] + if not mode or br.eop then + return 0 + end + return if mode.blockflag == 1 then st.n1 else st.n0 +end + +-- ------------------------------------------------------------------------------------------------ floor 1 +local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number + local dy = y1 - y0 + local adx = x1 - x0 + local off = ((if dy < 0 then -dy else dy) * (x - x0)) // adx + return if dy < 0 then y0 - off else y0 + off +end + +-- multiply out[x0 .. x1) by the floor line from (x0, y0) to (x1, y1) (stb draw_line) +local function drawLine(out: { number }, x0: number, y0: number, x1: number, y1: number, n: number) + local dy = y1 - y0 + local adx = x1 - x0 + local ady = if dy < 0 then -dy else dy + local base = if dy < 0 then -(ady // adx) else ady // adx + local sy = if dy < 0 then base - 1 else base + 1 + ady -= (if base < 0 then -base else base) * adx + if x1 > n then + x1 = n + end + local x, y, err = x0, y0, 0 + if x < x1 then + out[x + 1] *= INV_DB[y % 256 + 1] + x += 1 + while x < x1 do + err += ady + if err >= adx then + err -= adx + y += sy + else + y += base + end + out[x + 1] *= INV_DB[y % 256 + 1] + x += 1 + end + end +end + +-- decode the floor of one channel into finalY (-1 = unused point); false = this channel is silent +local function floorDecode(st: State, br: Codebook.Br, g: Setup.Floor1, finalY: { number }): boolean + if bits(br, 1) == 0 then + return false + end + local books = st.setup.books + local range = RANGE[g.multiplier] + local yb = ilog(range) - 1 + finalY[1] = bits(br, yb) + finalY[2] = bits(br, yb) + local offset = 2 + for j = 1, g.partitions do + local pclass = g.partitionClass[j] + 1 + local cdim = g.classDims[pclass] + local cbits = g.classSubs[pclass] + local csub = 2 ^ cbits + local cval = 0 + if cbits > 0 then + cval = decode(br, books[g.classMaster[pclass] + 1]) + if cval < 0 then + return false + end + end + local subs = g.subBooks[pclass] + for _ = 1, cdim do + local book = subs[cval % csub + 1] + cval = cval // csub + if book >= 0 then + local v = decode(br, books[book + 1]) + if v < 0 then + return false + end + finalY[offset + 1] = v + else + finalY[offset + 1] = 0 + end + offset += 1 + end + end + if br.eop then + return false + end + -- step 1: amplitude value synthesis + local step2 = st.step2 + step2[1], step2[2] = 1, 1 + local xl, low, high = g.xlist, g.low, g.high + for j = 2, g.values - 1 do + local lo, hi = low[j + 1], high[j + 1] + local pred = predict(xl[j + 1], xl[lo + 1], xl[hi + 1], finalY[lo + 1], finalY[hi + 1]) + local val = finalY[j + 1] + local highroom = range - pred + local lowroom = pred + local room = if highroom < lowroom then highroom * 2 else lowroom * 2 + if val ~= 0 then + step2[lo + 1], step2[hi + 1], step2[j + 1] = 1, 1, 1 + if val >= room then + if highroom > lowroom then + finalY[j + 1] = val - lowroom + pred + else + finalY[j + 1] = pred - val + highroom - 1 + end + elseif val % 2 == 1 then + finalY[j + 1] = pred - (val + 1) // 2 + else + finalY[j + 1] = pred + val // 2 + end + else + step2[j + 1] = 0 + finalY[j + 1] = pred + end + end + for j = 1, g.values do + if step2[j] == 0 then + finalY[j] = -1 + end + end + return true +end + +-- multiply target[1 .. n2] by the floor curve (stb do_floor) +local function floorCurve(g: Setup.Floor1, finalY: { number }, target: { number }, n2: number) + local mult = g.multiplier + local lx, ly = 0, finalY[1] * mult + local sorted, xl = g.sorted, g.xlist + for q = 2, g.values do + local j = sorted[q] + 1 + local fy = finalY[j] + if fy >= 0 then + local hy = fy * mult + local hx = xl[j] + if lx ~= hx then + drawLine(target, lx, ly, hx, hy, n2) + end + lx, ly = hx, hy + end + end + if lx < n2 then + local v = INV_DB[ly % 256 + 1] + for j = lx + 1, n2 do + target[j] *= v + end + end +end + +-- ------------------------------------------------------------------------------------------------ residue +-- add the vectors of one partition to target at offset (0-based) .. offset + psize (bounded by limit) +local function partition(br: Codebook.Br, book: Codebook.Book, target: { number }, offset: number, psize: number, rtype: number, limit: number): boolean + local vq = book.vq + if not vq then + br.eop = true -- a scalar book in a vector context: invalid stream + return false + end + local dims = book.dims + if rtype == 0 then + local step = psize // dims + for k = 0, step - 1 do + local e = decode(br, book) + if e < 0 then + return false + end + local base = e * dims + for i = 0, dims - 1 do + local at = offset + k + i * step + if at < limit then + target[at + 1] += vq[base + i + 1] + end + end + end + else + local k = 0 + while k < psize do + local e = decode(br, book) + if e < 0 then + return false + end + local base = e * dims + local len = math.min(dims, psize - k) + local at = offset + k + for i = 0, len - 1 do + if at + i < limit then + target[at + i + 1] += vq[base + i + 1] + end + end + k += dims + end + end + return true +end + +-- decode residue r for the channels `targets` (nil = do not decode) of length n2 each +local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { { number } | false }, ch: number, n2: number) + local books = st.setup.books + local rtype = r.type + local cbook = books[r.classbook + 1] + local classwords = cbook.dims + for j = 1, ch do + local t = targets[j] + if t then + for i = 1, n2 do + (t :: { number })[i] = 0 + end + end + end + local any = false + for j = 1, ch do + if targets[j] then + any = true + end + end + if not any then + return + end + local psize = r.partSize + local rb = r.books + local classdata = r.classdata + if rtype == 2 and ch > 1 then + local total = n2 * ch + local inter = st.inter + for i = 1, total do + inter[i] = 0 + end + local lb = math.min(r.begin, total) + local le = math.min(r.finish, total) + local partRead = (le - lb) // psize + local pc = st.partClass[1] + local done = false + for pass = 1, 8 do + if done then + break + end + local pcount, classSet = 0, 1 + while pcount < partRead do + if pass == 1 then + local q = decode(br, cbook) + if q < 0 then + done = true + break + end + pc[classSet] = classdata[q + 1] + end + local cls = pc[classSet] + local i = 0 + while i < classwords and pcount < partRead do + local b = rb[cls[i + 1] + 1][pass] + if b >= 0 then + if not partition(br, books[b + 1], inter, r.begin + pcount * psize, psize, 1, total) then + done = true + break + end + end + i += 1 + pcount += 1 + end + if done then + break + end + classSet += 1 + end + end + -- de-interleave into the channels that are decoded + for j = 1, ch do + local t = targets[j] + if t then + local tt = t :: { number } + local v = j + for i = 1, n2 do + tt[i] = inter[v] + v += ch + end + end + end + return + end + local lb = math.min(r.begin, n2) + local le = math.min(r.finish, n2) + local partRead = (le - lb) // psize + local pcs = st.partClass + for pass = 1, 8 do + local pcount, classSet = 0, 1 + while pcount < partRead do + if pass == 1 then + for j = 1, ch do + if targets[j] then + local q = decode(br, cbook) + if q < 0 then + return + end + pcs[j][classSet] = classdata[q + 1] + end + end + end + local i = 0 + while i < classwords and pcount < partRead do + for j = 1, ch do + local t = targets[j] + if t then + local c = pcs[j][classSet][i + 1] + local b = rb[c + 1][pass] + if b >= 0 then + if not partition(br, books[b + 1], t :: { number }, r.begin + pcount * psize, psize, rtype, n2) then + return + end + end + end + end + i += 1 + pcount += 1 + end + classSet += 1 + end + end +end + +-- ------------------------------------------------------------------------------------------------ packet +-- decode(st, buf, off, size) -> frames returned in st.out (0 for the first packet), -1 for a non-audio / bad packet +function Packet.decode(st: State, b: buffer, off: number, size: number): number + if size < 1 then + return -1 + end + local setup = st.setup + local br = Codebook.reader(b, off, size) + if bits(br, 1) ~= 0 then + return -1 + end + local mode = setup.modes[bits(br, setup.modeBits) + 1] + if not mode then + return -1 + end + local n, prevLong, nextLong + if mode.blockflag == 1 then + n = st.n1 + prevLong = bits(br, 1) == 1 + nextLong = bits(br, 1) == 1 + else + n = st.n0 + prevLong, nextLong = false, false + end + if br.eop then + return -1 + end + local n2 = n // 2 + local n0 = st.n0 + local leftStart, leftEnd, rightStart, rightEnd + if mode.blockflag == 1 and not prevLong then + leftStart, leftEnd = (n - n0) // 4, (n + n0) // 4 + else + leftStart, leftEnd = 0, n2 + end + if mode.blockflag == 1 and not nextLong then + rightStart, rightEnd = (n * 3 - n0) // 4, (n * 3 + n0) // 4 + else + rightStart, rightEnd = n2, n + end + local map = setup.mappings[mode.mapping + 1] + local ch = st.channels + local spec, zero, reallyZero = st.spec, st.zero, st.reallyZero + -- floors + for c = 1, ch do + local s = map.mux[c] + 1 + local g = setup.floors[map.submapFloor[s] + 1] + local ok = floorDecode(st, br, g, st.finalY[c]) + zero[c] = not ok + reallyZero[c] = not ok + end + -- channels coupled to a non-silent channel are decoded too + for i = 1, map.couplingSteps do + local m, a = map.magnitude[i] + 1, map.angle[i] + 1 + if not zero[m] or not zero[a] then + zero[m], zero[a] = false, false + end + end + -- residues, per submap + for i = 1, map.submaps do + local targets: { { number } | false } = {} + local k = 0 + for c = 1, ch do + if map.mux[c] == i - 1 then + k += 1 + targets[k] = if zero[c] then false else spec[c] + end + end + residue(st, br, setup.residues[map.submapResidue[i] + 1], targets, k, n2) + end + -- inverse coupling + for i = map.couplingSteps, 1, -1 do + local m, a = spec[map.magnitude[i] + 1], spec[map.angle[i] + 1] + for j = 1, n2 do + local mv, av = m[j], a[j] + local m2, a2 + if mv > 0 then + if av > 0 then + m2, a2 = mv, mv - av + else + a2, m2 = mv, mv + av + end + else + if av > 0 then + m2, a2 = mv, mv + av + else + a2, m2 = mv, mv - av + end + end + m[j], a[j] = m2, a2 + end + end + -- floor curves, IMDCT, windows + local plan = st.plans[n] + local lslope = st.slopes[leftEnd - leftStart] + local rslope = st.slopes[rightEnd - rightStart] + for c = 1, ch do + local sp = spec[c] + local fr = st.frame[c] + if reallyZero[c] then + for j = 1, n do + fr[j] = 0 + end + else + local s = map.mux[c] + 1 + floorCurve(setup.floors[map.submapFloor[s] + 1], st.finalY[c], sp, n2) + Mdct.inverse(plan, sp, 1, 1, fr, 1) + for j = 1, leftStart do + fr[j] = 0 + end + local L = leftEnd - leftStart + for j = 0, L - 1 do + fr[leftStart + j + 1] *= lslope[j + 1] + end + local R = rightEnd - rightStart + for j = 0, R - 1 do + fr[rightStart + j + 1] *= rslope[R - j] + end + for j = rightEnd + 1, n do + fr[j] = 0 + end + end + end + -- overlap-add with the previous frame; return the samples between the two centres + local prevN = st.prevN + local count = 0 + if prevN > 0 then + count = prevN // 4 + n // 4 + local o = prevN // 4 - n // 4 -- this frame starts o samples after the previous centre + local tl = st.tailLen + for c = 1, ch do + local out, tail, fr = st.out[c], st.tail[c], st.frame[c] + for j = 0, count - 1 do + local v = if j < tl then tail[j + 1] else 0 + local fi = j - o + if fi >= 0 then + v += fr[fi + 1] + end + out[j + 1] = v + end + end + end + -- the new tail: this frame from its centre to the end of its window + local tl = rightEnd - n2 + for c = 1, ch do + local tail, fr = st.tail[c], st.frame[c] + for j = 1, tl do + tail[j] = fr[n2 + j] + end + end + st.tailLen = tl + st.prevN = n + return count +end + +return Packet diff --git a/src/Formats/audio/vorbis/Setup.luau b/src/Formats/audio/vorbis/Setup.luau new file mode 100644 index 0000000..e5eb312 --- /dev/null +++ b/src/Formats/audio/vorbis/Setup.luau @@ -0,0 +1,429 @@ +--!strict +--!native +-- audio/vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2): identification (channels, rate, +-- bitrates, blocksizes), comment (vendor + user comments -> tags) and setup (codebooks, floors, residues, mappings, +-- modes). Ported from stb_vorbis 1.22 start_decoder (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). +-- Floor 0 is rejected as unsupported, as stb_vorbis does (no encoder has produced it since 2000). +-- Never throws: every parser returns nil, message on bad data. +local Codebook = require("@formats/audio/vorbis/Codebook") + +local Setup = {} + +local bits, ilog = Codebook.bits, Codebook.ilog +local readu8, readu32 = buffer.readu8, buffer.readu32 + +export type Ident = { + channels: number, + sampleRate: number, + bitrateMax: number, + bitrateNominal: number, + bitrateMin: number, + blocksize0: number, + blocksize1: number, +} + +export type Floor1 = { + partitions: number, + partitionClass: { number }, -- 1-based list of class numbers (0-based values) + classDims: { number }, -- [class + 1] + classSubs: { number }, + classMaster: { number }, + subBooks: { { number } }, -- [class + 1][sub + 1] = book (0-based) or -1 + multiplier: number, + xlist: { number }, -- [j + 1] + values: number, + sorted: { number }, -- point indices (0-based) by increasing x + low: { number }, -- neighbours, [j + 1] (0-based indices) + high: { number }, +} + +export type Residue = { + type: number, + begin: number, + finish: number, + partSize: number, + classifications: number, + classbook: number, + books: { { number } }, -- [class + 1][pass + 1] = book or -1 + classdata: { { number } }, -- [classbook entry + 1][k + 1] = class +} + +export type Mapping = { + submaps: number, + couplingSteps: number, + magnitude: { number }, -- [step + 1] channel (0-based) + angle: { number }, + mux: { number }, -- [channel + 1] submap (0-based) + submapFloor: { number }, + submapResidue: { number }, +} + +export type Mode = { blockflag: number, mapping: number } + +export type Setup = { + books: { Codebook.Book }, + floors: { Floor1 }, + residues: { Residue }, + mappings: { Mapping }, + modes: { Mode }, + modeBits: number, + maxFloorValues: number, +} + +local function isVorbis(b: buffer, o: number, n: number, kind: number): boolean + return n >= 7 and readu8(b, o) == kind and buffer.readstring(b, o + 1, 6) == "vorbis" +end +Setup.isVorbis = isVorbis + +-- ident(buf, offset, size) -> Ident | nil, message +function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?) + if not isVorbis(b, o, n, 1) then + return nil, "not a Vorbis identification header" + end + if n < 30 then + return nil, "short identification header" + end + if readu32(b, o + 7) ~= 0 then + return nil, "Vorbis version " .. readu32(b, o + 7) + end + local ch = readu8(b, o + 11) + local rate = readu32(b, o + 12) + local bs = readu8(b, o + 28) + local l0, l1 = bs % 16, bs // 16 + if ch == 0 or rate == 0 then + return nil, "no channels or no sample rate" + end + if l0 < 6 or l0 > 13 or l1 < 6 or l1 > 13 or l0 > l1 then + return nil, "bad blocksizes" + end + if readu8(b, o + 29) % 2 == 0 then + return nil, "identification header framing bit not set" + end + return { + channels = ch, + sampleRate = rate, + bitrateMax = buffer.readi32(b, o + 16), + bitrateNominal = buffer.readi32(b, o + 20), + bitrateMin = buffer.readi32(b, o + 24), + blocksize0 = 2 ^ l0, + blocksize1 = 2 ^ l1, + }, + nil +end + +-- comment(buf, offset, size) -> vendor, { "KEY=value" } | nil, message +function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?) + if not isVorbis(b, o, n, 3) then + return nil, nil + end + local p, e = o + 7, o + n + if p + 4 > e then + return nil, nil + end + local vlen = readu32(b, p) + p += 4 + if vlen > e - p then + return nil, nil + end + local vendor = buffer.readstring(b, p, vlen) + p += vlen + local list = {} + if p + 4 > e then + return vendor, list + end + local count = readu32(b, p) + p += 4 + for _ = 1, count do + if p + 4 > e then + break + end + local len = readu32(b, p) + p += 4 + if len > e - p then + break + end + table.insert(list, buffer.readstring(b, p, len)) + p += len + end + return vendor, list +end + +-- setup(buf, offset, size, ident) -> Setup | nil, message +function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, string?) + if not isVorbis(b, o, n, 5) then + return nil, "not a Vorbis setup header" + end + local br = Codebook.reader(b, o + 7, n - 7) + local channels = id.channels + -- codebooks + local books: { Codebook.Book } = {} + local nbooks = bits(br, 8) + 1 + for i = 1, nbooks do + local book, err = Codebook.read(br) + if not book then + return nil, "codebook " .. (i - 1) .. ": " .. tostring(err) + end + books[i] = book + end + -- time domain transforms (placeholders) + local ntimes = bits(br, 6) + 1 + for _ = 1, ntimes do + if bits(br, 16) ~= 0 then + return nil, "bad time domain transform" + end + end + -- floors + local floors: { Floor1 } = {} + local maxValues = 0 + local nfloors = bits(br, 6) + 1 + for i = 1, nfloors do + local ftype = bits(br, 16) + if ftype == 0 then + return nil, "floor 0" + elseif ftype ~= 1 then + return nil, "bad floor type " .. ftype + end + local parts = bits(br, 5) + local pclass = table.create(parts, 0) + local maxClass = -1 + for j = 1, parts do + pclass[j] = bits(br, 4) + if pclass[j] > maxClass then + maxClass = pclass[j] + end + end + local cdims, csubs, cmaster, subBooks = {}, {}, {}, {} + for j = 1, maxClass + 1 do + cdims[j] = bits(br, 3) + 1 + csubs[j] = bits(br, 2) + cmaster[j] = -1 + if csubs[j] > 0 then + cmaster[j] = bits(br, 8) + if cmaster[j] >= nbooks then + return nil, "bad floor master book" + end + end + local sb = {} + for k = 1, 2 ^ csubs[j] do + sb[k] = bits(br, 8) - 1 + if sb[k] >= nbooks then + return nil, "bad floor subclass book" + end + end + subBooks[j] = sb + end + local mult = bits(br, 2) + 1 + local rangebits = bits(br, 4) + local xlist = { 0, 2 ^ rangebits } + for j = 1, parts do + local c = pclass[j] + for _ = 1, cdims[c + 1] do + table.insert(xlist, bits(br, rangebits)) + end + end + local values = #xlist + if values > 65 * 8 then + return nil, "too many floor points" + end + if br.eop then + return nil, "setup header ends in a floor" + end + local order = table.create(values, 0) + for j = 1, values do + order[j] = j - 1 + end + table.sort(order, function(a: number, c: number): boolean + return xlist[a + 1] < xlist[c + 1] + end) + for j = 1, values - 1 do + if xlist[order[j] + 1] == xlist[order[j + 1] + 1] then + return nil, "duplicate floor x" + end + end + local low, high = table.create(values, 0), table.create(values, 0) + for j = 2, values - 1 do + local lo, hi = -1, 65536 + local x = xlist[j + 1] + for k = 0, j - 1 do + local xv = xlist[k + 1] + if xv > lo and xv < x then + low[j + 1], lo = k, xv + end + if xv < hi and xv > x then + high[j + 1], hi = k, xv + end + end + end + floors[i] = { + partitions = parts, + partitionClass = pclass, + classDims = cdims, + classSubs = csubs, + classMaster = cmaster, + subBooks = subBooks, + multiplier = mult, + xlist = xlist, + values = values, + sorted = order, + low = low, + high = high, + } + if values > maxValues then + maxValues = values + end + end + -- residues + local residues: { Residue } = {} + local nres = bits(br, 6) + 1 + for i = 1, nres do + local rtype = bits(br, 16) + if rtype > 2 then + return nil, "bad residue type " .. rtype + end + local rbegin, rend = bits(br, 24), bits(br, 24) + local psize = bits(br, 24) + 1 + local ncls = bits(br, 6) + 1 + local cbook = bits(br, 8) + if rend < rbegin then + return nil, "residue end before begin" + end + if cbook >= nbooks then + return nil, "bad residue classbook" + end + local cascade = table.create(ncls, 0) + for j = 1, ncls do + local lowBits = bits(br, 3) + local highBits = if bits(br, 1) == 1 then bits(br, 5) else 0 + cascade[j] = highBits * 8 + lowBits + end + local rbooks = {} + for j = 1, ncls do + local row = table.create(8, -1) + local c = cascade[j] + for k = 1, 8 do + if c % 2 == 1 then + row[k] = bits(br, 8) + if row[k] >= nbooks then + return nil, "bad residue book" + end + end + c = c // 2 + end + rbooks[j] = row + end + if br.eop then + return nil, "setup header ends in a residue" + end + -- class numbers of each classbook entry (stb's classdata) + local cb = books[cbook + 1] + local cw = cb.dims + if cb.entries * cw > 2 ^ 22 then + return nil, "residue classbook too large" + end + local classdata = table.create(cb.entries) + for j = 0, cb.entries - 1 do + local row = table.create(cw, 0) + local tmp = j + for k = cw, 1, -1 do + row[k] = tmp % ncls + tmp = tmp // ncls + end + classdata[j + 1] = row + end + residues[i] = { + type = rtype, + begin = rbegin, + finish = rend, + partSize = psize, + classifications = ncls, + classbook = cbook, + books = rbooks, + classdata = classdata, + } + end + -- mappings + local mappings: { Mapping } = {} + local nmaps = bits(br, 6) + 1 + local chBits = ilog(channels - 1) + for i = 1, nmaps do + if bits(br, 16) ~= 0 then + return nil, "bad mapping type" + end + local submaps = if bits(br, 1) == 1 then bits(br, 4) + 1 else 1 + local steps = 0 + local mag, ang = {}, {} + if bits(br, 1) == 1 then + steps = bits(br, 8) + 1 + if steps > channels then + return nil, "too many coupling steps" + end + for k = 1, steps do + mag[k] = bits(br, chBits) + ang[k] = bits(br, chBits) + if mag[k] >= channels or ang[k] >= channels or mag[k] == ang[k] then + return nil, "bad coupling channels" + end + end + end + if bits(br, 2) ~= 0 then + return nil, "mapping reserved bits set" + end + local mux = table.create(channels, 0) + if submaps > 1 then + for j = 1, channels do + mux[j] = bits(br, 4) + if mux[j] >= submaps then + return nil, "bad channel mux" + end + end + end + local sf, sr = {}, {} + for j = 1, submaps do + bits(br, 8) + sf[j] = bits(br, 8) + sr[j] = bits(br, 8) + if sf[j] >= nfloors or sr[j] >= nres then + return nil, "bad submap floor / residue" + end + end + mappings[i] = { + submaps = submaps, + couplingSteps = steps, + magnitude = mag, + angle = ang, + mux = mux, + submapFloor = sf, + submapResidue = sr, + } + end + -- modes + local modes: { Mode } = {} + local nmodes = bits(br, 6) + 1 + for i = 1, nmodes do + local bf = bits(br, 1) + local wt, tt = bits(br, 16), bits(br, 16) + local m = bits(br, 8) + if wt ~= 0 or tt ~= 0 or m >= nmaps then + return nil, "bad mode" + end + modes[i] = { blockflag = bf, mapping = m } + end + if br.eop then + return nil, "setup header truncated" + end + if bits(br, 1) ~= 1 then + return nil, "setup header framing bit not set" + end + return { + books = books, + floors = floors, + residues = residues, + mappings = mappings, + modes = modes, + modeBits = ilog(nmodes - 1), + maxFloorValues = maxValues, + }, + nil +end + +return Setup diff --git a/src/Formats/audio/vorbis/Tables.luau b/src/Formats/audio/vorbis/Tables.luau new file mode 100644 index 0000000..435f719 --- /dev/null +++ b/src/Formats/audio/vorbis/Tables.luau @@ -0,0 +1,37 @@ +--!strict +-- audio/vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification, section 10.1, as in stb_vorbis 1.22, +-- public domain / MIT, licenses/stb_vorbis-LICENSE.txt). 256 values, index = floor value (1-based here). +return table.freeze({ + 1.0649863e-07, 1.1341951e-07, 1.2079015e-07, 1.2863978e-07, 1.3699951e-07, 1.4590251e-07, 1.5538408e-07, 1.6548181e-07, + 1.7623575e-07, 1.8768855e-07, 1.9988561e-07, 2.1287530e-07, 2.2670913e-07, 2.4144197e-07, 2.5713223e-07, 2.7384213e-07, + 2.9163793e-07, 3.1059021e-07, 3.3077411e-07, 3.5226968e-07, 3.7516214e-07, 3.9954229e-07, 4.2550680e-07, 4.5315863e-07, + 4.8260743e-07, 5.1396998e-07, 5.4737065e-07, 5.8294187e-07, 6.2082472e-07, 6.6116941e-07, 7.0413592e-07, 7.4989464e-07, + 7.9862701e-07, 8.5052630e-07, 9.0579828e-07, 9.6466216e-07, 1.0273513e-06, 1.0941144e-06, 1.1652161e-06, 1.2409384e-06, + 1.3215816e-06, 1.4074654e-06, 1.4989305e-06, 1.5963394e-06, 1.7000785e-06, 1.8105592e-06, 1.9282195e-06, 2.0535261e-06, + 2.1869758e-06, 2.3290978e-06, 2.4804557e-06, 2.6416497e-06, 2.8133190e-06, 2.9961443e-06, 3.1908506e-06, 3.3982101e-06, + 3.6190449e-06, 3.8542308e-06, 4.1047004e-06, 4.3714470e-06, 4.6555282e-06, 4.9580707e-06, 5.2802740e-06, 5.6234160e-06, + 5.9888572e-06, 6.3780469e-06, 6.7925283e-06, 7.2339451e-06, 7.7040476e-06, 8.2047000e-06, 8.7378876e-06, 9.3057248e-06, + 9.9104632e-06, 1.0554501e-05, 1.1240392e-05, 1.1970856e-05, 1.2748789e-05, 1.3577278e-05, 1.4459606e-05, 1.5399272e-05, + 1.6400004e-05, 1.7465768e-05, 1.8600792e-05, 1.9809576e-05, 2.1096914e-05, 2.2467911e-05, 2.3928002e-05, 2.5482978e-05, + 2.7139006e-05, 2.8902651e-05, 3.0780908e-05, 3.2781225e-05, 3.4911534e-05, 3.7180282e-05, 3.9596466e-05, 4.2169667e-05, + 4.4910090e-05, 4.7828601e-05, 5.0936773e-05, 5.4246931e-05, 5.7772202e-05, 6.1526565e-05, 6.5524908e-05, 6.9783085e-05, + 7.4317983e-05, 7.9147585e-05, 8.4291040e-05, 8.9768747e-05, 9.5602426e-05, 0.00010181521, 0.00010843174, 0.00011547824, + 0.00012298267, 0.00013097477, 0.00013948625, 0.00014855085, 0.00015820453, 0.00016848555, 0.00017943469, 0.00019109536, + 0.00020351382, 0.00021673929, 0.00023082423, 0.00024582449, 0.00026179955, 0.00027881276, 0.00029693158, 0.00031622787, + 0.00033677814, 0.00035866388, 0.00038197188, 0.00040679456, 0.00043323036, 0.00046138411, 0.00049136745, 0.00052329927, + 0.00055730621, 0.00059352311, 0.00063209358, 0.00067317058, 0.00071691700, 0.00076350630, 0.00081312324, 0.00086596457, + 0.00092223983, 0.00098217216, 0.0010459992, 0.0011139742, 0.0011863665, 0.0012634633, 0.0013455702, 0.0014330129, + 0.0015261382, 0.0016253153, 0.0017309374, 0.0018434235, 0.0019632195, 0.0020908006, 0.0022266726, 0.0023713743, + 0.0025254795, 0.0026895994, 0.0028643847, 0.0030505286, 0.0032487691, 0.0034598925, 0.0036847358, 0.0039241906, + 0.0041792066, 0.0044507950, 0.0047400328, 0.0050480668, 0.0053761186, 0.0057254891, 0.0060975636, 0.0064938176, + 0.0069158225, 0.0073652516, 0.0078438871, 0.0083536271, 0.0088964928, 0.009474637, 0.010090352, 0.010746080, + 0.011444421, 0.012188144, 0.012980198, 0.013823725, 0.014722068, 0.015678791, 0.016697687, 0.017782797, + 0.018938423, 0.020169149, 0.021479854, 0.022875735, 0.024362330, 0.025945531, 0.027631618, 0.029427276, + 0.031339626, 0.033376252, 0.035545228, 0.037855157, 0.040315199, 0.042935108, 0.045725273, 0.048696758, + 0.051861348, 0.055231591, 0.058820850, 0.062643361, 0.066714279, 0.071049749, 0.075666962, 0.080584227, + 0.085821044, 0.091398179, 0.097337747, 0.10366330, 0.11039993, 0.11757434, 0.12521498, 0.13335215, + 0.14201813, 0.15124727, 0.16107617, 0.17154380, 0.18269168, 0.19456402, 0.20720788, 0.22067342, + 0.23501402, 0.25028656, 0.26655159, 0.28387361, 0.30232132, 0.32196786, 0.34289114, 0.36517414, + 0.38890521, 0.41417847, 0.44109412, 0.46975890, 0.50028648, 0.53279791, 0.56742212, 0.60429640, + 0.64356699, 0.68538959, 0.72993007, 0.77736504, 0.82788260, 0.88168307, 0.9389798, 1.0, +}) diff --git a/src/Formats/audio/vorbis/init.luau b/src/Formats/audio/vorbis/init.luau new file mode 100644 index 0000000..e432adf --- /dev/null +++ b/src/Formats/audio/vorbis/init.luau @@ -0,0 +1,486 @@ +--!strict +-- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau +-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/Mdct, +-- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last +-- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position). +-- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2, +-- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level +-- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Encode (audio/vorbis/Encode, new code): a basic +-- Ogg Vorbis encoder from an Audio or a streamed Decoder (long blocks, floor 1, coupled residue 2, a fixed codebook +-- set, quality -1 .. 10). Not supported: floor 0 (Err.UNSUPPORTED, as in stb_vorbis; no encoder has produced it since +-- 2000), chained streams (the first logical Vorbis stream is decoded), short blocks in the encoder. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Setup = require("@formats/audio/vorbis/Setup") +local Packet = require("@formats/audio/vorbis/Packet") +local Encode = require("@formats/audio/vorbis/Encode") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Vorbis = { + name = "vorbis", + category = "audio", + extensions = { "ogg", "oga" }, + mime = { "audio/ogg", "audio/vorbis" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, +} + +export type OpenOptions = { + verify: boolean?, -- check the Ogg page CRCs (default true) +} +export type EncodeOptions = { + quality: number?, -- -1 .. 10 (default 3): the floor sits 2 * quality - 1 dB under the band energies (8 dB + -- less at the top of the spectrum), which sets the residue's quantization step + serial: number?, -- the Ogg stream serial number (default 0x464C5541) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TAG_KEYS = { tracknumber = "track", description = "comment" } + +local function tagsOf(comments: { string }): Types.Tags + local tags: Types.Tags = {} + for _, s in comments do + local eq = string.find(s, "=", 1, true) + if eq then + local k = string.lower(string.sub(s, 1, eq - 1)) + local v = string.sub(s, eq + 1) + k = TAG_KEYS[k] or k + tags[k] = if tags[k] then tags[k] .. "; " .. v else v + end + end + return tags +end + +-- the three headers -> ident, setup, vendor, tags | nil, Err +local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, Err.Err?) + local id, ierr = Setup.ident(h1.data, h1.offset, h1.size) + if not id then + return nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header") + end + local vendor, comments = Setup.comment(h2.data, h2.offset, h2.size) + if not vendor then + return nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header") + end + local setup, serr = Setup.setup(h3.data, h3.offset, h3.size, id) + if not setup then + local code = if serr == "floor 0" then Err.UNSUPPORTED else Err.CORRUPT + return nil, nil, nil, nil, Err.new(code, serr or "bad setup header") + end + return id, setup, vendor, tagsOf(comments or {}), nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Vorbis.sniff(r: Bytes.Reader): number + if r:remaining() < 35 or r:peek(4) ~= "OggS" then + return 0 + end + local b, p = r.buf, r.pos + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 > r.limit then + return 0 + end + return if buffer.readu8(b, d) == 1 and buffer.readstring(b, d + 1, 6) == "vorbis" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Vorbis.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local ch = d.channels + local parts, total = {}, 0 + while true do + local b, n = d:read(65536) + if n == 0 then + break + end + local copy = buffer.create(n * ch * 4) + buffer.copy(copy, 0, b, 0, n * ch * 4) + table.insert(parts, copy) + total += n + end + local a = Types.Audio.new(d.sampleRate, ch, total) + local o = 0 + for _, p in parts do + buffer.copy(a.samples, o, p) + o += buffer.len(p) + end + a.tags = d.tags + a.meta.source = d.source + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err +function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local q = o.quality or 3 + if type(q) ~= "number" or q ~= q or q < -1 or q > 10 then + return nil, Err.new(Err.ARG, "quality must be -1 .. 10") + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local serial = o.serial or 0x464C5541 + if type(serial) ~= "number" or serial ~= math.floor(serial) or serial < 0 or serial >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "serial must be a 32-bit unsigned integer") + end + local out, msg = Encode.encode(src :: any, { quality = q, vendor = "formats-luau Vorbis encoder", serial = serial }) + if not out then + return nil, Err.new(Err.CORRUPT, tostring(msg)) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +local Stream = {} +Stream.__index = Stream + +-- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi) +local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number) + local lo = math.max(g0, self.startG, self.skipTo) + if hi > g0 + count then + hi = g0 + count + end + if hi > lo then + table.insert(self.queue, { arrays, lo - g0 + 1, hi - g0, lo }) + end +end + +local function copyOut(self: any, count: number): { { number } } + local t = table.create(self.channels) + for c = 1, self.channels do + local src = self.st.out[c] + local a = table.create(count, 0) + table.move(src, 1, count, 1, a) + t[c] = a + end + return t +end + +-- decode packets until something is queued; false at the end of the stream +local function decodeMore(self: any): boolean + local reader, st = self.reader, self.st + while not self.ended do + local p = reader:nextPacket() + if p == nil then + self.ended = true + break + end + if p.gap then + Packet.reset(st) + self.syncing, self.pend, self.pendCount = true, {}, 0 + end + local count = Packet.decode(st, p.data, p.offset, p.size) + if count >= 0 then + local endG = if p.eos and p.granule >= 0 then p.granule else math.huge + if self.syncing then + if count > 0 then + table.insert(self.pend, { copyOut(self, count), count }) + self.pendCount += count + end + if p.granule >= 0 then + -- the position is known again: this packet's output ends at its granule + local g = p.granule - self.pendCount + if p.eos and self.pendCount > 0 then + g = math.max(g, self.pos) -- an end-trimmed last page: keep the running position + end + for _, c in self.pend do + push(self, c[1], g, c[2], endG) + g += c[2] + end + self.pos = g + self.syncing, self.pend, self.pendCount = false, {}, 0 + end + else + local g0 = self.pos + self.pos += count + if count > 0 then + push(self, st.out, g0, count, endG) + end + if p.granule >= 0 and not p.eos then + self.pos = p.granule + end + end + if p.eos then + self.ended = true + end + if #self.queue > 0 then + return true + end + end + end + return #self.queue > 0 +end + +function Stream.read(self: any, n: number, out: buffer?): (buffer, number) + local ch = self.channels + n = math.max(0, math.floor(n)) + local b = if out and buffer.len(out) >= n * ch * 4 then out else buffer.create(n * ch * 4) + local got = 0 + local writef32 = buffer.writef32 + while got < n do + local q = self.queue[1] + if q == nil then + if not decodeMore(self) then + break + end + q = self.queue[1] + end + local arrays, first, last = q[1], q[2], q[3] + local take = math.min(n - got, last - first + 1) + for c = 1, ch do + local a = arrays[c] + local o = got * ch * 4 + (c - 1) * 4 + for i = first, first + take - 1 do + writef32(b, o, a[i]) + o += ch * 4 + end + end + got += take + self.next = q[4] + take + if first + take > last then + table.remove(self.queue, 1) + else + q[2] = first + take + q[4] += take + end + end + if got > 0 then + self.skipTo = -math.huge + end + return b, got +end + +function Stream.position(self: any): number + return (self.next - self.startG) / self.sampleRate +end + +-- back to the first audio packet +local function restart(self: any) + local r = self.reader + r:rewind() + for _ = 1, 3 do + r:nextPacket() + end + Packet.reset(self.st) + self.pos = self.base + self.syncing, self.pend, self.pendCount = false, {}, 0 + self.ended = false + self.queue = {} +end + +function Stream.seek(self: any, seconds: number) + local target = self.startG + math.floor(math.max(0, seconds) * self.sampleRate + 0.5) + if target ~= target then + target = self.startG + end + if self.lastG >= 0 and target > self.lastG then + target = self.lastG + end + self.skipTo = target + self.next = target + local r = self.reader + local g = target - self.st.n1 + for _ = 1, 16 do + if g <= self.startG then + break + end + local G = r:seekGranule(g) + if G == nil or G < 0 then + break + end + -- decode forward to the next page boundary to learn the exact position + Packet.reset(self.st) + self.queue = {} + self.ended = false + self.syncing, self.pend, self.pendCount = true, {}, 0 + self.pos = G + local ok = false + while true do + local p = r:nextPacket() + if p == nil then + break + end + local count = Packet.decode(self.st, p.data, p.offset, p.size) + if count > 0 then + table.insert(self.pend, { copyOut(self, count), count }) + self.pendCount += count + end + if p.granule >= 0 then + if not p.eos then + local g0 = p.granule - self.pendCount + for _, c in self.pend do + push(self, c[1], g0, c[2], math.huge) + g0 += c[2] + end + self.pos = p.granule + self.syncing, self.pend, self.pendCount = false, {}, 0 + ok = true + end + break + end + end + if ok then + return + end + g = G - 1 -- the last page: start one page earlier + end + restart(self) + self.skipTo = target + self.next = target +end + +function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) + if not demux then + return nil, derr + end + local serial = demux:find("vorbis") + if serial == nil then + return nil, Err.new(Err.CORRUPT, "no Vorbis stream in the Ogg file") + end + local reader = demux:reader(serial) + local h1 = reader:nextPacket() + if h1 == nil then + return nil, Err.new(Err.TRUNCATED, "missing identification header") + end + local id0, ierr = Setup.ident(h1.data, h1.offset, h1.size) + if not id0 then + return nil, Err.new(Err.CORRUPT, ierr or "bad identification header") + end + local h2 = reader:nextPacket() + if h2 == nil then + return nil, Err.new(Err.TRUNCATED, "missing comment header") + end + local h2copy = { data = Ogg.copy(h2), offset = 0, size = h2.size } + local h3 = reader:nextPacket() + if h3 == nil then + return nil, Err.new(Err.TRUNCATED, "missing setup header") + end + local id, setup, vendor, tags, herr = headers(h1, h2copy, h3) + if not id then + return nil, herr + end + local st = Packet.new(id, setup) + if not st then + return nil, Err.new(Err.CORRUPT, "bad block sizes") + end + -- the granule of the first returned sample: the first granule page minus what its packets return + local base = 0 + do + local prev, sum = 0, 0 + while true do + local p = reader:nextPacket() + if p == nil then + break + end + local bs = Packet.blocksize(st, p.data, p.offset, p.size) + if bs > 0 then + if prev > 0 then + sum += prev // 4 + bs // 4 + end + prev = bs + end + if p.granule >= 0 then + base = p.granule - sum + if p.eos then + base = 0 -- one page holds the whole stream: the spec trims its end, not its start + end + break + end + end + end + local info = demux:stream(serial) + local lastG = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else -1 + local startG = math.max(base, 0) + local frames = if lastG >= 0 then math.max(0, lastG - startG) else 0 + local rate = id.sampleRate + local self = setmetatable({ + sampleRate = rate, + channels = id.channels, + frames = frames, + duration = frames / rate, + bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / rate)) else id.bitrateNominal, + tags = tags, + vendor = vendor, + ident = id, + source = { + format = "vorbis", + codec = "vorbis", + vendor = vendor, + blocksizes = { id.blocksize0, id.blocksize1 }, + nominalBitrate = id.bitrateNominal, + }, + demux = demux, + reader = reader, + st = st, + base = base, + startG = startG, + lastG = lastG, + pos = base, + next = startG, + skipTo = -math.huge, + queue = {}, + syncing = false, + pend = {}, + pendCount = 0, + ended = false, + }, Stream) + restart(self) + return self :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three +-- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet. +-- local pd = Vorbis.packetDecoder(h1, h2, h3) +-- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n] +-- pd:reset() -- after a seek +function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err?) + local function pk(b: buffer): any + return { data = b, offset = 0, size = buffer.len(b) } + end + local id, setup, vendor, tags, err = headers(pk(h1), pk(h2), pk(h3)) + if not id then + return nil, err + end + local st = Packet.new(id, setup) + if not st then + return nil, Err.new(Err.CORRUPT, "bad block sizes") + end + return { + sampleRate = id.sampleRate, + channels = id.channels, + vendor = vendor, + tags = tags, + out = st.out, + decode = function(_self: any, b: buffer, offset: number, size: number): number + if offset < 0 or size < 0 or offset + size > buffer.len(b) then + return -1 + end + return Packet.decode(st, b, offset, size) + end, + reset = function(_self: any) + Packet.reset(st) + end, + }, + nil +end + +return Vorbis diff --git a/src/Formats/codecs/Pcm/Convert.luau b/src/Formats/codecs/Pcm/Convert.luau new file mode 100644 index 0000000..5d88d6e --- /dev/null +++ b/src/Formats/codecs/Pcm/Convert.luau @@ -0,0 +1,308 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/Pcm). Integers map to +-- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the +-- classic Sun g711.c algorithm, written from the spec). +-- +-- Formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw (u8: offset binary). +-- Never throws: callers check ranges (Convert.SIZE[fmt] * count bytes) before calling. +local Convert = {} + +local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32 +local readf32, readf64, writef32, writef64 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writef64 +local writeu8, writeu16, writeu32, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei16, buffer.writei32 +local floor = math.floor +local byteswap = bit32.byteswap + +local SIZE: { [string]: number } = { + u8 = 1, + s8 = 1, + s16le = 2, + s16be = 2, + s24le = 3, + s24be = 3, + s32le = 4, + s32be = 4, + f32le = 4, + f32be = 4, + f64le = 8, + f64be = 8, + alaw = 1, + ulaw = 1, +} +Convert.SIZE = SIZE +-- the integer bit depth of each format (float: 32 / 64; G.711: 16 after expansion) +Convert.BITS = { + u8 = 8, + s8 = 8, + s16le = 16, + s16be = 16, + s24le = 24, + s24be = 24, + s32le = 32, + s32be = 32, + f32le = 32, + f32be = 32, + f64le = 64, + f64be = 64, + alaw = 16, + ulaw = 16, +} + +-- ------------------------------------------------------------------------------------------------ G.711 +local ALAW = table.create(256, 0) -- code -> linear s16 +local ULAW = table.create(256, 0) +for code = 0, 255 do + -- A-law + local a = bit32.bxor(code, 0x55) + local t = bit32.band(a, 0x0F) * 16 + local seg = bit32.rshift(bit32.band(a, 0x70), 4) + if seg == 0 then + t += 8 + elseif seg == 1 then + t += 0x108 + else + t = (t + 0x108) * 2 ^ (seg - 1) + end + ALAW[code + 1] = if bit32.band(a, 0x80) ~= 0 then t else -t + -- mu-law + local u = bit32.bxor(code, 0xFF) + local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4) + ULAW[code + 1] = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84 +end + +local SEG_AEND = { 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF } +local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF } +local function segment(v: number, ends: { number }): number + for i = 1, 8 do + if v <= ends[i] then + return i - 1 + end + end + return 8 +end + +-- linear s16 -> A-law code +local function alawEncode(pcm: number): number + local mask + local v = floor(pcm / 8) -- 13-bit magnitude domain + if v >= 0 then + mask = 0xD5 + else + mask = 0x55 + v = -v - 1 + end + local seg = segment(v, SEG_AEND) + local aval + if seg >= 8 then + aval = 0x7F + else + aval = seg * 16 + if seg < 2 then + aval += bit32.band(floor(v / 2), 0x0F) + else + aval += bit32.band(floor(v / 2 ^ seg), 0x0F) + end + end + return bit32.bxor(aval, mask) +end + +-- linear s16 -> mu-law code +local function ulawEncode(pcm: number): number + local v = floor(pcm / 4) -- 14-bit + local mask + if v < 0 then + v = -v + mask = 0x7F + else + mask = 0xFF + end + if v > 8159 then + v = 8159 + end + v += 0x21 + local seg = segment(v, SEG_UEND) + local uval + if seg >= 8 then + uval = 0x7F + else + uval = seg * 16 + bit32.band(floor(v / 2 ^ (seg + 1)), 0x0F) + end + return bit32.bxor(uval, mask) +end +Convert.alawEncode = alawEncode +Convert.ulawEncode = ulawEncode +Convert.ALAW = ALAW +Convert.ULAW = ULAW + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(src, so, fmt, count, dst, do_) -> true | false (unknown fmt): count samples at src[so] -> f32 at dst[do_] +function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean + if fmt == "s16le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi16(src, so + i * 2) / 32768) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local p = so + i * 2 + local v = readu8(src, p) * 256 + readu8(src, p + 1) + if v >= 32768 then + v -= 65536 + end + writef32(dst, d + i * 4, v / 32768) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, (readu8(src, so + i) - 128) / 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi8(src, so + i) / 128) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readu8(src, p) + readu8(src, p + 1) * 256 + readi8(src, p + 2) * 65536 + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readi8(src, p) * 65536 + readu8(src, p + 1) * 256 + readu8(src, p + 2) + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi32(src, so + i * 4) / 2147483648) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + local v = byteswap(readu32(src, so + i * 4)) + if v >= 2147483648 then + v -= 4294967296 + end + writef32(dst, d + i * 4, v / 2147483648) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readf64(src, so + i * 8)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + local p = so + i * 8 + writeu32(tmp, 0, byteswap(readu32(src, p + 4))) + writeu32(tmp, 4, byteswap(readu32(src, p))) + writef32(dst, d + i * 4, readf64(tmp, 0)) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ALAW[readu8(src, so + i) + 1] / 32768) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ULAW[readu8(src, so + i) + 1] / 32768) + end + else + return false + end + return true +end + +-- ------------------------------------------------------------------------------------------------ encode +local function q(x: number, s: number): number + local v = floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +-- encode(src, so, count, fmt, dst, do_) -> true | false: count f32 samples at src[so] -> fmt at dst[do_] +function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean + if fmt == "s16le" then + for i = 0, count - 1 do + writei16(dst, d + i * 2, q(readf32(src, so + i * 4), 32768)) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 32768) % 65536 + writeu16(dst, d + i * 2, (v % 256) * 256 + v // 256) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) + 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) % 256) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v % 256) + writeu8(dst, p + 1, (v // 256) % 256) + writeu8(dst, p + 2, v // 65536) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v // 65536) + writeu8(dst, p + 1, (v // 256) % 256) + writeu8(dst, p + 2, v % 256) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writei32(dst, d + i * 4, q(readf32(src, so + i * 4), 2147483648)) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(q(readf32(src, so + i * 4), 2147483648) % 4294967296)) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef64(dst, d + i * 8, readf32(src, so + i * 4)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + writef64(tmp, 0, readf32(src, so + i * 4)) + local p = d + i * 8 + writeu32(dst, p, byteswap(readu32(tmp, 4))) + writeu32(dst, p + 4, byteswap(readu32(tmp, 0))) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, alawEncode(q(readf32(src, so + i * 4), 32768))) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, ulawEncode(q(readf32(src, so + i * 4), 32768))) + end + else + return false + end + return true +end + +return Convert diff --git a/src/Formats/codecs/Pcm/init.luau b/src/Formats/codecs/Pcm/init.luau new file mode 100644 index 0000000..8d60d05 --- /dev/null +++ b/src/Formats/codecs/Pcm/init.luau @@ -0,0 +1,234 @@ +--!strict +-- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. +-- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one +-- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au, +-- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder. +-- +-- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else +-- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read +-- local audio = Pcm.collect(src) -- read everything into a Types.Audio +-- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder +-- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio +-- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer +-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/Pcm/Convert) +-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767] +-- local x = Pcm.fromInt(s16, 16) -- s / 32768 +-- +-- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw. +-- Never throws (a decoder's read that throws is caught and ends the stream). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Convert = require("@formats/codecs/Pcm/Convert") + +local Pcm = {} +Pcm.Convert = Convert + +export type Source = { + sampleRate: number, + channels: number, + frames: number, -- total frames, 0 = unknown (a streaming decoder without an index) + tags: Types.Tags, + -- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end) + read: (self: Source, n: number, out: buffer?) -> (buffer, number), + err: Err.Err?, -- set when the underlying decoder failed mid-stream +} + +local function audioRead(self: any, n: number, out: buffer?): (buffer, number) + local a = self._audio + local ch = a.channels + local left = a.frames - self._pos + if n > left then + n = left + end + if n <= 0 then + return out or buffer.create(0), 0 + end + local bytes = n * ch * 4 + local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) + buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes) + self._pos += n + return b, n +end + +local function decoderRead(self: any, n: number, out: buffer?): (buffer, number) + if self._done then + return out or buffer.create(0), 0 + end + local ok, b, got = pcall(self._dec.read, self._dec, n, out) + if not ok then + self._done = true + self.err = Err.new(Err.CORRUPT, "source decoder failed: " .. tostring(b)) + return out or buffer.create(0), 0 + end + if type(b) ~= "buffer" or type(got) ~= "number" or got <= 0 then + self._done = true + return out or buffer.create(0), 0 + end + local ch = self.channels + if buffer.len(b) < got * ch * 4 then + got = buffer.len(b) // (ch * 4) + end + return b, got +end + +-- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read) +function Pcm.source(v: any): (Source?, Err.Err?) + if type(v) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") + end + local sr, ch = v.sampleRate, v.channels + if type(sr) ~= "number" or sr <= 0 or sr ~= sr or type(ch) ~= "number" or ch < 1 or ch ~= math.floor(ch) then + return nil, Err.new(Err.ARG, "bad sampleRate or channels") + end + if v.kind == "audio" and type(v.samples) == "buffer" then + local frames = v.frames + if type(frames) ~= "number" or frames < 0 or buffer.len(v.samples) < frames * ch * 4 then + return nil, Err.new(Err.ARG, "the Audio's samples buffer is shorter than frames * channels * 4") + end + return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = audioRead, _audio = v, _pos = 0 } :: any, nil + end + if type(v.read) == "function" then + local frames = if type(v.frames) == "number" and v.frames > 0 then v.frames else 0 + return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } :: any, nil + end + return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") +end + +-- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames) +function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) + local ch = src.channels + local cap = math.max(src.frames, 4096) + local data = buffer.create(cap * ch * 4) + local total = 0 + local limit = maxFrames or 2 ^ 31 + local tmp: buffer? = nil + while true do + local b, n = src:read(16384, tmp) + if n <= 0 then + break + end + tmp = b + if total + n > limit then + return nil, Err.new(Err.LIMIT, string.format("more than %d frames", limit)) + end + if total + n > cap then + cap = math.max(cap * 2, total + n) + local nd = buffer.create(cap * ch * 4) + buffer.copy(nd, 0, data, 0, total * ch * 4) + data = nd + end + buffer.copy(data, total * ch * 4, b, 0, n * ch * 4) + total += n + end + if src.err then + return nil, src.err + end + local a = Types.Audio.new(src.sampleRate, ch, 0) + a.frames = total + if buffer.len(data) == total * ch * 4 then + a.samples = data + else + a.samples = buffer.create(total * ch * 4) + buffer.copy(a.samples, 0, data, 0, total * ch * 4) + end + a.tags = table.clone(src.tags) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ decoders +-- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming +-- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf) +function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: number, sampleRate: number, fmt: string, tags: Types.Tags?): (Types.Decoder?, Err.Err?) + local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + if channels < 1 or sampleRate <= 0 or frames < 0 or offset < 0 or offset + frames * channels * size > buffer.len(buf) then + return nil, Err.new(Err.ARG, "bad raw PCM layout") + end + local pos = 0 + local frameBytes = channels * size + local dec = { + sampleRate = sampleRate, + channels = channels, + frames = frames, + duration = frames / sampleRate, + bitrate = sampleRate * frameBytes * 8, + tags = tags or {}, + } + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.clamp(math.floor(n), 0, frames - pos) + local bytes = n * channels * 4 + local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) + if n > 0 then + Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0) + pos += n + end + return b, n + end + function dec.seek(_self: any, seconds: number) + local f = math.floor(seconds * sampleRate + 0.5) + pos = if f ~= f then 0 else math.clamp(f, 0, frames) + end + function dec.position(_self: any): number + return pos / sampleRate + end + return dec :: any, nil +end + +-- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples) +function Pcm.audioDecoder(a: Types.Audio): Types.Decoder + local d = Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) :: any + d.bitrate = a.sampleRate * a.channels * 32 + return d +end + +-- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples +function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?) + local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + local ch = src.channels + local total = 0 + local tmp: buffer? = nil + while true do + local b, n = src:read(8192, tmp) + if n <= 0 then + break + end + tmp = b + local at = w:reserve(n * ch * size) + Convert.encode(b, 0, n * ch, fmt, w.buf, at) + w.pos = at + n * ch * size + total += n + end + if src.err then + return nil, src.err + end + return total, nil +end + +-- ------------------------------------------------------------------------------------------------ conversions +-- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0) +function Pcm.toInt(x: number, bits: number): number + local s = 2 ^ (bits - 1) + local v = math.floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +-- fromInt(v, bits) -> v / 2^(bits-1) +function Pcm.fromInt(v: number, bits: number): number + return v / 2 ^ (bits - 1) +end + +return Pcm diff --git a/src/Formats/core/Md5.luau b/src/Formats/core/Md5.luau new file mode 100644 index 0000000..3ec4379 --- /dev/null +++ b/src/Formats/core/Md5.luau @@ -0,0 +1,164 @@ +--!strict +--!native +--!optimize 2 +-- core/Md5: MD5 (RFC 1321), incremental. Written from the RFC. Used by the FLAC encoder (STREAMINFO's MD5 of the PCM); +-- not for security. +-- +-- local h = Md5.new() +-- h:update(buf, offset?, length?) -- any number of times +-- local digest = h:digest() -- 16-byte string (the state is finished; make a new one to hash again) +-- Md5.hex(digest) / Md5.of(buf) -> hex string +-- Never throws (ranges are clamped to the buffer). +local Md5 = {} + +local band, bor, bxor, bnot, lrotate = bit32.band, bit32.bor, bit32.bxor, bit32.bnot, bit32.lrotate +local readu32, writeu32, writeu8 = buffer.readu32, buffer.writeu32, buffer.writeu8 + +local K = table.create(64, 0) +for i = 0, 63 do + K[i + 1] = math.floor(math.abs(math.sin(i + 1)) * 4294967296) % 4294967296 +end +local S = { + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, +} +local G = table.create(64, 0) +for i = 0, 63 do + if i < 16 then + G[i + 1] = i + elseif i < 32 then + G[i + 1] = (5 * i + 1) % 16 + elseif i < 48 then + G[i + 1] = (3 * i + 5) % 16 + else + G[i + 1] = (7 * i) % 16 + end +end + +export type State = { + a: number, + b: number, + c: number, + d: number, + block: buffer, -- 64-byte pending block + fill: number, + total: number, -- bytes hashed + update: (self: State, buf: buffer, offset: number?, length: number?) -> (), + digest: (self: State) -> string, +} + +local M = table.create(16, 0) + +local function compress(st: State, blk: buffer, o: number) + for i = 0, 15 do + M[i + 1] = readu32(blk, o + i * 4) + end + local a, b, c, d = st.a, st.b, st.c, st.d + for i = 0, 63 do + local f + if i < 16 then + f = bor(band(b, c), band(bnot(b), d)) + elseif i < 32 then + f = bor(band(d, b), band(bnot(d), c)) + elseif i < 48 then + f = bxor(b, c, d) + else + f = bxor(c, bor(b, bnot(d))) + end + local tmp = d + d = c + c = b + b = (b + lrotate((a + f + K[i + 1] + M[G[i + 1] + 1]) % 4294967296, S[i + 1])) % 4294967296 + a = tmp + end + st.a = (st.a + a) % 4294967296 + st.b = (st.b + b) % 4294967296 + st.c = (st.c + c) % 4294967296 + st.d = (st.d + d) % 4294967296 +end + +local function update(self: State, buf: buffer, offset: number?, length: number?) + local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + local len = math.clamp(length or (n - o), 0, n - o) + self.total += len + local blk = self.block + if self.fill > 0 then + local take = math.min(64 - self.fill, len) + buffer.copy(blk, self.fill, buf, o, take) + self.fill += take + o += take + len -= take + if self.fill == 64 then + compress(self, blk, 0) + self.fill = 0 + end + end + while len >= 64 do + compress(self, buf, o) + o += 64 + len -= 64 + end + if len > 0 then + buffer.copy(blk, 0, buf, o, len) + self.fill = len + end +end + +local function digest(self: State): string + local bits = self.total * 8 + local blk = self.block + local f = self.fill + writeu8(blk, f, 0x80) + f += 1 + if f > 56 then + buffer.fill(blk, f, 0, 64 - f) + compress(self, blk, 0) + f = 0 + end + buffer.fill(blk, f, 0, 56 - f) + writeu32(blk, 56, bits % 4294967296) + writeu32(blk, 60, math.floor(bits / 4294967296) % 4294967296) + compress(self, blk, 0) + self.fill = 0 + local out = buffer.create(16) + writeu32(out, 0, self.a) + writeu32(out, 4, self.b) + writeu32(out, 8, self.c) + writeu32(out, 12, self.d) + return buffer.tostring(out) +end + +function Md5.new(): State + return { + a = 0x67452301, + b = 0xEFCDAB89, + c = 0x98BADCFE, + d = 0x10325476, + block = buffer.create(64), + fill = 0, + total = 0, + update = update, + digest = digest, + } +end + +-- hex(digest) -> 32 lower-case hex digits +function Md5.hex(d: string): string + local out = table.create(#d) + for i = 1, #d do + out[i] = string.format("%02x", string.byte(d, i)) + end + return table.concat(out) +end + +-- of(buf, offset?, length?) -> hex digest +function Md5.of(buf: buffer, offset: number?, length: number?): string + local h = Md5.new() + h:update(buf, offset, length) + return Md5.hex(h:digest()) +end + +return Md5 diff --git a/tests/audio/aiff.luau b/tests/audio/aiff.luau new file mode 100644 index 0000000..079f34a --- /dev/null +++ b/tests/audio/aiff.luau @@ -0,0 +1,183 @@ +-- audio/aiff tests: files written by ffmpeg and sox in every sample format (AIFF 8 / 12 / 16 / 24 / 32-bit, AIFF-C +-- sowt / fl32 / fl64 / ulaw / alaw, 6 channels, text chunks) against ffmpeg's decode; streaming reads and seeks; +-- our encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz. +-- Fixtures: tools/fixtures/aiff.py. +local T = require("@tests/T") +local Aiff = require("@formats/audio/aiff") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/aiff_cases") +local Enc = require("@tests/gen/aiff_enc") +local Sig = require("@tests/gen/aiff_sig") + +local t = T.suite("aiff") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +-- max |a - b| over n f32 samples (a at byte ao, b at byte bo) +local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4)) + if d > m then + m = d + end + end + return m +end + +-- the contract +t:eq(Aiff.name, "aiff", "name") +t:eq(Aiff.category, "audio", "category") +t:check(Aiff.caps.decode and Aiff.caps.encode and table.find(Aiff.extensions, "aif") ~= nil, "caps / extensions") + +-- reference files: decode, stream, seek +for _, c in Cases do + local a, err = Aiff.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.kind == "audio" and a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + local ref = buffer.fromstring(c.ref) + local n = c.frames * c.channels + t:check(maxDiff(a.samples, 0, ref, 0, n) < 1e-6, c.name .. ": samples match ffmpeg") + -- streaming in odd chunks + local dec = Aiff.open(reader(c.data)) :: Types.Decoder + local got, out = 0, buffer.create(0) + local ok = true + while true do + local b, k = dec:read(777, out) + if k == 0 then + break + end + out = b + ok = ok and maxDiff(b, 0, ref, got * c.channels * 4, k * c.channels) < 1e-6 + got += k + end + t:check(ok and got == c.frames, c.name .. ": streamed reads") + dec:seek(1000 / c.rate) + t:check(math.abs(dec:position() - 1000 / c.rate) < 1e-9, c.name .. ": position") + local b, k = dec:read(50) + t:check(k == 50 and maxDiff(b, 0, ref, 1000 * c.channels * 4, 50 * c.channels) < 1e-6, c.name .. ": seek") +end +t:note("%d reference files match ffmpeg", #Cases) + +-- details of particular files +local function case(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end +do + local a = Aiff.decode(reader(case("ffmpeg-tags").data)) :: Types.Audio + t:eq(a.tags.title, "Song Name", "NAME chunk") + t:eq(a.tags.artist, "Some One", "AUTH chunk") + local fl = Aiff.decode(reader(case("ffmpeg-fl32").data)) :: Types.Audio + t:check(fl.meta.source.aifc and fl.meta.source.compression == "fl32", "fl32 meta") + -- a 12-bit sample size: samples sit left-justified in 16-bit containers + local s16 = case("sox-aiff-s16") + local q = string.find(s16.data, "COMM", 1, true) :: number + local d12 = string.sub(s16.data, 1, q + 13) .. "\0\12" .. string.sub(s16.data, q + 16) + local s12 = Aiff.decode(reader(d12)) :: Types.Audio + t:check(s12.meta.source.bitDepth == 12 and maxDiff(s12.samples, 0, buffer.fromstring(s16.ref), 0, s16.frames * 2) < 1e-6, "12-bit sample size") + local sw = Aiff.info(reader(case("ffmpeg-sowt").data)) + t:check(sw and sw.compression == "sowt" and sw.format == "s16le", "info: sowt") + -- inside a bigger buffer + local c = case("ffmpeg-s16be") + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 5, c.data) + local a2 = Aiff.decode(Bytes.reader(big, 5, #c.data)) :: Types.Audio + t:check(a2 and maxDiff(a2.samples, 0, buffer.fromstring(c.ref), 0, c.frames * c.channels) < 1e-6, "decode from a sub-range") + -- truncated sample data: the frames present + local cut = string.sub(c.data, 1, #c.data - 1001) + local a3 = Aiff.decode(reader(cut)) :: Types.Audio + t:check(a3 and a3.frames < c.frames and a3.frames > 0 and a3.meta.source.truncated, "truncated SSND") +end + +-- our encoder: ffmpeg decodes every sample format (fixture step), within the format's step; streamed == from Audio +local TOL = { s8 = 0.5 / 128, ["s16-mono"] = 0.5 / 32768, s16 = 0.5 / 32768, sowt16 = 0.5 / 32768, ["aifc-s16"] = 0.5 / 32768, s24 = 0.5 / 8388608, sowt24 = 0.5 / 8388608, s32 = 1e-7, f32 = 0, f64 = 0, ulaw = 0.04, alaw = 0.04 } +local sig = buffer.fromstring(Sig.data) +for _, e in Enc do + t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors") + t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate") + t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff)) + t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes") + local back = Aiff.decode(reader(e.data)) :: Types.Audio + t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file") + if e.channels == 2 then + t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip") + end +end +t:note("%d encoder outputs read back by ffmpeg and by us", #Enc) + +-- encoder: tags, odd sizes, errors +do + local a = Types.Audio.new(44100, 1, 3) + buffer.writef32(a.samples, 0, 0.5) + buffer.writef32(a.samples, 4, -1) + buffer.writef32(a.samples, 8, 2) -- clips + a.tags = { title = "odd", artist = "me", comment = "x" } + local b = Aiff.encode(a, { sampleFormat = "s8" }) :: buffer + local back = Aiff.decode(Bytes.reader(b)) :: Types.Audio + t:check(back.frames == 3 and back.tags.title == "odd" and back.tags.artist == "me" and back.tags.comment == "x", "odd length + tags") + t:check(buffer.readf32(back.samples, 0) == 0.5 and buffer.readf32(back.samples, 4) == -1 and buffer.readf32(back.samples, 8) == 127 / 128, "s8 values, clipping") + t:eq(buffer.len(b) % 2, 0, "chunks padded to even sizes") + t:check(Aiff.info(Bytes.reader(b)).sampleRate == 44100, "80-bit rate round trip") + local empty = Aiff.encode(Types.Audio.new(8000, 2, 0)) :: buffer + local e0 = Aiff.decode(Bytes.reader(empty)) + t:check(e0 and e0.frames == 0, "empty audio") + local _, e1 = Aiff.encode({} :: any) + t:check(e1 and e1.code == Err.ARG, "encode junk: ARG") + local _, e2 = Aiff.encode(a, { sampleFormat = "s12" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG") + local _, e3 = Aiff.encode(a, { sampleFormat = "f32", littleEndian = true }) + t:check(e3 and e3.code == Err.ARG, "littleEndian float: ARG") + local _, e5 = Aiff.encode(a, { sampleFormat = "s24", littleEndian = true }) + t:check(e5 and e5.code == Err.ARG, "littleEndian 24-bit: ARG") + t:eq(Aiff.sniff(Bytes.reader(b)), 1, "sniff") + t:eq(Aiff.sniff(reader("RIFF....WAVE")), 0, "sniff wav") + t:eq(Aiff.sniff(reader("")), 0, "sniff nothing") +end + +-- errors +do + local _, e = Aiff.decode(reader("FORM\0\0\0\4WAVE")) + t:check(e and e.code == Err.CORRUPT, "wrong FORM type: " .. tostring(e)) + local c = case("ffmpeg-fl32").data + local p = string.find(c, "fl32", 1, true) :: number + local ima = string.sub(c, 1, p - 1) .. "ima4" .. string.sub(c, p + 4) + local _, e2 = Aiff.decode(reader(ima)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "ima4: UNSUPPORTED: " .. tostring(e2)) + local _, e3 = Aiff.decode(reader(string.sub(c, 1, 30))) + t:check(e3 and (e3.code == Err.TRUNCATED or e3.code == Err.CORRUPT), "cut in COMM: " .. tostring(e3)) + local _, e4 = Aiff.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 10 }) + t:check(e4 and e4.code == Err.LIMIT, "maxFrames: LIMIT") +end + +-- fuzz +do + local samples = {} + for i, c in Cases do + if i % 3 == 1 then + table.insert(samples, string.sub(c.data, 1, 600)) + end + end + t:fuzz("decode", function(b: buffer) + return Aiff.decode(Bytes.reader(b)) + end, samples, { mutations = 30, keepHeader = 0 }) + t:fuzz("open + read", function(b: buffer) + local d = Aiff.open(Bytes.reader(b)) + if d then + d:read(100) + d:seek(0.001) + d:read(100) + end + return d + end, samples, { mutations = 10, garbage = 50 }) +end + +t:done() diff --git a/tests/audio/au.luau b/tests/audio/au.luau new file mode 100644 index 0000000..c38e8c5 --- /dev/null +++ b/tests/audio/au.luau @@ -0,0 +1,147 @@ +-- audio/au tests: files written by ffmpeg and sox in every encoding (8 / 16 / 24 / 32-bit, float, double, mu-law, +-- A-law, an annotation) against ffmpeg's decode; streaming reads and seeks; our encoder's output for every encoding +-- decoded by ffmpeg (fixture step) and by us; an unknown data size; errors; fuzz. Fixtures: tools/fixtures/au.py. +local T = require("@tests/T") +local Au = require("@formats/audio/au") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/au_cases") +local Enc = require("@tests/gen/au_enc") +local Sig = require("@tests/gen/au_sig") + +local t = T.suite("au") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4)) + if d > m then + m = d + end + end + return m +end +local function case(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +t:eq(Au.name, "au", "name") +t:eq(Au.category, "audio", "category") +t:check(Au.caps.decode and Au.caps.encode and table.find(Au.extensions, "snd") ~= nil, "caps / extensions") + +for _, c in Cases do + local a, err = Au.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + local ref = buffer.fromstring(c.ref) + t:check(maxDiff(a.samples, 0, ref, 0, c.frames * c.channels) < 1e-6, c.name .. ": samples match ffmpeg") + local dec = Au.open(reader(c.data)) :: Types.Decoder + local got, ok = 0, true + while true do + local b, k = dec:read(1000) + if k == 0 then + break + end + ok = ok and maxDiff(b, 0, ref, got * c.channels * 4, k * c.channels) < 1e-6 + got += k + end + t:check(ok and got == c.frames, c.name .. ": streamed reads") + dec:seek(700 / c.rate) + local b, k = dec:read(40) + t:check(k == 40 and maxDiff(b, 0, ref, 700 * c.channels * 4, 40 * c.channels) < 1e-6, c.name .. ": seek") +end +t:note("%d reference files match ffmpeg", #Cases) + +do + local a = Au.decode(reader(case("sox-comment").data)) :: Types.Audio + t:check(a.tags.comment ~= nil and string.find(a.tags.comment, "hello sun", 1, true) ~= nil, "annotation as comment") + -- an unknown data size (0xFFFFFFFF) runs to the end of the file + local c = case("ffmpeg-s16be") + local unk = string.sub(c.data, 1, 8) .. "\255\255\255\255" .. string.sub(c.data, 13) + local a2 = Au.decode(reader(unk)) :: Types.Audio + t:check(a2 and a2.frames == c.frames, "unknown data size") + local cut = Au.decode(reader(string.sub(c.data, 1, #c.data - 400))) :: Types.Audio + t:check(cut and cut.frames == c.frames - 100 and cut.meta.source.truncated, "truncated data") + local big = buffer.create(#c.data + 3) + buffer.writestring(big, 3, c.data) + local a3 = Au.decode(Bytes.reader(big, 3, #c.data)) :: Types.Audio + t:check(a3 and maxDiff(a3.samples, 0, buffer.fromstring(c.ref), 0, c.frames * 2) < 1e-6, "decode from a sub-range") +end + +local TOL = { s8 = 0.5 / 128, ["s16-mono"] = 0.5 / 32768, s16 = 0.5 / 32768, s24 = 0.5 / 8388608, s32 = 1e-7, f32 = 0, f64 = 0, ulaw = 0.04, alaw = 0.04 } +local sig = buffer.fromstring(Sig.data) +for _, e in Enc do + t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors") + t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate") + t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff)) + t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes") + local back = Au.decode(reader(e.data)) :: Types.Audio + t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file") + if e.channels == 2 then + t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip") + end +end +t:note("%d encoder outputs read back by ffmpeg and by us", #Enc) + +do + local a = Types.Audio.new(8000, 1, 2) + buffer.writef32(a.samples, 0, 0.25) + buffer.writef32(a.samples, 4, -0.25) + a.tags = { comment = "annotated!" } + local b = Au.encode(a) :: buffer + t:eq(bit32.byteswap(buffer.readu32(b, 4)) % 8, 0, "data offset is a multiple of 8") + local back = Au.decode(Bytes.reader(b)) :: Types.Audio + t:check(back.frames == 2 and back.tags.comment == "annotated!" and buffer.readf32(back.samples, 0) == 0.25, "comment + samples") + local _, e1 = Au.encode(42 :: any) + t:check(e1 and e1.code == Err.ARG, "encode junk: ARG") + local _, e2 = Au.encode(a, { sampleFormat = "u8" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG") + local frac = Types.Audio.new(8000.5, 1, 1) + local _, e3 = Au.encode(frac) + t:check(e3 and e3.code == Err.ARG, "fractional rate: ARG") + t:eq(Au.sniff(Bytes.reader(b)), 1, "sniff") + t:eq(Au.sniff(reader("FORM")), 0, "sniff other") + -- G.721 ADPCM (encoding 23): unsupported + local adpcm = string.sub(buffer.tostring(b), 1, 12) .. "\0\0\0\23" .. string.sub(buffer.tostring(b), 17) + local _, e4 = Au.decode(reader(adpcm)) + t:check(e4 and e4.code == Err.UNSUPPORTED, "encoding 23: UNSUPPORTED") + local _, e5 = Au.decode(reader(".snd\0\0\0\24")) + t:check(e5 and e5.code == Err.CORRUPT, "short header: CORRUPT") + local _, e6 = Au.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 5 }) + t:check(e6 and e6.code == Err.LIMIT, "maxFrames: LIMIT") +end + +do + local samples = {} + for i, c in Cases do + if i % 2 == 1 then + table.insert(samples, string.sub(c.data, 1, 400)) + end + end + t:fuzz("decode", function(b: buffer) + return Au.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) + t:fuzz("open + read", function(b: buffer) + local d = Au.open(Bytes.reader(b)) + if d then + d:read(64) + d:seek(1e9) + d:read(64) + d:seek(-1) + d:read(64) + end + return d + end, samples, { mutations = 10, garbage = 50 }) +end + +t:done() diff --git a/tests/audio/flac.luau b/tests/audio/flac.luau index c1d2305..3f0f9a3 100644 --- a/tests/audio/flac.luau +++ b/tests/audio/flac.luau @@ -22,7 +22,7 @@ for _, c in Cases do end t:eq(Flac.name, "flac", "name") -t:check(Flac.caps.decode and not Flac.caps.encode, "caps") +t:check(Flac.caps.decode and Flac.caps.encode, "caps") -- encode: ws-audio (tests/audio/flac_encode.luau) local seekChecks = 0 for _, fx in Cases do @@ -156,8 +156,8 @@ do t:check(a and a.frames == fx.frames, "F.audio.load") local d = F.audio.open(byName.s16_l3.data) t:check(d and d.frames == byName.s16_l3.frames, "F.audio.open") - local _, se = F.save(a, nil, { format = "flac" }) - t:check(se and se.code == Err.UNSUPPORTED, "F.save flac is read-only here: " .. tostring(se)) + local saved, se = F.save(a, nil, { format = "flac" }) -- the encoder (ws-audio) + t:check(saved and F.audio.load(saved).frames == fx.frames, "F.save flac: " .. tostring(se)) end -- a damaged frame is dropped, the rest decodes diff --git a/tests/audio/flac_encode.luau b/tests/audio/flac_encode.luau new file mode 100644 index 0000000..7a0f204 --- /dev/null +++ b/tests/audio/flac_encode.luau @@ -0,0 +1,109 @@ +-- audio/flac encoder tests: every fixture-step encode (levels 0-8, 1 / 2 / 6 channels, 8 / 12 / 16 / 20 / 24 bits, +-- odd lengths and block sizes, odd rates, seek tables, padding) passed `flac -t` and carries the MD5 of the quantized +-- input; sizes within 10% of libFLAC at the same level; each decodes bit-exactly through our own decoder; streaming +-- from a Decoder gives the same bytes; tags; option errors. Fixtures: tools/fixtures/flac_enc.py. +local T = require("@tests/T") +local Flac = require("@formats/audio/flac") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Enc = require("@tests/gen/flac_enc") +local Sigs = require("@tests/gen/flac_enc_sigs") + +local t = T.suite("flac_encode") + +local sigCache: { [string]: any } = {} +local function sig(name: string): Types.Audio + local s = sigCache[name] + if not s then + local m = Sigs[name] + s = Types.Audio.new(m.rate, m.channels, m.frames) + buffer.writestring(s.samples, 0, m.data) + sigCache[name] = s + end + return s +end + +t:check(Flac.caps.encode and Flac.encode ~= nil, "caps.encode") + +local worst = 0 +for _, e in Enc do + t:eq(e.flacTest, "", e.name .. ": flac -t") + t:eq(e.md5, e.wantMd5, e.name .. ": STREAMINFO MD5 = MD5 of the quantized input") + if e.refSize then + local ratio = e.size / e.refSize + worst = math.max(worst, ratio) + t:check(ratio < 1.1, string.format("%s: %d bytes, libFLAC %d (%.3f)", e.name, e.size, e.refSize, ratio)) + end + -- our decoder: bit-exact against the input quantized to e.bits + local a = sig(e.sig) + local back, err = Flac.decode(Bytes.reader(buffer.fromstring(e.data))) + t:check(back, e.name .. ": our decoder: " .. tostring(err)) + t:check(back.frames == a.frames and back.channels == a.channels and back.sampleRate == a.sampleRate, e.name .. ": format") + local s = 2 ^ (e.bits - 1) + local exact = true + for i = 0, a.frames * a.channels - 1 do + local want = math.clamp(math.floor(buffer.readf32(a.samples, i * 4) * s + 0.5), -s, s - 1) + if math.floor(buffer.readf32(back.samples, i * 4) * s + 0.5) ~= want then + exact = false + break + end + end + t:check(exact, e.name .. ": bit-exact round trip") + t:eq(back.meta.source.bitDepth, e.bits, e.name .. ": bits per sample") +end +t:note("%d encodes pass flac -t with the right MD5 and decode bit-exactly; worst size vs libFLAC %.3f", #Enc, worst) + +-- streaming: a Decoder source gives the same bytes as the Audio +do + local a = sig("flacsig_music_2_7000_44100") + local f1 = Flac.encode(a, { level = 5 }) :: buffer + local f2 = Flac.encode(Pcm.audioDecoder(a), { level = 5 }) :: buffer + t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source") + -- a decoder of our own output re-encodes to the same stream (its bit depth carries over) + local dec = Flac.open(Bytes.reader(f1)) :: any + local f3 = Flac.encode(dec, { level = 5 }) :: buffer + t:check(buffer.tostring(f3) == buffer.tostring(f1), "FLAC -> FLAC through the streaming decoder") +end + +-- tags, bit depth from the source +do + local a = Types.Audio.new(48000, 1, 3000) + for i = 0, 2999 do + buffer.writef32(a.samples, i * 4, math.floor(math.sin(i / 7) * 100) / 128) + end + a.tags = { title = "Tïtle", artist = "Artist", track = "3" } + a.meta.source = { format = "wav", bitDepth = 8 } + local f = Flac.encode(a) :: buffer + local back = Flac.decode(Bytes.reader(f)) :: Types.Audio + t:eq(back.meta.source.bitDepth, 8, "bit depth from meta.source") + -- (the absorbed FLAC decoder keeps Vorbis comment keys upper case) + local tags = back.tags :: any + t:eq(tags.title or tags.TITLE, "Tïtle", "title") + t:eq(tags.artist or tags.ARTIST, "Artist", "artist") + t:eq(tags.track or tags.TRACKNUMBER, "3", "track number") + local empty = Flac.encode(Types.Audio.new(44100, 2, 0)) :: buffer + local e0 = Flac.decode(Bytes.reader(empty)) + t:check(e0 and e0.frames == 0, "empty audio") +end + +-- errors +do + local a = Types.Audio.new(44100, 2, 10) + local function code(v: any, o: any): string? + local _, e = Flac.encode(v, o) + return e and e.code + end + t:eq(code({}, nil), Err.ARG, "junk value") + t:eq(code(a, { level = 9 }), Err.ARG, "level 9") + t:eq(code(a, { level = 2.5 }), Err.ARG, "level 2.5") + t:eq(code(a, { bits = 32 }), Err.ARG, "32 bits") + t:eq(code(a, { bits = 3 }), Err.ARG, "3 bits") + t:eq(code(a, { blockSize = 8 }), Err.ARG, "block size 8") + t:eq(code(Types.Audio.new(44100, 9, 1), nil), Err.ARG, "9 channels") + t:eq(code(Types.Audio.new(44100.5, 1, 1), nil), Err.ARG, "fractional rate") +end + +-- (the decoder's fuzz pass is in tests/audio/flac.luau; the encoder takes no untrusted bytes) +t:done() diff --git a/tests/audio/mp3.luau b/tests/audio/mp3.luau index f973803..9d4412a 100644 --- a/tests/audio/mp3.luau +++ b/tests/audio/mp3.luau @@ -82,7 +82,7 @@ local rand = T.rng(12345) t:eq(Mp3.name, "mp3", "name") t:eq(Mp3.category, "audio", "category") t:check(table.find(Mp3.extensions, "mp3") ~= nil and table.find(Mp3.extensions, "mp2") ~= nil, "extensions") -t:check(Mp3.caps.decode and not Mp3.caps.encode and Mp3.open ~= nil, "caps") +t:check(Mp3.caps.decode and Mp3.caps.encode and Mp3.open ~= nil, "caps") -- encode: ws-audio (tests/audio/mp3_encode.luau) -- ------------------------------------------------------------------------------------------------ decode vs references for _, c in Cases do @@ -487,8 +487,8 @@ do t:check(a and a.kind == "audio" and a.frames == 22050 and a.tags.title == "Test Title", "F.audio.load: " .. tostring(err)) local dec = F.audio.open(data) t:check(dec and dec.sampleRate == 44100 and dec.frames == 22050, "F.audio.open") - local _, serr = F.save(a, nil, { format = "mp3" }) - t:check(serr and serr.code == Err.UNSUPPORTED, "F.save mp3: read-only") + local saved, serr = F.save(a, nil, { format = "mp3" }) -- the layer III encoder (ws-audio) + t:check(saved and F.audio.load(saved).sampleRate == 44100, "F.save mp3: " .. tostring(serr)) end -- ------------------------------------------------------------------------------------------------ fuzz diff --git a/tests/audio/mp3_encode.luau b/tests/audio/mp3_encode.luau new file mode 100644 index 0000000..f710cc9 --- /dev/null +++ b/tests/audio/mp3_encode.luau @@ -0,0 +1,143 @@ +-- audio/mp3 encoder tests (layer III and layer II): every fixture-step encode (sample rates of MPEG-1 / 2 / 2.5, +-- bit rates 24 .. 384 kbps, stereo / joint / mono) decodes in ffmpeg without errors and in LAME, with the expected +-- length and an SNR over a per-bit-rate floor after aligning the decoder delay; our own decoder (the minimp3 port) +-- agrees; streaming from a Decoder gives the same bytes; the ID3v2 tag round-trips; option errors. +-- Fixtures: tools/fixtures/mp3_enc.py. +local T = require("@tests/T") +local Mp3 = require("@formats/audio/mp3") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Enc = require("@tests/gen/mp3_enc") +local Sigs = require("@tests/gen/mp3_enc_sigs") + +local t = T.suite("mp3_encode") + +local function audio(name: string): Types.Audio + local s = Sigs[name] + local a = Types.Audio.new(s.rate, s.channels, s.frames) + buffer.writestring(a.samples, 0, s.data) + return a +end + +-- SNR of y (delayed by lag frames) against x over frames [from, to) +local function snr(x: Types.Audio, y: Types.Audio, lag: number, from: number, to: number): number + local ch = x.channels + local sig, er = 0, 0 + for i = from, to - 1 do + local j = i + lag + if j >= 0 and j < y.frames then + for c = 0, ch - 1 do + local a = buffer.readf32(x.samples, (i * ch + c) * 4) + local b = buffer.readf32(y.samples, (j * y.channels + math.min(c, y.channels - 1)) * 4) + sig += a * a + er += (a - b) * (a - b) + end + end + end + if er == 0 then + return 200 + end + return if sig > 0 then 10 * math.log10(sig / er) else -200 +end + +-- the SNR floors (dB) on the music / sine / sweep signals, by layer and bit rate per channel +local function floorFor(e: any): number + if string.find(e.name, "silence", 1, true) then + return -math.huge + elseif string.find(e.name, "noise", 1, true) then + return 8 -- white noise has no spectral structure to exploit + end + local perCh = e.bitrate / (if e.mode == "mono" then 1 else 2) + local nyquistBand = e.rate <= 16000 -- low rates lose little to the encoder's band limit + if e.layer == 3 then + if perCh >= 64 then + return 14 + elseif perCh >= 32 or nyquistBand then + return 8 + end + return 4 + end + if perCh >= 96 then + return 14 + elseif perCh >= 48 then + return 8 + end + return 4 +end + +t:check(Mp3.caps.encode and Mp3.encode ~= nil, "caps.encode") + +local minByLayer = { [2] = math.huge, [3] = math.huge } +for _, e in Enc do + t:eq(e.ffErrors, "", e.name .. ": ffmpeg decodes without errors") + t:check(e.ffRate == e.rate, e.name .. ": rate") + t:check(e.ffChannels == (if e.mode == "mono" then 1 else 2), e.name .. ": channels") + -- the stream covers the input: the encoder adds one frame of flush and the filterbank delay + local spf = if e.layer == 3 and e.rate < 32000 then 576 else 1152 + t:check(e.ffFrames >= e.frames and e.ffFrames <= e.frames + 3 * spf, string.format("%s: %d decoded frames for %d", e.name, e.ffFrames, e.frames)) + local f = floorFor(e) + t:check(e.ffSnr >= f, string.format("%s: ffmpeg SNR %.1f dB (floor %g)", e.name, e.ffSnr, f)) + if e.lameSnr then + t:check(e.lameSnr >= f, string.format("%s: LAME SNR %.1f dB (floor %g)", e.name, e.lameSnr, f)) + end + if f > -math.huge then + minByLayer[e.layer] = math.min(minByLayer[e.layer], e.ffSnr) + end + -- our decoder agrees with ffmpeg + local x = audio(e.sig) + local y, err = Mp3.decode(Bytes.reader(buffer.fromstring(e.data))) + t:check(y, e.name .. ": our decoder: " .. tostring(err)) + if e.channels == y.channels then + local s = snr(x, y, e.ffLag, 200, x.frames) + t:check(s >= f and math.abs(s - e.ffSnr) < 3, string.format("%s: our decoder %.1f dB, ffmpeg %.1f dB", e.name, s, e.ffSnr)) + end +end +t:note("%d encodes: ffmpeg + LAME decode them; lowest SNR layer III %.1f dB, layer II %.1f dB", #Enc, minByLayer[3], minByLayer[2]) + +-- streaming, tags, defaults +do + local a = audio("music_2_44100") + local f1 = Mp3.encode(a, { bitrate = 128 }) :: buffer + local f2 = Mp3.encode(Pcm.audioDecoder(a), { bitrate = 128 }) :: buffer + t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source") + a.tags = { title = "Ünïcode title", artist = "An Artist", album = "Album", track = "4", comment = "made here" } + local f3 = Mp3.encode(a, { layer = 2 }) :: buffer + t:eq(buffer.readstring(f3, 0, 3), "ID3", "an ID3v2 tag in front") + local back = Mp3.open(Bytes.reader(f3)) :: any + t:eq(back.tags.title, "Ünïcode title", "title") + t:eq(back.tags.artist, "An Artist", "artist") + t:eq(back.tags.album, "Album", "album") + t:eq(back.tags.track, "4", "track") + t:eq(back.layer, 2, "layer II by default bit rate 192") + local f4 = Mp3.encode(a, { id3 = false }) :: buffer + t:check(buffer.readu8(f4, 0) == 0xFF, "id3 = false") + local m = Types.Audio.new(22050, 1, 3000) + local fm = Mp3.encode(m) :: buffer + local dm = Mp3.open(Bytes.reader(fm)) :: any + t:check(dm.channels == 1 and dm.sampleRate == 22050, "mono MPEG-2 default") + local empty = Mp3.encode(Types.Audio.new(44100, 2, 0)) :: buffer + t:check(empty and buffer.len(empty) > 0, "empty input: one flush frame") +end + +-- errors +do + local function code(v: any, o: any): string? + local _, e = Mp3.encode(v, o) + return e and e.code + end + local a = Types.Audio.new(44100, 2, 100) + t:eq(code({}, nil), Err.ARG, "junk") + t:eq(code(a, { layer = 1 }), Err.ARG, "layer I") + t:eq(code(a, { bitrate = 100 }), Err.ARG, "100 kbps") + t:eq(code(a, { mode = "dual" }), Err.ARG, "dual mode") + t:eq(code(Types.Audio.new(44000, 2, 10), nil), Err.ARG, "44 kHz") + t:eq(code(Types.Audio.new(8000, 2, 10), { layer = 2 }), Err.ARG, "layer II at 8 kHz") + t:eq(code(Types.Audio.new(44100, 3, 10), nil), Err.ARG, "3 channels") + t:eq(code(a, { layer = 2, bitrate = 32 }), Err.ARG, "layer II stereo at 32 kbps") + t:eq(code(Types.Audio.new(44100, 1, 10), { layer = 2, bitrate = 320 }), Err.ARG, "layer II mono at 320 kbps") +end + +-- (the decoder's fuzz pass is in tests/audio/mp3.luau; the encoders take no untrusted bytes) +t:done() diff --git a/tests/audio/voc.luau b/tests/audio/voc.luau new file mode 100644 index 0000000..129c6b6 --- /dev/null +++ b/tests/audio/voc.luau @@ -0,0 +1,129 @@ +-- audio/voc tests: files written by ffmpeg (type 1 + 8 blocks for 8-bit, type 9 otherwise) and sox against ffmpeg's +-- decode; silence / text / continuation blocks and repeat markers built here; streaming reads and seeks; our +-- encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz. +-- Fixtures: tools/fixtures/voc.py. +local T = require("@tests/T") +local Voc = require("@formats/audio/voc") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/voc_cases") +local Enc = require("@tests/gen/voc_enc") +local Sig = require("@tests/gen/voc_sig") + +local t = T.suite("voc") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4)) + if d > m then + m = d + end + end + return m +end + +t:eq(Voc.name, "voc", "name") +t:eq(Voc.category, "audio", "category") +t:check(Voc.caps.decode and Voc.caps.encode, "caps") + +for _, c in Cases do + local a, err = Voc.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.sampleRate == c.rate and a.channels == c.channels, string.format("%s: format %d Hz x %d, want %d x %d", c.name, a.sampleRate, a.channels, c.rate, c.channels)) + t:eq(a.frames, c.frames, c.name .. ": frames") + local ref = buffer.fromstring(c.ref) + t:check(maxDiff(a.samples, 0, ref, 0, c.frames * c.channels) < 1e-6, c.name .. ": samples match ffmpeg") + local dec = Voc.open(reader(c.data)) :: Types.Decoder + dec:seek(500 / c.rate) + local b, k = dec:read(64) + t:check(k == 64 and maxDiff(b, 0, ref, 500 * c.channels * 4, 64 * c.channels) < 1e-6, c.name .. ": seek") +end +t:note("%d reference files match ffmpeg", #Cases) + +-- hand-built blocks: text, type 1 u8, silence, continuation, repeat markers, terminator +do + local hdr = "Creative Voice File\26\26\0\10\1\41\17" + local function blk(typ: number, payload: string): string + local n = #payload + return string.char(typ, n % 256, (n // 256) % 256, n // 65536) .. payload + end + local data = hdr + .. blk(5, "made by hand\0") + .. blk(1, string.char(156, 0) .. string.char(128, 192, 64)) -- 10 kHz, 3 samples + .. blk(3, string.char(4, 0, 156)) -- 5 frames of silence + .. blk(6, string.char(2, 0)) -- repeat start (ignored) + .. blk(2, string.char(255, 0)) -- continuation + .. blk(7, "") -- repeat end + .. blk(4, string.char(1, 0)) -- marker + .. "\0" + local a, err = Voc.decode(reader(data)) + t:check(a, "hand-built: " .. tostring(err)) + t:check(a.sampleRate == 10000 and a.channels == 1 and a.frames == 10, "hand-built: 10 kHz, 3 + 5 + 2 frames") + t:eq(a.tags.comment, "made by hand", "text block") + local want = { 0, 0.5, -0.5, 0, 0, 0, 0, 0, 127 / 128, -1 } + local ok = true + for i, v in want do + ok = ok and buffer.readf32(a.samples, (i - 1) * 4) == v + end + t:check(ok, "hand-built samples") + -- no terminator, a block cut short: the data present + local cut = Voc.decode(reader(string.sub(data, 1, 26 + 17 + 4 + 2 + 2))) + t:check(cut and cut.frames == 2 and cut.meta.source.truncated, "cut in a block") + -- Creative ADPCM: unsupported + local _, e = Voc.decode(reader(hdr .. blk(1, string.char(156, 1) .. "\0\0") .. "\0")) + t:check(e and e.code == Err.UNSUPPORTED, "ADPCM: UNSUPPORTED") + local _, e2 = Voc.decode(reader(hdr .. blk(2, "\0\0") .. "\0")) + t:check(e2 and e2.code == Err.CORRUPT, "continuation first: CORRUPT") + local _, e3 = Voc.decode(reader(hdr .. "\0")) + t:check(e3 and e3.code == Err.CORRUPT, "no sound: CORRUPT") + local _, e4 = Voc.decode(reader("Creative Voice Fil")) + t:check(e4 and e4.code == Err.CORRUPT, "short: CORRUPT") + t:eq(Voc.sniff(reader(data)), 1, "sniff") + t:eq(Voc.sniff(reader(".snd")), 0, "sniff other") +end + +local TOL = { s16 = 0.5 / 32768, ["s16-mono"] = 0.5 / 32768, u8 = 0.5 / 128, ulaw = 0.04, alaw = 0.04 } +local sig = buffer.fromstring(Sig.data) +for _, e in Enc do + t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors") + t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate") + t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff)) + t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes") + local back = Voc.decode(reader(e.data)) :: Types.Audio + t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file") + if e.channels == 2 then + t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip") + end +end +t:note("%d encoder outputs read back by ffmpeg and by us", #Enc) + +do + local a = Types.Audio.new(22050, 2, 1) + a.tags = { comment = "hi" } + local b = Voc.encode(a) :: buffer + local back = Voc.decode(Bytes.reader(b)) :: Types.Audio + t:check(back.frames == 1 and back.tags.comment == "hi", "one frame + comment") + local _, e1 = Voc.encode(nil :: any) + t:check(e1 and e1.code == Err.ARG, "encode nil: ARG") + local _, e2 = Voc.encode(a, { sampleFormat = "s24" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG") + local _, e3 = Voc.decode(reader(Cases[1].data), { maxFrames = 5 }) + t:check(e3 and e3.code == Err.LIMIT, "maxFrames: LIMIT") +end + +do + local samples = {} + for _, c in Cases do + table.insert(samples, string.sub(c.data, 1, 300)) + end + t:fuzz("decode", function(b: buffer) + return Voc.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) +end + +t:done() diff --git a/tests/audio/vorbis.luau b/tests/audio/vorbis.luau new file mode 100644 index 0000000..2cc5c01 --- /dev/null +++ b/tests/audio/vorbis.luau @@ -0,0 +1,193 @@ +-- audio/vorbis tests: oggenc / ffmpeg streams (qualities -1 .. 10, managed bitrate, 8 .. 96 kHz, mono / stereo / 5.1, +-- transients, silence, tags, sub-block lengths) against oggdec (libvorbisfile: sample counts and 16-bit samples, so +-- start / end trimming is exact) and ffmpeg's f32 decode (SNR); streaming reads; seeking (sample-exact against the +-- reference at the target); the packet-level decoder; errors; fuzz. Fixtures: tools/fixtures/vorbis.py. +local T = require("@tests/T") +local Vorbis = require("@formats/audio/vorbis") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Cases = require("@tests/gen/vorbis_cases") + +local t = T.suite("vorbis") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +local function s16(x: number): number + local v = math.floor(x * 32768 + 0.5) + return math.clamp(v, -32768, 32767) +end +-- the largest |our sample as s16 - oggdec's| over n samples of ours at byte a0 against ref16 from sample r0 +local function maxDiff16(a: buffer, a0: number, ref: buffer, r0: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(s16(buffer.readf32(a, a0 + i * 4)) - buffer.readi16(ref, (r0 + i) * 2)) + if d > m then + m = d + end + end + return m +end +local function snr(a: buffer, ref: buffer, n: number): number + local sig, er = 0, 0 + for i = 0, n - 1 do + local x = buffer.readf32(ref, i * 4) + local d = x - buffer.readf32(a, i * 4) + sig += x * x + er += d * d + end + if er == 0 then + return 200 + end + return if sig > 0 then 10 * math.log10(sig / er) else -200 +end + +t:eq(Vorbis.name, "vorbis", "name") +t:eq(Vorbis.category, "audio", "category") +t:check(Vorbis.caps.decode and Vorbis.open ~= nil, "caps") + +local minSnr = math.huge +for _, c in Cases do + local a, err = Vorbis.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames = oggdec's") + t:eq(a.frames, c.inputFrames, c.name .. ": frames = the encoder's input") + local ref16 = buffer.fromstring(c.ref16) + local n = c.frames * c.channels + local d = maxDiff16(a.samples, 0, ref16, 0, n) + t:check(d <= 1, string.format("%s: within 1 LSB of oggdec (max %d)", c.name, d)) + if c.ffRef then + local s = snr(a.samples, buffer.fromstring(c.ffRef), n) + minSnr = math.min(minSnr, s) + t:check(s > 100, string.format("%s: SNR vs ffmpeg %.1f dB", c.name, s)) + end + -- streaming in odd chunks gives the same samples + local dec = Vorbis.open(reader(c.data)) :: Types.Decoder + t:eq(dec.frames, c.frames, c.name .. ": Decoder.frames") + local got, ok = 0, true + while true do + local b, k = dec:read(1013) + if k == 0 then + break + end + for i = 0, k * c.channels - 1, 7 do + ok = ok and buffer.readf32(b, i * 4) == buffer.readf32(a.samples, got * c.channels * 4 + i * 4) + end + got += k + end + t:check(ok and got == c.frames, c.name .. ": streamed reads") + -- seeks: sample-exact against the full decode + for _, frac in { 0.5, 0.1, 0.93, 0 } do + local target = math.floor(c.frames * frac) + dec:seek(target / c.rate) + t:check(math.abs(dec:position() - target / c.rate) < 1e-9, c.name .. ": position after seek") + local b, k = dec:read(300) + local want = math.min(300, c.frames - target) + t:eq(k, want, string.format("%s: frames after seek to %d", c.name, target)) + local same = true + for i = 0, k * c.channels - 1 do + same = same and buffer.readf32(b, i * 4) == buffer.readf32(a.samples, (target * c.channels + i) * 4) + end + t:check(same, string.format("%s: samples after seek to %d", c.name, target)) + end +end +t:note("%d streams match oggdec (counts, 1 LSB) and ffmpeg (min SNR %.1f dB)", #Cases, minSnr) + +local function case(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +-- tags, meta, sniff, sub-range +do + local c = case("q2-stereo-32k-tags") + local dec = Vorbis.open(reader(c.data)) :: any + t:eq(dec.tags.title, "A Title", "title tag") + t:eq(dec.tags.artist, "An Artist", "artist tag") + t:eq(dec.tags.album, "The Album", "album tag") + t:eq(dec.tags.track, "7", "track tag") + t:eq(dec.tags.comment, "hello vorbis", "comment tag") + t:check(type(dec.vendor) == "string" and string.find(dec.vendor, "Xiph", 1, true) ~= nil, "vendor") + t:check(dec.bitrate > 0 and math.abs(dec.duration - c.frames / c.rate) < 1e-9, "bitrate / duration") + t:eq(Vorbis.sniff(reader(c.data)), 1, "sniff") + t:eq(Vorbis.sniff(reader("OggS")), 0, "sniff short") + t:eq(Vorbis.sniff(reader("RIFF")), 0, "sniff other") + local big = buffer.create(#c.data + 11) + buffer.writestring(big, 11, c.data) + local a = Vorbis.decode(Bytes.reader(big, 11, #c.data)) + t:check(a and a.frames == c.frames, "decode from a sub-range") +end + +-- the packet-level decoder (as Matroska / MP4 would use it) gives the same samples, minus the Ogg trimming +do + local c = case("q5-stereo-44k-music") + local full = Vorbis.decode(reader(c.data)) :: Types.Audio + local demux = Ogg.open(buffer.fromstring(c.data)) + local serial = demux:find("vorbis") + local h = {} + for i = 1, 3 do + h[i] = Ogg.copy(demux:nextPacket(serial)) + end + local pd = Vorbis.packetDecoder(h[1], h[2], h[3]) + t:check(pd and pd.channels == 2 and pd.sampleRate == 44100, "packetDecoder") + local total, same = 0, true + for p in demux:packets(serial) do + local n = pd:decode(p.data, p.offset, p.size) + for i = 1, n, 13 do + if total + i <= full.frames then + same = same and math.abs(pd.out[1][i] - buffer.readf32(full.samples, (total + i - 1) * 8)) < 1e-6 + end + end + total += math.max(n, 0) + end + t:check(same and total >= full.frames, "packetDecoder samples") + local _, e = Vorbis.packetDecoder(h[2], h[1], h[3]) + t:check(e and e.code == Err.CORRUPT, "packetDecoder with headers swapped") +end + +-- errors +do + local _, e1 = Vorbis.decode(reader("OggS but not really")) + t:check(e1 and Err.is(e1), "junk: " .. tostring(e1)) + local c = case("short-100").data + local _, e2 = Vorbis.decode(reader(string.sub(c, 1, 60))) + t:check(e2 and Err.is(e2), "cut in the headers: " .. tostring(e2)) + -- a truncated stream decodes what is there + local q = case("q5-stereo-44k-music") + local cut = Vorbis.decode(reader(string.sub(q.data, 1, #q.data // 2)), { verify = false }) + t:check(cut and cut.frames > 0 and cut.frames < q.frames, "truncated stream") +end + +-- fuzz: whole streams with mutations past the headers, truncations, garbage +do + local samples = {} + for _, name in { "short-100", "short-3000-mono", "q-1-mono-8k-music", "ffmpeg-mono-16k" } do + table.insert(samples, case(name).data) + end + t:fuzz("decode", function(b: buffer) + return Vorbis.decode(Bytes.reader(b), { verify = false }) + end, samples, { mutations = 40 }) + t:fuzz("decode (CRC checked)", function(b: buffer) + return Vorbis.decode(Bytes.reader(b)) + end, samples, { mutations = 5, garbage = 20 }) + t:fuzz("open + seek", function(b: buffer) + local d = Vorbis.open(Bytes.reader(b), { verify = false }) + if d then + d:read(500) + d:seek(0.05) + d:read(500) + d:seek(1e9) + d:read(10) + end + return d + end, samples, { mutations = 10, garbage = 20 }) +end + +t:done() diff --git a/tests/audio/vorbis_encode.luau b/tests/audio/vorbis_encode.luau new file mode 100644 index 0000000..c85a39d --- /dev/null +++ b/tests/audio/vorbis_encode.luau @@ -0,0 +1,110 @@ +-- audio/vorbis encoder tests: every fixture-step encode (qualities -1 .. 10, mono / stereo / 5.1, 8 .. 96 kHz, odd +-- lengths, silence) passes ogginfo, decodes in oggdec (libvorbisfile) with the exact input length and an SNR over a +-- per-quality floor, and in ffmpeg; our own decoder gives the same; the codebooks are valid prefix codes; streaming +-- from a Decoder gives the same bytes; tags round-trip; option errors. Fixtures: tools/fixtures/vorbis_enc.py. +local T = require("@tests/T") +local Vorbis = require("@formats/audio/vorbis") +local VEnc = require("@formats/audio/vorbis/Encode") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Enc = require("@tests/gen/vorbis_enc") +local Sigs = require("@tests/gen/vorbis_enc_sigs") + +local t = T.suite("vorbis_encode") + +local function audio(name: string): Types.Audio + local s = Sigs[name] + local a = Types.Audio.new(s.rate, s.channels, s.frames) + buffer.writestring(a.samples, 0, s.data) + return a +end +local function snr(x: Types.Audio, y: Types.Audio): number + local sig, er = 0, 0 + for i = 0, math.min(x.frames, y.frames) * x.channels - 1 do + local a = buffer.readf32(x.samples, i * 4) + local d = a - buffer.readf32(y.samples, i * 4) + sig += a * a + er += d * d + end + if er == 0 then + return 200 + end + return if sig > 0 then 10 * math.log10(sig / er) else -200 +end +local function floorFor(q: number): number + return 8 + 1.2 * math.max(q, 0) +end + +t:check(Vorbis.caps.encode and Vorbis.encode ~= nil, "caps.encode") + +-- the codebooks: Kraft sums of exactly 1 (complete prefix codes) and lengths 1 .. 24 +for i, b in VEnc.BOOKS do + local k, okLen = 0, true + for _, l in b.lengths do + k += 2 ^ -l + okLen = okLen and l >= 1 and l <= 24 + end + t:check(math.abs(k - 1) < 1e-9 and okLen, "codebook " .. (i - 1) .. ": complete prefix code") +end + +local minSnr = math.huge +for _, e in Enc do + t:eq(e.ogginfo, "", e.name .. ": ogginfo reports no warnings / errors") + t:eq(e.oggdecFrames, e.frames, e.name .. ": oggdec frames = input frames") + t:eq(e.ffErrors, "", e.name .. ": ffmpeg decodes without errors") + local silent = string.find(e.name, "silence", 1, true) ~= nil + local f = if silent then -math.huge else floorFor(e.quality) + t:check(e.oggdecSnr >= f, string.format("%s: oggdec SNR %.1f dB (floor %.1f)", e.name, e.oggdecSnr, f)) + if e.frames >= 2048 then + -- (ffmpeg does not trim the end of a stream that fits on one Ogg page: up to a block more) + t:check(e.ffFrames >= e.frames and e.ffFrames <= e.frames + 1024, string.format("%s: ffmpeg frames %d", e.name, e.ffFrames)) + t:check(e.ffSnr >= f, string.format("%s: ffmpeg SNR %.1f dB", e.name, e.ffSnr)) + end + if not silent then + minSnr = math.min(minSnr, e.oggdecSnr) + end + -- our decoder: the same length and quality (it is sample-exact with libvorbis) + local x = audio(e.sig) + local y, err = Vorbis.decode(Bytes.reader(buffer.fromstring(e.data))) + t:check(y, e.name .. ": our decoder: " .. tostring(err)) + t:eq(y.frames, e.frames, e.name .. ": our decoder's frames") + local s = snr(x, y) + t:check(math.abs(s - e.oggdecSnr) < 0.5 or s >= 100, string.format("%s: our decoder %.1f dB, oggdec %.1f dB", e.name, s, e.oggdecSnr)) +end +t:note("%d encodes pass ogginfo / oggdec / ffmpeg; lowest SNR %.1f dB", #Enc, minSnr) + +-- streaming, tags +do + local a = audio("music_2_3000_44100") + local f1 = Vorbis.encode(a) :: buffer + local f2 = Vorbis.encode(Pcm.audioDecoder(a)) :: buffer + t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source") + a.tags = { title = "Tïtle", artist = "Artist", track = "9" } + local f3 = Vorbis.encode(a, { quality = 1, serial = 77 }) :: buffer + local d = Vorbis.open(Bytes.reader(f3)) :: any + t:eq(d.tags.title, "Tïtle", "title tag") + t:eq(d.tags.track, "9", "track tag") + t:check(string.find(d.vendor, "formats-luau", 1, true) ~= nil, "vendor") + local empty = Vorbis.encode(Types.Audio.new(44100, 1, 0)) :: buffer + local e0 = Vorbis.decode(Bytes.reader(empty)) + t:check(e0 and e0.frames == 0, "empty input") +end + +-- errors +do + local a = Types.Audio.new(44100, 2, 10) + local function code(v: any, o: any): string? + local _, e = Vorbis.encode(v, o) + return e and e.code + end + t:eq(code("x", nil), Err.ARG, "junk") + t:eq(code(a, { quality = 11 }), Err.ARG, "quality 11") + t:eq(code(a, { quality = -2 }), Err.ARG, "quality -2") + t:eq(code(a, { serial = -1 }), Err.ARG, "serial -1") + t:eq(code(Types.Audio.new(44100.5, 1, 1), nil), Err.ARG, "fractional rate") +end + +-- (the decoder's fuzz pass is in tests/audio/vorbis.luau; the encoder takes no untrusted bytes) +t:done() diff --git a/tests/core/md5.luau b/tests/core/md5.luau new file mode 100644 index 0000000..a40b8c8 --- /dev/null +++ b/tests/core/md5.luau @@ -0,0 +1,30 @@ +-- core/Md5 tests: the RFC 1321 test suite, incremental updates at every split, sub-ranges, a long input. +local T = require("@tests/T") +local Md5 = require("@formats/core/Md5") + +local t = T.suite("md5") +local VECTORS = { + { "", "d41d8cd98f00b204e9800998ecf8427e" }, + { "a", "0cc175b9c0f1b6a831c399e269772661" }, + { "abc", "900150983cd24fb0d6963f7d28e17f72" }, + { "message digest", "f96b697d7cb7938d525a2f31aaf161d0" }, + { "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b" }, + { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f" }, + { string.rep("1234567890", 8), "57edf4a22be3c955ac49da2e2107b67a" }, +} +for _, v in VECTORS do + t:eq(Md5.of(buffer.fromstring(v[1])), v[2], "md5 of " .. string.format("%q", v[1])) +end +-- incremental: every split point of a 130-byte message, three pieces +local msg = string.rep("The quick brown fox jumps over the lazy dog. ", 3) +local want = Md5.of(buffer.fromstring(msg)) +for cut = 0, #msg, 7 do + local h = Md5.new() + h:update(buffer.fromstring(string.sub(msg, 1, cut))) + h:update(buffer.fromstring(string.sub(msg, cut + 1, cut + 20))) + h:update(buffer.fromstring(string.sub(msg, cut + 21))) + t:eq(Md5.hex(h:digest()), want, "split at " .. cut) +end +t:eq(Md5.of(buffer.fromstring("xxabcyy"), 2, 3), "900150983cd24fb0d6963f7d28e17f72", "sub-range") +t:eq(Md5.of(buffer.fromstring(string.rep("a", 1000000))), "7707d6ae4e027c70eea2a935c2296f21", "a million a's") +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 21ab2f7..9dc9d26 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -90,6 +90,16 @@ for _, c in { { "celt 128k", OpusCelt }, { "silk wb", OpusSilk }, { "hybrid", Op Opus.decode(Bytes.reader(b)) end) end +-- vorbis (ws-audio): 10 s of 44.1 kHz stereo music at oggenc -q 5 (tools/fixtures/vorbis.py) +do + local Vorbis = require("@formats/audio/vorbis") + local VB = require("@tests/gen/vorbis_bench") + local b = buffer.fromstring(VB.data) + local dt = bench("vorbis decode q5 (10 s st)", 3, VB.frames * VB.channels * 4, function() + Vorbis.decode(Bytes.reader(b)) + end) + print(string.format("%-8s %-30s %8.0fx real time", runtime, "", VB.frames / VB.rate / dt)) +end for _, name in { "s16_long", "s24_96k" } do for _, c in FC do if c.name == name then @@ -116,6 +126,55 @@ do Wav.decode(Bytes.reader(file)) end) end +-- flac encode (ws-audio): 10 s of 44.1 kHz stereo 16-bit (a synthetic two-tone signal with noise) +do + local Fl = require("@formats/audio/flac") + local n = 441000 + local a = Types.Audio.new(44100, 2, n) + local seed = 1 + for i = 0, n - 1 do + seed = (seed * 1103515245 + 12345) % 2147483648 + local noise = (seed / 2147483648 - 0.5) * 0.01 + buffer.writef32(a.samples, i * 8, math.floor((math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1 + noise) * 32768) / 32768) + buffer.writef32(a.samples, i * 8 + 4, math.floor((math.sin(i * 0.017) * 0.3 + noise) * 32768) / 32768) + end + for _, level in { 0, 5, 8 } do + local dt = bench("flac encode -" .. level .. " (10 s st 16)", 2, n * 4, function() + Fl.encode(a, { level = level }) + end) + print(string.format("%-8s %-30s %8.0fx real time", runtime, "", 10 / dt)) + end +end +-- mp3 / mp2 encode (ws-audio): 10 s of 44.1 kHz stereo tones +do + local M3 = require("@formats/audio/mp3") + local n = 441000 + local a = Types.Audio.new(44100, 2, n) + for i = 0, n - 1 do + buffer.writef32(a.samples, i * 8, math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1) + buffer.writef32(a.samples, i * 8 + 4, math.sin(i * 0.017) * 0.3) + end + for _, cfg in { { layer = 3, bitrate = 128 }, { layer = 2, bitrate = 192 } } do + local dt = bench(string.format("mp%d encode %d kbps (10 s st)", cfg.layer, cfg.bitrate), 2, n * 8, function() + M3.encode(a, cfg) + end) + print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt)) + end +end +-- vorbis encode (ws-audio): 10 s of 44.1 kHz stereo tones at quality 3 +do + local Vb = require("@formats/audio/vorbis") + local n = 441000 + local a = Types.Audio.new(44100, 2, n) + for i = 0, n - 1 do + buffer.writef32(a.samples, i * 8, math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1) + buffer.writef32(a.samples, i * 8 + 4, math.sin(i * 0.017) * 0.3) + end + local dt = bench("vorbis encode q3 (10 s st)", 2, n * 8, function() + Vb.encode(a, { quality = 3 }) + end) + print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt)) +end do local Json = require("@formats/codecs/Json") local JB = require("@tests/gen/json_bench") diff --git a/tools/fixtures/_audio.py b/tools/fixtures/_audio.py new file mode 100644 index 0000000..566ce86 --- /dev/null +++ b/tools/fixtures/_audio.py @@ -0,0 +1,334 @@ +# Shared helpers for the audio fixture generators (aiff, au, voc, vorbis, flac encoder, mp3 / mp2 encoders): +# A = _audio.load() in a generator: import this file (generators are loaded by path, not as a package) +# A.signal(kind, rate, ch, frames) deterministic test signals -> list of float frames-interleaved samples +# A.f32le(samples) / A.from_f32le(b) float list <-> raw little-endian f32 bytes +# A.wav(samples, rate, ch, bits=16) a WAV file (PCM 8/16/24/32 or float 32) for reference tools to read +# A.ffdecode(ctx, data, fmt=None) decode any file with ffmpeg -> (rate, ch, floats) +# A.tool(ctx, pkg, argv, data, ext) run a nix reference tool on a temp input file, return its stdout +# A.snr(ref, test, ch, max_lag=0) SNR in dB of test against ref (searching an alignment lag up to max_lag frames, +# either direction), and the lag found +# A.luau(ctx, code) run Luau code (luau --codegen -O2 from the repo root, the .luaurc aliases +# apply) and return its stdout bytes. Encoder fixtures use it to encode with our +# encoder in the fixture step, then decode the output with the reference tool: +# print(buffer.tostring(buf)) writes the raw bytes (plus one newline, stripped). +import array, math, os, random, shutil, struct, subprocess, sys, tempfile, importlib.util + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + + +def load(): + return sys.modules[__name__] + + +def signal(kind, rate, ch, frames, seed=1): + """kinds: sine (440 Hz + 1 kHz per channel), sweep (50 Hz .. rate/2.2 log sweep), noise (white, -12 dBFS), + music (a few harmonic notes with an envelope + a little noise), silence, square (aliased square, a stress test), + loud (a full-scale sine near clipping).""" + rng = random.Random(seed) + out = [0.0] * (frames * ch) + for c in range(ch): + ph = 0.0 + notes = [(220.0 * 2 ** (rng.randrange(0, 24) / 12.0), rng.random() * 0.25 + 0.05) for _ in range(4)] + for i in range(frames): + t = i / rate + if kind == "sine": + v = 0.5 * math.sin(2 * math.pi * (440 + 110 * c) * t) + 0.2 * math.sin(2 * math.pi * 1000 * t + c) + elif kind == "sweep": + f0, f1 = 50.0, rate / 2.2 + dur = frames / rate + f = f0 * (f1 / f0) ** (t / dur) + ph += 2 * math.pi * f / rate + v = 0.6 * math.sin(ph + c) + elif kind == "noise": + v = (rng.random() * 2 - 1) * 0.25 + elif kind == "music": + v = 0.0 + for k, (f, a) in enumerate(notes): + seg = (i // max(1, rate // 4) + k) % 4 + env = math.exp(-3.0 * ((i % max(1, rate // 4)) / rate)) + if seg != 3: + v += a * env * (math.sin(2 * math.pi * f * t) + 0.3 * math.sin(4 * math.pi * f * t) + 0.1 * math.sin(6 * math.pi * f * t)) + v += (rng.random() * 2 - 1) * 0.01 + elif kind == "silence": + v = 0.0 + elif kind == "square": + v = 0.4 if math.sin(2 * math.pi * (300 + 50 * c) * t) >= 0 else -0.4 + elif kind == "loud": + v = 0.98 * math.sin(2 * math.pi * 330 * t + c) + else: + raise ValueError(kind) + out[i * ch + c] = v + return out + + +def quantize(samples, bits): + s = 2 ** (bits - 1) + return [max(-s, min(s - 1, int(math.floor(v * s + 0.5)))) / s for v in samples] + + +def f32le(samples): + a = array.array("f", samples) + if sys.byteorder != "little": + a.byteswap() + return a.tobytes() + + +def from_f32le(b): + a = array.array("f") + a.frombytes(b[: len(b) // 4 * 4]) + if sys.byteorder != "little": + a.byteswap() + return a.tolist() + + +def wav(samples, rate, ch, bits=16, float_=False): + n = len(samples) // ch + if float_: + data = f32le(samples) + fmt = struct.pack("= 10: + return got + best = (-1e9, 0) + nref, ntest = len(ref) // ch, len(test) // ch + lags = range(-max_lag, max_lag + 1) if max_lag else [0] + if max_lag > 64: + # coarse cross-correlation on the first channel to find candidate lags, then refine + cands = [] + m = min(nref, 1 << 15) + seg = [ref[i * ch] for i in range(skip, min(nref, skip + m))] + for lag in range(-max_lag, max_lag + 1): + acc = 0.0 + for i in range(0, len(seg), 7): + j = skip + i + lag + if 0 <= j < ntest: + acc += seg[i] * test[j * ch] + cands.append((acc, lag)) + cands.sort(reverse=True) + lags = sorted(set(l for _, l in cands[:3])) + for lag in lags: + sig = err = 0.0 + for i in range(skip, nref): + j = i + lag + if j < 0 or j >= ntest: + continue + for c in range(ch): + a = ref[i * ch + c] + e = a - test[j * ch + c] + sig += a * a + err += e * e + s = 200.0 if err == 0 else (10 * math.log10(sig / err) if sig > 0 else -200.0) + if s > best[0]: + best = (s, lag) + return best + + +def _snr_at(ref, test, ch, lag, skip): + sig = err = 0.0 + nref, ntest = len(ref) // ch, len(test) // ch + for i in range(skip, nref): + j = i + lag + if 0 <= j < ntest: + for c in range(ch): + a = ref[i * ch + c] + e = a - test[j * ch + c] + sig += a * a + err += e * e + return (200.0 if err == 0 else (10 * math.log10(sig / err) if sig > 0 else -200.0), lag) + + +def luau_bin(): + p = shutil.which("luau") + if p: + return p + return subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "sh", "-c", "command -v luau"], capture_output=True, check=True, + text=True).stdout.strip() + + +def luau(ctx, code): + d = os.path.join(ROOT, "tests", "gen") + os.makedirs(d, exist_ok=True) + fd, path = tempfile.mkstemp(prefix="_run_", suffix=".luau", dir=d) + try: + with os.fdopen(fd, "w") as f: + f.write(code) + r = subprocess.run([luau_bin(), "--codegen", "-O2", path], cwd=ROOT, capture_output=True) + if r.returncode != 0: + raise RuntimeError("luau failed:\n" + r.stderr.decode(errors="replace") + r.stdout.decode(errors="replace")[-2000:]) + out = r.stdout + return out[:-1] if out.endswith(b"\n") else out + finally: + os.unlink(path) + + +def emit_signal(ctx, name, samples, rate, ch): + """emit tests/gen/.luau = { rate, channels, frames, data = f32le bytes } (the input encoders are tested on)""" + ctx.emit(name, {"rate": rate, "channels": ch, "frames": len(samples) // ch, "data": f32le(samples)}) + + +def encode_luau(ctx, module, sigmod, opts_lua="nil", source="audio"): + """encode the emitted signal module `sigmod` with require("@formats/").encode(audio, opts) in Luau; returns + the encoded bytes. source = "decoder" feeds a streaming Decoder (codecs/Pcm.audioDecoder) instead of the Audio.""" + code = """ +local S = require("@tests/gen/%s") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local M = require("@formats/%s") +local a = Types.Audio.new(S.rate, S.channels, S.frames) +buffer.writestring(a.samples, 0, S.data) +local src: any = a +if "%s" == "decoder" then src = Pcm.audioDecoder(a) end +local out, err = M.encode(src, %s) +if not out then error("encode failed: " .. tostring(err)) end +print(buffer.tostring(out)) +""" % (sigmod, module, source, opts_lua) + return luau(ctx, code) + + +def max_diff(a, b): + if len(a) != len(b): + return float("inf") + return max((abs(x - y) for x, y in zip(a, b)), default=0.0) + + +def pcm_fixtures(ctx, fmt, made, encodes, sig_rate=22050, sig_frames=3000): + """The fixtures of an uncompressed container (aiff, au, voc): + made = [(name, packages, argv)]: reference tools write files from {in} (a stereo / mono 16-bit or float WAV of + the test signal; argv may use {in_mono}, {in_float}) into {out}; each file is decoded by ffmpeg as the + reference (f32le) + encodes = [(name, opts_lua, channels)]: our encoder's output (in the fixture step) decoded by ffmpeg, compared + against the f32 input (max abs difference, which the test bounds by the format's quantization step) + Emits _cases (files + references), _sig / _sig1 (the inputs, stereo / mono) and _enc.""" + stereo = signal("music", sig_rate, 2, sig_frames, seed=3) + mono = signal("sweep", sig_rate, 1, sig_frames, seed=4) + emit_signal(ctx, fmt + "_sig", stereo, sig_rate, 2) + emit_signal(ctx, fmt + "_sig1", mono, sig_rate, 1) + inputs = {"{in}": wav(stereo, sig_rate, 2, 16), "{in_mono}": wav(mono, sig_rate, 1, 16), + "{in_float}": wav(stereo, sig_rate, 2, float_=True)} + cases = [] + for name, packages, argv in made: + d = tempfile.mkdtemp(prefix="fmt-audio-") + try: + paths = {} + for key, data in inputs.items(): + paths[key] = os.path.join(d, key.strip("{}") + ".wav") + with open(paths[key], "wb") as f: + f.write(data) + out = os.path.join(d, "out." + fmt) + args = [] + for a in argv: + for key, p in paths.items(): + a = a.replace(key, p) + args.append(a.replace("{out}", out)) + ctx.nix(packages, args) + with open(out, "rb") as f: + data = f.read() + finally: + shutil.rmtree(d, ignore_errors=True) + rate, ch, ref = ffdecode(ctx, data, ext=fmt) + cases.append({"name": name, "data": data, "rate": rate, "channels": ch, "frames": len(ref) // ch, "ref": f32le(ref)}) + ctx.emit(fmt + "_cases", cases) + results = [] + for name, opts_lua, ch in encodes: + sig = stereo if ch == 2 else mono + out = encode_luau(ctx, "audio/" + fmt, fmt + ("_sig" if ch == 2 else "_sig1"), opts_lua) + streamed = encode_luau(ctx, "audio/" + fmt, fmt + ("_sig" if ch == 2 else "_sig1"), opts_lua, source="decoder") + rate, dch, dec = ffdecode(ctx, out, ext=fmt) + errs = tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], out, fmt) + results.append({"name": name, "opts": opts_lua, "channels": dch, "rate": rate, "frames": len(dec) // max(1, dch), + "maxDiff": max_diff(sig, dec) if dch == ch else 99.0, "ffmpegErrors": errs.decode(errors="replace"), + "bytes": len(out), "sameStreamed": out == streamed, "data": out}) + ctx.emit(fmt + "_enc", results) + + +def encode_luau_many(ctx, module, jobs, sigmod): + """jobs = [(signal name, opts_lua)] over the emitted module sigmod = { [name] = { rate, channels, frames, data } } + -> [bytes]: one Luau run encodes them all (length-prefixed on stdout)""" + body = ['job("%s", %s)' % (name, opts) for name, opts in jobs] + code = """ +local Types = require("@formats/Types") +local M = require("@formats/%s") +local S = require("@tests/gen/%s") +local outs = {} +local function job(name, opts) + local s = S[name] + local a = Types.Audio.new(s.rate, s.channels, s.frames) + buffer.writestring(a.samples, 0, s.data) + local out, err = M.encode(a, opts) + if not out then error("encode failed: " .. tostring(err)) end + local n = buffer.len(out) + table.insert(outs, string.format("%%012d", n) .. buffer.tostring(out)) +end +%s +print(table.concat(outs)) +""" % (module, sigmod, "\n".join(body)) + raw = luau(ctx, code) + res, p = [], 0 + while p < len(raw): + n = int(raw[p:p + 12]) + res.append(raw[p + 12:p + 12 + n]) + p += 12 + n + return res + + +def shell_many(ctx, packages, files, script): + """write files {name: bytes} into a temp dir and run `sh -c script` there under nix; returns stdout""" + d = tempfile.mkdtemp(prefix="fmt-audio-") + try: + for name, data in files.items(): + with open(os.path.join(d, name), "wb") as f: + f.write(data) + return ctx.nix(packages, ["sh", "-c", "cd '%s' && %s" % (d, script)]) + finally: + shutil.rmtree(d, ignore_errors=True) diff --git a/tools/fixtures/aiff.py b/tools/fixtures/aiff.py new file mode 100644 index 0000000..15fbdb2 --- /dev/null +++ b/tools/fixtures/aiff.py @@ -0,0 +1,51 @@ +# AIFF / AIFF-C fixtures (tools/fixtures.py): files written by ffmpeg and sox in every sample format we read, each +# with ffmpeg's f32 decode as the reference; our encoder's output for every sample format, decoded by ffmpeg in the +# fixture step (tools/fixtures/_audio.py pcm_fixtures). +# tests/gen/aiff_cases.luau { name, data, rate, channels, frames, ref (f32le) } +# tests/gen/aiff_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data } +# tests/gen/aiff_sig*.luau the encoder inputs +import importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/Pcm"] + + +def ff(codec, src="{in}", extra=()): + return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "aiff", "-y", "{out}"] + + +def generate(ctx): + made = [ + ("ffmpeg-s16be", "ffmpeg", ff("pcm_s16be")), + ("ffmpeg-s16be-mono", "ffmpeg", ff("pcm_s16be", "{in_mono}")), + ("ffmpeg-s8", "ffmpeg", ff("pcm_s8")), + ("ffmpeg-s24be", "ffmpeg", ff("pcm_s24be", "{in_float}")), + ("ffmpeg-s32be", "ffmpeg", ff("pcm_s32be", "{in_float}")), + ("ffmpeg-sowt", "ffmpeg", ff("pcm_s16le")), + ("ffmpeg-fl32", "ffmpeg", ff("pcm_f32be", "{in_float}")), + ("ffmpeg-fl64", "ffmpeg", ff("pcm_f64be", "{in_float}")), + ("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw")), + ("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")), + ("ffmpeg-48k-6ch", "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-af", "aresample=48000,pan=5.1|c0=c0|c1=c1|c2=c0|c3=c1|c4=c0|c5=c1", "-c:a", "pcm_s16be", "-f", "aiff", "-y", "{out}"]), + ("ffmpeg-tags", "ffmpeg", ff("pcm_s16be", extra=("-metadata", "title=Song Name", "-metadata", "author=Some One", "-metadata", "comment=hello"))), + ("sox-aiff-s16", "sox", ["sox", "{in}", "-t", "aiff", "{out}"]), + ("sox-aiff-s24-mono", "sox", ["sox", "{in_mono}", "-b", "24", "-t", "aiff", "{out}"]), + ("sox-aifc-s16", "sox", ["sox", "{in}", "-t", "aifc", "{out}"]), + ] + encodes = [ + ("s16", "nil", 2), + ("s16-mono", "nil", 1), + ("s8", '{ sampleFormat = "s8" }', 2), + ("s24", '{ sampleFormat = "s24" }', 2), + ("s32", '{ sampleFormat = "s32" }', 1), + ("f32", '{ sampleFormat = "f32" }', 2), + ("f64", '{ sampleFormat = "f64" }', 2), + ("ulaw", '{ sampleFormat = "ulaw" }', 2), + ("alaw", '{ sampleFormat = "alaw" }', 1), + ("sowt16", '{ littleEndian = true }', 2), + ("aifc-s16", '{ aifc = true }', 2), + ] + A.pcm_fixtures(ctx, "aiff", made, encodes) diff --git a/tools/fixtures/au.py b/tools/fixtures/au.py new file mode 100644 index 0000000..eb34539 --- /dev/null +++ b/tools/fixtures/au.py @@ -0,0 +1,47 @@ +# Sun AU fixtures (tools/fixtures.py): files written by ffmpeg and sox in every encoding we read, each with ffmpeg's +# f32 decode as the reference; our encoder's output for every encoding, decoded by ffmpeg in the fixture step +# (tools/fixtures/_audio.py pcm_fixtures). +# tests/gen/au_cases.luau { name, data, rate, channels, frames, ref (f32le) } +# tests/gen/au_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data } +# tests/gen/au_sig*.luau the encoder inputs +import importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/au", "src/Formats/codecs/Pcm"] + + +def ff(codec, src="{in}", extra=()): + return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "au", "-y", "{out}"] + + +def generate(ctx): + made = [ + ("ffmpeg-s16be", "ffmpeg", ff("pcm_s16be")), + ("ffmpeg-s16be-mono", "ffmpeg", ff("pcm_s16be", "{in_mono}")), + ("ffmpeg-s8", "ffmpeg", ff("pcm_s8")), + ("ffmpeg-s24be", "ffmpeg", ff("pcm_s24be", "{in_float}")), + ("ffmpeg-s32be", "ffmpeg", ff("pcm_s32be", "{in_float}")), + ("ffmpeg-f32be", "ffmpeg", ff("pcm_f32be", "{in_float}")), + ("ffmpeg-f64be", "ffmpeg", ff("pcm_f64be", "{in_float}")), + ("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw")), + ("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")), + ("sox-comment", "sox", ["sox", "{in}", "--comment", "hello sun", "-t", "au", "{out}"]), + ("sox-ulaw-8k", "sox", ["sox", "{in_mono}", "-r", "8000", "-e", "mu-law", "-t", "au", "{out}"]), + ("sox-s16", "sox", ["sox", "{in}", "-t", "au", "{out}"]), + ("sox-f32", "sox", ["sox", "{in_float}", "-e", "floating-point", "-b", "32", "-t", "au", "{out}"]), + ] + encodes = [ + ("s16", "nil", 2), + ("s16-mono", "nil", 1), + ("s8", '{ sampleFormat = "s8" }', 2), + ("s24", '{ sampleFormat = "s24" }', 2), + ("s32", '{ sampleFormat = "s32" }', 1), + ("f32", '{ sampleFormat = "f32" }', 2), + ("f64", '{ sampleFormat = "f64" }', 2), + ("ulaw", '{ sampleFormat = "ulaw" }', 2), + ("alaw", '{ sampleFormat = "alaw" }', 1), + ] + A.pcm_fixtures(ctx, "au", made, encodes) diff --git a/tools/fixtures/flac_enc.py b/tools/fixtures/flac_enc.py new file mode 100644 index 0000000..19cf672 --- /dev/null +++ b/tools/fixtures/flac_enc.py @@ -0,0 +1,89 @@ +# FLAC encoder fixtures (tools/fixtures.py): our encoder runs in the fixture step (tools/fixtures/_audio.py +# encode_luau_many) on test signals; every output must pass `flac -t` (which also checks the decoded PCM against the +# STREAMINFO MD5), and that MD5 must equal the MD5 of the input quantized here, so the stream is bit-exact. The level +# sweep is compared in size with `flac -` (libFLAC 1.5, --no-padding --no-seektable). +# tests/gen/flac_enc.luau { name, sig, opts, bits, channels, frames, flacTest, md5, wantMd5, size, refSize?, data } +# tests/gen/flac_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } }: the inputs +import hashlib, importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/flac", "src/Formats/codecs/Pcm", "src/Formats/core/Md5.luau"] + + +def pcm_bytes(samples, bits): + s = 2 ** (bits - 1) + nb = (bits + 7) // 8 + out = bytearray() + for v in samples: + q = max(-s, min(s - 1, int(__import__("math").floor(v * s + 0.5)))) + out += (q & ((1 << (8 * nb)) - 1)).to_bytes(nb, "little") + return bytes(out) + + +def generate(ctx): + sigs = {} + + def sig(kind, ch, frames, rate=44100): + name = "flacsig_%s_%d_%d_%d" % (kind, ch, frames, rate) + if name not in sigs: + samples = A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=frames + ch))) # f32-rounded + sigs[name] = (samples, rate, ch) + return name + + cases = [] # (name, sigmod, bits, opts_lua, ref_level) + for level in range(9): + cases.append(("L%d-music-st16" % level, sig("music", 2, 20000), 16, "{ level = %d, bits = 16 }" % level, level)) + cases.append(("L%d-noise-mono24" % level, sig("noise", 1, 9000), 24, "{ level = %d, bits = 24 }" % level, level)) + cases.append(("L%d-sweep-6ch8" % level, sig("sweep", 6, 5000, 48000), 8, "{ level = %d, bits = 8 }" % level, level)) + for kind in ("sine", "silence", "loud", "square"): + for ch in (1, 2): + for bits in (8, 16, 24): + cases.append(("%s-%dch-%d" % (kind, ch, bits), sig(kind, ch, 4500), bits, "{ bits = %d }" % bits, None)) + for level in (0, 5, 8): + for n in (1, 15, 100, 1153, 4097): + cases.append(("L%d-len%d" % (level, n), sig("music", 2, n), 16, "{ level = %d }" % level, None)) + for bs in (192, 576, 1000, 4608, 16): + cases.append(("bs%d" % bs, sig("music", 2, 7000), 16, "{ blockSize = %d }" % bs, None)) + cases.append(("bits12-22k", sig("music", 1, 6000, 22050), 12, "{ bits = 12 }", None)) + cases.append(("bits20-96k", sig("sweep", 2, 6000, 96000), 20, "{ bits = 20, level = 8 }", None)) + cases.append(("rate-11111", sig("sine", 2, 3000, 11111), 16, "nil", None)) + cases.append(("seek-1s", sig("music", 2, 30000), 16, "{ seekInterval = 0.25 }", None)) + cases.append(("padding", sig("sine", 1, 1000), 16, "{ padding = 100 }", None)) + + ctx.emit("flac_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()}) + outs = A.encode_luau_many(ctx, "audio/flac", [(c[1], c[3]) for c in cases], "flac_enc_sigs") + files = {"c%03d.flac" % i: o for i, o in enumerate(outs)} + script = 'for f in c*.flac; do r=$(flac -s -t "$f" 2>&1); echo "$f|$?|$(metaflac --show-md5sum "$f")|$(echo $r | tr "\\n" " ")"; done' + report = A.shell_many(ctx, "flac", files, script).decode(errors="replace") + rows = {} + for line in report.strip().split("\n"): + f, rc, md5, msg = line.split("|", 3) + rows[f] = (int(rc), md5.strip(), msg.strip()) + # libFLAC reference sizes for the level sweep + refs = {} + wavs = {} + for i, c in enumerate(cases): + if c[4] is not None: + samples, rate, ch = sigs[c[1]] + wavs["r%03d.raw" % i] = pcm_bytes(samples, c[2]) + wavs["r%03d.arg" % i] = ("-%d --channels=%d --bps=%d --sample-rate=%d" % (c[4], ch, c[2], rate)).encode() + script = ('for i in r*.raw; do rm -f out.flac; flac -s $(cat "${i%.raw}.arg") --force-raw-format --endian=little --sign=signed ' + '--no-padding --no-seektable -f -o out.flac "$i"; echo "$i $(stat -c %s out.flac)"; done') + for line in A.shell_many(ctx, "flac", wavs, script).decode().strip().split("\n"): + f, size = line.split() + refs[int(f[1:4])] = int(size) + emitted = [] + for i, (name, sigmod, bits, opts, lvl) in enumerate(cases): + samples, rate, ch = sigs[sigmod] + rc, md5, msg = rows["c%03d.flac" % i] + want = hashlib.md5(pcm_bytes(samples, bits)).hexdigest() + e = {"name": name, "sig": sigmod, "opts": opts, "bits": bits, "channels": ch, "frames": len(samples) // ch, + "flacTest": "" if rc == 0 else (msg or "rc %d" % rc), "md5": md5, "wantMd5": want, "size": len(outs[i]), + "data": outs[i]} + if i in refs: + e["refSize"] = refs[i] + emitted.append(e) + ctx.emit("flac_enc", emitted) diff --git a/tools/fixtures/mp3_enc.py b/tools/fixtures/mp3_enc.py new file mode 100644 index 0000000..5b95717 --- /dev/null +++ b/tools/fixtures/mp3_enc.py @@ -0,0 +1,80 @@ +# MP3 / MP2 encoder fixtures (tools/fixtures.py): our layer III and layer II encoders run in the fixture step +# (tools/fixtures/_audio.py encode_luau_many) on test signals at every MPEG sample rate group, several bit rates and +# modes; ffmpeg (mp3float / mp2float) and LAME (`lame --decode`, layer III) decode the files. Recorded per file: ffmpeg's +# error output (must be empty), the decoded frame counts, and the SNR against the input after aligning the decoder delay. +# tests/gen/mp3_enc.luau { name, sig, layer, bitrate, mode, rate, channels, frames, ffErrors, ffFrames, ffSnr, +# ffLag, lameFrames?, lameSnr?, size, data } +# tests/gen/mp3_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } } +import importlib.util, io, os, wave + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/mp3", "src/Formats/codecs/Pcm"] + + +def generate(ctx): + sigs = {} + + def sig(kind, ch, secs, rate): + name = "%s_%d_%d" % (kind, ch, rate) + if name not in sigs: + frames = int(secs * rate) + sigs[name] = (A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=ch * 7 + rate % 97))), rate, ch) + return name + + cases = [] # name, sig, layer, bitrate, mode + for kind in ("music", "sine", "sweep"): + for br in (64, 128, 192, 320): + cases.append(("l3-%s-44k-%d-joint" % (kind, br), sig(kind, 2, 1.0, 44100), 3, br, "joint")) + cases.append(("l3-music-44k-128-stereo", sig("music", 2, 1.0, 44100), 3, 128, "stereo")) + cases.append(("l3-music-48k-160-joint", sig("music", 2, 1.0, 48000), 3, 160, "joint")) + cases.append(("l3-music-32k-96-mono", sig("music", 1, 1.0, 32000), 3, 96, "mono")) + cases.append(("l3-noise-44k-128-mono", sig("noise", 1, 0.6, 44100), 3, 128, "mono")) + cases.append(("l3-music-22k-64-joint", sig("music", 2, 1.0, 22050), 3, 64, "joint")) + cases.append(("l3-music-24k-96-stereo", sig("music", 2, 1.0, 24000), 3, 96, "stereo")) + cases.append(("l3-sweep-16k-48-mono", sig("sweep", 1, 1.0, 16000), 3, 48, "mono")) + cases.append(("l3-music-11k-32-mono", sig("music", 1, 1.0, 11025), 3, 32, "mono")) + cases.append(("l3-music-8k-24-joint", sig("music", 2, 1.0, 8000), 3, 24, "joint")) + cases.append(("l3-music-12k-64-stereo", sig("music", 2, 1.0, 12000), 3, 64, "stereo")) + cases.append(("l3-silence-44k-128", sig("silence", 2, 0.3, 44100), 3, 128, "joint")) + cases.append(("l3-loud-44k-128", sig("loud", 2, 0.5, 44100), 3, 128, "joint")) + for kind in ("music", "sine", "sweep"): + for br in (128, 192, 256, 384): + cases.append(("l2-%s-44k-%d" % (kind, br), sig(kind, 2, 1.0, 44100), 2, br, "stereo")) + cases.append(("l2-music-48k-192", sig("music", 2, 1.0, 48000), 2, 192, "stereo")) + cases.append(("l2-music-32k-mono-96", sig("music", 1, 1.0, 32000), 2, 96, "mono")) + cases.append(("l2-music-44k-mono-64", sig("music", 1, 1.0, 44100), 2, 64, "mono")) + cases.append(("l2-music-24k-96", sig("music", 2, 1.0, 24000), 2, 96, "stereo")) + cases.append(("l2-sweep-16k-mono-48", sig("sweep", 1, 1.0, 16000), 2, 48, "mono")) + cases.append(("l2-loud-44k-192", sig("loud", 2, 0.5, 44100), 2, 192, "stereo")) + + ctx.emit("mp3_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()}) + jobs = [(c[1], '{ layer = %d, bitrate = %d, mode = "%s" }' % (c[2], c[3], c[4])) for c in cases] + outs = A.encode_luau_many(ctx, "audio/mp3", jobs, "mp3_enc_sigs") + emitted = [] + for (name, sigmod, layer, br, mode), data in zip(cases, outs): + samples, rate, ch = sigs[sigmod] + ext = "mp3" if layer == 3 else "mp2" + errs = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], data, ext).decode(errors="replace") + frate, fch, dec = A.ffdecode(ctx, data, ext=ext) + dch = fch + ref = samples if dch == ch else [samples[i // dch] for i in range(len(samples) // ch * dch)] + snr, lag = A.snr(ref, dec, dch, max_lag=1600, skip=200, hints=[1057 if layer == 3 else 481]) if dch == ch else (-99.0, 0) + e = {"name": name, "sig": sigmod, "layer": layer, "bitrate": br, "mode": mode, "rate": rate, "channels": ch, + "frames": len(samples) // ch, "ffErrors": errs, "ffFrames": len(dec) // max(1, fch), "ffRate": frate, + "ffChannels": fch, "ffSnr": snr, "ffLag": lag, "size": len(data), "data": data} + if layer == 3: + wavb = A.tool(ctx, "lame", ["lame", "--quiet", "--decode", "{in}", "{out}"], data, "mp3", "wav") + with wave.open(io.BytesIO(wavb)) as wf: + lch, raw = wf.getnchannels(), wf.readframes(wf.getnframes()) + lame = [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw), 2)] + if lch == ch: + ls, ll = A.snr(samples, lame, ch, max_lag=1600, skip=200, hints=[1057, 528, 529]) + e["lameSnr"], e["lameLag"] = ls, ll + e["lameFrames"] = len(lame) // lch + emitted.append(e) + print(" mp3_enc: %-28s %5d bytes ffmpeg %.1f dB (lag %d)%s%s" % (name, len(data), snr, lag, + (" lame %.1f dB" % e["lameSnr"]) if "lameSnr" in e else "", (" ERR " + errs.strip()[:60]) if errs.strip() else "")) + ctx.emit("mp3_enc", emitted) diff --git a/tools/fixtures/voc.py b/tools/fixtures/voc.py new file mode 100644 index 0000000..b207bd8 --- /dev/null +++ b/tools/fixtures/voc.py @@ -0,0 +1,39 @@ +# Creative VOC fixtures (tools/fixtures.py): files written by ffmpeg (type 1 + type 8 blocks for 8-bit, type 9 for the +# rest) and sox, each with ffmpeg's f32 decode as the reference; our encoder's output for every sample format, decoded +# by ffmpeg in the fixture step (tools/fixtures/_audio.py pcm_fixtures). +# tests/gen/voc_cases.luau { name, data, rate, channels, frames, ref (f32le) } +# tests/gen/voc_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data } +# tests/gen/voc_sig*.luau the encoder inputs +import importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/voc", "src/Formats/codecs/Pcm"] + + +def ff(codec, src="{in}", extra=()): + return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "voc", "-y", "{out}"] + + +def generate(ctx): + made = [ + ("ffmpeg-u8-stereo", "ffmpeg", ff("pcm_u8")), + ("ffmpeg-u8-mono", "ffmpeg", ff("pcm_u8", "{in_mono}")), + ("ffmpeg-s16", "ffmpeg", ff("pcm_s16le")), + ("ffmpeg-s16-mono-44k", "ffmpeg", ff("pcm_s16le", "{in_mono}", ("-ar", "44100"))), + ("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")), + ("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw", "{in_mono}")), + ("sox-u8-mono-11k", "sox", ["sox", "{in_mono}", "-r", "11025", "-b", "8", "-t", "voc", "{out}"]), + ("sox-u8-stereo", "sox", ["sox", "{in}", "-b", "8", "-t", "voc", "{out}"]), + ("sox-s16-stereo", "sox", ["sox", "{in}", "-b", "16", "-t", "voc", "{out}"]), + ] + encodes = [ + ("s16", "nil", 2), + ("s16-mono", "nil", 1), + ("u8", '{ sampleFormat = "u8" }', 2), + ("alaw", '{ sampleFormat = "alaw" }', 2), + ("ulaw", '{ sampleFormat = "ulaw" }', 1), + ] + A.pcm_fixtures(ctx, "voc", made, encodes) diff --git a/tools/fixtures/vorbis.py b/tools/fixtures/vorbis.py new file mode 100644 index 0000000..e4994ee --- /dev/null +++ b/tools/fixtures/vorbis.py @@ -0,0 +1,57 @@ +# Ogg Vorbis fixtures (tools/fixtures.py): files made by oggenc (libvorbis, vorbis-tools) and ffmpeg (libvorbis) from +# the test signals in tools/fixtures/_audio.py: qualities -1 .. 10, managed bitrate, 8 .. 96 kHz, mono / stereo / 5.1, +# transients (block switching), silence, tags, a stream shorter than one block. References: oggdec (libvorbisfile: +# the authority on start / end trimming) as 16-bit samples, and ffmpeg's f32 decode (more precise, but its Ogg demuxer +# trims some streams differently: the test uses it only when its frame count agrees with oggdec). +# tests/gen/vorbis_cases.luau { name, data, rate, channels, frames (oggdec), ref16 (s16le, oggdec), ffFrames, +# ffRef (f32le, ffmpeg), inputFrames } +import importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +CASES = [ + # name, signal, rate, channels, seconds, tool, args + ("q5-stereo-44k-music", "music", 44100, 2, 1.5, "oggenc", ["-q", "5"]), + ("q-1-mono-8k-music", "music", 8000, 1, 1.0, "oggenc", ["-q", "-1"]), + ("q10-stereo-48k-sweep", "sweep", 48000, 2, 1.0, "oggenc", ["-q", "10"]), + ("q3-mono-22k-noise", "noise", 22050, 1, 0.7, "oggenc", ["-q", "3"]), + ("q0-stereo-44k-square", "square", 44100, 2, 1.0, "oggenc", ["-q", "0"]), + ("q2-stereo-32k-tags", "sine", 32000, 2, 0.6, "oggenc", ["-q", "2", "-t", "A Title", "-a", "An Artist", "-l", "The Album", "-N", "7", "-c", "comment=hello vorbis"]), + ("managed-64k-stereo", "music", 44100, 2, 1.0, "oggenc", ["--managed", "-b", "64"]), + ("silence-stereo", "silence", 44100, 2, 0.5, "oggenc", ["-q", "4"]), + ("short-100", "sine", 44100, 2, 100 / 44100, "oggenc", ["-q", "4"]), + ("short-3000-mono", "music", 44100, 1, 3000 / 44100, "oggenc", ["-q", "4"]), + ("q6-stereo-96k", "music", 96000, 2, 0.4, "oggenc", ["-q", "6"]), + ("ffmpeg-5.1-48k", "music", 48000, 6, 0.6, "ffmpeg", ["-c:a", "libvorbis", "-q:a", "4"]), + ("ffmpeg-mono-16k", "sweep", 16000, 1, 0.8, "ffmpeg", ["-c:a", "libvorbis", "-q:a", "1"]), + ("loud-stereo", "loud", 44100, 2, 0.5, "oggenc", ["-q", "8"]), +] + +INPUTS = [] + + +def generate(ctx): + cases = [] + bench = None + for name, kind, rate, ch, secs, tool, args in CASES: + frames = max(1, int(round(secs * rate))) + sig = A.signal(kind, rate, ch, frames, seed=len(name)) + wav = A.wav(sig, rate, ch, float_=True) if tool == "ffmpeg" else A.wav(sig, rate, ch, 16) + if tool == "oggenc": + data = A.tool(ctx, "vorbis-tools", ["oggenc", "-Q", "--serial", "1234"] + args + ["-o", "{out}", "{in}"], wav, "wav", "ogg") + else: + data = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}"] + args + ["-f", "ogg", "-y", "{out}"], wav, "wav", "ogg") + rrate, rch, ref = A.ffdecode(ctx, data, ext="ogg") + raw = A.tool(ctx, "vorbis-tools", ["oggdec", "-Q", "-R", "-o", "{out}", "{in}"], data, "ogg", "raw") + case = {"name": name, "data": data, "rate": rrate, "channels": rch, "frames": len(raw) // (2 * rch), "ref16": raw, + "ffFrames": len(ref) // rch, "inputFrames": frames} + if len(ref) // rch == len(raw) // (2 * rch): + case["ffRef"] = A.f32le(ref) + cases.append(case) + ctx.emit("vorbis_cases", cases) + # bench: 10 s of stereo music at q5 + sig = A.signal("music", 44100, 2, 441000, seed=9) + data = A.tool(ctx, "vorbis-tools", ["oggenc", "-Q", "-q", "5", "-o", "{out}", "{in}"], A.wav(sig, 44100, 2, 16), "wav", "ogg") + ctx.emit("vorbis_bench", {"data": data, "frames": 441000, "rate": 44100, "channels": 2}) diff --git a/tools/fixtures/vorbis_enc.py b/tools/fixtures/vorbis_enc.py new file mode 100644 index 0000000..8cfc69c --- /dev/null +++ b/tools/fixtures/vorbis_enc.py @@ -0,0 +1,74 @@ +# Vorbis encoder fixtures (tools/fixtures.py): our encoder runs in the fixture step (tools/fixtures/_audio.py +# encode_luau_many) on test signals (qualities -1 .. 10, mono / stereo / 5.1, 8 .. 96 kHz, odd lengths, silence); +# oggdec (libvorbisfile) and ffmpeg decode every file, ogginfo checks the stream. Recorded per file: ogginfo's warnings +# and errors, oggdec's frame count, the SNR of oggdec's and ffmpeg's decodes against the input (no delay: the +# granules are exact). +# tests/gen/vorbis_enc.luau { name, sig, quality, rate, channels, frames, ogginfo, oggdecFrames, oggdecSnr, +# ffFrames, ffSnr, ffErrors, kbps, data } +# tests/gen/vorbis_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } } +import importlib.util, os, re + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/vorbis", "src/Formats/codecs", "src/Formats/containers/Ogg"] + + +WAVE_FROM_VORBIS6 = [0, 2, 1, 4, 5, 3] # vorbis channel k is WAVE channel WAVE_FROM_VORBIS6[k] + + +def reorder(x): + out = [0.0] * len(x) + for i in range(0, len(x) - 5, 6): + for k in range(6): + out[i + k] = x[i + WAVE_FROM_VORBIS6[k]] + return out + + +def generate(ctx): + sigs = {} + + def sig(kind, ch, frames, rate): + name = "%s_%d_%d_%d" % (kind, ch, frames, rate) + if name not in sigs: + sigs[name] = (A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=frames % 1000 + ch))), rate, ch) + return name + + cases = [] + for q in (-1, 0, 3, 6, 10): + cases.append(("music-st-44k-q%d" % q, sig("music", 2, 44100, 44100), q)) + cases.append(("sine-st-44k-q3", sig("sine", 2, 30000, 44100), 3)) + cases.append(("sweep-mono-48k-q3", sig("sweep", 1, 40000, 48000), 3)) + cases.append(("noise-mono-22k-q5", sig("noise", 1, 15000, 22050), 5)) + cases.append(("music-mono-8k-q2", sig("music", 1, 9000, 8000), 2)) + cases.append(("music-st-96k-q4", sig("music", 2, 30000, 96000), 4)) + cases.append(("music-6ch-48k-q3", sig("music", 6, 20000, 48000), 3)) + cases.append(("square-st-32k-q5", sig("square", 2, 20000, 32000), 5)) + cases.append(("loud-st-44k-q8", sig("loud", 2, 20000, 44100), 8)) + cases.append(("silence-st-44k", sig("silence", 2, 10000, 44100), 3)) + for n in (1, 100, 1024, 1025, 3000): + cases.append(("len-%d" % n, sig("music", 2, n, 44100), 3)) + ctx.emit("vorbis_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()}) + outs = A.encode_luau_many(ctx, "audio/vorbis", [(c[1], "{ quality = %d }" % c[2]) for c in cases], "vorbis_enc_sigs") + emitted = [] + for (name, sigmod, q), data in zip(cases, outs): + samples, rate, ch = sigs[sigmod] + frames = len(samples) // ch + info = A.tool(ctx, "vorbis-tools", ["sh", "-c", "ogginfo {in} 2>&1; true"], data, "ogg").decode(errors="replace") + problems = "\n".join(l for l in info.split("\n") if re.search(r"(?i)warning|error", l)) + raw = A.tool(ctx, "vorbis-tools", ["oggdec", "-Q", "-R", "-o", "{out}", "{in}"], data, "ogg", "raw") + od = [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw) - 1, 2)] + osnr, _ = A.snr(samples, od, ch) # (oggdec -R keeps the Vorbis channel order) + ffe = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], data, "ogg").decode(errors="replace") + _, fch, ff = A.ffdecode(ctx, data, ext="ogg") + if ch == 6: # ffmpeg reorders to WAVE order (FL FR FC LFE RL RR); Vorbis order is FL FC FR RL RR LFE + ff = reorder(ff) + fsnr, _ = A.snr(samples, ff, ch) if fch == ch else (-99.0, 0) + e = {"name": name, "sig": sigmod, "quality": q, "rate": rate, "channels": ch, "frames": frames, "ogginfo": problems, + "oggdecFrames": len(od) // ch, "oggdecSnr": osnr, "ffFrames": len(ff) // max(1, fch), "ffSnr": fsnr, + "ffErrors": ffe, "kbps": len(data) * 8 / (frames / rate) / 1000, "data": data} + emitted.append(e) + print(" vorbis_enc: %-22s %7.1f kbps oggdec %d/%d frames %.1f dB ffmpeg %.1f dB%s" % (name, e["kbps"], e["oggdecFrames"], frames, + osnr, fsnr, (" OGGINFO " + problems[:80]) if problems else "")) + ctx.emit("vorbis_enc", emitted)