From 9c553b9d1a5d18c41d608a6b1780c700104df95f Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 12:00:59 -0500 Subject: [PATCH] ws-cleanup: shared plumbing: Err.from, core/Sniff, Pcm.drain, Bits.msbPut; DUP lint; tools/move.py - core/Err.from(message, offset?, kind?): the private-submodule -> Err plumbing (a kind, or a 'code: ' prefix / 'truncated' / 'past the end' in the message) that Brotli, Bzip2, Zstd, Jpeg, WOFF2, FBX, plist, msgpack and bmfont each wrote. - core/Sniff (new): Sniff.text(r, n, trim?) (the start of a text file without its BOM), Sniff.dropBom(s), Sniff.magic(r, s); 13 text formats' sniff / decode BOM handling goes through it. - codecs/Pcm.drain(dec, source?, maxFrames?): a format's decode() through its open(); the collect-the-Decoder loops of aac, aiff, au, caf, flac, m4a, mp3, opus, vorbis and wav are one call each. - core/Bits.msbPut: the MSB-first bit writer the MP3 / MP2 / FLAC encoders each copied. - tools/lint_rules.py DUP: a function body of 12+ code lines repeated token for token in another module fails. - tools/move.py: moves a module and rewrites every reference (requires, deps, headers, fixture INPUTS, docs). - tools/fixtures/zstd.py: the incompressible corpus is smaller (zstd.luau 15.1 -> 13.4 MB; every fixture module is now under 14.3 MB). - tools/bench.luau: MPEG-1 also runs with the api's LuaJIT trace limits; the sections that compare tuned / default limits set them explicitly (jitTune), so the order of sections no longer leaks the tuning. Co-Authored-By: Claude Opus 5.5 --- src/Formats/Registry.luau | 38 +++++++------- src/Formats/audio/aac/init.luau | 20 ++------ src/Formats/audio/aiff/init.luau | 7 +-- src/Formats/audio/au/init.luau | 7 +-- src/Formats/audio/caf/init.luau | 20 ++------ src/Formats/audio/flac/Encode.luau | 22 ++------ src/Formats/audio/flac/init.luau | 31 +---------- src/Formats/audio/m4a/init.luau | 30 ++--------- src/Formats/audio/mp3/Encode2.luau | 21 ++------ src/Formats/audio/mp3/Encode3.luau | 21 ++------ src/Formats/audio/mp3/init.luau | 13 ++--- src/Formats/audio/opus/init.luau | 21 +------- src/Formats/audio/vorbis/init.luau | 23 +-------- src/Formats/audio/wav/init.luau | 16 ++---- src/Formats/cad/step/init.luau | 8 ++- src/Formats/codecs/Brotli/init.luau | 13 ++--- src/Formats/codecs/Bzip2/init.luau | 10 +--- src/Formats/codecs/Jpeg/init.luau | 6 +-- src/Formats/codecs/Pcm/init.luau | 20 ++++++++ src/Formats/codecs/Zstd/init.luau | 10 +--- src/Formats/core/Bits.luau | 23 +++++++++ src/Formats/core/Err.luau | 36 +++++++++++++ src/Formats/core/Sniff.luau | 36 +++++++++++++ src/Formats/data/csv/init.luau | 7 ++- src/Formats/data/ini/init.luau | 7 ++- src/Formats/data/json/init.luau | 8 ++- src/Formats/data/msgpack/init.luau | 2 +- src/Formats/data/plist/init.luau | 2 +- src/Formats/data/xml/init.luau | 8 ++- src/Formats/font/bmfont/init.luau | 3 +- src/Formats/font/woff2/init.luau | 4 +- src/Formats/model/fbx/init.luau | 13 +---- src/Formats/model/gltf/init.luau | 5 +- src/Formats/playlist/m3u/init.luau | 8 ++- src/Formats/playlist/pls/init.luau | 8 ++- src/Formats/subtitle/ass/init.luau | 12 ++--- src/Formats/subtitle/srt/init.luau | 12 ++--- src/Formats/subtitle/vtt/init.luau | 12 ++--- src/Formats/vector/svg/init.luau | 8 ++- src/Formats/vector/tiled/init.luau | 8 ++- tools/bench.luau | 53 ++++++++++++++----- tools/fixtures/zstd.py | 2 +- tools/lint_rules.py | 31 +++++++++++ tools/move.py | 79 +++++++++++++++++++++++++++++ 44 files changed, 374 insertions(+), 370 deletions(-) create mode 100644 src/Formats/core/Sniff.luau create mode 100644 tools/move.py diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 86bd0ce..79b5789 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -152,7 +152,7 @@ local list: { Entry } = { path = "audio/aac", extensions = { "aac", "adts" }, mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Pcm" }, caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, load = function() return require("@formats/audio/aac") @@ -188,7 +188,7 @@ local list: { Entry } = { path = "audio/caf", extensions = { "caf", "caff" }, mime = { "audio/x-caf" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac", "codecs/Pcm" }, caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, load = function() return require("@formats/audio/caf") @@ -200,7 +200,7 @@ local list: { Entry } = { path = "audio/flac", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" }, 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") @@ -212,7 +212,7 @@ local list: { Entry } = { path = "audio/m4a", extensions = { "m4a", "m4b", "m4r" }, mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac", "codecs/Pcm" }, caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, load = function() return require("@formats/audio/m4a") @@ -224,7 +224,7 @@ local list: { Entry } = { path = "audio/mp3", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm", "codecs/Resample" }, + deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/Pcm", "codecs/Resample" }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 }, load = function() return require("@formats/audio/mp3") @@ -272,7 +272,7 @@ local list: { Entry } = { path = "audio/wav", extensions = { "wav", "wave", "rf64", "bw64" }, mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, load = function() return require("@formats/audio/wav") @@ -404,7 +404,7 @@ local list: { Entry } = { path = "model/gltf", extensions = { "gltf", "glb" }, mime = { "model/gltf+json", "model/gltf-binary" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64", "core/Sniff" }, caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, load = function() return require("@formats/model/gltf") @@ -488,7 +488,7 @@ local list: { Entry } = { path = "cad/step", extensions = { "step", "stp", "p21" }, mime = { "model/step", "application/step", "application/p21" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, load = function() return require("@formats/cad/step") @@ -656,7 +656,7 @@ local list: { Entry } = { path = "data/csv", extensions = { "csv", "tsv" }, mime = { "text/csv", "text/tab-separated-values" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" }, caps = { decode = true, encode = true, header = true }, load = function() return require("@formats/data/csv") @@ -668,7 +668,7 @@ local list: { Entry } = { path = "data/ini", extensions = { "ini", "cfg", "conf", "inf", "desktop" }, mime = { "text/plain" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true }, load = function() return require("@formats/data/ini") @@ -680,7 +680,7 @@ local list: { Entry } = { path = "data/json", extensions = { "json", "jsonl", "ndjson", "geojson" }, mime = { "application/json", "application/x-ndjson" }, - deps = { "core/Err", "core/Bytes", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "codecs/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true, streaming = true }, load = function() return require("@formats/data/json") @@ -728,7 +728,7 @@ local list: { Entry } = { path = "data/xml", extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, mime = { "application/xml", "text/xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Sniff" }, caps = { decode = true, encode = true, namespaces = true, streaming = true }, load = function() return require("@formats/data/xml") @@ -752,7 +752,7 @@ local list: { Entry } = { path = "vector/svg", extensions = { "svg" }, mime = { "image/svg+xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend", "core/Sniff" }, caps = { decode = true, encode = true, rasterize = true, text = false }, load = function() return require("@formats/vector/svg") @@ -764,7 +764,7 @@ local list: { Entry } = { path = "vector/tiled", extensions = { "tmx", "tmj", "tsx", "tsj" }, mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" }, - deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate", "core/Sniff" }, caps = { decode = true, encode = true, tilesets = true, infinite = true }, load = function() return require("@formats/vector/tiled") @@ -800,7 +800,7 @@ local list: { Entry } = { path = "subtitle/ass", extensions = { "ass", "ssa" }, mime = { "text/x-ssa", "text/x-ass" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = true }, load = function() return require("@formats/subtitle/ass") @@ -812,7 +812,7 @@ local list: { Entry } = { path = "subtitle/srt", extensions = { "srt" }, mime = { "application/x-subrip", "text/srt" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = false }, load = function() return require("@formats/subtitle/srt") @@ -824,7 +824,7 @@ local list: { Entry } = { path = "subtitle/vtt", extensions = { "vtt", "webvtt" }, mime = { "text/vtt" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = true }, load = function() return require("@formats/subtitle/vtt") @@ -908,7 +908,7 @@ local list: { Entry } = { path = "playlist/m3u", extensions = { "m3u", "m3u8" }, mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" }, caps = { decode = true, encode = true, hls = true }, load = function() return require("@formats/playlist/m3u") @@ -920,7 +920,7 @@ local list: { Entry } = { path = "playlist/pls", extensions = { "pls" }, mime = { "audio/x-scpls", "audio/scpls" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" }, caps = { decode = true, encode = true }, load = function() return require("@formats/playlist/pls") diff --git a/src/Formats/audio/aac/init.luau b/src/Formats/audio/aac/init.luau index 84ded12..21deaf5 100644 --- a/src/Formats/audio/aac/init.luau +++ b/src/Formats/audio/aac/init.luau @@ -8,6 +8,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") local Aac = require("@formats/codecs/Aac") -- ------------------------------------------------------------------------------------------------ contract @@ -16,7 +17,7 @@ local AacFormat = { category = "audio", extensions = { "aac", "adts" }, mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Pcm" }, caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, } @@ -256,22 +257,7 @@ function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, return nil, err end local d: any = dec - local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) - local done = 0 - while done < d.frames do - local b, n = d:read(math.min(65536, d.frames - done)) - if n == 0 then - break - end - buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) - done += n - end - if d.error then - return nil, d.error - end - audio.tags = d.tags - audio.meta.source = { format = "aac", codec = "aac", bitrate = d.bitrate } - return audio, nil + return Pcm.drain(d, { format = "aac", codec = "aac", bitrate = d.bitrate }) end return AacFormat diff --git a/src/Formats/audio/aiff/init.luau b/src/Formats/audio/aiff/init.luau index dfd2a29..baf8ad2 100644 --- a/src/Formats/audio/aiff/init.luau +++ b/src/Formats/audio/aiff/init.luau @@ -248,12 +248,7 @@ function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err. 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 + return Pcm.drain(dec) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/au/init.luau b/src/Formats/audio/au/init.luau index 0215799..08a45ab 100644 --- a/src/Formats/audio/au/init.luau +++ b/src/Formats/audio/au/init.luau @@ -66,12 +66,7 @@ function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Er 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 + return Pcm.drain(dec) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/caf/init.luau b/src/Formats/audio/caf/init.luau index f935b96..48769f9 100644 --- a/src/Formats/audio/caf/init.luau +++ b/src/Formats/audio/caf/init.luau @@ -9,6 +9,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") local Aac = require("@formats/codecs/Aac") local Alac = require("@formats/codecs/Alac") @@ -18,7 +19,7 @@ local Caf = { category = "audio", extensions = { "caf", "caff" }, mime = { "audio/x-caf" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac", "codecs/Pcm" }, caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, } @@ -559,22 +560,7 @@ function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E return nil, err end local d: any = dec - local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) - local done = 0 - while done < d.frames do - local b, n = d:read(math.min(65536, d.frames - done)) - if n == 0 then - break - end - buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) - done += n - end - if d.error then - return nil, d.error - end - audio.tags = d.tags - audio.meta.source = { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample } - return audio, nil + return Pcm.drain(d, { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample }) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/flac/Encode.luau b/src/Formats/audio/flac/Encode.luau index 09bb289..ecc187c 100644 --- a/src/Formats/audio/flac/Encode.luau +++ b/src/Formats/audio/flac/Encode.luau @@ -10,6 +10,7 @@ -- 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 Bits = require("@formats/core/Bits") local Md5 = require("@formats/core/Md5") local VorbisComment = require("@formats/codecs/VorbisComment") local Frame = require("@formats/audio/flac/Frame") @@ -35,7 +36,7 @@ end Encode.crc8, Encode.crc16 = crc8, crc16 -- ------------------------------------------------------------------------------------------------ bit writer (MSB first) -type W = { buf: buffer, pos: number, acc: number, cnt: number } +type W = Bits.RawWriter local function ensure(w: W, n: number) local need = w.pos + n + 16 @@ -47,24 +48,7 @@ local function ensure(w: W, n: number) 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 put = Bits.msbPut local function putSigned(w: W, v: number, n: number) put(w, if v < 0 then v + POW[n + 1] else v, n) diff --git a/src/Formats/audio/flac/init.luau b/src/Formats/audio/flac/init.luau index 724774d..26e321c 100644 --- a/src/Formats/audio/flac/init.luau +++ b/src/Formats/audio/flac/init.luau @@ -29,7 +29,7 @@ local Flac = { category = "audio", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, } @@ -89,34 +89,7 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er if d.frames > limit or d.frames * d.channels > 2 ^ 28 then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) end - local ch = d.channels - local parts, total = {}, 0 - if d.frames > 0 then - local out, n = d:read(d.frames) - table.insert(parts, out) - total = n - end - while true do -- frames past what STREAMINFO / the scan said - local out, n = d:read(65536) - if n == 0 then - break - end - table.insert(parts, out) - total += n - if total > limit then - return nil, Err.new(Err.LIMIT, "stream over the frame limit") - end - end - local a = Types.Audio.new(d.sampleRate, ch, total) - local o = 0 - for _, p in parts do - local n = math.min(buffer.len(p), total * ch * 4 - o) - buffer.copy(a.samples, o, p, 0, n) - o += n - end - a.tags = d.tags - a.meta.source = { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures, comments = d.comments } - return a, nil + return Pcm.drain(d, { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures, comments = d.comments }, limit) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/m4a/init.luau b/src/Formats/audio/m4a/init.luau index c7b06b8..babc9bd 100644 --- a/src/Formats/audio/m4a/init.luau +++ b/src/Formats/audio/m4a/init.luau @@ -9,6 +9,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") local IsoBmff = require("@formats/containers/IsoBmff") local Aac = require("@formats/codecs/Aac") local Alac = require("@formats/codecs/Alac") @@ -19,7 +20,7 @@ local M4a = { category = "audio", extensions = { "m4a", "m4b", "m4r" }, mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac", "codecs/Pcm" }, caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, } @@ -306,32 +307,11 @@ function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E return nil, err end local d: any = dec - local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) - local done = 0 - local chunk = buffer.create(65536 * d.channels * 4) - while done < d.frames do - local b, n = d:read(math.min(65536, d.frames - done), chunk) - if n == 0 then - break - end - buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) - done += n - end - if d.error then - return nil, d.error - end - if done < d.frames then - local short = buffer.create(done * d.channels * 4) - buffer.copy(short, 0, audio.samples, 0, buffer.len(short)) - audio.samples = short - audio.frames = done - end - audio.tags = d.tags - audio.meta.source = { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand } - if #d.pictures > 0 then + local audio, derr = Pcm.drain(d, { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand }) + if audio and #d.pictures > 0 then audio.meta.pictures = d.pictures end - return audio, nil + return audio, derr end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/mp3/Encode2.luau b/src/Formats/audio/mp3/Encode2.luau index 3ce1594..5d8db97 100644 --- a/src/Formats/audio/mp3/Encode2.luau +++ b/src/Formats/audio/mp3/Encode2.luau @@ -8,6 +8,7 @@ -- 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 Bits = require("@formats/core/Bits") local T = require("@formats/audio/mp3/Tables") local Analysis = require("@formats/audio/mp3/Analysis") @@ -87,24 +88,8 @@ local BITRATES_V1 = { 32, 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 } 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 +type W = Bits.RawWriter +local put = Bits.msbPut export type Source = { sampleRate: number, diff --git a/src/Formats/audio/mp3/Encode3.luau b/src/Formats/audio/mp3/Encode3.luau index 39e6dbf..e088369 100644 --- a/src/Formats/audio/mp3/Encode3.luau +++ b/src/Formats/audio/mp3/Encode3.luau @@ -8,6 +8,7 @@ -- 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 Bits = require("@formats/core/Bits") local E = require("@formats/audio/mp3/EncTables") local T = require("@formats/audio/mp3/Tables") local Analysis = require("@formats/audio/mp3/Analysis") @@ -87,25 +88,9 @@ for m = 0, 15 do end -- ------------------------------------------------------------------------------------------------ bit writer -type W = { buf: buffer, pos: number, acc: number, cnt: number } +type W = Bits.RawWriter -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 put = Bits.msbPut Encode3.put = put -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau index 9fd3a8c..5029c4e 100644 --- a/src/Formats/audio/mp3/init.luau +++ b/src/Formats/audio/mp3/init.luau @@ -32,7 +32,7 @@ local Mp3 = { category = "audio", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm", "codecs/Resample" }, + deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/Pcm", "codecs/Resample" }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 }, } @@ -91,14 +91,11 @@ function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err if not dec then return nil, err end - local a = Types.Audio.new(dec.sampleRate, dec.channels, dec.frames) - local _, n = dec:read(dec.frames, a.samples) - if n < dec.frames then - return nil, Err.new(Err.CORRUPT, string.format("decoded %d of %d frames", n, dec.frames)) + local a, derr = Pcm.drain(dec, { format = "mp3", layer = dec.layer, version = dec.version, bitrate = dec.bitrate, vbr = dec.vbr }) + if a and a.frames < dec.frames then + return nil, Err.new(Err.CORRUPT, string.format("decoded %d of %d frames", a.frames, dec.frames)) end - a.tags = dec.tags - a.meta.source = { format = "mp3", layer = dec.layer, version = dec.version, bitrate = dec.bitrate, vbr = dec.vbr } - return a, nil + return a, derr end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau index 9138762..b1d213d 100644 --- a/src/Formats/audio/opus/init.luau +++ b/src/Formats/audio/opus/init.luau @@ -191,26 +191,7 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) if not dec then return nil, err end - local ch = dec.channels - local a = Types.Audio.new(SAMPLE_RATE, ch, dec.frames) - local total = 0 - while total < dec.frames do - local pcm, n = dec:read(math.min(65536, dec.frames - total)) - if n == 0 then - break - end - buffer.copy(a.samples, total * ch * 4, pcm, 0, n * ch * 4) - total += n - end - if total < dec.frames then -- a truncated file: keep what decoded - local s = buffer.create(total * ch * 4) - buffer.copy(s, 0, a.samples, 0, total * ch * 4) - a.samples = s - a.frames = total - end - a.tags = dec.tags - a.meta.source = { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, comments = dec.comments, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate } - return a, nil + return Pcm.drain(dec, { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, comments = dec.comments, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate }) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/vorbis/init.luau b/src/Formats/audio/vorbis/init.luau index 0cc48bc..8081e1c 100644 --- a/src/Formats/audio/vorbis/init.luau +++ b/src/Formats/audio/vorbis/init.luau @@ -93,28 +93,7 @@ function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err. 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 + return Pcm.drain(dec) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/wav/init.luau b/src/Formats/audio/wav/init.luau index ed5d071..1c1f60b 100644 --- a/src/Formats/audio/wav/init.luau +++ b/src/Formats/audio/wav/init.luau @@ -18,6 +18,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") local Riff = require("@formats/containers/Riff") local Codecs = require("@formats/audio/wav/Codecs") @@ -27,7 +28,7 @@ local Wav = { category = "audio", extensions = { "wav", "wave", "rf64", "bw64" }, mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, } @@ -170,23 +171,14 @@ function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err if not dec then return nil, err end - local a = Types.Audio.new(dec.sampleRate, dec.channels, dec.frames) - local _, n = dec:read(dec.frames, a.samples) - if n < dec.frames then - local s = buffer.create(n * dec.channels * 4) - buffer.copy(s, 0, a.samples, 0, n * dec.channels * 4) - a.samples, a.frames = s, n - end - a.tags = dec.tags - a.meta.source = { + return Pcm.drain(dec, { format = "wav", codec = dec.format, bitDepth = dec.bitsPerSample, container = dec.container, channelMask = dec.channelMask, truncated = dec.truncated, - } - return a, nil + }) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/cad/step/init.luau b/src/Formats/cad/step/init.luau index 1062a7a..d490f0c 100644 --- a/src/Formats/cad/step/init.luau +++ b/src/Formats/cad/step/init.luau @@ -22,6 +22,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Parse = require("@formats/cad/step/Parse") @@ -34,7 +35,7 @@ local Step = { category = "cad", extensions = { "step", "stp", "p21" }, mime = { "model/step", "application/step", "application/p21" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, } @@ -83,10 +84,7 @@ Step.schemaOf = schemaOf -- ------------------------------------------------------------------------------------------------ sniff function Step.sniff(r: Bytes.Reader): number - local head = r:peek(256) - if string.sub(head, 1, 3) == "\239\187\191" then - head = string.sub(head, 4) - end + local head = Sniff.text(r, 256) head = string.gsub(head, "^%s*/%*.-%*/", "") if string.find(head, "^%s*ISO%-10303%-21%s*;") then return 1 diff --git a/src/Formats/codecs/Brotli/init.luau b/src/Formats/codecs/Brotli/init.luau index 2fd2bb1..9d50131 100644 --- a/src/Formats/codecs/Brotli/init.luau +++ b/src/Formats/codecs/Brotli/init.luau @@ -86,16 +86,9 @@ function Brotli.decompress(buf: buffer | string, offset: number?, length: number end local out, size, consumed = Decode.decompress(b, o, l, maxBytes, S, large) if not out then - local msg = tostring(size) - local code = Err.CORRUPT - if string.find(msg, "truncated", 1, true) then - code = Err.TRUNCATED - elseif string.sub(msg, 1, 6) == "limit:" then - code = Err.LIMIT - elseif string.sub(msg, 1, 12) == "unsupported:" then - code = Err.UNSUPPORTED - end - return nil, Err.new(code, "brotli: " .. msg, o) + local e = Err.from(size, o) + e.message = "brotli: " .. e.message + return nil, e end local res = out if buffer.len(out) ~= size then diff --git a/src/Formats/codecs/Bzip2/init.luau b/src/Formats/codecs/Bzip2/init.luau index c9a2584..86c72db 100644 --- a/src/Formats/codecs/Bzip2/init.luau +++ b/src/Formats/codecs/Bzip2/init.luau @@ -19,14 +19,6 @@ export type Options = { maxBytes: number?, -- refuse output larger than this (default 2^30) } -local KINDS = { - truncated = Err.TRUNCATED, - corrupt = Err.CORRUPT, - checksum = Err.CHECKSUM, - limit = Err.LIMIT, - unsupported = Err.UNSUPPORTED, -} - -- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length) @@ -39,7 +31,7 @@ function Bzip2.decompress(buf: buffer | string, offset: number?, length: number? end local out, nOut, consumed = Decode.decode(b, o, o + l, maxBytes) if not out then - return nil, Err.new(KINDS[consumed] or Err.CORRUPT, "bzip2: " .. tostring(nOut), o) + return nil, Err.from("bzip2: " .. tostring(nOut), o, consumed) end local res = out if buffer.len(out) ~= nOut then diff --git a/src/Formats/codecs/Jpeg/init.luau b/src/Formats/codecs/Jpeg/init.luau index 3163222..de75b4c 100644 --- a/src/Formats/codecs/Jpeg/init.luau +++ b/src/Formats/codecs/Jpeg/init.luau @@ -72,8 +72,6 @@ export type Info = { avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header } -local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG } - local function range(buf: buffer, off: number?, len: number?): (number, number) local n = buffer.len(buf) local o = math.clamp(math.floor(tonumber(off) or 0), 0, n) @@ -87,7 +85,7 @@ local function parse(buf: buffer, o: number, l: number, opts: any, headerOnly: b return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st)) end if not st then - return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed", o) + return nil, Err.from(msg or "decode failed", o, code) end return st, nil end @@ -187,7 +185,7 @@ local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions? return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) end if not w then - return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px), o) + return nil, Err.from(px, o, h) end space = sp if opts and opts.orient then diff --git a/src/Formats/codecs/Pcm/init.luau b/src/Formats/codecs/Pcm/init.luau index ab98e26..6faadec 100644 --- a/src/Formats/codecs/Pcm/init.luau +++ b/src/Formats/codecs/Pcm/init.luau @@ -150,6 +150,26 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) return a, nil end +-- drain(dec, source?, maxFrames?) -> Types.Audio | nil, Err: a format's decode() through its open(): every frame of +-- the Decoder (dec.frames is only a hint: short or long streams keep what decodes), dec.tags, meta.source = source +-- (default dec.source). A decoder that recorded a failure in dec.error (an Err) fails the drain. +function Pcm.drain(dec: any, source: { [string]: any }?, maxFrames: number?): (Types.Audio?, Err.Err?) + local src, err = Pcm.source(dec) + if not src then + return nil, err + end + local a, cerr = Pcm.collect(src, maxFrames) + if not a then + return nil, cerr + end + if Err.is(dec.error) then + return nil, dec.error + end + a.tags = dec.tags or {} + a.meta.source = source or dec.source + 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) diff --git a/src/Formats/codecs/Zstd/init.luau b/src/Formats/codecs/Zstd/init.luau index 5a1c5f3..2d9cb04 100644 --- a/src/Formats/codecs/Zstd/init.luau +++ b/src/Formats/codecs/Zstd/init.luau @@ -21,14 +21,6 @@ export type Options = { verify: boolean?, -- check the content checksum when a frame has one (default true) } -local CODES: { [string]: string } = { - TRUNCATED = Err.TRUNCATED, - CORRUPT = Err.CORRUPT, - CHECKSUM = Err.CHECKSUM, - UNSUPPORTED = Err.UNSUPPORTED, - LIMIT = Err.LIMIT, -} - -- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F) Zstd.MAGIC = "\40\181\47\253" @@ -56,7 +48,7 @@ function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, local verify = not (opts and opts.verify == false) local out, len, consumed, at = Decode.decompress(b, o, o + l, maxBytes, verify) if not out then - return nil, Err.new(CODES[len] or Err.CORRUPT, tostring(consumed), at) + return nil, Err.from(consumed, at, len) end if buffer.len(out) ~= len then local r = buffer.create(len) diff --git a/src/Formats/core/Bits.luau b/src/Formats/core/Bits.luau index e2d1fa1..ca79f13 100644 --- a/src/Formats/core/Bits.luau +++ b/src/Formats/core/Bits.luau @@ -12,6 +12,8 @@ -- local br = Bits.lsbReader(buf, offset?, length?) -- or Bits.msbReader -- local v = br:read(5); if br.err then return nil, br.err end -- local bw = Bits.msbWriter(); bw:write(0b101, 3); local out = bw:finish() +-- local w = { buf = buffer.create(n), pos = 0, acc = 0, cnt = 0 }; Bits.msbPut(w, v, nbits) -- encoders' fast path +-- (a plain record the caller sizes / grows itself: MP3, MP2 and FLAC frames) local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") @@ -276,6 +278,27 @@ function MsbW.finish(self: any): buffer return self.out:finish() end +-- msbPut(w, v, n): append the low n bits (n <= 32) of the non-negative integer v to the record w = { buf, pos, acc, +-- cnt }, MSB first. No growth: the caller keeps buf large enough (whole bytes go to buf[pos]; acc holds cnt < 8 bits). +export type RawWriter = { buf: buffer, pos: number, acc: number, cnt: number } +function Bits.msbPut(w: RawWriter, 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) + buffer.writeu8(b, p, byte) + p += 1 + acc -= byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + -- lsbWriter(capacity?) / msbWriter(capacity?) -> BitWriter function Bits.lsbWriter(capacity: number?): BitWriter return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) :: any diff --git a/src/Formats/core/Err.luau b/src/Formats/core/Err.luau index 80b8373..784a545 100644 --- a/src/Formats/core/Err.luau +++ b/src/Formats/core/Err.luau @@ -38,6 +38,42 @@ function Err.new(code: string, message: string, offset: number?): Err return setmetatable({ code = code, message = message, offset = offset, format = nil :: string? }, Meta) :: any end +-- the kinds a private submodule may report: Err codes in either case ("truncated", "CORRUPT", ...) +local KIND: { [string]: string } = {} +for _, c in { "TRUNCATED", "CORRUPT", "CHECKSUM", "UNSUPPORTED", "LIMIT", "ARG", "IO", "UNKNOWN_FORMAT" } do + KIND[c] = c + KIND[string.lower(c)] = c +end + +-- from(message, offset?, kind?) -> Err: the error plumbing between a private submodule (which returns +-- nil / false, "message"[, kind]) and the contract. kind names the code ("truncated", "LIMIT", ...); without it the +-- message decides: a ": ..." prefix ("limit: ...", "unsupported: ...") names the code and is dropped; +-- "...truncated..." / "...past the end" / "...runs past..." -> TRUNCATED; "unsupported..." -> UNSUPPORTED; +-- "checksum..." -> CHECKSUM; anything else CORRUPT. An Err passes +-- through unchanged. +function Err.from(message: any, offset: number?, kind: string?): Err + if Err.is(message) then + return message + end + local msg = if message == nil then "failed" else tostring(message) + local code = kind and KIND[kind] + if not code then + local head, rest = string.match(msg, "^(%a+):%s*(.*)$") + if head and KIND[head] then + code, msg = KIND[head], rest :: string + elseif string.find(msg, "truncated", 1, true) or string.find(msg, "past the end", 1, true) or string.find(msg, "runs past", 1, true) then + code = Err.TRUNCATED + elseif string.find(msg, "^unsupported") then + code = Err.UNSUPPORTED + elseif string.find(msg, "^checksum") then + code = Err.CHECKSUM + else + code = Err.CORRUPT + end + end + return Err.new(code, msg, offset) +end + -- is(v) -> true when v is an Err function Err.is(v: any): boolean return type(v) == "table" and getmetatable(v) == Meta diff --git a/src/Formats/core/Sniff.luau b/src/Formats/core/Sniff.luau new file mode 100644 index 0000000..c849e1a --- /dev/null +++ b/src/Formats/core/Sniff.luau @@ -0,0 +1,36 @@ +--!strict +-- core/Sniff: helpers for the formats' sniff functions (which return 0..1 from the first bytes, never consuming and +-- never throwing): magic comparison and the start of a text file without its UTF-8 byte order mark. +-- +-- function Qoi.sniff(r) return Sniff.magic(r, "qoif") end -- 1 or 0 +-- function Gz.sniff(r) return Sniff.magic(r, "\31\139\8", 0, 0.9) end -- a custom score +-- local head = Sniff.text(r, 64) -- the first 64 bytes, BOM dropped +-- local head = Sniff.text(r, 512, true) -- ... and leading whitespace too +-- local text = Sniff.dropBom(whole) -- decoders: the BOM off a whole file +local Sniff = {} + +type Peeker = { peek: (any, number, number?) -> string } + +-- magic(r, s, at?, score?) -> score (default 1) when the bytes at offset at (default 0) are s, else 0 +function Sniff.magic(r: Peeker, s: string, at: number?, score: number?): number + return if r:peek(#s, at) == s then score or 1 else 0 +end + +-- dropBom(s) -> s without a leading UTF-8 byte order mark (for decoders reading a whole text file) +function Sniff.dropBom(s: string): string + return if string.sub(s, 1, 3) == "\239\187\191" then string.sub(s, 4) else s +end + +-- text(r, n, trim?) -> up to n bytes from the start without a UTF-8 BOM (and leading whitespace when trim) +function Sniff.text(r: Peeker, n: number, trim: boolean?): string + local s = r:peek(n) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + if trim then + s = string.match(s, "^%s*(.*)$") :: string + end + return s +end + +return Sniff diff --git a/src/Formats/data/csv/init.luau b/src/Formats/data/csv/init.luau index 0e57eea..8bab313 100644 --- a/src/Formats/data/csv/init.luau +++ b/src/Formats/data/csv/init.luau @@ -8,6 +8,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Json = require("@formats/codecs/Json") @@ -18,7 +19,7 @@ local Csv = { category = "data", extensions = { "csv", "tsv" }, mime = { "text/csv", "text/tab-separated-values" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" }, caps = { decode = true, encode = true, header = true }, } @@ -175,9 +176,7 @@ end function Csv.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local s = buffer.readstring(r.buf, r.base, r.limit - r.base) - if sub(s, 1, 3) == "\239\187\191" then - s = sub(s, 4) - end + s = Sniff.dropBom(s) local rows, err = Csv.parse(s, opts) if not rows then return nil, err diff --git a/src/Formats/data/ini/init.luau b/src/Formats/data/ini/init.luau index 816bd6a..14a94c8 100644 --- a/src/Formats/data/ini/init.luau +++ b/src/Formats/data/ini/init.luau @@ -9,6 +9,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Json = require("@formats/codecs/Json") @@ -19,7 +20,7 @@ local Ini = { category = "data", extensions = { "ini", "cfg", "conf", "inf", "desktop" }, mime = { "text/plain" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true }, } @@ -73,9 +74,7 @@ end function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local s = buffer.readstring(r.buf, r.base, r.limit - r.base) - if string.sub(s, 1, 3) == "\239\187\191" then - s = string.sub(s, 4) - end + s = Sniff.dropBom(s) local root = Types.object() local cur = root local lastKey: string? = nil diff --git a/src/Formats/data/json/init.luau b/src/Formats/data/json/init.luau index bf75d5f..78a4df7 100644 --- a/src/Formats/data/json/init.luau +++ b/src/Formats/data/json/init.luau @@ -5,6 +5,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Json = require("@formats/codecs/Json") @@ -14,7 +15,7 @@ local JsonFormat = { category = "data", extensions = { "json", "jsonl", "ndjson", "geojson" }, mime = { "application/json", "application/x-ndjson" }, - deps = { "core/Err", "core/Bytes", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "codecs/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true, streaming = true }, } @@ -27,10 +28,7 @@ export type EncodeOptions = Json.EncodeOptions & { -- ------------------------------------------------------------------------------------------------ sniff function JsonFormat.sniff(r: Bytes.Reader): number - local head = r:peek(64) - if string.sub(head, 1, 3) == "\239\187\191" then - head = string.sub(head, 4) - end + local head = Sniff.text(r, 64) local first = string.match(head, "^[ \t\r\n]*(.)") if first == "{" then local nxt = string.match(head, "^[^{]*{[ \t\r\n]*(.)") diff --git a/src/Formats/data/msgpack/init.luau b/src/Formats/data/msgpack/init.luau index ecd96f9..aa624b8 100644 --- a/src/Formats/data/msgpack/init.luau +++ b/src/Formats/data/msgpack/init.luau @@ -40,7 +40,7 @@ function Msgpack.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) while not r:eof() do local v, e, at = Codec.decode(r, o) if e then - return nil, Err.new(if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED else Err.CORRUPT, e, at) + return nil, Err.from(e, at) end table.insert(out, v) end diff --git a/src/Formats/data/plist/init.luau b/src/Formats/data/plist/init.luau index aafd126..6f46277 100644 --- a/src/Formats/data/plist/init.luau +++ b/src/Formats/data/plist/init.luau @@ -143,7 +143,7 @@ function Plist.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if len >= 8 and buffer.readstring(r.buf, r.base, 6) == "bplist" then local v, e = Binary.decode(r.buf, r.base, len, opts) if e then - return nil, Err.new(if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED else Err.CORRUPT, e) + return nil, Err.from(e) end return v, nil end diff --git a/src/Formats/data/xml/init.luau b/src/Formats/data/xml/init.luau index c992418..6479ec5 100644 --- a/src/Formats/data/xml/init.luau +++ b/src/Formats/data/xml/init.luau @@ -5,6 +5,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Xml = require("@formats/codecs/Xml") @@ -15,7 +16,7 @@ local XmlFormat = { category = "data", extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, mime = { "application/xml", "text/xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Sniff" }, caps = { decode = true, encode = true, namespaces = true, streaming = true }, } @@ -24,10 +25,7 @@ export type EncodeOptions = Xml.EncodeOptions -- ------------------------------------------------------------------------------------------------ sniff function XmlFormat.sniff(r: Bytes.Reader): number - local head = r:peek(64) - if string.sub(head, 1, 3) == "\239\187\191" then - head = string.sub(head, 4) - end + local head = Sniff.text(r, 64) if string.match(head, "^<%?xml[ \t\r\n]") or string.sub(head, 1, 4) == "\255\254<\0" or string.sub(head, 1, 4) == "\254\255\0<" then return 0.5 end diff --git a/src/Formats/font/bmfont/init.luau b/src/Formats/font/bmfont/init.luau index f70cf94..617033a 100644 --- a/src/Formats/font/bmfont/init.luau +++ b/src/Formats/font/bmfont/init.luau @@ -191,8 +191,7 @@ function Bmfont.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end if not d then - local code = if err and (string.find(err, "truncated", 1, true) or string.find(err, "past the end", 1, true)) then Err.TRUNCATED elseif err and string.find(err, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT - return nil, Err.new(code, err or "bad descriptor", r.base) + return nil, Err.from(err or "bad descriptor", r.base) end local f = face(d, variant) if opts and type(opts.pages) == "table" then diff --git a/src/Formats/font/woff2/init.luau b/src/Formats/font/woff2/init.luau index 1d368b4..1e697cb 100644 --- a/src/Formats/font/woff2/init.luau +++ b/src/Formats/font/woff2/init.luau @@ -24,8 +24,6 @@ export type DecodeOptions = { } -- ------------------------------------------------------------------------------------------------ constants -local CODES = { truncated = Err.TRUNCATED, corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT } - -- ------------------------------------------------------------------------------------------------ sniff function Woff2.sniff(r: Bytes.Reader): number return if r:peek(4) == "wOF2" then 1 else 0 @@ -38,7 +36,7 @@ function Woff2.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) local at = r.base local out, msg, code = Rebuild.sfnt(r, maxBytes) if not out then - return nil, Err.new(CODES[code or "corrupt"] or Err.CORRUPT, msg or "rebuild failed", at) + return nil, Err.from(msg or "rebuild failed", at, code or "corrupt") end return out, nil end diff --git a/src/Formats/model/fbx/init.luau b/src/Formats/model/fbx/init.luau index f20cd90..bf8bfcf 100644 --- a/src/Formats/model/fbx/init.luau +++ b/src/Formats/model/fbx/init.luau @@ -98,18 +98,7 @@ local function fetcher(opts: DecodeOptions?): Read.Fetch end end -local function toErr(msg: any, offset: number?): Err.Err - local s = tostring(msg) - local code = Err.CORRUPT - if string.sub(s, 1, 12) == "unsupported:" then - code, s = Err.UNSUPPORTED, string.sub(s, 13) - elseif string.sub(s, 1, 6) == "limit:" then - code, s = Err.LIMIT, string.sub(s, 7) - elseif string.find(s, "truncated", 1, true) or string.find(s, "runs past", 1, true) then - code = Err.TRUNCATED - end - return Err.new(code, s, offset) -end +local toErr = Err.from -- tree(r, opts?) -> the node tree { name = "", children = { { name, props, children } } }, version, binary | nil, Err. -- Property values: numbers, booleans, strings, buffers (raw), Arrays { array = true, type, count, data = f64 buffer }. diff --git a/src/Formats/model/gltf/init.luau b/src/Formats/model/gltf/init.luau index cf98697..bf14547 100644 --- a/src/Formats/model/gltf/init.luau +++ b/src/Formats/model/gltf/init.luau @@ -17,6 +17,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Json = require("@formats/codecs/Json") @@ -30,7 +31,7 @@ local Gltf = { category = "model", extensions = { "gltf", "glb" }, mime = { "model/gltf+json", "model/gltf-binary" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64", "core/Sniff" }, caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, } @@ -60,7 +61,7 @@ function Gltf.sniff(r: Bytes.Reader): number return 1 end local head = r:peek(1024) - local s = string.gsub(head, "^\239\187\191", "") + local s = Sniff.dropBom(head) if string.find(s, "^%s*{") and string.find(s, "\"asset\"", 1, true) then return 0.9 end diff --git a/src/Formats/playlist/m3u/init.luau b/src/Formats/playlist/m3u/init.luau index d023619..4e3acb4 100644 --- a/src/Formats/playlist/m3u/init.luau +++ b/src/Formats/playlist/m3u/init.luau @@ -14,6 +14,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Url = require("@formats/codecs/Url") @@ -25,7 +26,7 @@ local M3u = { category = "playlist", extensions = { "m3u", "m3u8" }, mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" }, caps = { decode = true, encode = true, hls = true }, } @@ -141,10 +142,7 @@ end -- ------------------------------------------------------------------------------------------------ sniff function M3u.sniff(r: Bytes.Reader): number - local s = r:peek(512) - if string.sub(s, 1, 3) == "\239\187\191" then - s = string.sub(s, 4) - end + local s = Sniff.text(r, 512) s = (string.match(s, "^%s*(.*)$") :: string) if string.sub(s, 1, 7) == "#EXTM3U" then return 0.95 diff --git a/src/Formats/playlist/pls/init.luau b/src/Formats/playlist/pls/init.luau index 0951336..676f302 100644 --- a/src/Formats/playlist/pls/init.luau +++ b/src/Formats/playlist/pls/init.luau @@ -10,6 +10,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Url = require("@formats/codecs/Url") @@ -21,7 +22,7 @@ local Pls = { category = "playlist", extensions = { "pls" }, mime = { "audio/x-scpls", "audio/scpls" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" }, caps = { decode = true, encode = true }, } @@ -75,10 +76,7 @@ end -- ------------------------------------------------------------------------------------------------ sniff function Pls.sniff(r: Bytes.Reader): number - local s = r:peek(64) - if string.sub(s, 1, 3) == "\239\187\191" then - s = string.sub(s, 4) - end + local s = Sniff.text(r, 64) local first = string.match(s, "^%s*([^\r\n]*)") return if first and string.lower(Text.trim(first)) == "[playlist]" then 0.95 else 0 end diff --git a/src/Formats/subtitle/ass/init.luau b/src/Formats/subtitle/ass/init.luau index 2be1b4f..be7b620 100644 --- a/src/Formats/subtitle/ass/init.luau +++ b/src/Formats/subtitle/ass/init.luau @@ -12,6 +12,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") @@ -21,7 +22,7 @@ local Ass = { category = "subtitle", extensions = { "ass", "ssa" }, mime = { "text/x-ssa", "text/x-ass" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = true }, } @@ -144,10 +145,7 @@ end -- ------------------------------------------------------------------------------------------------ sniff function Ass.sniff(r: Bytes.Reader): number - local head = r:peek(64) - if string.sub(head, 1, 3) == "\239\187\191" then - head = string.sub(head, 4) - end + local head = Sniff.text(r, 64) if string.match(head, "^%s*%[[Ss]cript [Ii]nfo%]") then return 1 end @@ -167,9 +165,7 @@ function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E if string.find(s, "\0", 1, true) then return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") end - if string.sub(s, 1, 3) == "\239\187\191" then - s = string.sub(s, 4) - end + s = Sniff.dropBom(s) s = string.gsub(s, "\r\n", "\n") s = string.gsub(s, "\r", "\n") local subs = Types.Subtitles.new() diff --git a/src/Formats/subtitle/srt/init.luau b/src/Formats/subtitle/srt/init.luau index 67ae65d..c3ab1fd 100644 --- a/src/Formats/subtitle/srt/init.luau +++ b/src/Formats/subtitle/srt/init.luau @@ -9,6 +9,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") @@ -18,7 +19,7 @@ local Srt = { category = "subtitle", extensions = { "srt" }, mime = { "application/x-subrip", "text/srt" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = false }, } @@ -38,9 +39,7 @@ local function text(r: Bytes.Reader): string? if string.find(s, "\0", 1, true) then return nil end - if string.sub(s, 1, 3) == "\239\187\191" then - s = string.sub(s, 4) - end + s = Sniff.dropBom(s) s = string.gsub(s, "\r\n", "\n") s = string.gsub(s, "\r", "\n") return s @@ -63,10 +62,7 @@ end -- ------------------------------------------------------------------------------------------------ sniff function Srt.sniff(r: Bytes.Reader): number - local head = r:peek(512) - if string.sub(head, 1, 3) == "\239\187\191" then - head = string.sub(head, 4) - end + local head = Sniff.text(r, 512) head = string.gsub(head, "\r", "\n") local first, second = string.match(head, "^%s*([^\n]*)\n([^\n]*)") if first and string.match(first, "^%d+%s*$") and second and timing(second) then diff --git a/src/Formats/subtitle/vtt/init.luau b/src/Formats/subtitle/vtt/init.luau index 1592219..a35668f 100644 --- a/src/Formats/subtitle/vtt/init.luau +++ b/src/Formats/subtitle/vtt/init.luau @@ -8,6 +8,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") @@ -17,7 +18,7 @@ local Vtt = { category = "subtitle", extensions = { "vtt", "webvtt" }, mime = { "text/vtt" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = true }, } @@ -64,10 +65,7 @@ end -- ------------------------------------------------------------------------------------------------ sniff function Vtt.sniff(r: Bytes.Reader): number - local head = r:peek(10) - if string.sub(head, 1, 3) == "\239\187\191" then - head = string.sub(head, 4) - end + local head = Sniff.text(r, 10) if string.sub(head, 1, 6) == "WEBVTT" then local c = string.sub(head, 7, 7) if c == "" or c == " " or c == "\t" or c == "\n" or c == "\r" then @@ -90,9 +88,7 @@ function Vtt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E if string.find(s, "\0", 1, true) then return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") end - if string.sub(s, 1, 3) == "\239\187\191" then - s = string.sub(s, 4) - end + s = Sniff.dropBom(s) s = string.gsub(s, "\r\n", "\n") s = string.gsub(s, "\r", "\n") local lines = string.split(s, "\n") diff --git a/src/Formats/vector/svg/init.luau b/src/Formats/vector/svg/init.luau index 0ec3be9..811f89a 100644 --- a/src/Formats/vector/svg/init.luau +++ b/src/Formats/vector/svg/init.luau @@ -13,6 +13,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Xml = require("@formats/codecs/Xml") @@ -26,7 +27,7 @@ local Svg = { category = "vector", extensions = { "svg" }, mime = { "image/svg+xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend", "core/Sniff" }, caps = { decode = true, encode = true, rasterize = true, text = false }, } @@ -38,10 +39,7 @@ export type RasterizeOptions = Render.Options -- ------------------------------------------------------------------------------------------------ sniff function Svg.sniff(r: Bytes.Reader): number - local h = r:peek(4096) - if string.sub(h, 1, 3) == "\239\187\191" then - h = string.sub(h, 4) - end + local h = Sniff.text(r, 4096) if not string.match(h, "^%s*<") then return 0 end diff --git a/src/Formats/vector/tiled/init.luau b/src/Formats/vector/tiled/init.luau index 114ca33..e3a34aa 100644 --- a/src/Formats/vector/tiled/init.luau +++ b/src/Formats/vector/tiled/init.luau @@ -12,6 +12,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Xml = require("@formats/codecs/Xml") @@ -25,7 +26,7 @@ local Tiled = { category = "vector", extensions = { "tmx", "tmj", "tsx", "tsj" }, mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" }, - deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate", "core/Sniff" }, caps = { decode = true, encode = true, tilesets = true, infinite = true }, } @@ -42,10 +43,7 @@ export type EncodeOptions = { -- ------------------------------------------------------------------------------------------------ sniff local function head(r: Bytes.Reader): string - local h = r:peek(1024) - if string.sub(h, 1, 3) == "\239\187\191" then - h = string.sub(h, 4) - end + local h = Sniff.text(r, 1024) return h end diff --git a/tools/bench.luau b/tools/bench.luau index 451d9b4..f6d624f 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -22,6 +22,19 @@ local Types = require("@formats/Types") local runtime = if (_G :: any).jit ~= nil then "luajit" else "luau" +-- jitTune(on): LuaJIT's trace limits as host/init.luau sets them for the api (on) or LuaJIT's defaults (off); the +-- codec sections that care print both +local function jitTune(on: boolean) + local jit = (_G :: any).jit + if jit and type(jit.opt) == "table" then + if on then + jit.opt.start("maxtrace=8000", "maxmcode=65536") + else + jit.opt.start("maxtrace=1000", "maxmcode=8192") + end + end +end + local function bench(label: string, n: number, bytes: number, f: () -> ()) f() local dt = math.huge -- best of n: the machine is shared, the mean is noisy @@ -935,19 +948,29 @@ do Jpeg.encode(img, { quality = 85 }) end) end - for _, s in M1 do - local file = Base64.decode(s.file) :: buffer - for _, rgba in { false, true } do - fps(string.format("mpeg1 decode %s %dx%d", if rgba then "rgba" else "yuv", s.width, s.height), 3, #s.units, function() - local dec = Mpeg1.new({ reorder = true, rgba = rgba }) - for i, u in s.units do - dec:decode(file, u[1], u[2], i) - end - while dec:flush() do - end - end) + -- (LuaJIT also with the trace limits the api sets, host/init.luau: the default 1000 traces thrash on MPEG-1) + local function mpeg1(tag: string) + for _, s in M1 do + local file = Base64.decode(s.file) :: buffer + for _, rgba in { false, true } do + fps(string.format("mpeg1 decode %s %dx%d%s", if rgba then "rgba" else "yuv", s.width, s.height, tag), 3, #s.units, function() + local dec = Mpeg1.new({ reorder = true, rgba = rgba }) + for i, u in s.units do + dec:decode(file, u[1], u[2], i) + end + while dec:flush() do + end + end) + end end end + jitTune(false) + mpeg1("") + if runtime == "luajit" then + jitTune(true) + mpeg1(" (jit tuned)") + jitTune(false) + end end -- ------------------------------------------------------------------------------------------- ws-video: containers do @@ -1024,10 +1047,12 @@ do print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #frames .. " frames)", #frames / dt)) end end + jitTune(false) run("") if runtime == "luajit" then - require("@formats/host") + jitTune(true) run(" (jit tuned)") + jitTune(false) end end do @@ -1045,9 +1070,11 @@ do print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #c.frames .. " frames)", #c.frames / dt)) end end + jitTune(false) run("") if runtime == "luajit" then - require("@formats/host") + jitTune(true) run(" (jit tuned)") + jitTune(false) end end diff --git a/tools/fixtures/zstd.py b/tools/fixtures/zstd.py index afaa29c..ce02d59 100644 --- a/tools/fixtures/zstd.py +++ b/tools/fixtures/zstd.py @@ -42,7 +42,7 @@ def generate(ctx): "one": b"a", "short": b"hello, hello, hello zstd world\n", "text": text[:200000], - "random": rng.randbytes(50000), + "random": rng.randbytes(16000), # incompressible: kept small (each case stores it again) "runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300, "far": (lambda r: r + rng.randbytes(30000) + r)(rng.randbytes(20000)), "binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)), diff --git a/tools/lint_rules.py b/tools/lint_rules.py index 3c16eea..0131d1a 100644 --- a/tools/lint_rules.py +++ b/tools/lint_rules.py @@ -16,6 +16,9 @@ # extensions, mime, deps, caps (with decode / encode matching the functions), function .sniff, at least # one of decode / encode / open, the section markers in order, and ends with return ; it has a test # tests//.luau with a fuzz pass (:fuzz(). +# DUP no copy-pasted code: a function body of DUP_LINES (12) or more code lines whose tokens (comments and +# whitespace dropped, identifiers kept) equal another module's function body fails; move it down to a +# shared module (core / codecs / containers) and call it from both. import os, re, sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -275,5 +278,33 @@ for folder in folders: elif ":fuzz(" not in open(test).read(): bad(test, 0, "CONTRACT: a format test includes the fuzz no-throw pass (t:fuzz(...))") +# ---------------------------------------------------------------------------------------------------- DUP +DUP_LINES = 12 +TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|\[=*\[.*?\]=*\]|[A-Za-z_][A-Za-z0-9_]*|\d[\w.]*|\S') +FUNC = re.compile(r"^(\s*)(?:local\s+)?function\b") +bodies = {} +for f, lines in text.items(): + for i, line in enumerate(lines): + m = FUNC.match(line) + if not m: + continue + end = re.compile("^" + re.escape(m.group(1)) + r"end\b") + j = i + 1 + while j < len(lines) and not end.match(lines[j]): + j += 1 + body = [code(x).strip() for x in lines[i + 1:j]] + body = [x for x in body if x] + if len(body) < DUP_LINES: + continue + key = " ".join(TOKEN.findall(" ".join(body))) + bodies.setdefault(key, []).append((f, i + 1, line.strip())) +for key, where in bodies.items(): + files_ = {w[0] for w in where} + if len(files_) > 1: + first = where[0] + for f, ln, head in where[1:]: + if f != first[0]: + bad(f, ln, "DUP: `%s` repeats %s:%d (move it to a shared module)" % (head[:60], os.path.relpath(first[0], ROOT), first[1])) + print("\n".join(out)) sys.exit(1 if out else 0) diff --git a/tools/move.py b/tools/move.py new file mode 100644 index 0000000..bcde84d --- /dev/null +++ b/tools/move.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +# Module moves (python3 -I tools/move.py [--dry] old=new ...): moves src/Formats/(.luau | /) to with +# git mv, then rewrites every reference to the module path in the repo: requires ("@formats/old" and +# "@formats/old/Sub"), contract deps ("old"), header comment lines ("-- old: ..." / "-- old/Sub: ..."), fixture +# INPUTS ("src/Formats/old"), docs and comments ("old" as a whole path token). Paths are module paths +# (codecs/Deflate, core/Huffman). Generated files are not edited: rerun tools/gen_registry.py afterwards. +# +# python3 -I tools/move.py codecs/Deflate=codecs/compress/Deflate core/Huffman=codecs/entropy/Huffman +import os, re, subprocess, sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SRC = os.path.join(ROOT, "src", "Formats") +SCAN = ["src", "tests", "tools", "docs", "examples", "README.md", "default.project.json"] +SKIP = {os.path.join("tests", "gen"), os.path.join("tools", "move.py"), "build"} +EXTS = (".luau", ".lua", ".py", ".md", ".json", ".sh") + + +def files(): + for top in SCAN: + p = os.path.join(ROOT, top) + if os.path.isfile(p): + yield p + continue + for d, dirs, fs in os.walk(p): + rel = os.path.relpath(d, ROOT) + dirs[:] = [x for x in dirs if os.path.join(rel, x) not in SKIP and x not in ("build", "__pycache__")] + for f in fs: + q = os.path.join(d, f) + if f.endswith(EXTS) and os.path.relpath(q, ROOT) not in SKIP: + yield q + + +def source(mod): + base = os.path.join(SRC, *mod.split("/")) + if os.path.isdir(base): + return base + if os.path.isfile(base + ".luau"): + return base + ".luau" + return None + + +def main(): + dry = "--dry" in sys.argv + pairs = [a.split("=", 1) for a in sys.argv[1:] if "=" in a] + if not pairs: + print(__doc__ if __doc__ else "usage: move.py old=new ...") + sys.exit(2) + for old, new in pairs: + src = source(old) + if not src: + sys.exit("move.py: no module %s" % old) + dst = os.path.join(SRC, *new.split("/")) + ("" if os.path.isdir(src) else ".luau") + if os.path.exists(dst): + sys.exit("move.py: %s exists" % os.path.relpath(dst, ROOT)) + print("move %s -> %s" % (os.path.relpath(src, ROOT), os.path.relpath(dst, ROOT))) + if not dry: + os.makedirs(os.path.dirname(dst), exist_ok=True) + subprocess.run(["git", "mv", src, dst], cwd=ROOT, check=True) + # a path token: not preceded by a word char or "."; not followed by a word char + subs = [(re.compile(r"(?