ws-audio2: TTA: codecs/audio/Tta (written from the TTA1 format description; no libtta / ffmpeg code) + audio/tta

TTA1 format 1, 8/16/24 bits, any channel count, header / seek table / frame CRC-32s, seeking, ID3v2 skipped, APEv2
tags; password-protected files -> UNSUPPORTED. 20 fixtures (ttaenc 3.4.1, the FATE inside.tta sample) bit-exact
against ttaenc -d. Branch-free filter steps (LuaJIT: no register-coalescing aborts, 7 -> 40 MB/s).
WavPack: the unary / gamma counts a byte at a time (LuaJIT traces). APE: the predictor rotations as single
assignments. docs/guide/audio.md: the lossless section (+ tools/fixtures/docs_lossless.py inputs) and the Formats
table.
This commit is contained in:
4DBug committed 2026-10-31 15:08:47 -05:00
1 parent ae8ff9d6bf
commit 085e385674
12 files changed
+857 -20

No files matched your search

+12
View File
@@ -254,6 +254,18 @@ local list: { Entry } = {
return require("@formats/audio/opus")
end,
},
{
name = "tta",
category = "audio",
path = "audio/tta",
extensions = { "tta" },
mime = { "audio/x-tta", "audio/tta" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } },
load = function()
return require("@formats/audio/tta")
end,
},
{
name = "voc",
category = "audio",
+123
View File
@@ -0,0 +1,123 @@
--!strict
-- audio/tta: True Audio (.tta, TTA1) files around codecs/audio/Tta: an optional ID3v2 tag in front (skipped), the
-- header and seek table, independent frames (sample-accurate seeking), APEv2 tags at the end (codecs/audio/ApeTag).
-- Written from the TTA1 format description; no libtta / ffmpeg code. Supports 8 / 16 / 24 bits, any channel count.
-- Not supported: password-protected files (Err.UNSUPPORTED), TTA2, ID3v2 tag contents, encoding.
--
-- local dec = Tta.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, readInt
-- local audio = Tta.decode(Bytes.reader(buf)) -- Types.Audio
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/audio/Pcm")
local Stream = require("@formats/codecs/audio/Stream")
local ApeTag = require("@formats/codecs/audio/ApeTag")
local TtaCodec = require("@formats/codecs/audio/Tta")
-- ------------------------------------------------------------------------------------------------ contract
local Tta = {
name = "tta",
category = "audio",
extensions = { "tta" },
mime = { "audio/x-tta", "audio/tta" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ sniff
-- the size of an ID3v2 tag at the reader's start (0 when none)
local function id3Size(r: Bytes.Reader): number
if r:peek(3) ~= "ID3" then
return 0
end
local sz = 0
for i = 6, 9 do
local v = r:peekU8(i)
if v < 0 then
return 0
end
sz = sz * 128 + bit32.band(v, 127)
end
local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0
return 10 + sz + (if footer then 10 else 0)
end
function Tta.sniff(r: Bytes.Reader): number
return if r:peek(4, id3Size(r)) == "TTA1" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Tta.open(r, opts)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
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
return Pcm.drain(d, d.source, limit)
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err
function Tta.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
if type(r) == "buffer" then
r = Bytes.reader(r :: any)
end
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local buf, base, limit = r.buf, r.base, r.limit
local at = base + id3Size(r)
local tags, tagInfo = ApeTag.find(buf, at, limit)
local stop = if tagInfo then tagInfo.start else limit
local info, err = TtaCodec.info(buf, at, stop)
if not info then
return nil, err
end
if info.channels * info.frameLength > 2 ^ 26 then
return nil, Err.new(Err.LIMIT, info.channels .. " channels of " .. info.frameLength .. "-sample frames")
end
local codec = TtaCodec.decoder(info, stop)
local frames = info.samples
local dec: any = {
sampleRate = info.sampleRate,
channels = info.channels,
frames = frames,
duration = frames / info.sampleRate,
bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0,
tags = tags or {},
bitsPerSample = info.bitsPerSample,
float = false,
source = { format = "tta", bitDepth = info.bitsPerSample, tags = tagInfo and tagInfo.items },
}
local fl, count = info.frameLength, info.frames
return Stream.packets(dec, {
count = count,
start = function(i: number): number
return if i > count then frames else (i - 1) * fl
end,
decode = function(i: number): (number?, Err.Err?)
return codec:frame(buf, i)
end,
pcm = function(): { number }
return codec.pcm
end,
reset = function() end,
stop = frames,
scale = 1 / 2 ^ (info.bitsPerSample - 1),
ints = true,
})
end
return Tta
+31 -11
View File
@@ -277,7 +277,10 @@ local function values(st: State, q: number, lim: number, n: number, order: { num
value = x1 + rcBits(rc, S, k - 16) * 65536
end
value += ov * 2 ^ k
q, low, range, prev = rc.q, rc.low, rc.range, rc.prev
q = rc.q
low = rc.low
range = rc.range
prev = rc.prev
end
ks = (ks + (value + 1) // 2 - (ks + 16) // 32) % TWO32
ksum[ci] = ks
@@ -437,7 +440,9 @@ local function predictOne(st: State, v: { number }, n: number)
for t = 1, n do
local nA = v[t]
local A0 = lastA
A3, A2, A1 = A2, A1, A0 - prevA0
A3 = A2
A2 = A1
A1 = A0 - prevA0
prevA0 = A0
local predA = A0 * MA0 + A1 * MA1 + A2 * MA2 + A3 * MA3
local cur
@@ -487,11 +492,16 @@ local function predictStereo(st: State, X: { number }, Y: { number }, n: number)
-- Y
local nA = Y[t]
local A0 = yLast
yA3, yA2, yA1 = yA2, yA1, A0 - yPrev
yA3 = yA2
yA2 = yA1
yA1 = A0 - yPrev
yPrev = A0
local B0 = lastX - (yBin * 31) // 32
yBin = lastX
yB4, yB3, yB2, yB1 = yB3, yB2, yB1, B0 - yBprev
yB4 = yB3
yB3 = yB2
yB2 = yB1
yB1 = B0 - yBprev
yBprev = B0
local predA = A0 * yMA0 + yA1 * yMA1 + yA2 * yMA2 + yA3 * yMA3
local predB = B0 * yMB0 + yB1 * yMB1 + yB2 * yMB2 + yB3 * yMB3 + yB4 * yMB4
@@ -532,11 +542,16 @@ local function predictStereo(st: State, X: { number }, Y: { number }, n: number)
-- X
nA = X[t]
A0 = xLast
xA3, xA2, xA1 = xA2, xA1, A0 - xPrev
xA3 = xA2
xA2 = xA1
xA1 = A0 - xPrev
xPrev = A0
B0 = yv - (xBin * 31) // 32
xBin = yv
xB4, xB3, xB2, xB1 = xB3, xB2, xB1, B0 - xBprev
xB4 = xB3
xB3 = xB2
xB2 = xB1
xB1 = B0 - xBprev
xBprev = B0
predA = A0 * xMA0 + xA1 * xMA1 + xA2 * xMA2 + xA3 * xMA3
predB = B0 * xMB0 + xB1 * xMB1 + xB2 * xMB2 + xB3 * xMB3 + xB4 * xMB4
@@ -627,15 +642,19 @@ function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: num
local mode -- "silence", "pseudo", "stereo", "mono", "multi"
if C == 1 then
if band(special, 1) ~= 0 then
mode, order = "silence", {}
mode = "silence"
order = {}
else
mode, order = "mono", { 1 }
mode = "mono"
order = { 1 }
end
elseif C == 2 then
if band(special, 3) == 3 then
mode, order = "silence", {}
mode = "silence"
order = {}
elseif band(special, 4) ~= 0 then
mode, order = "pseudo", { 1 }
mode = "pseudo"
order = { 1 }
else
mode, order = "stereo", { 2, 1 }
end
@@ -696,7 +715,8 @@ function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: num
local a: number, b2: number = 0, 0
local pair = paired[c]
if mode == "silence" then
a, b2 = 0, 0
a = 0
b2 = 0
elseif mono then
a = X[t]
b2 = a
+259
View File
@@ -0,0 +1,259 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Tta/Decode: one TTA1 frame -> samples. Written from the TTA1 format description (the True Audio
-- format notes: adaptive Rice codes with two running sums per channel, the order-8 sign-LMS "hybrid" filter, the
-- first-order fixed predictor, inter-channel decorrelation, a CRC-32 per frame); no libtta / ffmpeg code. Checked
-- bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). Never throws: returns nil, message.
local Crc32 = require("@formats/core/Crc32")
local readu8, readu32 = buffer.readu8, buffer.readu32
local band, rshift = bit32.band, bit32.rshift
local min, max, floor = math.min, math.max, math.floor
local Decode = {}
local TWO31, TWO32 = 2147483648, 4294967296
local INV31 = 1 / TWO31
local PAD = 16
local P2: { number } = table.create(40, 0) -- P2[k + 1] = 2^k
for i = 0, 39 do
P2[i + 1] = 2 ^ i
end
-- ONES[b + 1]: the trailing 1 bits of the byte b
local ONES: { number } = table.create(256, 0)
for b = 0, 255 do
local n, v = 0, b
while v % 2 == 1 do
n += 1
v //= 2
end
ONES[b + 1] = n
end
-- longUnary(S, pos, lim) -> the count of 1 bits from pos, the position after the 0 | nil (past lim)
local function longUnary(S: buffer, pos: number, lim: number): (number?, number)
local unary = 0
while pos <= lim do
local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7))
local ones = ONES[band(w, 255) + 1]
if ones < 8 then
return unary + ones, pos + ones + 1
end
unary += 8
pos += 8
end
return nil, pos
end
export type State = {
channels: number,
bytes: number, -- 1 .. 3
S: buffer, -- the frame's bits (+ PAD zeros)
-- per channel: rice k0, k1, sum0, sum1; filter error, Q (weights), X (steps), L (delay line) x 8; the last value
R: { number },
Q: { number },
X: { number },
L: { number },
E: { number },
last: { number },
cur: { number },
}
function Decode.state(channels: number, bytes: number): State
return {
channels = channels,
bytes = bytes,
S = buffer.create(4096),
R = table.create(channels * 4, 0),
Q = table.create(channels * 8, 0),
X = table.create(channels * 8, 0),
L = table.create(channels * 8, 0),
E = table.create(channels, 0),
last = table.create(channels, 0),
cur = table.create(channels, 0),
}
end
-- frame(st, buf, o, len, n, P) -> n | nil, message: the frame of len bytes at o (its CRC-32 last) holding n samples per
-- channel, into P (interleaved integers)
function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, P: { number }): (number?, string?)
if len < 4 then
return nil, "truncated frame"
end
local dlen = len - 4
if Crc32.of(buf, o, dlen) ~= readu32(buf, o + dlen) then
return nil, "checksum: frame CRC mismatch"
end
local S = st.S
if buffer.len(S) < dlen + PAD then
S = buffer.create(dlen + PAD + 4096)
st.S = S
end
buffer.copy(S, 0, buf, o, dlen)
buffer.fill(S, dlen, 0, PAD)
local C, bytes = st.channels, st.bytes
local shift = if bytes == 2 then 9 else 10 -- the filter's precision per sample size
local fdiv = 2 ^ shift
local round = fdiv // 2
local pk = if bytes == 1 then 16 else 32 -- the fixed predictor: last * (pk - 1) / pk
local R, Q, X, L, E, last, cur = st.R, st.Q, st.X, st.L, st.E, st.last, st.cur
for c = 0, C - 1 do
R[c * 4 + 1], R[c * 4 + 2], R[c * 4 + 3], R[c * 4 + 4] = 10, 10, 16384, 16384
E[c + 1], last[c + 1] = 0, 0
for i = 1, 8 do
Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0
end
end
local pos = 0 -- bit position
local lim = dlen * 8
local c = 0 -- the channel of the sample at idx
for idx = 1, n * C do
do
if pos > lim then
return nil, "truncated frame"
end
-- the unary prefix: 1 bits up to a 0 (a run past one byte goes to longUnary)
local unary
local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7))
local ones = ONES[band(w, 255) + 1]
if ones < 8 then
unary = ones
pos += ones + 1
else
local u, p2 = longUnary(S, pos, lim)
if not u then
return nil, "truncated frame"
end
unary, pos = u, p2
end
local rb = c * 4
local k0, k1, s0, s1 = R[rb + 1], R[rb + 2], R[rb + 3], R[rb + 4]
local deep = unary > 0
local k
if deep then
k = k1
unary -= 1
else
k = k0
end
local value = unary
if k > 0 then
local bits
if k <= 24 then
bits = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), P2[k + 1] - 1)
else
local lo = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), 0xFFFF)
local p2 = pos + 16
bits = lo + band(rshift(readu32(S, rshift(p2, 3)), band(p2, 7)), P2[k - 15] - 1) * 65536
end
pos += k
value = unary * P2[k + 1] + bits
end
if deep then
s1 += value - s1 // 16
if k1 > 0 and s1 < P2[k1 + 5] then
k1 -= 1
elseif s1 > P2[k1 + 6] then
k1 += 1
end
value += P2[k0 + 1]
end
s0 += value - s0 // 16
if k0 > 0 and s0 < P2[k0 + 5] then
k0 -= 1
elseif s0 > P2[k0 + 6] then
k0 += 1
end
R[rb + 1] = math.min(k0, 31)
R[rb + 2] = math.min(k1, 31)
R[rb + 3] = s0
R[rb + 4] = s1
local odd = value % 2 -- odd -> (v + 1) / 2, even -> -v / 2 (branch-free)
value = (value + odd) // 2 * (2 * odd - 1)
-- the adaptive filter: the weights step toward the sign of the last residual
local fb = c * 8
local err = E[c + 1]
-- (one assignment per statement: LuaJIT cannot coalesce long multiple assignments)
local dq = max(-1, min(1, err))
local x1, x2, x3, x4 = X[fb + 1], X[fb + 2], X[fb + 3], X[fb + 4]
local x5, x6, x7, x8 = X[fb + 5], X[fb + 6], X[fb + 7], X[fb + 8]
local q1 = Q[fb + 1] + x1 * dq
local q2 = Q[fb + 2] + x2 * dq
local q3 = Q[fb + 3] + x3 * dq
local q4 = Q[fb + 4] + x4 * dq
local q5 = Q[fb + 5] + x5 * dq
local q6 = Q[fb + 6] + x6 * dq
local q7 = Q[fb + 7] + x7 * dq
local q8 = Q[fb + 8] + x8 * dq
Q[fb + 1] = q1
Q[fb + 2] = q2
Q[fb + 3] = q3
Q[fb + 4] = q4
Q[fb + 5] = q5
Q[fb + 6] = q6
Q[fb + 7] = q7
Q[fb + 8] = q8
local l2, l3, l4, l5 = L[fb + 2], L[fb + 3], L[fb + 4], L[fb + 5]
local l6, l7, l8 = L[fb + 6], L[fb + 7], L[fb + 8]
local sum = round + L[fb + 1] * q1 + l2 * q2 + l3 * q3 + l4 * q4 + l5 * q5 + l6 * q6 + l7 * q7 + l8 * q8
if sum >= TWO31 or sum < -TWO31 then
sum = (sum + TWO31) % TWO32 - TWO31
end
-- the steps follow the delay line's signs (x 1, 2, 2, 4)
X[fb + 1] = x2
X[fb + 2] = x3
X[fb + 3] = x4
X[fb + 4] = x5
X[fb + 5] = 1 + 2 * floor(l5 * INV31) -- -1 for a negative value, else 1 (branch-free)
X[fb + 6] = 2 + 4 * floor(l6 * INV31)
X[fb + 7] = 2 + 4 * floor(l7 * INV31)
X[fb + 8] = 4 + 8 * floor(l8 * INV31)
E[c + 1] = value
value += sum // fdiv
-- the delay line: the last value and its first and second differences
local n7 = value - l8
local n6 = n7 - l7
L[fb + 1] = l2
L[fb + 2] = l3
L[fb + 3] = l4
L[fb + 4] = l5
L[fb + 5] = n6 - l6
L[fb + 6] = n6
L[fb + 7] = n7
L[fb + 8] = value
-- the fixed predictor
value += (last[c + 1] * (pk - 1)) // pk
last[c + 1] = value
cur[c + 1] = value
end
c += 1
if c == C then
-- inter-channel decorrelation: the last channel carries half the previous one, the others are differences
c = 0
local o = idx - C
if C == 1 then
P[idx] = cur[1]
elseif C == 2 then
local a = cur[1]
local b = cur[2] + (if a >= 0 then a // 2 else -((-a) // 2))
P[o + 1], P[o + 2] = b - a, b
else
local a = cur[C - 1]
cur[C] += if a >= 0 then a // 2 else -((-a) // 2)
for r = C - 1, 1, -1 do
cur[r] = cur[r + 1] - cur[r]
end
for k = 1, C do
P[o + k] = cur[k]
end
end
end
end
if pos > lim then
return nil, "truncated frame"
end
return n, nil
end
return Decode
+126
View File
@@ -0,0 +1,126 @@
--!strict
-- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description
-- (the 22-byte header with its CRC-32, the seek table of frame sizes with its CRC-32, frames of 256 / 245 seconds);
-- no libtta / ffmpeg code (those are LGPL). The frame decoder is codecs/audio/Tta/Decode. Supports format 1 (plain
-- PCM), 8 / 16 / 24 bits, any channel count, the header / seek table / frame CRCs. Not supported: format 2
-- (password-protected: UNSUPPORTED), TTA2.
--
-- local info, err = Tta.info(buf, at, limit) -- the header at `at` (after any ID3v2 tag) + the frame table
-- local dec = Tta.decoder(info)
-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved integers)
--
-- Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Crc32 = require("@formats/core/Crc32")
local Decode = require("@formats/codecs/audio/Tta/Decode")
local Tta = {}
export type Info = {
format: number,
channels: number,
bitsPerSample: number,
sampleRate: number,
samples: number, -- per channel
frameLength: number, -- samples per frame (256 * rate / 245)
frames: number,
offsets: { number }, -- each frame's byte offset
sizes: { number },
}
-- info(buf, at, limit) -> Info | nil, Err: the TTA1 header at byte `at`
function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?)
if at + 22 > limit then
return nil, Err.new(Err.TRUNCATED, "truncated header")
end
if buffer.readstring(buf, at, 4) ~= "TTA1" then
return nil, Err.new(Err.CORRUPT, "no TTA1 header")
end
if Crc32.of(buf, at, 18) ~= buffer.readu32(buf, at + 18) then
return nil, Err.new(Err.CHECKSUM, "header CRC mismatch", at)
end
local format = buffer.readu16(buf, at + 4)
local info: Info = {
format = format,
channels = buffer.readu16(buf, at + 6),
bitsPerSample = buffer.readu16(buf, at + 8),
sampleRate = buffer.readu32(buf, at + 10),
samples = buffer.readu32(buf, at + 14),
frameLength = 0,
frames = 0,
offsets = {},
sizes = {},
}
if format == 2 then
return nil, Err.new(Err.UNSUPPORTED, "password-protected TTA")
elseif format ~= 1 then
return nil, Err.new(Err.UNSUPPORTED, "TTA format " .. format)
end
local bits = info.bitsPerSample
if bits ~= 8 and bits ~= 16 and bits ~= 24 then
return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit TTA")
end
if info.channels < 1 or info.sampleRate < 1 then
return nil, Err.new(Err.CORRUPT, "bad header")
end
info.frameLength = (256 * info.sampleRate) // 245
if info.frameLength < 1 then
return nil, Err.new(Err.CORRUPT, "bad sample rate")
end
local frames = (info.samples + info.frameLength - 1) // info.frameLength
info.frames = frames
local st = at + 22
if st + frames * 4 + 4 > limit then
return nil, Err.new(Err.TRUNCATED, "truncated seek table")
end
if Crc32.of(buf, st, frames * 4) ~= buffer.readu32(buf, st + frames * 4) then
return nil, Err.new(Err.CHECKSUM, "seek table CRC mismatch", st)
end
local o = st + frames * 4 + 4
for i = 1, frames do
local size = buffer.readu32(buf, st + (i - 1) * 4)
info.offsets[i] = o
info.sizes[i] = size
o += size
end
return info, nil
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Decoder = {
info: Info,
pcm: { number },
limit: number,
frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?),
state: Decode.State,
}
local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?)
local info = self.info
if i < 1 or i > info.frames then
return nil, Err.new(Err.ARG, "no frame " .. i)
end
local o, size = info.offsets[i], info.sizes[i]
if o + size > self.limit then
return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " runs past the end", o)
end
local n = if i < info.frames then info.frameLength else info.samples - (info.frames - 1) * info.frameLength
local got, msg = Decode.frame(self.state, buf, o, size, n, self.pcm)
if not got then
return nil, Err.from(msg, o)
end
return got, nil
end
-- decoder(info, limit) -> Decoder (limit: the end of the file data)
function Tta.decoder(info: Info, limit: number): Decoder
return {
info = info,
pcm = table.create(info.frameLength * info.channels, 0),
limit = limit,
frame = frame,
state = Decode.state(info.channels, info.bitsPerSample // 8),
}
end
return Tta
+30 -8
View File
@@ -170,12 +170,37 @@ local function bit(R: Reader): number
return bits(R, 1)
end
-- trailing(R, max) -> the number of 1 bits from the read position (up to max; a byte at a time), consumed with the 0
-- after them when fewer than max
local function trailing(R: Reader, max: number): number
local c = 0
while c < max do
local p = R.p
local byte = rshift(p, 3)
if byte + 8 > R.n then
R.p = R.e + 1
return max
end
local ones = ONES[band(rshift(readu32(R.b, byte), band(p, 7)), 255) + 1]
if ones < 8 then
if c + ones >= max then
R.p = p + (max - c)
return max
end
R.p = p + ones + 1
return c + ones
end
c += 8
R.p = p + 8
end
-- (max reached inside a run of 8: give back the extra ones)
R.p -= c - max
return max
end
-- the "Elias gamma"-like count (cbits ones, a zero, cbits - 1 bits) -> value | nil (33 ones)
local function gamma(R: Reader): number?
local c = 0
while c < 33 and bits(R, 1) == 1 do
c += 1
end
local c = trailing(R, 33)
if c == 33 then
return nil
end
@@ -201,10 +226,7 @@ end
-- ones(R) -> the unary count with its escape (LIMIT_ONES = 16) | nil (the end marker)
local function onesCount(R: Reader): number?
local c = 0
while c < 17 and bits(R, 1) == 1 do
c += 1
end
local c = trailing(R, 17)
if c == 17 then
return nil
end