--!strict --!native --!optimize 2 -- codecs/audio/WavPack/Block: one WavPack 4 / 5 block (one mono or stereo stream of a frame) -> samples. -- Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt): unpack.c, read_words.c, -- unpack_floats.c, decorr_utils.c / entropy_utils.c, open_utils.c. DSD blocks are UNSUPPORTED. local Tables = require("@rosetta/codecs/audio/WavPack/Tables") local readu8, readi8, readu16, readi16, readu32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32 local writeu32, readf32 = buffer.writeu32, buffer.readf32 local band, rshift, countlz = bit32.band, bit32.rshift, bit32.countlz local exp2s, log2, restoreWeight = Tables.exp2s, Tables.log2, Tables.restoreWeight local sign, clamp = math.sign, math.clamp local Block = {} local TWO32 = 4294967296 local P2: { number } = table.create(34, 0) for i = 0, 33 do P2[i + 1] = 2 ^ i end 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 = v // 2 end ONES[b + 1] = n end local MONO_FLAG, HYBRID, JOINT, CROSS, SHAPE, FLOAT, INT32 = 4, 8, 0x10, 0x20, 0x40, 0x80, 0x100 local HBITRATE, HBALANCE, NEW_SHAPING, FALSE_STEREO, DSD = 0x200, 0x400, 0x20000000, 0x40000000, 0x80000000 local FLOAT_SHIFT_ONES, FLOAT_SHIFT_SAME, FLOAT_SHIFT_SENT, FLOAT_ZEROS_SENT, FLOAT_NEG_ZEROS = 1, 2, 4, 8, 0x10 local PAD = 64 -- zero bytes after each copied bitstream: reads past the end stay in the buffer local MAX_SAMPLES = 2 ^ 20 local D2, D1 = 17, 9 -- the first data index of the work table (stereo / mono): 8 frames of history in front export type Meta = { [number]: number } -- id -> offset; id + 256 -> byte length function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?) local m: Meta = {} local q, stop = p + 32, p + size while stop - q >= 2 do local id = readu8(buf, q) local len = readu8(buf, q + 1) * 2 q += 2 if band(id, 0x80) ~= 0 then if stop - q < 2 then return nil, "truncated metadata" end len += readu8(buf, q) * 512 + readu8(buf, q + 1) * 131072 q += 2 id -= 0x80 end local odd = 0 if band(id, 0x40) ~= 0 then if len == 0 then return nil, "odd-sized empty metadata" end id -= 0x40 len -= 1 odd = 1 end if stop - q < len + odd then return nil, "truncated metadata" end m[id] = q m[id + 256] = len q += len + odd end return m, nil end function Block.checksum(buf: buffer, p: number, m: Meta): boolean local o = m[0x2F] if not o then return true end local len = m[0x2F + 256] if len ~= 2 and len ~= 4 then return false end local words = (o - 2 - p) // 2 local csum = TWO32 - 1 for i = 0, words - 1 do csum = (csum * 3 + readu16(buf, p + i * 2)) % TWO32 end if len == 4 then return readu32(buf, o) == csum end csum = bit32.bxor(csum, rshift(csum, 16)) return readu16(buf, o) == band(csum, 0xFFFF) end export type Reader = { b: buffer, p: number, e: number, n: number } export type State = { [string]: any } function Block.state(): State return { W = table.create(D2 + 2 * 4096, 0), term = table.create(16, 0), delta = table.create(16, 0), wA = table.create(16, 0), wB = table.create(16, 0), sA = table.create(16 * 8, 0), sB = table.create(16 * 8, 0), med = table.create(6, 0), slow = { 0, 0 }, limit = { 0, 0 }, bacc = { 0, 0 }, bdelta = { 0, 0 }, sacc = { 0, 0 }, sdelta = { 0, 0 }, err = { 0, 0 }, R1 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, R2 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, R3 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, scratch = buffer.create(4), } end local function openReader(R: Reader, buf: buffer, o: number, len: number) if buffer.len(R.b) < len + PAD then R.b = buffer.create(len + PAD + 1024) else buffer.fill(R.b, len, 0, PAD) end buffer.copy(R.b, 0, buf, o, len) R.p = 0 R.e = len * 8 R.n = len + PAD end local function bits(R: Reader, n: number): number if n <= 0 then return 0 end local p = R.p local byte = rshift(p, 3) if byte + 8 > R.n then R.p = R.e + 1 return 0 end local b = R.b if n <= 25 then R.p = p + n return band(rshift(readu32(b, byte), band(p, 7)), P2[n + 1] - 1) end local lo = band(rshift(readu32(b, byte), band(p, 7)), 0xFFFF) p += 16 R.p = p + n - 16 return lo + band(rshift(readu32(b, rshift(p, 3)), band(p, 7)), P2[n - 15] - 1) * 65536 end local function bit(R: Reader): number return bits(R, 1) end 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 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 = trailing(R, 33) if c == 33 then return nil end if c < 2 then return c end return bits(R, c - 1) + P2[c] end -- read_code local function readCode(R: Reader, maxcode: number): number if maxcode < 2 then return if maxcode == 1 then bits(R, 1) else 0 end local bc = 32 - countlz(maxcode) local extras = P2[bc + 1] - maxcode - 1 local code = bits(R, bc - 1) if code >= extras then code = code * 2 - extras + bits(R, 1) end return code end -- ones(R) -> the unary count with its escape (LIMIT_ONES = 16) | nil (the end marker) local function onesCount(R: Reader): number? local c = trailing(R, 17) if c == 17 then return nil end if c == 16 then local g = gamma(R) if not g then return nil end c = g + 16 end return c end -- get_words_lossless local function wordsLossless(st: State, count: number, d: number): boolean local R: Reader = st.R1 local b, pos, lim = R.b, R.p, R.e local W = st.W local med = st.med local stereo = d == D2 local a0, a1, a2, c0, c1, c2 = med[4], med[5], med[6], med[1], med[2], med[3] if not stereo then a0, a1, a2, c0, c1, c2 = med[1], med[2], med[3], 0, 0, 0 end local hz, ho, za = 0, 0, 0 for idx = d, d + count - 1 do if stereo then a0, a1, a2, c0, c1, c2 = c0, c1, c2, a0, a1, a2 end if pos > lim then return false end if hz ~= 0 then hz = 0 local maxcode = a0 // 16 a0 -= ((a0 + 126) // 128) * 2 local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) local low, used = 0, 0 if maxcode < 2 then if maxcode == 1 then low, used = band(w, 1), 1 end else local bc = 32 - countlz(maxcode) if bc > 24 then R.p = pos low = readCode(R, maxcode) pos = R.p w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) else local extras = P2[bc + 1] - maxcode - 1 low = band(w, P2[bc] - 1) if low >= extras then low = low * 2 - extras + band(rshift(w, bc - 1), 1) used = bc else used = bc - 1 end end end if band(rshift(w, used), 1) ~= 0 then W[idx] = -low - 1 else W[idx] = low end pos += used + 1 continue end if a0 < 2 and ho == 0 and c0 < 2 then if za > 0 then za -= 1 if za > 0 then W[idx] = 0 continue end else R.p = pos local g = gamma(R) pos = R.p if not g then return false end za = g if za > 0 then a0, a1, a2, c0, c1, c2 = 0, 0, 0, 0, 0, 0 W[idx] = 0 continue end end end local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) local ones = ONES[band(w, 255) + 1] if ones == 8 then ones = 8 + ONES[band(rshift(w, 8), 255) + 1] end if ones < 16 then pos += ones + 1 else if band(w, 0x10000) ~= 0 then return false end R.p = pos + 17 local g = gamma(R) pos = R.p if not g then return false end ones = g + 16 end local hold = ho ho = band(ones, 1) hz = 1 - ho ones = ones // 2 + hold local low, high if ones == 0 then low = 0 high = a0 // 16 a0 -= ((a0 + 126) // 128) * 2 else low = a0 // 16 + 1 a0 += ((a0 + 128) // 128) * 5 if ones == 1 then high = low + a1 // 16 a1 -= ((a1 + 62) // 64) * 2 else low += a1 // 16 + 1 a1 += ((a1 + 64) // 64) * 5 if ones == 2 then high = low + a2 // 16 a2 -= ((a2 + 30) // 32) * 2 else low += (ones - 2) * (a2 // 16 + 1) high = low + a2 // 16 a2 += ((a2 + 32) // 32) * 5 end end end local maxcode = high - low w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) local used = 0 if maxcode < 2 then if maxcode == 1 then low += band(w, 1) used = 1 end else if maxcode >= 536870912 then return false end local bc = 32 - countlz(maxcode) if bc > 24 then R.p = pos low += readCode(R, maxcode) pos = R.p w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) else local extras = P2[bc + 1] - maxcode - 1 local code = band(w, P2[bc] - 1) if code >= extras then code = code * 2 - extras + band(rshift(w, bc - 1), 1) used = bc else used = bc - 1 end low += code end end if band(rshift(w, used), 1) ~= 0 then W[idx] = -low - 1 else W[idx] = low end pos += used + 1 end R.p = pos return pos <= lim end local function updateErrorLimit(st: State, flags: number, mono: boolean) local bacc, bdelta, slow, limit = st.bacc, st.bdelta, st.slow, st.limit bacc[1] = (bacc[1] + bdelta[1]) % TWO32 local br0 = bacc[1] // 65536 if mono then if band(flags, HBITRATE) ~= 0 then local sl0 = (slow[1] + 128) // 256 limit[1] = if sl0 - br0 > -256 then exp2s(sl0 - br0 + 256) % TWO32 else 0 else limit[1] = exp2s(br0) % TWO32 end return end bacc[2] = (bacc[2] + bdelta[2]) % TWO32 local br1 = bacc[2] // 65536 if band(flags, HBITRATE) ~= 0 then local sl0 = (slow[1] + 128) // 256 local sl1 = (slow[2] + 128) // 256 if band(flags, HBALANCE) ~= 0 then local balance = (sl1 - sl0 + br1 + 1) // 2 if balance > br0 then br1 = br0 * 2 br0 = 0 elseif -balance > br0 then br0 = br0 * 2 br1 = 0 else br1 = br0 + balance br0 = br0 - balance end end limit[1] = if sl0 - br0 > -256 then exp2s(sl0 - br0 + 256) % TWO32 else 0 limit[2] = if sl1 - br1 > -256 then exp2s(sl1 - br1 + 256) % TWO32 else 0 else limit[1] = exp2s(br0) % TWO32 limit[2] = exp2s(br1) % TWO32 end end -- get_word local function getWord(st: State, chan: number, flags: number, mono: boolean): (number?, number) local R: Reader = st.R1 local med = st.med local mb = chan * 3 local correction = 0 if R.p > R.e then return nil, 0 end if med[1] < 2 and st.hz == 0 and st.ho == 0 and med[4] < 2 then if st.za > 0 then st.za -= 1 if st.za > 0 then local s = st.slow s[chan + 1] -= (s[chan + 1] + 128) // 256 return 0, 0 end else local g = gamma(R) if not g then return nil, 0 end st.za = g if g > 0 then local s = st.slow s[chan + 1] -= (s[chan + 1] + 128) // 256 for k = 1, 6 do med[k] = 0 end return 0, 0 end end end local ones if st.hz ~= 0 then ones = 0 st.hz = 0 else local c = onesCount(R) if not c then return nil, 0 end ones = c if st.ho ~= 0 then st.ho = band(ones, 1) ones = ones // 2 + 1 else st.ho = band(ones, 1) ones = ones // 2 end st.hz = 1 - st.ho end if band(flags, HYBRID) ~= 0 and chan == 0 then updateErrorLimit(st, flags, mono) end local m0, m1, m2 = med[mb + 1], med[mb + 2], med[mb + 3] local low, high if ones == 0 then low = 0 high = m0 // 16 m0 -= ((m0 + 126) // 128) * 2 else low = m0 // 16 + 1 m0 += ((m0 + 128) // 128) * 5 if ones == 1 then high = low + m1 // 16 m1 -= ((m1 + 62) // 64) * 2 else low += m1 // 16 + 1 m1 += ((m1 + 64) // 64) * 5 if ones == 2 then high = low + m2 // 16 m2 -= ((m2 + 30) // 32) * 2 else low += (ones - 2) * (m2 // 16 + 1) high = low + m2 // 16 m2 += ((m2 + 32) // 32) * 5 end end end med[mb + 1], med[mb + 2], med[mb + 3] = m0 % TWO32, m1 % TWO32, m2 % TWO32 low = band(low % TWO32, 0x7FFFFFFF) high = band(high % TWO32, 0x7FFFFFFF) if low > high then high = low end local mid = (high + low + 1) // 2 local limit = st.limit[chan + 1] if limit == 0 then mid = readCode(R, high - low) + low else while high - low > limit do if R.p > R.e then return nil, 0 end if bits(R, 1) == 1 then low = mid mid = (high + low + 1) // 2 else high = mid - 1 mid = (high + low + 1) // 2 end end end local sign = bits(R, 1) if st.wvc and limit ~= 0 then local value = readCode(st.R2, high - low) + low correction = if sign == 1 then mid - value else value - mid end if band(flags, HBITRATE) ~= 0 then local s = st.slow s[chan + 1] = s[chan + 1] - (s[chan + 1] + 128) // 256 + log2(mid) end return if sign == 1 then -mid - 1 else mid, correction end -- the decorrelation passes over the whole block (stereo, from W[D2]): unpack.c decorr_stereo_pass local function passesStereo(st: State, n: number) local W = st.W local last = D2 + 2 * n - 2 local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB for t = 1, st.nterms do local term, delta, wA, wB = terms[t], deltas[t], wAs[t], wBs[t] local so = (t - 1) * 8 if term > 8 then local a0, a1, b0, b1 = sA[so + 1], sA[so + 2], sB[so + 1], sB[so + 2] local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 for i = D2, last, 2 do local sam = a0 + (a0 - a1) // dv local x = W[i] local o = (wA * sam + 512) // 1024 + x wA += delta * sign(sam * x) a1, a0 = a0, o W[i] = o sam = b0 + (b0 - b1) // dv x = W[i + 1] o = (wB * sam + 512) // 1024 + x wB += delta * sign(sam * x) b1, b0 = b0, o W[i + 1] = o end elseif term > 0 then for j = 0, term - 1 do W[D2 + 2 * (j - term)] = sA[so + j + 1] W[D2 + 1 + 2 * (j - term)] = sB[so + j + 1] end local back = 2 * term for i = D2, last, 2 do local sam = W[i - back] local x = W[i] W[i] = (wA * sam + 512) // 1024 + x wA += delta * sign(sam * x) sam = W[i + 1 - back] x = W[i + 1] W[i + 1] = (wB * sam + 512) // 1024 + x wB += delta * sign(sam * x) end elseif term == -1 then local sa = sA[so + 1] for i = D2, last, 2 do local x = W[i] local sam = x + (wA * sa + 512) // 1024 wA = clamp(wA + delta * sign(sa * x), -1024, 1024) W[i] = sam x = W[i + 1] sa = x + (wB * sam + 512) // 1024 wB = clamp(wB + delta * sign(sam * x), -1024, 1024) W[i + 1] = sa end elseif term == -2 then local sb = sB[so + 1] for i = D2, last, 2 do local x = W[i + 1] local sam = x + (wB * sb + 512) // 1024 wB = clamp(wB + delta * sign(sb * x), -1024, 1024) W[i + 1] = sam x = W[i] sb = x + (wA * sam + 512) // 1024 wA = clamp(wA + delta * sign(sam * x), -1024, 1024) W[i] = sb end else -- -3 local sa, sb = sA[so + 1], sB[so + 1] for i = D2, last, 2 do local x = W[i] local samA = x + (wA * sa + 512) // 1024 wA = clamp(wA + delta * sign(sa * x), -1024, 1024) x = W[i + 1] local samB = x + (wB * sb + 512) // 1024 wB = clamp(wB + delta * sign(sb * x), -1024, 1024) W[i], W[i + 1] = samA, samB sa, sb = samB, samA end end end end -- the decorrelation passes (mono, from W[D1]): unpack.c decorr_mono_pass local function passesMono(st: State, n: number) local W = st.W local last = D1 + n - 1 local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA for t = 1, st.nterms do local term, delta, wA = terms[t], deltas[t], wAs[t] local so = (t - 1) * 8 if term > 8 then local a0, a1 = sA[so + 1], sA[so + 2] local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 for i = D1, last do local sam = a0 + (a0 - a1) // dv local x = W[i] local o = (wA * sam + 512) // 1024 + x wA += delta * sign(sam * x) a1, a0 = a0, o W[i] = o end else for j = 0, term - 1 do W[D1 + j - term] = sA[so + j + 1] end for i = D1, last do local sam = W[i - term] local x = W[i] W[i] = (wA * sam + 512) // 1024 + x wA += delta * sign(sam * x) end end end end local function shaped(st: State, c: number, flags: number, correction: number): number -- returns the value to subtract (temp) and updates the error state (noise shaping, unpack.c) local sacc, sdelta, err = st.sacc, st.sdelta, st.err sacc[c] = (sacc[c] + sdelta[c]) % TWO32 local sw = sacc[c] // 65536 if sw >= 32768 then sw -= 65536 end local temp = -((sw * err[c] + 512) // 1024) if band(flags, NEW_SHAPING) ~= 0 and sw < 0 and temp ~= 0 then if temp == err[c] then temp = if temp < 0 then temp + 1 else temp - 1 end err[c] = temp - correction else err[c] = -correction end return temp end local function hybridMono(st: State, n: number, flags: number): boolean local W = st.W local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA local nterms = st.nterms local m = 0 local crc = TWO32 - 1 for i = 0, n - 1 do local word, corr = getWord(st, 0, flags, true) if not word then return false end local rw = word for t = 1, nterms do local term, so = terms[t], (t - 1) * 8 local sam, k if term > 8 then sam = if term % 2 == 1 then 2 * sA[so + 1] - sA[so + 2] else (3 * sA[so + 1] - sA[so + 2]) // 2 sA[so + 2] = sA[so + 1] k = 0 else sam = sA[so + m + 1] k = band(m + term, 7) end local temp = (wAs[t] * sam + 512) // 1024 + rw wAs[t] += deltas[t] * sign(sam * rw) sA[so + k + 1] = temp rw = temp end m = band(m + 1, 7) if band(flags, SHAPE) ~= 0 then local temp = shaped(st, 1, flags, corr) rw += corr - temp else rw += corr end crc = (crc * 3 + rw) % TWO32 W[D1 + i] = rw end st.crcv = crc return true end local function hybridStereo(st: State, n: number, flags: number): boolean local W = st.W local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB local nterms = st.nterms local m = 0 local crc = TWO32 - 1 local cross = band(flags, CROSS) ~= 0 local joint = band(flags, JOINT) ~= 0 for i = 0, n - 1 do local left, corr0 = getWord(st, 0, flags, false) if not left then return false end local right, corr1 = getWord(st, 1, flags, false) if not right then return false end local leftc, rightc = 0, 0 if cross then leftc, rightc = left + corr0, right + corr1 for t = 1, nterms do local term, so = terms[t], (t - 1) * 8 if term > 0 then local samA, samB if term > 8 then if term % 2 == 1 then samA = 2 * sA[so + 1] - sA[so + 2] samB = 2 * sB[so + 1] - sB[so + 2] else samA = (3 * sA[so + 1] - sA[so + 2]) // 2 samB = (3 * sB[so + 1] - sB[so + 2]) // 2 end else samA, samB = sA[so + m + 1], sB[so + m + 1] end leftc += (wAs[t] * samA + 512) // 1024 rightc += (wBs[t] * samB + 512) // 1024 elseif term == -1 then leftc += (wAs[t] * sA[so + 1] + 512) // 1024 rightc += (wBs[t] * leftc + 512) // 1024 else rightc += (wBs[t] * sB[so + 1] + 512) // 1024 if term == -3 then leftc += (wAs[t] * sA[so + 1] + 512) // 1024 else leftc += (wAs[t] * rightc + 512) // 1024 end end end if joint then rightc -= leftc // 2 leftc += rightc end end for t = 1, nterms do local term, delta, so = terms[t], deltas[t], (t - 1) * 8 if term > 0 then local samA, samB, k if term > 8 then if term % 2 == 1 then samA = 2 * sA[so + 1] - sA[so + 2] samB = 2 * sB[so + 1] - sB[so + 2] else samA = (3 * sA[so + 1] - sA[so + 2]) // 2 samB = (3 * sB[so + 1] - sB[so + 2]) // 2 end sA[so + 2] = sA[so + 1] sB[so + 2] = sB[so + 1] k = 0 else samA, samB = sA[so + m + 1], sB[so + m + 1] k = band(m + term, 7) end local left2 = (wAs[t] * samA + 512) // 1024 + left local right2 = (wBs[t] * samB + 512) // 1024 + right wAs[t] += delta * sign(samA * left) wBs[t] += delta * sign(samB * right) left, right = left2, right2 sA[so + k + 1], sB[so + k + 1] = left, right elseif term == -1 then local sa = sA[so + 1] local left2 = left + (wAs[t] * sa + 512) // 1024 wAs[t] = clamp(wAs[t] + delta * sign(sa * left), -1024, 1024) left = left2 local right2 = right + (wBs[t] * left2 + 512) // 1024 wBs[t] = clamp(wBs[t] + delta * sign(left2 * right), -1024, 1024) right = right2 sA[so + 1] = right else local sb = sB[so + 1] local right2 = right + (wBs[t] * sb + 512) // 1024 wBs[t] = clamp(wBs[t] + delta * sign(sb * right), -1024, 1024) right = right2 if term == -3 then right2 = sA[so + 1] sA[so + 1] = right end local left2 = left + (wAs[t] * right2 + 512) // 1024 wAs[t] = clamp(wAs[t] + delta * sign(right2 * left), -1024, 1024) left = left2 sB[so + 1] = left end end m = band(m + 1, 7) if not cross then leftc, rightc = left + corr0, right + corr1 if joint then rightc -= leftc // 2 leftc += rightc end end if joint then right -= left // 2 left += right end if band(flags, SHAPE) ~= 0 then local temp = shaped(st, 1, flags, leftc - left) left = leftc - temp temp = shaped(st, 2, flags, rightc - right) right = rightc - temp else left, right = leftc, rightc end crc = (crc * 9 + left * 3 + right) % TWO32 W[D2 + 2 * i], W[D2 + 2 * i + 1] = left, right end st.crcv = crc return true end local function readMeta(st: State, buf: buffer, m: Meta, flags: number, version: number): string? local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 local o = m[2] if o then -- decorrelation terms local cnt = m[2 + 256] if cnt > 16 then return "too many decorrelation terms" end st.nterms = cnt for i = 0, cnt - 1 do local v = readu8(buf, o + i) local t = cnt - i local term = band(v, 0x1F) - 5 if term == 0 or term < -3 or (term > 8 and term < 17) or term > 18 or (mono and term < 0) then return "bad decorrelation term" end st.term[t] = term st.delta[t] = band(rshift(v, 5), 7) end end local nterms = st.nterms o = m[3] if o then -- weights, from the last pass back for t = 1, nterms do st.wA[t], st.wB[t] = 0, 0 end local cnt = m[3 + 256] if not mono then cnt //= 2 end if cnt > nterms then return "too many decorrelation weights" end local q = o for t = nterms, nterms - cnt + 1, -1 do st.wA[t] = restoreWeight(readi8(buf, q)) q += 1 if not mono then st.wB[t] = restoreWeight(readi8(buf, q)) q += 1 end end end local sA, sB = st.sA, st.sB o = m[4] if o then -- decorrelation samples, from the last pass back for k = 1, nterms * 8 do sA[k], sB[k] = 0, 0 end local q, stop = o, o + m[4 + 256] if version == 0x402 and band(flags, HYBRID) ~= 0 then if q + (if mono then 2 else 4) > stop then return "bad decorrelation samples" end st.err[1] = exp2s(readi16(buf, q)) q += 2 if not mono then st.err[2] = exp2s(readi16(buf, q)) q += 2 end end local t = nterms while t >= 1 and q < stop do local term, so = st.term[t], (t - 1) * 8 if term > 8 then if q + (if mono then 4 else 8) > stop then return "bad decorrelation samples" end sA[so + 1], sA[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) q += 4 if not mono then sB[so + 1], sB[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) q += 4 end elseif term < 0 then if q + 4 > stop then return "bad decorrelation samples" end sA[so + 1], sB[so + 1] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) q += 4 else for k = 1, term do if q + (if mono then 2 else 4) > stop then return "bad decorrelation samples" end sA[so + k] = exp2s(readi16(buf, q)) q += 2 if not mono then sB[so + k] = exp2s(readi16(buf, q)) q += 2 end end end t -= 1 end if q ~= stop then return "bad decorrelation samples" end end o = m[5] if o then -- entropy medians if m[5 + 256] ~= (if mono then 6 else 12) then return "bad entropy variables" end for k = 0, (if mono then 2 else 5) do st.med[k + 1] = exp2s(readu16(buf, o + k * 2)) % TWO32 end end o = m[6] if o then -- hybrid profile local q, stop = o, o + m[6 + 256] local w = if mono then 2 else 4 if band(flags, HBITRATE) ~= 0 then if q + w > stop then return "bad hybrid profile" end st.slow[1] = exp2s(readu16(buf, q)) % TWO32 if not mono then st.slow[2] = exp2s(readu16(buf, q + 2)) % TWO32 end q += w end if q + w > stop then return "bad hybrid profile" end st.bacc[1] = readu16(buf, q) * 65536 if not mono then st.bacc[2] = readu16(buf, q + 2) * 65536 end q += w if q < stop then if q + w > stop then return "bad hybrid profile" end st.bdelta[1] = exp2s(readi16(buf, q)) if not mono then st.bdelta[2] = exp2s(readi16(buf, q + 2)) end q += w if q < stop then return "bad hybrid profile" end end end o = m[7] if o then -- noise shaping local len = m[7 + 256] if len == 2 then st.sacc[1] = (restoreWeight(readi8(buf, o)) * 65536) % TWO32 st.sacc[2] = (restoreWeight(readi8(buf, o + 1)) * 65536) % TWO32 elseif len >= (if mono then 4 else 8) then st.err[1] = exp2s(readi16(buf, o)) st.sacc[1] = exp2s(readi16(buf, o + 2)) % TWO32 if not mono then st.err[2] = exp2s(readi16(buf, o + 4)) st.sacc[2] = exp2s(readi16(buf, o + 6)) % TWO32 end local q = o + (if mono then 4 else 8) if len == (if mono then 6 else 12) then st.sdelta[1] = exp2s(readi16(buf, q)) % TWO32 if not mono then st.sdelta[2] = exp2s(readi16(buf, q + 2)) % TWO32 end end else return "bad shaping weights" end end o = m[8] if o then if m[8 + 256] ~= 4 then return "bad float info" end st.fflags, st.fshift, st.fmaxexp = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2) end o = m[9] if o then if m[9 + 256] ~= 4 then return "bad int32 info" end st.isent, st.izeros, st.iones, st.idups = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2), readu8(buf, o + 3) end return nil end -- float_values (R = the wvx stream or nil) local function floatValue(st: State, v: number, R: Reader?): number local fflags, exp = st.fflags, st.fmaxexp local mant, e, sign = 0, 0, 0 if v == 0 then if R then if band(fflags, FLOAT_ZEROS_SENT) ~= 0 then if bits(R, 1) == 1 then mant = bits(R, 23) if exp >= 25 then e = bits(R, 8) end sign = bits(R, 1) elseif band(fflags, FLOAT_NEG_ZEROS) ~= 0 then sign = bits(R, 1) end end end else v = (v * P2[band(st.fshift, 31) + 1]) % TWO32 if v >= 2147483648 then v -= TWO32 end if v < 0 then v = -v sign = 1 end if R then if v == 0x1000000 then if bits(R, 1) == 1 then mant = bits(R, 23) end e = 255 else local shift = 0 if exp > 0 then while v < 0x800000 do exp -= 1 if exp == 0 then break end shift += 1 v *= 2 end end shift = band(shift, 31) if shift > 0 then if band(fflags, FLOAT_SHIFT_ONES) ~= 0 or (band(fflags, FLOAT_SHIFT_SAME) ~= 0 and bits(R, 1) == 1) then v += P2[shift + 1] - 1 elseif band(fflags, FLOAT_SHIFT_SENT) ~= 0 then local mask = P2[shift + 1] - 1 local zeros = 0 local maxOnes, minZeros = st.fmaxones, st.fminzeros if maxOnes > 0 and shift > maxOnes then zeros = shift - maxOnes end if minZeros > zeros then zeros = if minZeros > shift then shift else minZeros end local sc = shift - zeros if sc > 0 then v = bit32.bor(v % TWO32, band(bits(R, sc) * P2[zeros + 1], mask)) end end end mant = band(v % TWO32, 0x7FFFFF) e = band(exp, 255) end else if v >= 0x1000000 then while band(v, 0xF000000) ~= 0 do v //= 2 exp += 1 end elseif exp > 0 then local shift = 0 while v < 0x800000 do exp -= 1 if exp == 0 then break end shift += 1 v *= 2 end shift = band(shift, 31) if shift > 0 and band(fflags, FLOAT_SHIFT_ONES) ~= 0 then v += P2[shift + 1] - 1 end end mant = band(v % TWO32, 0x7FFFFF) e = band(exp, 255) end end if R then st.crcx = (st.crcx * 27 + mant * 9 + e * 3 + sign) % TWO32 end local sc = st.scratch writeu32(sc, 0, sign * 2147483648 + e * 8388608 + mant) return readf32(sc, 0) end -- fixup_samples + false stereo + interleave local function emit(st: State, flags: number, n: number, d: number, P: { number }, c0: number, C: number, lossy: boolean) local W = st.W local s = if d == D2 then 2 else 1 local count = n * s local R: Reader? = if st.wvx then st.R3 else nil if band(flags, FLOAT) ~= 0 then for k = 0, count - 1 do W[d + k] = floatValue(st, W[d + k], R) end else local shift = band(rshift(flags, 13), 31) if band(flags, INT32) ~= 0 then local sent, zeros, ones, dups = band(st.isent, 31), band(st.izeros, 31), band(st.iones, 31), band(st.idups, 31) if R then local maxw = st.imaxw local crc = st.crcx for k = d, d + count - 1 do local v = W[k] if sent > 0 then if maxw > 0 then local pv = if v < 0 then -v - 1 else v local width = (32 - countlz(pv)) + sent local btr = sent if width > maxw then btr -= width - maxw end if width <= maxw or btr > 0 then v = (v * P2[btr + 1] + bits(R, btr)) * P2[sent - btr + 1] else v *= P2[sent + 1] end else v = v * P2[sent + 1] + bits(R, sent) end end if zeros > 0 then v *= P2[zeros + 1] elseif ones > 0 then v = (v + 1) * P2[ones + 1] - 1 elseif dups > 0 then local lo = v % 2 v = (v + lo) * P2[dups + 1] - lo end v %= TWO32 if v >= 2147483648 then v -= TWO32 end crc = (crc * 9 + (v % 65536) * 3 + (v // 65536) % 65536) % TWO32 W[k] = v end st.crcx = crc elseif sent == 0 and zeros + ones + dups > 0 then while lossy and band(flags, 3) == 3 and shift < 8 do if zeros > 0 then zeros -= 1 elseif ones > 0 then ones -= 1 elseif dups > 0 then dups -= 1 else break end shift += 1 end for k = d, d + count - 1 do local v = W[k] if zeros > 0 then v *= P2[zeros + 1] elseif ones > 0 then v = (v + 1) * P2[ones + 1] - 1 elseif dups > 0 then local lo = v % 2 v = (v + lo) * P2[dups + 1] - lo end W[k] = v end else shift += zeros + sent + ones + dups end end shift = band(shift, 31) if lossy then local bytes = band(flags, 3) local top = if bytes == 0 then 127 elseif bytes == 1 then 32767 elseif bytes == 2 then 8388607 else 2147483647 local minv, maxv = (-top - 1) // P2[shift + 1], top // P2[shift + 1] local mul = P2[shift + 1] for k = d, d + count - 1 do local v = W[k] if v < minv then v = minv elseif v > maxv then v = maxv end W[k] = v * mul end elseif shift > 0 then local mul = P2[shift + 1] for k = d, d + count - 1 do W[k] *= mul end end end if s == 2 then if c0 == 0 and C == 2 then for k = 0, count - 1 do P[k + 1] = W[d + k] end elseif c0 + 2 <= C then for i = 0, n - 1 do P[i * C + c0 + 1] = W[d + 2 * i] P[i * C + c0 + 2] = W[d + 2 * i + 1] end else for i = 0, n - 1 do P[i * C + c0 + 1] = W[d + 2 * i] end end elseif band(flags, FALSE_STEREO) ~= 0 and c0 + 2 <= C then for i = 0, n - 1 do local v = W[d + i] P[i * C + c0 + 1] = v P[i * C + c0 + 2] = v end elseif C == 1 then for k = 0, n - 1 do P[k + 1] = W[d + k] end else for i = 0, n - 1 do P[i * C + c0 + 1] = W[d + i] end end end function Block.decode(st: State, buf: buffer, p: number, size: number, P: { number }, c0: number, C: number, cbuf: buffer?, cp: number?, csize: number?): (number?, string?) local version = readu16(buf, p + 8) local n = readu32(buf, p + 20) local flags = readu32(buf, p + 24) local crcWant = readu32(buf, p + 28) if band(flags, DSD) ~= 0 then return nil, "unsupported: DSD audio" end if version < 0x402 or version > 0x410 then return nil, "unsupported: stream version " .. version end if n > MAX_SAMPLES then return nil, "limit: block of " .. n .. " samples" end if band(flags, MONO_FLAG + FALSE_STEREO) == MONO_FLAG + FALSE_STEREO then return nil, "bad block flags" end local mm, merr = Block.meta(buf, p, size) if not mm then return nil, merr end local m: Meta = mm local cm: Meta = {} local cb: buffer = buf local hasC = false if cbuf and cp and csize then local cmeta, cerr = Block.meta(cbuf, cp, csize) if not cmeta then return nil, cerr end cm, cb, hasC = cmeta, cbuf, true crcWant = readu32(cbuf, cp + 28) end st.nterms = 0 local sA, sB, wA, wB = st.sA, st.sB, st.wA, st.wB for k = 1, 128 do sA[k], sB[k] = 0, 0 end for t = 1, 16 do wA[t], wB[t] = 0, 0 end local med = st.med for k = 1, 6 do med[k] = 0 end st.slow[1], st.slow[2], st.limit[1], st.limit[2] = 0, 0, 0, 0 st.bacc[1], st.bacc[2], st.bdelta[1], st.bdelta[2] = 0, 0, 0, 0 st.sacc[1], st.sacc[2], st.sdelta[1], st.sdelta[2], st.err[1], st.err[2] = 0, 0, 0, 0, 0, 0 st.fflags, st.fshift, st.fmaxexp, st.fminzeros, st.fmaxones = 0, 0, 0, 0, 0 st.isent, st.izeros, st.iones, st.idups, st.imaxw = 0, 0, 0, 0, 0 st.hz, st.ho, st.za = 0, 0, 0 st.crcx = TWO32 - 1 st.wvc, st.wvx = false, false local e = readMeta(st, buf, m, flags, version) if e then return nil, e end if hasC then e = readMeta(st, cb, cm, flags, version) if e then return nil, e end end local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 local out = if band(flags, MONO_FLAG) ~= 0 then 1 else 2 if n == 0 then return out, nil end local o = m[0xA] if not o or m[0xA + 256] == 0 or m[0xA + 256] % 2 == 1 then return nil, "no audio bitstream" end openReader(st.R1, buf, o, m[0xA + 256]) if hasC then local co = cm[0xB] if co and cm[0xB + 256] > 0 and cm[0xB + 256] % 2 == 0 then openReader(st.R2, cb, co, cm[0xB + 256]) st.wvc = true end end -- the wvx stream: in the wv block (pure lossless) or the wvc block (hybrid lossless) local xb, xm = buf, m if hasC and (cm[0xC] or cm[0x2C]) then xb, xm = cb, cm end local xid = if xm[0x2C] then 0x2C elseif xm[0xC] then 0xC else nil if xid then local xo, xl = xm[xid], xm[xid + 256] if xl <= 4 or xl % 2 == 1 then return nil, "bad wvx bitstream" end st.crcwvx = readu32(xb, xo) openReader(st.R3, xb, xo + 4, xl - 4) st.wvx = true if xid == 0x2C then if band(flags, FLOAT) ~= 0 then st.fminzeros = bits(st.R3, 5) st.fmaxones = bits(st.R3, 5) else st.imaxw = bits(st.R3, 5) end end end local hybrid = band(flags, HYBRID) ~= 0 local d = if mono then D1 else D2 local W = st.W if #W < d + 2 * n then W = table.create(d + 2 * n + 64, 0) st.W = W end local crc = TWO32 - 1 if not st.wvc then if hybrid then if mono then for i = 0, n - 1 do local v = getWord(st, 0, flags, true) if not v then return nil, "bad audio bitstream" end W[d + i] = v end else for i = 0, n - 1 do local l = getWord(st, 0, flags, false) local r = l and getWord(st, 1, flags, false) if not l or not r then return nil, "bad audio bitstream" end W[d + 2 * i], W[d + 2 * i + 1] = l, r end end elseif not wordsLossless(st, if mono then n else 2 * n, d) then return nil, "bad audio bitstream" end if mono then passesMono(st, n) for k = d, d + n - 1 do crc = (crc * 3 + W[k]) % TWO32 end else passesStereo(st, n) local last = d + 2 * n - 2 if band(flags, JOINT) ~= 0 then for k = d, last, 2 do local l = W[k] local r = W[k + 1] - l // 2 l += r W[k], W[k + 1] = l, r crc = (crc * 9 + l * 3 + r) % TWO32 end else for k = d, last, 2 do crc = (crc * 9 + W[k] * 3 + W[k + 1]) % TWO32 end end end else local ok = if mono then hybridMono(st, n, flags) else hybridStereo(st, n, flags) if not ok then return nil, "bad audio bitstream" end crc = st.crcv end if st.R1.p > st.R1.e or (st.wvc and st.R2.p > st.R2.e) then return nil, "truncated audio bitstream" end if crc ~= crcWant then return nil, "checksum: block CRC mismatch" end emit(st, flags, n, d, P, c0, C, hybrid and not st.wvc) if st.wvx and (st.R3.p > st.R3.e or st.crcx ~= st.crcwvx) then return nil, "checksum: wvx CRC mismatch" end return out, nil end Block.bits = bits Block.bit = bit return Block