Files
rosetta/src/Formats/core/Bits.luau
T
4DBugandClaude Opus 5.5 9c553b9d1a 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 <[email protected]>
2026-10-31 12:00:59 -05:00

311 lines
8.6 KiB
Luau

--!strict
--!native
-- core/Bits: bit readers and writers, LSB-first (DEFLATE, GIF LZW, VP8L, ...) and MSB-first (JPEG entropy data
-- without the 0xFF00 unstuffing, MPEG, H.264, FLAC, ...). Up to 32 bits per read / write.
--
-- Plain arithmetic on an accumulator of at most 31 bits (no bit32 calls), exact on doubles, cheap on both runtimes.
-- These are the generic, convenient readers: a codec's innermost loop usually keeps its own local bit buffer (see
-- codecs/Deflate/Inflate) and uses these for headers.
--
-- Never throws: reading past the end returns zero bits and sets the sticky `err` (Err.TRUNCATED).
--
-- 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")
local readu8, blen = buffer.readu8, buffer.len
local floor = math.floor
-- 2^n for n = 0..32
local POW = table.create(33, 0)
for i = 0, 32 do
POW[i + 1] = 2 ^ i
end
local Bits = {}
Bits.POW = POW
-- ------------------------------------------------------------------------------------------------ readers
export type BitReader = {
buf: buffer,
pos: number, -- next byte to load
limit: number,
acc: number, -- loaded, unread bits
cnt: number, -- how many
err: Err.Err?,
read: (BitReader, number) -> number,
peek: (BitReader, number) -> number,
skip: (BitReader, number) -> (),
align: (BitReader) -> (),
bytePos: (BitReader) -> number,
bitsLeft: (BitReader) -> number,
}
local function overrun(self: any)
if not self.err then
self.err = Err.new(Err.TRUNCATED, "bit stream ends early", self.limit)
end
end
-- LSB-first: the first bit of the stream is bit 0 of the first byte; a field's first bit is its least significant
local Lsb = {}
Lsb.__index = Lsb
local function lsbFill(self: any, n: number)
local acc, cnt, pos = self.acc, self.cnt, self.pos
while cnt < n do
if pos < self.limit then
acc += readu8(self.buf, pos) * POW[cnt + 1]
pos += 1
else
overrun(self)
end
cnt += 8
end
self.acc, self.cnt, self.pos = acc, cnt, pos
end
function Lsb.read(self: any, n: number): number
if n > 24 then
local lo = Lsb.read(self, 16)
return lo + Lsb.read(self, n - 16) * 65536
end
if self.cnt < n then
lsbFill(self, n)
end
local m = POW[n + 1]
local v = self.acc % m
self.acc = (self.acc - v) / m
self.cnt -= n
return v
end
function Lsb.peek(self: any, n: number): number
if self.cnt < n then
local acc, cnt, pos = self.acc, self.cnt, self.pos
while cnt < n do -- no error for peeking past the end: the bits are zeros
if pos < self.limit then
acc += readu8(self.buf, pos) * POW[cnt + 1]
pos += 1
end
cnt += 8
end
-- keep the loaded bytes only when they are all real (zero padding past the end is not data)
if (pos - self.pos) * 8 == cnt - self.cnt then
self.acc, self.cnt, self.pos = acc, cnt, pos
end
return acc % POW[n + 1]
end
return self.acc % POW[n + 1]
end
function Lsb.skip(self: any, n: number)
while n > 24 do
Lsb.read(self, 24)
n -= 24
end
Lsb.read(self, n)
end
-- align(): drop the bits up to the next byte boundary
function Lsb.align(self: any)
local k = self.cnt % 8
if k > 0 then
Lsb.read(self, k)
end
end
-- bytePos(): the offset of the first byte not yet (even partly) consumed
function Lsb.bytePos(self: any): number
return self.pos - floor(self.cnt / 8)
end
function Lsb.bitsLeft(self: any): number
return (self.limit - self.pos) * 8 + self.cnt
end
-- MSB-first: the first bit of the stream is bit 7 of the first byte; a field's first bit is its most significant
local Msb = {}
Msb.__index = Msb
local function msbFill(self: any, n: number)
local acc, cnt, pos = self.acc, self.cnt, self.pos
while cnt < n do
if pos < self.limit then
acc = acc * 256 + readu8(self.buf, pos)
pos += 1
else
acc *= 256
overrun(self)
end
cnt += 8
end
self.acc, self.cnt, self.pos = acc, cnt, pos
end
function Msb.read(self: any, n: number): number
if n > 24 then
local hi = Msb.read(self, n - 16)
return hi * 65536 + Msb.read(self, 16)
end
if self.cnt < n then
msbFill(self, n)
end
local sh = POW[self.cnt - n + 1]
local v = floor(self.acc / sh)
self.acc -= v * sh
self.cnt -= n
return v
end
function Msb.peek(self: any, n: number): number
local acc, cnt, pos = self.acc, self.cnt, self.pos
while cnt < n do
if pos < self.limit then
acc = acc * 256 + readu8(self.buf, pos)
pos += 1
else
acc *= 256
end
cnt += 8
end
-- keep the loaded bytes only when they are all real (zero padding past the end is not data)
if (pos - self.pos) * 8 == cnt - self.cnt then
self.acc, self.cnt, self.pos = acc, cnt, pos
end
return floor(acc / POW[cnt - n + 1])
end
function Msb.skip(self: any, n: number)
while n > 24 do
Msb.read(self, 24)
n -= 24
end
Msb.read(self, n)
end
function Msb.align(self: any)
local k = self.cnt % 8
if k > 0 then
Msb.read(self, k)
end
end
Msb.bytePos = Lsb.bytePos
Msb.bitsLeft = Lsb.bitsLeft
local function reader(meta: any, buf: buffer, offset: number?, length: number?): BitReader
local n = blen(buf)
local o = math.clamp(offset or 0, 0, n)
local l = math.clamp(length or (n - o), 0, n - o)
return setmetatable({ buf = buf, pos = o, limit = o + l, acc = 0, cnt = 0, err = nil }, meta) :: any
end
-- lsbReader(buf, offset?, length?) / msbReader(buf, offset?, length?) -> BitReader
function Bits.lsbReader(buf: buffer, offset: number?, length: number?): BitReader
return reader(Lsb, buf, offset, length)
end
function Bits.msbReader(buf: buffer, offset: number?, length: number?): BitReader
return reader(Msb, buf, offset, length)
end
-- ------------------------------------------------------------------------------------------------ writers
export type BitWriter = {
out: Bytes.Writer, -- the bytes so far (whole bytes only)
acc: number,
cnt: number,
write: (BitWriter, number, number) -> (),
align: (BitWriter) -> (),
finish: (BitWriter) -> buffer,
}
local LsbW = {}
LsbW.__index = LsbW
function LsbW.write(self: any, v: number, n: number)
if n > 24 then
local lo = v % 65536
LsbW.write(self, lo, 16)
LsbW.write(self, (v - lo) / 65536, n - 16)
return
end
local acc = self.acc + (v % POW[n + 1]) * POW[self.cnt + 1]
local cnt = self.cnt + n
local out = self.out
while cnt >= 8 do
local byte = acc % 256
out:u8(byte)
acc = (acc - byte) / 256
cnt -= 8
end
self.acc, self.cnt = acc, cnt
end
-- align(): pad with zero bits to a byte boundary
function LsbW.align(self: any)
if self.cnt > 0 then
self.out:u8(self.acc)
self.acc, self.cnt = 0, 0
end
end
function LsbW.finish(self: any): buffer
LsbW.align(self)
return self.out:finish()
end
local MsbW = {}
MsbW.__index = MsbW
function MsbW.write(self: any, v: number, n: number)
if n > 24 then
local lo = v % 65536
MsbW.write(self, (v - lo) / 65536, n - 16)
MsbW.write(self, lo, 16)
return
end
local acc = self.acc * POW[n + 1] + (v % POW[n + 1])
local cnt = self.cnt + n
local out = self.out
while cnt >= 8 do
local sh = POW[cnt - 8 + 1]
local byte = floor(acc / sh)
out:u8(byte)
acc -= byte * sh
cnt -= 8
end
self.acc, self.cnt = acc, cnt
end
function MsbW.align(self: any)
if self.cnt > 0 then
self.out:u8(self.acc * POW[8 - self.cnt + 1])
self.acc, self.cnt = 0, 0
end
end
function MsbW.finish(self: any): buffer
MsbW.align(self)
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
end
function Bits.msbWriter(capacity: number?): BitWriter
return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, MsbW) :: any
end
return Bits