ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically): - codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder; codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url; codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err Crc32 Adler32 Base64 Md5 Input Sniff. - LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md). - Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes. C3, generic code out of format folders: - containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first, trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64 through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it. - codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position, priming and end trimming) that aac, caf and m4a each carried (~70 lines each). - codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of its own (the AND mask / alpha rule stay ICO's). - codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model), Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the fixtures' bind shapes). - README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes: FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.
This commit is contained in:
1 parent
763f4a7c04
commit
51b08575c4
283 files changed
+1877
-1660
No files matched your search
@@ -0,0 +1,873 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes,
|
||||
-- LZ77 backward references with the 2-D distance map, the colour cache, and the four inverse transforms (predictor,
|
||||
-- cross colour, subtract green, colour indexing with pixel bundling). A port of libwebp 1.6 src/dec/vp8l_dec.c,
|
||||
-- src/utils/huffman_utils.c and src/dsp/lossless.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); bit-exact with it.
|
||||
--
|
||||
-- Pixels are ARGB u32 values (0xAARRGGBB) in a buffer, 4 bytes each, rows top to bottom. Never throws: every
|
||||
-- function returns nil, "message" (prefixed "truncated: " when the data ends early) on bad data.
|
||||
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
|
||||
local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8
|
||||
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
|
||||
|
||||
local Decode = {}
|
||||
|
||||
local ROOT_BITS = 8
|
||||
local MAX_LEN = 15
|
||||
local NUM_LITERAL = 256
|
||||
local NUM_LENGTH = 24
|
||||
local NUM_DISTANCE = 40
|
||||
local MAX_CACHE_BITS = 11
|
||||
local ARGB_BLACK = 0xff000000
|
||||
|
||||
local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
|
||||
local CODE_TO_PLANE = {
|
||||
0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36,
|
||||
0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34,
|
||||
0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67,
|
||||
0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79,
|
||||
0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52,
|
||||
0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61,
|
||||
0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70,
|
||||
}
|
||||
-- distance map (x offset 8 - (v & 15), y offset v >> 4) as a plain distance for a row width: done per image
|
||||
Decode.CODE_TO_PLANE = CODE_TO_PLANE
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit reader
|
||||
-- LSB-first; bytes past the end read as zero and are counted in `over`: the stream is overrun when fewer bits are
|
||||
-- left in the buffer than phantom bits were added (bitcnt < over * 8).
|
||||
export type State = {
|
||||
buf: buffer,
|
||||
pos: number,
|
||||
limit: number,
|
||||
bitbuf: number,
|
||||
bitcnt: number,
|
||||
over: number,
|
||||
-- prefix code tables (u32 entries value * 32 + bits), shared by every group of every level
|
||||
tab: buffer,
|
||||
tabUsed: number,
|
||||
maxPixels: number,
|
||||
}
|
||||
|
||||
local function fill(d: State)
|
||||
local bitbuf, bitcnt = d.bitbuf, d.bitcnt
|
||||
while bitcnt <= 24 do
|
||||
local p = d.pos
|
||||
local b = 0
|
||||
if p < d.limit then
|
||||
b = readu8(d.buf, p)
|
||||
d.pos = p + 1
|
||||
else
|
||||
d.over += 1
|
||||
end
|
||||
bitbuf += lshift(b, bitcnt)
|
||||
bitcnt += 8
|
||||
end
|
||||
d.bitbuf, d.bitcnt = bitbuf, bitcnt
|
||||
end
|
||||
|
||||
-- readBits(d, n) n <= 24
|
||||
local function readBits(d: State, n: number): number
|
||||
if d.bitcnt < n then
|
||||
fill(d)
|
||||
end
|
||||
local v = band(d.bitbuf, lshift(1, n) - 1)
|
||||
d.bitbuf = rshift(d.bitbuf, n)
|
||||
d.bitcnt -= n
|
||||
return v
|
||||
end
|
||||
|
||||
local function eos(d: State): boolean
|
||||
return d.bitcnt < d.over * 8
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ prefix codes
|
||||
local count = table.create(MAX_LEN + 1, 0)
|
||||
local offset = table.create(MAX_LEN + 2, 0)
|
||||
|
||||
local function ensure(d: State, n: number)
|
||||
local cap = blen(d.tab) // 4
|
||||
if d.tabUsed + n > cap then
|
||||
local nb = bcreate(math.max(cap * 2, d.tabUsed + n) * 4)
|
||||
bcopy(nb, 0, d.tab, 0, d.tabUsed * 4)
|
||||
d.tab = nb
|
||||
end
|
||||
end
|
||||
|
||||
local function replicate(tab: buffer, at: number, step: number, size: number, entry: number)
|
||||
local e = size
|
||||
repeat
|
||||
e -= step
|
||||
writeu32(tab, (at + e) * 4, entry)
|
||||
until e <= 0
|
||||
end
|
||||
|
||||
local function nextKey(key: number, len: number): number
|
||||
local step = lshift(1, len - 1)
|
||||
while band(key, step) ~= 0 do
|
||||
step = rshift(step, 1)
|
||||
end
|
||||
return if step ~= 0 then band(key, step - 1) + step else key
|
||||
end
|
||||
|
||||
-- build(d, lens (0-based Lua array), n) -> table offset in d.tab, or -1 for an invalid code set (libwebp
|
||||
-- BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits)
|
||||
local sorted = table.create(2400, 0)
|
||||
local function build(d: State, lens: { number }, n: number): number
|
||||
for l = 0, MAX_LEN do
|
||||
count[l + 1] = 0
|
||||
end
|
||||
for s = 0, n - 1 do
|
||||
local l = lens[s + 1]
|
||||
if l > MAX_LEN then
|
||||
return -1
|
||||
end
|
||||
count[l + 1] += 1
|
||||
end
|
||||
if count[1] == n then
|
||||
return -1
|
||||
end
|
||||
offset[2] = 0
|
||||
for len = 1, MAX_LEN - 1 do
|
||||
if count[len + 1] > lshift(1, len) then
|
||||
return -1
|
||||
end
|
||||
offset[len + 2] = offset[len + 1] + count[len + 1]
|
||||
end
|
||||
for s = 0, n - 1 do
|
||||
local l = lens[s + 1]
|
||||
if l > 0 then
|
||||
sorted[offset[l + 1] + 1] = s
|
||||
offset[l + 1] += 1
|
||||
end
|
||||
end
|
||||
local long = 0
|
||||
for len = ROOT_BITS + 1, MAX_LEN do
|
||||
long += count[len + 1]
|
||||
end
|
||||
ensure(d, lshift(1, ROOT_BITS) + long * lshift(1, MAX_LEN - ROOT_BITS))
|
||||
local tab = d.tab
|
||||
local root = d.tabUsed
|
||||
local totalSize = lshift(1, ROOT_BITS)
|
||||
if offset[MAX_LEN + 1] == 1 then
|
||||
replicate(tab, root, 1, totalSize, sorted[1] * 32)
|
||||
d.tabUsed = root + totalSize
|
||||
return root
|
||||
end
|
||||
local key = 0
|
||||
local numNodes, numOpen = 1, 1
|
||||
local tableBits = ROOT_BITS
|
||||
local tableSize = lshift(1, tableBits)
|
||||
local tableAt = root
|
||||
local low = -1
|
||||
local mask = totalSize - 1
|
||||
local symbol = 1
|
||||
local step = 2
|
||||
for len = 1, ROOT_BITS do
|
||||
numOpen *= 2
|
||||
numNodes += numOpen
|
||||
numOpen -= count[len + 1]
|
||||
if numOpen < 0 then
|
||||
return -1
|
||||
end
|
||||
while count[len + 1] > 0 do
|
||||
replicate(tab, root + key, step, tableSize, sorted[symbol] * 32 + len)
|
||||
symbol += 1
|
||||
key = nextKey(key, len)
|
||||
count[len + 1] -= 1
|
||||
end
|
||||
step *= 2
|
||||
end
|
||||
step = 2
|
||||
for len = ROOT_BITS + 1, MAX_LEN do
|
||||
numOpen *= 2
|
||||
numNodes += numOpen
|
||||
numOpen -= count[len + 1]
|
||||
if numOpen < 0 then
|
||||
return -1
|
||||
end
|
||||
while count[len + 1] > 0 do
|
||||
if band(key, mask) ~= low then
|
||||
tableAt += tableSize
|
||||
-- NextTableBitSize
|
||||
local l2 = len
|
||||
local left = lshift(1, l2 - ROOT_BITS)
|
||||
while l2 < MAX_LEN do
|
||||
left -= count[l2 + 1]
|
||||
if left <= 0 then
|
||||
break
|
||||
end
|
||||
l2 += 1
|
||||
left *= 2
|
||||
end
|
||||
tableBits = l2 - ROOT_BITS
|
||||
tableSize = lshift(1, tableBits)
|
||||
totalSize += tableSize
|
||||
low = band(key, mask)
|
||||
writeu32(tab, (root + low) * 4, (tableAt - root - low) * 32 + tableBits + ROOT_BITS)
|
||||
end
|
||||
replicate(tab, tableAt + rshift(key, ROOT_BITS), step, tableSize, sorted[symbol] * 32 + len - ROOT_BITS)
|
||||
symbol += 1
|
||||
key = nextKey(key, len)
|
||||
count[len + 1] -= 1
|
||||
end
|
||||
step *= 2
|
||||
end
|
||||
if numNodes ~= 2 * offset[MAX_LEN + 1] - 1 then
|
||||
return -1
|
||||
end
|
||||
d.tabUsed = root + totalSize
|
||||
return root
|
||||
end
|
||||
|
||||
-- readSymbol(d, at) -> symbol (the reader is refilled to >= 15 bits first)
|
||||
local function readSymbol(d: State, at: number): number
|
||||
if d.bitcnt < MAX_LEN then
|
||||
fill(d)
|
||||
end
|
||||
local tab = d.tab
|
||||
local bitbuf = d.bitbuf
|
||||
local idx = at + band(bitbuf, 255)
|
||||
local e = readu32(tab, idx * 4)
|
||||
local nb = band(e, 31)
|
||||
if nb > ROOT_BITS then
|
||||
bitbuf = rshift(bitbuf, ROOT_BITS)
|
||||
d.bitcnt -= ROOT_BITS
|
||||
e = readu32(tab, (idx + rshift(e, 5) + band(bitbuf, lshift(1, nb - ROOT_BITS) - 1)) * 4)
|
||||
nb = band(e, 31)
|
||||
end
|
||||
d.bitbuf = rshift(bitbuf, nb)
|
||||
d.bitcnt -= nb
|
||||
return rshift(e, 5)
|
||||
end
|
||||
|
||||
local codeLengths = table.create(2400, 0)
|
||||
local clLens = table.create(19, 0)
|
||||
|
||||
-- readCode(d, alphabetSize) -> table offset, or -1
|
||||
local function readCode(d: State, size: number): number
|
||||
for i = 1, size do
|
||||
codeLengths[i] = 0
|
||||
end
|
||||
if readBits(d, 1) == 1 then
|
||||
local numSymbols = readBits(d, 1) + 1
|
||||
local first = readBits(d, 1)
|
||||
local s = readBits(d, if first == 0 then 1 else 8)
|
||||
if s < size then
|
||||
codeLengths[s + 1] = 1
|
||||
end
|
||||
if numSymbols == 2 then
|
||||
s = readBits(d, 8)
|
||||
if s < size then
|
||||
codeLengths[s + 1] = 1
|
||||
end
|
||||
end
|
||||
else
|
||||
for i = 1, 19 do
|
||||
clLens[i] = 0
|
||||
end
|
||||
local numCodes = readBits(d, 4) + 4
|
||||
for i = 1, numCodes do
|
||||
clLens[CODE_LENGTH_ORDER[i] + 1] = readBits(d, 3)
|
||||
end
|
||||
local mark = d.tabUsed
|
||||
local clt = build(d, clLens, 19)
|
||||
if clt < 0 then
|
||||
return -1
|
||||
end
|
||||
local maxSymbol = size
|
||||
if readBits(d, 1) == 1 then
|
||||
local nbits = 2 + 2 * readBits(d, 3)
|
||||
maxSymbol = 2 + readBits(d, nbits)
|
||||
if maxSymbol > size then
|
||||
return -1
|
||||
end
|
||||
end
|
||||
local prev = 8
|
||||
local s = 0
|
||||
while s < size do
|
||||
if maxSymbol == 0 then
|
||||
break
|
||||
end
|
||||
maxSymbol -= 1
|
||||
local cl = readSymbol(d, clt)
|
||||
if cl < 16 then
|
||||
codeLengths[s + 1] = cl
|
||||
s += 1
|
||||
if cl ~= 0 then
|
||||
prev = cl
|
||||
end
|
||||
else
|
||||
local rep, len
|
||||
if cl == 16 then
|
||||
rep, len = readBits(d, 2) + 3, prev
|
||||
elseif cl == 17 then
|
||||
rep, len = readBits(d, 3) + 3, 0
|
||||
else
|
||||
rep, len = readBits(d, 7) + 11, 0
|
||||
end
|
||||
if s + rep > size then
|
||||
return -1
|
||||
end
|
||||
for k = s + 1, s + rep do
|
||||
codeLengths[k] = len
|
||||
end
|
||||
s += rep
|
||||
end
|
||||
end
|
||||
d.tabUsed = mark -- the code length table is temporary
|
||||
end
|
||||
if eos(d) then
|
||||
return -1
|
||||
end
|
||||
return build(d, codeLengths, size)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ pixel data
|
||||
local function subSample(size: number, bits: number): number
|
||||
return rshift(size + lshift(1, bits) - 1, bits)
|
||||
end
|
||||
Decode.subSample = subSample
|
||||
|
||||
local function cacheKey(argb: number, shift: number): number
|
||||
-- (0x1e35a7bd * argb) mod 2^32 >> shift, exact in doubles
|
||||
local lo = argb % 65536
|
||||
local hi = (argb - lo) / 65536
|
||||
local m = (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296
|
||||
return rshift(m, shift)
|
||||
end
|
||||
Decode.cacheKey = cacheKey
|
||||
|
||||
-- decodeData: the entropy-coded pixels of one level into `data` (w * h u32)
|
||||
local function decodeData(d: State, data: buffer, w: number, h: number, cacheBits: number, groups: { number }, himg: buffer?, hbits: number, hxs: number): (boolean, string?)
|
||||
local total = w * h
|
||||
local cache: buffer? = if cacheBits > 0 then bcreate(lshift(1, cacheBits) * 4) else nil
|
||||
local cshift = 32 - cacheBits
|
||||
local lenLimit = NUM_LITERAL + NUM_LENGTH
|
||||
local cacheLimit = lenLimit + (if cacheBits > 0 then lshift(1, cacheBits) else 0)
|
||||
local hmask = if himg then lshift(1, hbits) - 1 else -1
|
||||
local i, col, row = 0, 0, 0
|
||||
local gG, gR, gB, gA, gD = groups[1], groups[2], groups[3], groups[4], groups[5]
|
||||
local function setGroup()
|
||||
if himg then
|
||||
local g = readu32(himg, (hxs * rshift(row, hbits) + rshift(col, hbits)) * 4) * 5
|
||||
gG, gR, gB, gA, gD = groups[g + 1], groups[g + 2], groups[g + 3], groups[g + 4], groups[g + 5]
|
||||
end
|
||||
end
|
||||
while i < total do
|
||||
if band(col, hmask) == 0 then
|
||||
setGroup()
|
||||
end
|
||||
local code = readSymbol(d, gG)
|
||||
if code < NUM_LITERAL then
|
||||
local r = readSymbol(d, gR)
|
||||
local b = readSymbol(d, gB)
|
||||
local a = readSymbol(d, gA)
|
||||
if d.bitcnt < d.over * 8 then
|
||||
break
|
||||
end
|
||||
local argb = a * 16777216 + r * 65536 + code * 256 + b
|
||||
writeu32(data, i * 4, argb)
|
||||
if cache then
|
||||
writeu32(cache, cacheKey(argb, cshift) * 4, argb)
|
||||
end
|
||||
i += 1
|
||||
col += 1
|
||||
if col >= w then
|
||||
col = 0
|
||||
row += 1
|
||||
end
|
||||
elseif code < lenLimit then
|
||||
local ls = code - NUM_LITERAL
|
||||
local length
|
||||
if ls < 4 then
|
||||
length = ls + 1
|
||||
else
|
||||
local eb = rshift(ls - 2, 1)
|
||||
length = lshift(2 + band(ls, 1), eb) + readBits(d, eb) + 1
|
||||
end
|
||||
local ds = readSymbol(d, gD)
|
||||
local dc
|
||||
if ds < 4 then
|
||||
dc = ds + 1
|
||||
else
|
||||
local eb = rshift(ds - 2, 1)
|
||||
dc = lshift(2 + band(ds, 1), eb) + readBits(d, eb) + 1
|
||||
end
|
||||
local dist
|
||||
if dc > 120 then
|
||||
dist = dc - 120
|
||||
else
|
||||
local v = CODE_TO_PLANE[dc]
|
||||
dist = rshift(v, 4) * w + 8 - band(v, 15)
|
||||
if dist < 1 then
|
||||
dist = 1
|
||||
end
|
||||
end
|
||||
if d.bitcnt < d.over * 8 then
|
||||
break
|
||||
end
|
||||
if i < dist or total - i < length then
|
||||
return false, "bad backward reference"
|
||||
end
|
||||
if dist >= length then
|
||||
bcopy(data, i * 4, data, (i - dist) * 4, length * 4)
|
||||
else
|
||||
for k = i, i + length - 1 do
|
||||
writeu32(data, k * 4, readu32(data, (k - dist) * 4))
|
||||
end
|
||||
end
|
||||
if cache then
|
||||
for k = i, i + length - 1 do
|
||||
local argb = readu32(data, k * 4)
|
||||
writeu32(cache, cacheKey(argb, cshift) * 4, argb)
|
||||
end
|
||||
end
|
||||
i += length
|
||||
col += length
|
||||
while col >= w do
|
||||
col -= w
|
||||
row += 1
|
||||
end
|
||||
if band(col, hmask) ~= 0 then
|
||||
setGroup()
|
||||
end
|
||||
elseif code < cacheLimit and cache then
|
||||
if d.bitcnt < d.over * 8 then
|
||||
break
|
||||
end
|
||||
local argb = readu32(cache, (code - lenLimit) * 4)
|
||||
writeu32(data, i * 4, argb)
|
||||
writeu32(cache, cacheKey(argb, cshift) * 4, argb)
|
||||
i += 1
|
||||
col += 1
|
||||
if col >= w then
|
||||
col = 0
|
||||
row += 1
|
||||
end
|
||||
else
|
||||
return false, "bad symbol"
|
||||
end
|
||||
end
|
||||
if eos(d) then
|
||||
return false, "truncated: pixel data"
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
local function addPixels(a: number, b: number): number
|
||||
return band(band(a, 0xff00ff00) + band(b, 0xff00ff00), 0xff00ff00) + band(band(a, 0x00ff00ff) + band(b, 0x00ff00ff), 0x00ff00ff)
|
||||
end
|
||||
Decode.addPixels = addPixels
|
||||
|
||||
local function average2(a: number, b: number): number
|
||||
return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b)
|
||||
end
|
||||
Decode.average2 = average2
|
||||
|
||||
local function clip255(v: number): number
|
||||
return if v < 0 then 0 elseif v > 255 then 255 else v
|
||||
end
|
||||
|
||||
local function sub3(a: number, b: number, c: number): number
|
||||
local pb, pa = b - c, a - c
|
||||
return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa)
|
||||
end
|
||||
|
||||
-- select(T, L, TL)
|
||||
local function select3(a: number, b: number, c: number): number
|
||||
local s = sub3(rshift(a, 24), rshift(b, 24), rshift(c, 24))
|
||||
+ sub3(band(rshift(a, 16), 255), band(rshift(b, 16), 255), band(rshift(c, 16), 255))
|
||||
+ sub3(band(rshift(a, 8), 255), band(rshift(b, 8), 255), band(rshift(c, 8), 255))
|
||||
+ sub3(band(a, 255), band(b, 255), band(c, 255))
|
||||
return if s <= 0 then a else b
|
||||
end
|
||||
|
||||
local function clampedFull(c0: number, c1: number, c2: number): number
|
||||
local a = clip255(rshift(c0, 24) + rshift(c1, 24) - rshift(c2, 24))
|
||||
local r = clip255(band(rshift(c0, 16), 255) + band(rshift(c1, 16), 255) - band(rshift(c2, 16), 255))
|
||||
local g = clip255(band(rshift(c0, 8), 255) + band(rshift(c1, 8), 255) - band(rshift(c2, 8), 255))
|
||||
local b = clip255(band(c0, 255) + band(c1, 255) - band(c2, 255))
|
||||
return a * 16777216 + r * 65536 + g * 256 + b
|
||||
end
|
||||
|
||||
local function half(a: number, b: number): number
|
||||
local dd = a - b
|
||||
-- C division truncates toward zero
|
||||
local q = if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1)
|
||||
return clip255(a + q)
|
||||
end
|
||||
|
||||
local function clampedHalf(c0: number, c1: number, c2: number): number
|
||||
local ave = average2(c0, c1)
|
||||
local a = half(rshift(ave, 24), rshift(c2, 24))
|
||||
local r = half(band(rshift(ave, 16), 255), band(rshift(c2, 16), 255))
|
||||
local g = half(band(rshift(ave, 8), 255), band(rshift(c2, 8), 255))
|
||||
local b = half(band(ave, 255), band(c2, 255))
|
||||
return a * 16777216 + r * 65536 + g * 256 + b
|
||||
end
|
||||
|
||||
-- predict(mode, L, T, TR, TL) -> the predicted pixel (libwebp VP8LPredictors; 14 and 15 are black)
|
||||
local function predict(mode: number, L: number, T: number, TR: number, TL: number): number
|
||||
if mode == 0 then
|
||||
return ARGB_BLACK
|
||||
elseif mode == 1 then
|
||||
return L
|
||||
elseif mode == 2 then
|
||||
return T
|
||||
elseif mode == 3 then
|
||||
return TR
|
||||
elseif mode == 4 then
|
||||
return TL
|
||||
elseif mode == 5 then
|
||||
return average2(average2(L, TR), T)
|
||||
elseif mode == 6 then
|
||||
return average2(L, TL)
|
||||
elseif mode == 7 then
|
||||
return average2(L, T)
|
||||
elseif mode == 8 then
|
||||
return average2(TL, T)
|
||||
elseif mode == 9 then
|
||||
return average2(T, TR)
|
||||
elseif mode == 10 then
|
||||
return average2(average2(L, TL), average2(T, TR))
|
||||
elseif mode == 11 then
|
||||
return select3(T, L, TL)
|
||||
elseif mode == 12 then
|
||||
return clampedFull(L, T, TL)
|
||||
elseif mode == 13 then
|
||||
return clampedHalf(L, T, TL)
|
||||
end
|
||||
return ARGB_BLACK
|
||||
end
|
||||
Decode.predict = predict
|
||||
|
||||
local function inversePredictor(data: buffer, w: number, h: number, bits: number, sub: buffer)
|
||||
local tw = subSample(w, bits)
|
||||
-- first row: black, then L
|
||||
writeu32(data, 0, addPixels(readu32(data, 0), ARGB_BLACK))
|
||||
for x = 1, w - 1 do
|
||||
writeu32(data, x * 4, addPixels(readu32(data, x * 4), readu32(data, (x - 1) * 4)))
|
||||
end
|
||||
for y = 1, h - 1 do
|
||||
local row = y * w
|
||||
local up = row - w
|
||||
writeu32(data, row * 4, addPixels(readu32(data, row * 4), readu32(data, up * 4)))
|
||||
local trow = rshift(y, bits) * tw
|
||||
local x = 1
|
||||
while x < w do
|
||||
local mode = band(rshift(readu32(sub, (trow + rshift(x, bits)) * 4), 8), 15)
|
||||
local xe = math.min(w, lshift(rshift(x, bits) + 1, bits))
|
||||
local L = readu32(data, (row + x - 1) * 4)
|
||||
if mode == 1 then
|
||||
for k = x, xe - 1 do
|
||||
L = addPixels(readu32(data, (row + k) * 4), L)
|
||||
writeu32(data, (row + k) * 4, L)
|
||||
end
|
||||
elseif mode == 2 then
|
||||
for k = x, xe - 1 do
|
||||
writeu32(data, (row + k) * 4, addPixels(readu32(data, (row + k) * 4), readu32(data, (up + k) * 4)))
|
||||
end
|
||||
else
|
||||
for k = x, xe - 1 do
|
||||
local p = predict(mode, L, readu32(data, (up + k) * 4), readu32(data, (up + k + 1) * 4), readu32(data, (up + k - 1) * 4))
|
||||
L = addPixels(readu32(data, (row + k) * 4), p)
|
||||
writeu32(data, (row + k) * 4, L)
|
||||
end
|
||||
end
|
||||
x = xe
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function sint8(v: number): number
|
||||
return if v >= 128 then v - 256 else v
|
||||
end
|
||||
|
||||
local function inverseCrossColor(data: buffer, w: number, h: number, bits: number, sub: buffer)
|
||||
local tw = subSample(w, bits)
|
||||
for y = 0, h - 1 do
|
||||
local trow = rshift(y, bits) * tw
|
||||
local x = 0
|
||||
while x < w do
|
||||
local m = readu32(sub, (trow + rshift(x, bits)) * 4)
|
||||
local g2r = sint8(band(m, 255))
|
||||
local g2b = sint8(band(rshift(m, 8), 255))
|
||||
local r2b = sint8(band(rshift(m, 16), 255))
|
||||
local xe = math.min(w, lshift(rshift(x, bits) + 1, bits))
|
||||
for k = y * w + x, y * w + xe - 1 do
|
||||
local argb = readu32(data, k * 4)
|
||||
local g = sint8(band(rshift(argb, 8), 255))
|
||||
local r = band(band(rshift(argb, 16), 255) + ((g2r * g) // 32), 255)
|
||||
local b = band(band(argb, 255) + ((g2b * g) // 32) + ((r2b * sint8(r)) // 32), 255)
|
||||
writeu32(data, k * 4, band(argb, 0xff00ff00) + r * 65536 + b)
|
||||
end
|
||||
x = xe
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function inverseSubtractGreen(data: buffer, n: number)
|
||||
for k = 0, n - 1 do
|
||||
local argb = readu32(data, k * 4)
|
||||
local g = band(rshift(argb, 8), 255)
|
||||
writeu32(data, k * 4, band(argb, 0xff00ff00) + band(band(argb, 0x00ff00ff) + g * 65537, 0x00ff00ff))
|
||||
end
|
||||
end
|
||||
|
||||
-- inverseColorIndexing(src (sw x h), w, h, bits, map (2^(8 >> bits) u32)) -> w x h
|
||||
local function inverseColorIndexing(src: buffer, sw: number, w: number, h: number, bits: number, map: buffer): buffer
|
||||
local out = bcreate(w * h * 4)
|
||||
if bits == 0 then
|
||||
for k = 0, w * h - 1 do
|
||||
writeu32(out, k * 4, readu32(map, band(rshift(readu32(src, k * 4), 8), 255) * 4))
|
||||
end
|
||||
return out
|
||||
end
|
||||
local bpp = rshift(8, bits)
|
||||
local cmask = lshift(1, bits) - 1
|
||||
local vmask = lshift(1, bpp) - 1
|
||||
for y = 0, h - 1 do
|
||||
local packed = 0
|
||||
local s = y * sw
|
||||
local o = y * w
|
||||
for x = 0, w - 1 do
|
||||
if band(x, cmask) == 0 then
|
||||
packed = band(rshift(readu32(src, s * 4), 8), 255)
|
||||
s += 1
|
||||
end
|
||||
writeu32(out, (o + x) * 4, readu32(map, band(packed, vmask) * 4))
|
||||
packed = rshift(packed, bpp)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ image stream
|
||||
type Transform = { kind: number, xsize: number, bits: number, data: buffer? }
|
||||
|
||||
local decodeStream: (d: State, xs: number, ys: number, level0: boolean) -> (buffer?, string?)
|
||||
|
||||
-- readCodes(d, xs, ys, cacheBits, level0) -> groups (5 table offsets each), huffman image, bits, image width
|
||||
local function readCodes(d: State, xs: number, ys: number, cacheBits: number, level0: boolean): ({ number }?, buffer?, number, number, string?)
|
||||
local himg: buffer? = nil
|
||||
local hbits, hxs = 0, 0
|
||||
local numGroups = 1
|
||||
local mapping: { number }? = nil
|
||||
local numMax = 1
|
||||
if level0 and readBits(d, 1) == 1 then
|
||||
hbits = readBits(d, 3) + 2
|
||||
hxs = subSample(xs, hbits)
|
||||
local hys = subSample(ys, hbits)
|
||||
local img, err = decodeStream(d, hxs, hys, false)
|
||||
if not img then
|
||||
return nil, nil, 0, 0, err
|
||||
end
|
||||
local n = hxs * hys
|
||||
for k = 0, n - 1 do
|
||||
local g = band(rshift(readu32(img, k * 4), 8), 0xffff)
|
||||
writeu32(img, k * 4, g)
|
||||
if g >= numMax then
|
||||
numMax = g + 1
|
||||
end
|
||||
end
|
||||
if numMax > 1000 or numMax > xs * ys then
|
||||
-- remap the used groups to [0, numGroups); unused ones are read and checked but not kept
|
||||
local map = table.create(numMax, -1) :: { number }
|
||||
numGroups = 0
|
||||
for k = 0, n - 1 do
|
||||
local g = readu32(img, k * 4)
|
||||
if map[g + 1] == -1 then
|
||||
map[g + 1] = numGroups
|
||||
numGroups += 1
|
||||
end
|
||||
writeu32(img, k * 4, map[g + 1])
|
||||
end
|
||||
mapping = map
|
||||
else
|
||||
numGroups = numMax
|
||||
end
|
||||
himg = img
|
||||
end
|
||||
if eos(d) then
|
||||
return nil, nil, 0, 0, "truncated: meta codes"
|
||||
end
|
||||
local groups = table.create(numGroups * 5, 0) :: { number }
|
||||
local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0
|
||||
for i = 0, numMax - 1 do
|
||||
local slot = if mapping then mapping[i + 1] else i
|
||||
local mark = d.tabUsed
|
||||
for j = 0, 4 do
|
||||
local size = if j == 0 then NUM_LITERAL + NUM_LENGTH + cacheSize elseif j == 4 then NUM_DISTANCE else NUM_LITERAL
|
||||
local at = readCode(d, size)
|
||||
if at < 0 then
|
||||
return nil, nil, 0, 0, if eos(d) then "truncated: prefix code" else "bad prefix code"
|
||||
end
|
||||
if slot >= 0 then
|
||||
groups[slot * 5 + j + 1] = at
|
||||
end
|
||||
end
|
||||
if slot < 0 then
|
||||
d.tabUsed = mark
|
||||
end
|
||||
end
|
||||
return groups, himg, hbits, hxs, nil
|
||||
end
|
||||
|
||||
decodeStream = function(d: State, xs: number, ys: number, level0: boolean): (buffer?, string?)
|
||||
local transforms: { Transform } = {}
|
||||
local seen = 0
|
||||
local txs = xs
|
||||
if level0 then
|
||||
while readBits(d, 1) == 1 do
|
||||
local kind = readBits(d, 2)
|
||||
if band(seen, lshift(1, kind)) ~= 0 then
|
||||
return nil, "repeated transform"
|
||||
end
|
||||
seen = bor(seen, lshift(1, kind))
|
||||
local t: Transform = { kind = kind, xsize = txs, bits = 0, data = nil }
|
||||
if kind == 0 or kind == 1 then
|
||||
t.bits = readBits(d, 3) + 2
|
||||
local sub, err = decodeStream(d, subSample(txs, t.bits), subSample(ys, t.bits), false)
|
||||
if not sub then
|
||||
return nil, err
|
||||
end
|
||||
t.data = sub
|
||||
elseif kind == 3 then
|
||||
local num = readBits(d, 8) + 1
|
||||
local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3
|
||||
t.bits = bits
|
||||
local pal, err = decodeStream(d, num, 1, false)
|
||||
if not pal then
|
||||
return nil, err
|
||||
end
|
||||
local final = lshift(1, rshift(8, bits))
|
||||
local map = bcreate(final * 4)
|
||||
local prev = 0
|
||||
for k = 0, num - 1 do
|
||||
prev = addPixels(readu32(pal, k * 4), prev)
|
||||
writeu32(map, k * 4, prev)
|
||||
end
|
||||
t.data = map
|
||||
txs = subSample(txs, bits)
|
||||
end
|
||||
table.insert(transforms, t)
|
||||
if eos(d) then
|
||||
return nil, "truncated: transforms"
|
||||
end
|
||||
end
|
||||
end
|
||||
local cacheBits = 0
|
||||
if readBits(d, 1) == 1 then
|
||||
cacheBits = readBits(d, 4)
|
||||
if cacheBits < 1 or cacheBits > MAX_CACHE_BITS then
|
||||
return nil, "bad colour cache size"
|
||||
end
|
||||
end
|
||||
local mark = d.tabUsed
|
||||
local groups, himg, hbits, hxs, err = readCodes(d, txs, ys, cacheBits, level0)
|
||||
if not groups then
|
||||
return nil, err
|
||||
end
|
||||
local data = bcreate(txs * ys * 4)
|
||||
local ok, derr = decodeData(d, data, txs, ys, cacheBits, groups, himg, hbits, hxs)
|
||||
if not ok then
|
||||
return nil, derr
|
||||
end
|
||||
d.tabUsed = mark
|
||||
-- inverse transforms, last read first
|
||||
for k = #transforms, 1, -1 do
|
||||
local t = transforms[k]
|
||||
if t.kind == 0 then
|
||||
inversePredictor(data, t.xsize, ys, t.bits, t.data :: buffer)
|
||||
elseif t.kind == 1 then
|
||||
inverseCrossColor(data, t.xsize, ys, t.bits, t.data :: buffer)
|
||||
elseif t.kind == 2 then
|
||||
inverseSubtractGreen(data, t.xsize * ys)
|
||||
else
|
||||
data = inverseColorIndexing(data, subSample(t.xsize, t.bits), t.xsize, ys, t.bits, t.data :: buffer)
|
||||
end
|
||||
end
|
||||
return data, nil
|
||||
end
|
||||
|
||||
local function newState(buf: buffer, off: number, len: number, maxPixels: number): State
|
||||
return {
|
||||
buf = buf,
|
||||
pos = off,
|
||||
limit = off + len,
|
||||
bitbuf = 0,
|
||||
bitcnt = 0,
|
||||
over = 0,
|
||||
tab = bcreate(4096 * 4),
|
||||
tabUsed = 0,
|
||||
maxPixels = maxPixels,
|
||||
}
|
||||
end
|
||||
|
||||
-- header(buf, off, len) -> width, height, alphaHint | nil, message
|
||||
function Decode.header(buf: buffer, off: number, len: number): (number?, number, boolean, string?)
|
||||
if len < 5 then
|
||||
return nil, 0, false, "truncated: header"
|
||||
end
|
||||
if readu8(buf, off) ~= 0x2f then
|
||||
return nil, 0, false, "bad VP8L signature"
|
||||
end
|
||||
local v = readu32(buf, off + 1)
|
||||
local w = band(v, 0x3fff) + 1
|
||||
local h = band(rshift(v, 14), 0x3fff) + 1
|
||||
local alpha = band(rshift(v, 28), 1) == 1
|
||||
if rshift(v, 29) ~= 0 then
|
||||
return nil, 0, false, "bad VP8L version"
|
||||
end
|
||||
return w, h, alpha, nil
|
||||
end
|
||||
|
||||
-- argb(buf, off, len, maxPixels) -> ARGB pixels, width, height, alphaHint | nil, message
|
||||
function Decode.argb(buf: buffer, off: number, len: number, maxPixels: number): (buffer?, number, number, boolean, string?)
|
||||
local w, h, alpha, err = Decode.header(buf, off, len)
|
||||
if not w then
|
||||
return nil, 0, 0, false, err
|
||||
end
|
||||
if w * h > maxPixels then
|
||||
return nil, w, h, alpha, "limit: " .. w .. " x " .. h .. " is over maxPixels"
|
||||
end
|
||||
local d = newState(buf, off + 5, len - 5, maxPixels)
|
||||
local data, derr = decodeStream(d, w, h, true)
|
||||
if not data then
|
||||
return nil, w, h, alpha, derr
|
||||
end
|
||||
return data, w, h, alpha, nil
|
||||
end
|
||||
|
||||
-- stream(buf, off, len, w, h) -> ARGB pixels | nil, message: a headerless image stream (the ALPH chunk's payload)
|
||||
function Decode.stream(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, string?)
|
||||
local d = newState(buf, off, len, w * h)
|
||||
return decodeStream(d, w, h, true)
|
||||
end
|
||||
|
||||
-- toRgba(argb, n, out?, outOff?) -> rgba8 bytes
|
||||
function Decode.toRgba(argb: buffer, n: number, out: buffer?, outOff: number?): buffer
|
||||
local o = out or bcreate(n * 4)
|
||||
local base = outOff or 0
|
||||
for k = 0, n - 1 do
|
||||
local v = readu32(argb, k * 4)
|
||||
-- 0xAARRGGBB (bytes B G R A) -> bytes R G B A
|
||||
writeu32(o, base + k * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536)
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
-- green(argb, n) -> the green channel as bytes (alpha planes)
|
||||
function Decode.green(argb: buffer, n: number): buffer
|
||||
local o = bcreate(n)
|
||||
for k = 0, n - 1 do
|
||||
writeu8(o, k, band(rshift(readu32(argb, k * 4), 8), 255))
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -0,0 +1,976 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from the specification (RFC 9649 section 3).
|
||||
-- Transforms: colour indexing with pixel bundling (<= 256 colours), else subtract green + predictor (per-tile mode
|
||||
-- chosen from a residual cost) + cross colour (per-tile least-squares multipliers). Entropy coding: LZ77 with hash
|
||||
-- chains, the left / up run candidates and the 2-D distance codes, a colour cache whose size is chosen by an entropy
|
||||
-- estimate, one prefix code group per image, code lengths limited to 15 bits (codecs/entropy/Huffman) and run-length coded.
|
||||
-- Never throws (the init module validates the arguments).
|
||||
local Huffman = require("@formats/codecs/entropy/Huffman")
|
||||
|
||||
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
|
||||
local readu32, writeu8, writeu32 = buffer.readu32, buffer.writeu8, buffer.writeu32
|
||||
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
|
||||
local log = math.log
|
||||
|
||||
local Encode = {}
|
||||
|
||||
local NUM_LITERAL = 256
|
||||
local NUM_LENGTH = 24
|
||||
local NUM_DISTANCE = 40
|
||||
local MAX_LENGTH = 4096
|
||||
local WINDOW = 1048576 - 120
|
||||
local ARGB_BLACK = 0xff000000
|
||||
|
||||
local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
|
||||
local CODE_TO_PLANE = {
|
||||
0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36,
|
||||
0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34,
|
||||
0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67,
|
||||
0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79,
|
||||
0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52,
|
||||
0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61,
|
||||
0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70,
|
||||
}
|
||||
-- PLANE_TO_CODE[v + 1] = the distance code (1..120) of the plane offset v = yoffset * 16 + 8 - xoffset
|
||||
local PLANE_TO_CODE = table.create(128, 0)
|
||||
for i, v in CODE_TO_PLANE do
|
||||
PLANE_TO_CODE[v + 1] = i
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit writer
|
||||
type W = { buf: buffer, pos: number, acc: number, cnt: number }
|
||||
|
||||
local function newWriter(cap: number): W
|
||||
return { buf = bcreate(math.max(64, cap)), pos = 0, acc = 0, cnt = 0 }
|
||||
end
|
||||
|
||||
-- put(w, v, n): the n <= 24 low bits of v, LSB first
|
||||
local function put(w: W, v: number, n: number)
|
||||
local acc = w.acc + v * 2 ^ w.cnt
|
||||
local cnt = w.cnt + n
|
||||
if cnt >= 8 then
|
||||
local pos = w.pos
|
||||
local buf = w.buf
|
||||
if pos + 8 > blen(buf) then
|
||||
local nb = bcreate(blen(buf) * 2)
|
||||
bcopy(nb, 0, buf, 0, pos)
|
||||
buf = nb
|
||||
w.buf = nb
|
||||
end
|
||||
repeat
|
||||
local byte = acc % 256
|
||||
writeu8(buf, pos, byte)
|
||||
pos += 1
|
||||
acc = (acc - byte) / 256
|
||||
cnt -= 8
|
||||
until cnt < 8
|
||||
w.pos = pos
|
||||
end
|
||||
w.acc, w.cnt = acc, cnt
|
||||
end
|
||||
|
||||
local function finish(w: W): buffer
|
||||
if w.cnt > 0 then
|
||||
put(w, 0, 8 - w.cnt)
|
||||
end
|
||||
local out = bcreate(w.pos)
|
||||
bcopy(out, 0, w.buf, 0, w.pos)
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ helpers
|
||||
local function subSample(size: number, bits: number): number
|
||||
return rshift(size + lshift(1, bits) - 1, bits)
|
||||
end
|
||||
|
||||
-- (0x1e35a7bd * v) mod 2^32: the colour cache hash before its shift
|
||||
local function mulHash(v: number): number
|
||||
local lo = v % 65536
|
||||
local hi = (v - lo) / 65536
|
||||
return (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296
|
||||
end
|
||||
|
||||
-- prefix(v) -> code, extra bits, extra value of a length or distance code value v >= 1
|
||||
local function prefix(v: number): (number, number, number)
|
||||
local d = v - 1
|
||||
if d < 4 then
|
||||
return d, 0, 0
|
||||
end
|
||||
local hb = 0
|
||||
local t = d
|
||||
while t >= 2 do
|
||||
t = rshift(t, 1)
|
||||
hb += 1
|
||||
end
|
||||
local second = band(rshift(d, hb - 1), 1)
|
||||
local eb = hb - 1
|
||||
return 2 * hb + second, eb, band(d, lshift(1, eb) - 1)
|
||||
end
|
||||
|
||||
-- distCode(xs, dist) -> the distance code value (1..120 for the 2-D plane offsets, else dist + 120)
|
||||
local function distCode(xs: number, dist: number): number
|
||||
local yo = dist // xs
|
||||
local xo = dist - yo * xs
|
||||
if xo <= 8 and yo < 8 then
|
||||
return PLANE_TO_CODE[yo * 16 + 8 - xo + 1]
|
||||
elseif xo > xs - 8 and yo < 7 then
|
||||
return PLANE_TO_CODE[(yo + 1) * 16 + 8 + (xs - xo) + 1]
|
||||
end
|
||||
return dist + 120
|
||||
end
|
||||
|
||||
local function subPixels(a: number, b: number): number
|
||||
return band(bor(a, 0x00ff00ff) - band(b, 0xff00ff00), 0xff00ff00) + band(bor(a, 0xff00ff00) - band(b, 0x00ff00ff), 0x00ff00ff)
|
||||
end
|
||||
|
||||
local function average2(a: number, b: number): number
|
||||
return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b)
|
||||
end
|
||||
|
||||
local function clip255(v: number): number
|
||||
return if v < 0 then 0 elseif v > 255 then 255 else v
|
||||
end
|
||||
|
||||
local function sub3(a: number, b: number, c: number): number
|
||||
local pb, pa = b - c, a - c
|
||||
return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa)
|
||||
end
|
||||
|
||||
local function half(x: number, y: number): number
|
||||
local dd = x - y
|
||||
return clip255(x + (if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1)))
|
||||
end
|
||||
|
||||
-- predict(mode, L, T, TR, TL): the decoder's predictors (codecs/image/Vp8L/Decode)
|
||||
local function predict(mode: number, L: number, T: number, TR: number, TL: number): number
|
||||
if mode == 1 then
|
||||
return L
|
||||
elseif mode == 2 then
|
||||
return T
|
||||
elseif mode == 3 then
|
||||
return TR
|
||||
elseif mode == 4 then
|
||||
return TL
|
||||
elseif mode == 5 then
|
||||
return average2(average2(L, TR), T)
|
||||
elseif mode == 6 then
|
||||
return average2(L, TL)
|
||||
elseif mode == 7 then
|
||||
return average2(L, T)
|
||||
elseif mode == 8 then
|
||||
return average2(TL, T)
|
||||
elseif mode == 9 then
|
||||
return average2(T, TR)
|
||||
elseif mode == 10 then
|
||||
return average2(average2(L, TL), average2(T, TR))
|
||||
elseif mode == 11 then
|
||||
local s = sub3(rshift(T, 24), rshift(L, 24), rshift(TL, 24))
|
||||
+ sub3(band(rshift(T, 16), 255), band(rshift(L, 16), 255), band(rshift(TL, 16), 255))
|
||||
+ sub3(band(rshift(T, 8), 255), band(rshift(L, 8), 255), band(rshift(TL, 8), 255))
|
||||
+ sub3(band(T, 255), band(L, 255), band(TL, 255))
|
||||
return if s <= 0 then T else L
|
||||
elseif mode == 12 then
|
||||
local a = clip255(rshift(L, 24) + rshift(T, 24) - rshift(TL, 24))
|
||||
local r = clip255(band(rshift(L, 16), 255) + band(rshift(T, 16), 255) - band(rshift(TL, 16), 255))
|
||||
local g = clip255(band(rshift(L, 8), 255) + band(rshift(T, 8), 255) - band(rshift(TL, 8), 255))
|
||||
local b = clip255(band(L, 255) + band(T, 255) - band(TL, 255))
|
||||
return a * 16777216 + r * 65536 + g * 256 + b
|
||||
elseif mode == 13 then
|
||||
local ave = average2(L, T)
|
||||
local a = half(rshift(ave, 24), rshift(TL, 24))
|
||||
local r = half(band(rshift(ave, 16), 255), band(rshift(TL, 16), 255))
|
||||
local g = half(band(rshift(ave, 8), 255), band(rshift(TL, 8), 255))
|
||||
local b = half(band(ave, 255), band(TL, 255))
|
||||
return a * 16777216 + r * 65536 + g * 256 + b
|
||||
end
|
||||
return ARGB_BLACK
|
||||
end
|
||||
|
||||
-- COST[v + 1]: an estimate of the bits of a residual byte v (small magnitudes, mod 256, are cheap)
|
||||
local COST = table.create(256, 0)
|
||||
for v = 0, 255 do
|
||||
local m = math.min(v, 256 - v)
|
||||
COST[v + 1] = log(1 + m) / log(2)
|
||||
end
|
||||
|
||||
local function residualCost(r: number): number
|
||||
return COST[band(r, 255) + 1] + COST[band(rshift(r, 8), 255) + 1] + COST[band(rshift(r, 16), 255) + 1] + COST[rshift(r, 24) + 1]
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
local MODES_FAST = { 1, 2, 11 }
|
||||
local MODES_MID = { 0, 1, 2, 4, 5, 7, 10, 11, 12, 13 }
|
||||
local MODES_ALL = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }
|
||||
|
||||
-- predictorTransform(px, w, h, bits, effort) -> the modes sub-image; px becomes the residuals
|
||||
local function predictorTransform(px: buffer, w: number, h: number, bits: number, effort: number): buffer
|
||||
local tw, th = subSample(w, bits), subSample(h, bits)
|
||||
local modesImg = bcreate(tw * th * 4)
|
||||
local modes = if effort <= 2 then MODES_FAST elseif effort <= 6 then MODES_MID else MODES_ALL
|
||||
local ts = lshift(1, bits)
|
||||
for ty = 0, th - 1 do
|
||||
for tx = 0, tw - 1 do
|
||||
local x0, y0 = tx * ts, ty * ts
|
||||
local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts)
|
||||
local best, bestCost = 1, math.huge
|
||||
for _, m in modes do
|
||||
local cost = 0
|
||||
for y = math.max(y0, 1), y1 - 1 do
|
||||
local row = y * w
|
||||
for x = math.max(x0, 1), x1 - 1 do
|
||||
local i = row + x
|
||||
local up = i - w
|
||||
local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4))
|
||||
cost += residualCost(subPixels(readu32(px, i * 4), p))
|
||||
end
|
||||
if cost >= bestCost then
|
||||
break
|
||||
end
|
||||
end
|
||||
if cost < bestCost then
|
||||
best, bestCost = m, cost
|
||||
end
|
||||
end
|
||||
writeu32(modesImg, (ty * tw + tx) * 4, ARGB_BLACK + best * 256)
|
||||
end
|
||||
end
|
||||
-- residuals with the chosen modes (and the decoder's fixed first row and column)
|
||||
local res = bcreate(w * h * 4)
|
||||
writeu32(res, 0, subPixels(readu32(px, 0), ARGB_BLACK))
|
||||
for x = 1, w - 1 do
|
||||
writeu32(res, x * 4, subPixels(readu32(px, x * 4), readu32(px, (x - 1) * 4)))
|
||||
end
|
||||
for y = 1, h - 1 do
|
||||
local row = y * w
|
||||
writeu32(res, row * 4, subPixels(readu32(px, row * 4), readu32(px, (row - w) * 4)))
|
||||
local trow = rshift(y, bits) * tw
|
||||
for x = 1, w - 1 do
|
||||
local m = band(rshift(readu32(modesImg, (trow + rshift(x, bits)) * 4), 8), 15)
|
||||
local i = row + x
|
||||
local up = i - w
|
||||
local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4))
|
||||
writeu32(res, i * 4, subPixels(readu32(px, i * 4), p))
|
||||
end
|
||||
end
|
||||
bcopy(px, 0, res, 0, w * h * 4)
|
||||
return modesImg
|
||||
end
|
||||
|
||||
local function sint8(v: number): number
|
||||
return if v >= 128 then v - 256 else v
|
||||
end
|
||||
|
||||
local function clampM(v: number): number
|
||||
local m = math.floor(v + 0.5)
|
||||
return if m < -128 then -128 elseif m > 127 then 127 else m
|
||||
end
|
||||
|
||||
-- crossColorTransform(px, w, h, bits) -> the multipliers sub-image; px is transformed in place. Per tile: the
|
||||
-- least-squares multipliers (r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32), kept when they lower the cost
|
||||
local function crossColorTransform(px: buffer, w: number, h: number, bits: number): buffer
|
||||
local tw, th = subSample(w, bits), subSample(h, bits)
|
||||
local img = bcreate(tw * th * 4)
|
||||
local ts = lshift(1, bits)
|
||||
local function tileCost(x0: number, y0: number, x1: number, y1: number, g2r: number, g2b: number, r2b: number): number
|
||||
local c = 0
|
||||
for y = y0, y1 - 1 do
|
||||
for x = x0, x1 - 1 do
|
||||
local argb = readu32(px, (y * w + x) * 4)
|
||||
local g = sint8(band(rshift(argb, 8), 255))
|
||||
local r = band(rshift(argb, 16), 255)
|
||||
local b = band(argb, 255)
|
||||
local nr = band(r - ((g2r * g) // 32), 255)
|
||||
local nb = band(b - ((g2b * g) // 32) - ((r2b * sint8(r)) // 32), 255)
|
||||
c += COST[nr + 1] + COST[nb + 1]
|
||||
end
|
||||
end
|
||||
return c
|
||||
end
|
||||
for ty = 0, th - 1 do
|
||||
for tx = 0, tw - 1 do
|
||||
local x0, y0 = tx * ts, ty * ts
|
||||
local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts)
|
||||
local sgg, sgr, sgb, srr, srb = 0, 0, 0, 0, 0
|
||||
for y = y0, y1 - 1 do
|
||||
for x = x0, x1 - 1 do
|
||||
local argb = readu32(px, (y * w + x) * 4)
|
||||
local g = sint8(band(rshift(argb, 8), 255))
|
||||
local r = sint8(band(rshift(argb, 16), 255))
|
||||
local b = sint8(band(argb, 255))
|
||||
sgg += g * g
|
||||
sgr += g * r
|
||||
sgb += g * b
|
||||
srr += r * r
|
||||
srb += r * b
|
||||
end
|
||||
end
|
||||
local g2r, g2b, r2b = 0, 0, 0
|
||||
if sgg > 0 then
|
||||
g2r = clampM(32 * sgr / sgg)
|
||||
local det = sgg * srr - sgr * sgr
|
||||
if det > 0 then
|
||||
g2b = clampM(32 * (sgb * srr - srb * sgr) / det)
|
||||
r2b = clampM(32 * (srb * sgg - sgb * sgr) / det)
|
||||
else
|
||||
g2b = clampM(32 * sgb / sgg)
|
||||
end
|
||||
end
|
||||
if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then
|
||||
if tileCost(x0, y0, x1, y1, g2r, g2b, r2b) >= tileCost(x0, y0, x1, y1, 0, 0, 0) then
|
||||
g2r, g2b, r2b = 0, 0, 0
|
||||
end
|
||||
end
|
||||
writeu32(img, (ty * tw + tx) * 4, ARGB_BLACK + band(r2b, 255) * 65536 + band(g2b, 255) * 256 + band(g2r, 255))
|
||||
if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then
|
||||
for y = y0, y1 - 1 do
|
||||
for x = x0, x1 - 1 do
|
||||
local k = (y * w + x) * 4
|
||||
local argb = readu32(px, k)
|
||||
local g = sint8(band(rshift(argb, 8), 255))
|
||||
local r = band(rshift(argb, 16), 255)
|
||||
local b = band(argb, 255)
|
||||
local nr = band(r - ((g2r * g) // 32), 255)
|
||||
local nb = band(b - ((g2b * g) // 32) - ((r2b * sint8(r)) // 32), 255)
|
||||
writeu32(px, k, band(argb, 0xff00ff00) + nr * 65536 + nb)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return img
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ LZ77
|
||||
-- tokens: L[i] >= 0 is a literal ARGB pixel; L[i] < 0 is a copy of -L[i] pixels with the distance code value D[i]
|
||||
local HASH_BITS = 16
|
||||
|
||||
local function hash2(a: number, b: number): number
|
||||
return rshift(mulHash(bxor(a, (b * 31) % 4294967296)), 32 - HASH_BITS)
|
||||
end
|
||||
|
||||
local function matchLen(px: buffer, i: number, j: number, max: number): number
|
||||
local n = 0
|
||||
while n < max and readu32(px, (i + n) * 4) == readu32(px, (j + n) * 4) do
|
||||
n += 1
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
local function lz77(px: buffer, xs: number, n: number, effort: number): ({ number }, { number })
|
||||
local L: { number } = {}
|
||||
local D: { number } = {}
|
||||
if effort == 0 then
|
||||
for i = 0, n - 1 do
|
||||
L[i + 1] = readu32(px, i * 4)
|
||||
D[i + 1] = 0
|
||||
end
|
||||
return L, D
|
||||
end
|
||||
local head = table.create(lshift(1, HASH_BITS), -1)
|
||||
local prev = table.create(n, -1)
|
||||
local maxIter = if effort <= 2 then 4 elseif effort <= 5 then 16 elseif effort <= 7 then 48 else 128
|
||||
local function insert(i: number)
|
||||
if i + 1 < n then
|
||||
local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1
|
||||
prev[i + 1] = head[h]
|
||||
head[h] = i
|
||||
end
|
||||
end
|
||||
-- best(i) -> length, distance (0, 0 when no useful match)
|
||||
local function best(i: number): (number, number)
|
||||
local max = math.min(MAX_LENGTH, n - i)
|
||||
if max < 2 then
|
||||
return 0, 0
|
||||
end
|
||||
local bl, bd, bc = 0, 0, math.huge
|
||||
local function try(j: number)
|
||||
local d = i - j
|
||||
if d < 1 or d > WINDOW then
|
||||
return
|
||||
end
|
||||
local l = matchLen(px, i, j, max)
|
||||
if l >= 2 then
|
||||
local c = distCode(xs, d)
|
||||
if l > bl or (l == bl and c < bc) then
|
||||
bl, bd, bc = l, d, c
|
||||
end
|
||||
end
|
||||
end
|
||||
if i >= 1 then
|
||||
try(i - 1)
|
||||
end
|
||||
if i >= xs then
|
||||
try(i - xs)
|
||||
end
|
||||
if bl < max then
|
||||
local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1
|
||||
local j = head[h]
|
||||
local it = 0
|
||||
while j >= 0 and it < maxIter and i - j <= WINDOW do
|
||||
if j ~= i - 1 and j ~= i - xs then
|
||||
try(j)
|
||||
if bl >= max then
|
||||
break
|
||||
end
|
||||
end
|
||||
j = prev[j + 1]
|
||||
it += 1
|
||||
end
|
||||
end
|
||||
-- a 2-pixel copy only pays with a short 2-D distance code
|
||||
if bl == 2 and bc > 120 then
|
||||
return 0, 0
|
||||
end
|
||||
return bl, bd
|
||||
end
|
||||
local i = 0
|
||||
local k = 0
|
||||
local lazy = effort >= 4
|
||||
local nl, nd = 0, 0
|
||||
local haveNext = false
|
||||
while i < n do
|
||||
local l, d
|
||||
if haveNext then
|
||||
l, d = nl, nd
|
||||
haveNext = false
|
||||
else
|
||||
l, d = best(i)
|
||||
end
|
||||
if l >= 2 and lazy and l < 64 and i + 1 < n then
|
||||
insert(i)
|
||||
nl, nd = best(i + 1)
|
||||
if nl > l + 1 then
|
||||
-- a literal now, the longer match next
|
||||
k += 1
|
||||
L[k] = readu32(px, i * 4)
|
||||
D[k] = 0
|
||||
i += 1
|
||||
haveNext = true
|
||||
else
|
||||
k += 1
|
||||
L[k] = -l
|
||||
D[k] = distCode(xs, d)
|
||||
for t = i + 1, i + l - 1 do
|
||||
insert(t)
|
||||
end
|
||||
i += l
|
||||
end
|
||||
elseif l >= 2 then
|
||||
k += 1
|
||||
L[k] = -l
|
||||
D[k] = distCode(xs, d)
|
||||
local stop = i + l
|
||||
if effort <= 2 and l > 16 then
|
||||
insert(i)
|
||||
insert(stop - 1)
|
||||
else
|
||||
for t = i, stop - 1 do
|
||||
insert(t)
|
||||
end
|
||||
end
|
||||
i = stop
|
||||
else
|
||||
insert(i)
|
||||
k += 1
|
||||
L[k] = readu32(px, i * 4)
|
||||
D[k] = 0
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
return L, D
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ prefix codes
|
||||
local function entropy(h: { number }): number
|
||||
local total = 0
|
||||
for _, c in h do
|
||||
total += c
|
||||
end
|
||||
if total == 0 then
|
||||
return 0
|
||||
end
|
||||
local bits = 0
|
||||
local lt = log(total)
|
||||
for _, c in h do
|
||||
if c > 0 then
|
||||
bits += c * (lt - log(c))
|
||||
end
|
||||
end
|
||||
return bits / log(2)
|
||||
end
|
||||
|
||||
-- chooseCache(px, L, effort) -> the colour cache bits (0..10) with the smallest estimated literal cost
|
||||
local function chooseCache(px: buffer, L: { number }, effort: number): number
|
||||
if effort < 2 then
|
||||
return 0
|
||||
end
|
||||
local cands = if effort < 5 then { 0, 4, 7, 10 } else { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
|
||||
local caches: { { number } } = {}
|
||||
local hg: { { number } } = {}
|
||||
local hr: { { number } } = {}
|
||||
local hb: { { number } } = {}
|
||||
local ha: { { number } } = {}
|
||||
for c, bits in cands do
|
||||
caches[c] = table.create(lshift(1, bits), -1)
|
||||
hg[c] = table.create(256 + lshift(1, bits), 0)
|
||||
hr[c] = table.create(256, 0)
|
||||
hb[c] = table.create(256, 0)
|
||||
ha[c] = table.create(256, 0)
|
||||
end
|
||||
local pos = 0
|
||||
for _, t in L do
|
||||
if t >= 0 then
|
||||
local hsh = mulHash(t)
|
||||
for c, bits in cands do
|
||||
local cache = caches[c]
|
||||
local key = if bits > 0 then rshift(hsh, 32 - bits) else 0
|
||||
if bits > 0 and cache[key + 1] == t then
|
||||
hg[c][257 + key] += 1
|
||||
else
|
||||
hg[c][band(rshift(t, 8), 255) + 1] += 1
|
||||
hr[c][band(rshift(t, 16), 255) + 1] += 1
|
||||
hb[c][band(t, 255) + 1] += 1
|
||||
ha[c][rshift(t, 24) + 1] += 1
|
||||
end
|
||||
if bits > 0 then
|
||||
cache[key + 1] = t
|
||||
end
|
||||
end
|
||||
pos += 1
|
||||
else
|
||||
for p = pos, pos - t - 1 do
|
||||
local v = readu32(px, p * 4)
|
||||
local hsh = mulHash(v)
|
||||
for c, bits in cands do
|
||||
if bits > 0 then
|
||||
caches[c][rshift(hsh, 32 - bits) + 1] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
pos -= t
|
||||
end
|
||||
end
|
||||
local bestBits, bestCost = 0, math.huge
|
||||
for c, bits in cands do
|
||||
-- + a rough price for the longer green code lengths
|
||||
local cost = entropy(hg[c]) + entropy(hr[c]) + entropy(hb[c]) + entropy(ha[c]) + lshift(1, bits) * 0.5
|
||||
if cost < bestCost then
|
||||
bestBits, bestCost = bits, cost
|
||||
end
|
||||
end
|
||||
return bestBits
|
||||
end
|
||||
|
||||
type Code = { lens: { number }, codes: { number }, single: boolean }
|
||||
|
||||
-- buildCode(freqs, maxLen) -> code lengths, reversed (LSB-first) codes, single (<= 1 used symbol: 0 bits each)
|
||||
local function buildCode(freqs: { number }, maxLen: number): Code
|
||||
local lens = Huffman.lengths(freqs, maxLen)
|
||||
local used = 0
|
||||
for _, l in lens do
|
||||
if l > 0 then
|
||||
used += 1
|
||||
end
|
||||
end
|
||||
local codes = Huffman.codes(lens)
|
||||
for i, l in lens do
|
||||
if l > 0 then
|
||||
codes[i] = Huffman.reverse(codes[i], l)
|
||||
end
|
||||
end
|
||||
return { lens = lens, codes = codes, single = used <= 1 }
|
||||
end
|
||||
|
||||
local function emit(w: W, c: Code, sym: number)
|
||||
if not c.single then
|
||||
put(w, c.codes[sym + 1], c.lens[sym + 1])
|
||||
end
|
||||
end
|
||||
|
||||
local function zeroRun(tok: { number }, ext: { number }, run: number)
|
||||
local r = run
|
||||
while r > 0 do
|
||||
if r >= 11 then
|
||||
local k = math.min(r, 138)
|
||||
table.insert(tok, 18)
|
||||
table.insert(ext, k - 11)
|
||||
r -= k
|
||||
elseif r >= 3 then
|
||||
table.insert(tok, 17)
|
||||
table.insert(ext, r - 3)
|
||||
r = 0
|
||||
else
|
||||
table.insert(tok, 0)
|
||||
table.insert(ext, 0)
|
||||
r -= 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- writeCode(w, code, alphabetSize): the code lengths (a simple code when possible, else run-length coded)
|
||||
local function writeCode(w: W, c: Code, size: number)
|
||||
local syms: { number } = {}
|
||||
for s = 0, size - 1 do
|
||||
if (c.lens[s + 1] or 0) > 0 then
|
||||
table.insert(syms, s)
|
||||
if #syms > 2 then
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
if #syms == 0 then
|
||||
-- an unused alphabet: the simple code of symbol 0
|
||||
put(w, 1, 1)
|
||||
put(w, 0, 1)
|
||||
put(w, 0, 1)
|
||||
put(w, 0, 1)
|
||||
return
|
||||
end
|
||||
if #syms <= 2 and syms[#syms] < 256 then
|
||||
put(w, 1, 1)
|
||||
put(w, #syms - 1, 1)
|
||||
if syms[1] <= 1 then
|
||||
put(w, 0, 1)
|
||||
put(w, syms[1], 1)
|
||||
else
|
||||
put(w, 1, 1)
|
||||
put(w, syms[1], 8)
|
||||
end
|
||||
if #syms == 2 then
|
||||
put(w, syms[2], 8)
|
||||
end
|
||||
return
|
||||
end
|
||||
-- run-length tokens of every length: 0..15 literal, 16 repeats the previous non-zero length (3..6 times; the
|
||||
-- decoder's "previous" starts at 8), 17 zeros (3..10), 18 zeros (11..138)
|
||||
local tok: { number } = {}
|
||||
local ext: { number } = {}
|
||||
local keep = 0 -- tokens up to the last non-zero length
|
||||
local prev = 8
|
||||
local s = 1
|
||||
while s <= size do
|
||||
local l = c.lens[s] or 0
|
||||
local run = 1
|
||||
while s + run <= size and (c.lens[s + run] or 0) == l do
|
||||
run += 1
|
||||
end
|
||||
if l == 0 then
|
||||
zeroRun(tok, ext, run)
|
||||
else
|
||||
local r = run
|
||||
if l ~= prev then
|
||||
table.insert(tok, l)
|
||||
table.insert(ext, 0)
|
||||
r -= 1
|
||||
prev = l
|
||||
end
|
||||
while r > 0 do
|
||||
if r >= 3 then
|
||||
local k = math.min(r, 6)
|
||||
table.insert(tok, 16)
|
||||
table.insert(ext, k - 3)
|
||||
r -= k
|
||||
else
|
||||
table.insert(tok, l)
|
||||
table.insert(ext, 0)
|
||||
r -= 1
|
||||
end
|
||||
end
|
||||
keep = #tok
|
||||
end
|
||||
s += run
|
||||
end
|
||||
local ntok = #tok
|
||||
local trim = keep < ntok and keep >= 2
|
||||
if trim then
|
||||
ntok = keep
|
||||
end
|
||||
local hist = table.create(19, 0)
|
||||
for i = 1, ntok do
|
||||
hist[tok[i] + 1] += 1
|
||||
end
|
||||
local cl = buildCode(hist, 7)
|
||||
local nc = 19
|
||||
while nc > 4 and (cl.lens[CODE_LENGTH_ORDER[nc] + 1] or 0) == 0 do
|
||||
nc -= 1
|
||||
end
|
||||
put(w, 0, 1)
|
||||
put(w, nc - 4, 4)
|
||||
for i = 1, nc do
|
||||
put(w, cl.lens[CODE_LENGTH_ORDER[i] + 1] or 0, 3)
|
||||
end
|
||||
if trim then
|
||||
put(w, 1, 1)
|
||||
local v = ntok - 2
|
||||
local nbits = 0
|
||||
while lshift(1, nbits) <= v do
|
||||
nbits += 1
|
||||
end
|
||||
local pairs = math.max(1, (nbits + 1) // 2)
|
||||
put(w, pairs - 1, 3)
|
||||
put(w, v, pairs * 2)
|
||||
else
|
||||
put(w, 0, 1)
|
||||
end
|
||||
for i = 1, ntok do
|
||||
local t = tok[i]
|
||||
emit(w, cl, t)
|
||||
if t == 16 then
|
||||
put(w, ext[i], 2)
|
||||
elseif t == 17 then
|
||||
put(w, ext[i], 3)
|
||||
elseif t == 18 then
|
||||
put(w, ext[i], 7)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ image data
|
||||
-- writeImage(w, px, xs, n, effort, level0): colour cache bits, [the meta-code bit], the five codes, the pixels
|
||||
local function writeImage(w: W, px: buffer, xs: number, n: number, effort: number, level0: boolean)
|
||||
local L, D = lz77(px, xs, n, effort)
|
||||
local cacheBits = if level0 then chooseCache(px, L, effort) else 0
|
||||
if cacheBits > 0 then
|
||||
put(w, 1, 1)
|
||||
put(w, cacheBits, 4)
|
||||
else
|
||||
put(w, 0, 1)
|
||||
end
|
||||
if level0 then
|
||||
put(w, 0, 1) -- no meta prefix codes
|
||||
end
|
||||
local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0
|
||||
local cshift = 32 - cacheBits
|
||||
local hg = table.create(NUM_LITERAL + NUM_LENGTH + cacheSize, 0)
|
||||
local hr = table.create(256, 0)
|
||||
local hb = table.create(256, 0)
|
||||
local ha = table.create(256, 0)
|
||||
local hd = table.create(NUM_DISTANCE, 0)
|
||||
-- token kinds after the cache: 0 literal, 1 cache hit, 2 copy
|
||||
local cache: { number }? = if cacheBits > 0 then table.create(cacheSize, -1) else nil
|
||||
local K = table.create(#L, 0)
|
||||
local pos = 0
|
||||
for i, t in L do
|
||||
if t >= 0 then
|
||||
local hit = false
|
||||
if cache then
|
||||
local key = rshift(mulHash(t), cshift)
|
||||
if cache[key + 1] == t then
|
||||
hit = true
|
||||
hg[NUM_LITERAL + NUM_LENGTH + key + 1] += 1
|
||||
end
|
||||
cache[key + 1] = t
|
||||
end
|
||||
if hit then
|
||||
K[i] = 1
|
||||
else
|
||||
hg[band(rshift(t, 8), 255) + 1] += 1
|
||||
hr[band(rshift(t, 16), 255) + 1] += 1
|
||||
hb[band(t, 255) + 1] += 1
|
||||
ha[rshift(t, 24) + 1] += 1
|
||||
end
|
||||
pos += 1
|
||||
else
|
||||
K[i] = 2
|
||||
hg[NUM_LITERAL + prefix(-t) + 1] += 1
|
||||
hd[prefix(D[i]) + 1] += 1
|
||||
if cache then
|
||||
for p = pos, pos - t - 1 do
|
||||
local v = readu32(px, p * 4)
|
||||
cache[rshift(mulHash(v), cshift) + 1] = v
|
||||
end
|
||||
end
|
||||
pos -= t
|
||||
end
|
||||
end
|
||||
local cg, cr, cb, ca, cd = buildCode(hg, 15), buildCode(hr, 15), buildCode(hb, 15), buildCode(ha, 15), buildCode(hd, 15)
|
||||
writeCode(w, cg, NUM_LITERAL + NUM_LENGTH + cacheSize)
|
||||
writeCode(w, cr, 256)
|
||||
writeCode(w, cb, 256)
|
||||
writeCode(w, ca, 256)
|
||||
writeCode(w, cd, NUM_DISTANCE)
|
||||
for i, t in L do
|
||||
local k = K[i]
|
||||
if k == 0 then
|
||||
emit(w, cg, band(rshift(t, 8), 255))
|
||||
emit(w, cr, band(rshift(t, 16), 255))
|
||||
emit(w, cb, band(t, 255))
|
||||
emit(w, ca, rshift(t, 24))
|
||||
elseif k == 1 then
|
||||
emit(w, cg, NUM_LITERAL + NUM_LENGTH + rshift(mulHash(t), cshift))
|
||||
else
|
||||
local lc, leb, lev = prefix(-t)
|
||||
emit(w, cg, NUM_LITERAL + lc)
|
||||
if leb > 0 then
|
||||
put(w, lev, leb)
|
||||
end
|
||||
local dc, deb, dev = prefix(D[i])
|
||||
emit(w, cd, dc)
|
||||
if deb > 0 then
|
||||
put(w, dev, deb)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- toArgb(rgba, n, exact) -> ARGB pixels, any alpha < 255. Without exact, fully transparent pixels become 0.
|
||||
local function toArgb(rgba: buffer, n: number, exact: boolean): (buffer, boolean)
|
||||
local px = bcreate(n * 4)
|
||||
local alpha = false
|
||||
for i = 0, n - 1 do
|
||||
local v = readu32(rgba, i * 4)
|
||||
local a = rshift(v, 24)
|
||||
if a ~= 255 then
|
||||
alpha = true
|
||||
end
|
||||
if a == 0 and not exact then
|
||||
v = 0
|
||||
end
|
||||
-- bytes R G B A (0xAABBGGRR) -> 0xAARRGGBB
|
||||
writeu32(px, i * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536)
|
||||
end
|
||||
return px, alpha
|
||||
end
|
||||
|
||||
-- palette(px, n) -> the sorted colours when there are at most 256, else nil
|
||||
local function palette(px: buffer, n: number): { number }?
|
||||
local seen: { [number]: boolean } = {}
|
||||
local list: { number } = {}
|
||||
for i = 0, n - 1 do
|
||||
local v = readu32(px, i * 4)
|
||||
if not seen[v] then
|
||||
if #list == 256 then
|
||||
return nil
|
||||
end
|
||||
seen[v] = true
|
||||
table.insert(list, v)
|
||||
end
|
||||
end
|
||||
table.sort(list)
|
||||
return list
|
||||
end
|
||||
|
||||
type Config = { palette: { number }?, pbits: number, cc: boolean, ccbits: number }
|
||||
|
||||
-- stream(px, w, h, effort, cfg, bw): the transforms and the main image of one configuration (px is consumed)
|
||||
local function stream(px: buffer, w: number, h: number, effort: number, cfg: Config, bw: W)
|
||||
local n = w * h
|
||||
local xs = w
|
||||
local sub = math.min(effort, 3)
|
||||
local pal = cfg.palette
|
||||
if pal then
|
||||
local num = #pal
|
||||
local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3
|
||||
put(bw, 1, 1)
|
||||
put(bw, 3, 2)
|
||||
put(bw, num - 1, 8)
|
||||
local pimg = bcreate(num * 4)
|
||||
local prevc = 0
|
||||
local index: { [number]: number } = {}
|
||||
for i, c in pal do
|
||||
writeu32(pimg, (i - 1) * 4, subPixels(c, prevc))
|
||||
prevc = c
|
||||
index[c] = i - 1
|
||||
end
|
||||
writeImage(bw, pimg, num, num, sub, false)
|
||||
xs = subSample(w, bits)
|
||||
local packed = bcreate(xs * h * 4)
|
||||
local bpp = rshift(8, bits)
|
||||
local cmask = lshift(1, bits) - 1
|
||||
for y = 0, h - 1 do
|
||||
local acc = 0
|
||||
local o = y * xs
|
||||
for x = 0, w - 1 do
|
||||
local sh = band(x, cmask)
|
||||
acc += index[readu32(px, (y * w + x) * 4)] * 2 ^ (bpp * sh)
|
||||
if sh == cmask or x == w - 1 then
|
||||
writeu32(packed, (o + rshift(x, bits)) * 4, ARGB_BLACK + acc * 256)
|
||||
acc = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
px = packed
|
||||
elseif cfg.pbits > 0 then
|
||||
-- subtract green
|
||||
put(bw, 1, 1)
|
||||
put(bw, 2, 2)
|
||||
for i = 0, n - 1 do
|
||||
local v = readu32(px, i * 4)
|
||||
local g = band(rshift(v, 8), 255)
|
||||
writeu32(px, i * 4, band(v, 0xff00ff00) + band(band(v, 0x00ff00ff) + 0x01000100 - g * 65537, 0x00ff00ff))
|
||||
end
|
||||
-- predictor
|
||||
local pbits = cfg.pbits
|
||||
local modes = predictorTransform(px, w, h, pbits, effort)
|
||||
put(bw, 1, 1)
|
||||
put(bw, 0, 2)
|
||||
put(bw, pbits - 2, 3)
|
||||
writeImage(bw, modes, subSample(w, pbits), subSample(w, pbits) * subSample(h, pbits), sub, false)
|
||||
-- cross colour
|
||||
if cfg.cc then
|
||||
local cbits = cfg.ccbits
|
||||
local cimg = crossColorTransform(px, w, h, cbits)
|
||||
put(bw, 1, 1)
|
||||
put(bw, 1, 2)
|
||||
put(bw, cbits - 2, 3)
|
||||
writeImage(bw, cimg, subSample(w, cbits), subSample(w, cbits) * subSample(h, cbits), sub, false)
|
||||
end
|
||||
end
|
||||
put(bw, 0, 1) -- no more transforms
|
||||
writeImage(bw, px, xs, xs * h, effort, true)
|
||||
end
|
||||
|
||||
-- encode(rgba, w, h, effort, exact, alphaHint?, headerless) -> the VP8L bitstream (headerless: the image stream only,
|
||||
-- as an ALPH chunk stores it). Efforts 6+ try several transform configurations and keep the smallest.
|
||||
function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact: boolean, alphaHint: boolean?, headerless: boolean): buffer
|
||||
local n = w * h
|
||||
local px, usesAlpha = toArgb(rgba, n, exact)
|
||||
local pal = if effort > 0 then palette(px, n) else nil
|
||||
local configs: { Config } = {}
|
||||
if effort == 0 then
|
||||
table.insert(configs, { palette = nil, pbits = 0, cc = false, ccbits = 0 })
|
||||
else
|
||||
local pbits = if effort >= 5 then 4 else 5
|
||||
local plain: Config = { palette = nil, pbits = pbits, cc = effort >= 3, ccbits = if effort >= 6 then 4 else 5 }
|
||||
if pal then
|
||||
table.insert(configs, { palette = pal, pbits = 0, cc = false, ccbits = 0 })
|
||||
if effort >= 6 then
|
||||
table.insert(configs, plain)
|
||||
end
|
||||
else
|
||||
table.insert(configs, plain)
|
||||
end
|
||||
if effort >= 9 then
|
||||
table.insert(configs, { palette = nil, pbits = 3, cc = true, ccbits = 3 })
|
||||
table.insert(configs, { palette = nil, pbits = 5, cc = false, ccbits = 0 })
|
||||
end
|
||||
end
|
||||
local best: buffer? = nil
|
||||
for k, cfg in configs do
|
||||
local bw = newWriter(n + 256)
|
||||
if not headerless then
|
||||
put(bw, 0x2f, 8)
|
||||
put(bw, w - 1, 14)
|
||||
put(bw, h - 1, 14)
|
||||
local hint = if alphaHint == nil then usesAlpha else alphaHint
|
||||
put(bw, if hint then 1 else 0, 1)
|
||||
put(bw, 0, 3)
|
||||
end
|
||||
local work = px
|
||||
if k < #configs then
|
||||
work = bcreate(n * 4)
|
||||
bcopy(work, 0, px, 0, n * 4)
|
||||
end
|
||||
stream(work, w, h, effort, cfg, bw)
|
||||
local out = finish(bw)
|
||||
if not best or blen(out) < blen(best) then
|
||||
best = out
|
||||
end
|
||||
end
|
||||
return best :: buffer
|
||||
end
|
||||
|
||||
return Encode
|
||||
@@ -0,0 +1,120 @@
|
||||
--!strict
|
||||
-- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
|
||||
-- image/webp uses it for VP8L frames and for compressed ALPH planes; other containers may carry it too.
|
||||
-- Decoder: a port of libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it. Encoder: new
|
||||
-- (subtract green, predictor and cross-colour transforms with per-tile mode search, colour indexing with pixel
|
||||
-- bundling for <= 256 colours, LZ77 with hash chains and the 2-D distance codes, a colour cache chosen by entropy,
|
||||
-- one prefix code group per image or meta codes for big images).
|
||||
--
|
||||
-- local Vp8L = require("@formats/codecs/image/Vp8L")
|
||||
-- local rgba, w, h, alpha = Vp8L.decode(buf, off, len) -- a VP8L bitstream (0x2f signature) -> rgba8
|
||||
-- local a8 = Vp8L.decodeAlpha(buf, off, len, w, h) -- a headerless stream's green channel (ALPH)
|
||||
-- local bits = Vp8L.encode(rgba, w, h, { effort = 4 }) -- rgba8 -> a VP8L bitstream
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / LIMIT / ARG).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Decode = require("@formats/codecs/image/Vp8L/Decode")
|
||||
local Encode = require("@formats/codecs/image/Vp8L/Encode")
|
||||
|
||||
local Vp8L = {}
|
||||
|
||||
local DEFAULT_MAX_PIXELS = 2 ^ 28
|
||||
|
||||
local function fail(msg: string?, offset: number?): Err.Err
|
||||
local m = msg or "bad data"
|
||||
if string.sub(m, 1, 11) == "truncated: " then
|
||||
return Err.new(Err.TRUNCATED, string.sub(m, 12), offset)
|
||||
elseif string.sub(m, 1, 7) == "limit: " then
|
||||
return Err.new(Err.LIMIT, string.sub(m, 8), offset)
|
||||
end
|
||||
return Err.new(Err.CORRUPT, m, offset)
|
||||
end
|
||||
Vp8L.fail = fail
|
||||
|
||||
local function range(buf: buffer, off: number?, len: number?): (number, number)
|
||||
local n = buffer.len(buf)
|
||||
local o = math.clamp(off or 0, 0, n)
|
||||
return o, math.clamp(len or (n - o), 0, n - o)
|
||||
end
|
||||
|
||||
-- info(buf, off?, len?) -> { width, height, alpha } | nil, Err: the 5-byte header
|
||||
function Vp8L.info(buf: buffer, off: number?, len: number?): ({ width: number, height: number, alpha: boolean }?, Err.Err?)
|
||||
local o, l = range(buf, off, len)
|
||||
local w, h, alpha, err = Decode.header(buf, o, l)
|
||||
if not w then
|
||||
return nil, fail(err, o)
|
||||
end
|
||||
return { width = w, height = h, alpha = alpha }, nil
|
||||
end
|
||||
|
||||
-- decodeArgb(buf, off?, len?, maxPixels?) -> ARGB u32 pixels (0xAARRGGBB), width, height, alphaHint | nil, Err
|
||||
function Vp8L.decodeArgb(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?)
|
||||
local o, l = range(buf, off, len)
|
||||
local px, w, h, alpha, err = Decode.argb(buf, o, l, maxPixels or DEFAULT_MAX_PIXELS)
|
||||
if not px then
|
||||
return nil, fail(err, o)
|
||||
end
|
||||
return px, w, h, alpha
|
||||
end
|
||||
|
||||
-- decode(buf, off?, len?, maxPixels?) -> rgba8 pixels, width, height, alphaHint | nil, Err
|
||||
function Vp8L.decode(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?)
|
||||
local px, w, h, alpha = Vp8L.decodeArgb(buf, off, len, maxPixels)
|
||||
if not px then
|
||||
return nil, w
|
||||
end
|
||||
return Decode.toRgba(px, w * (h :: number)), w, h, alpha
|
||||
end
|
||||
|
||||
-- decodeAlpha(buf, off, len, width, height) -> width * height bytes (the green channel) | nil, Err
|
||||
function Vp8L.decodeAlpha(buf: buffer, off: number?, len: number?, width: number, height: number): (buffer?, Err.Err?)
|
||||
local o, l = range(buf, off, len)
|
||||
local px, err = Decode.stream(buf, o, l, width, height)
|
||||
if not px then
|
||||
return nil, fail(err, o)
|
||||
end
|
||||
return Decode.green(px, width * height), nil
|
||||
end
|
||||
|
||||
-- toRgba(argb, n) -> rgba8 bytes of n ARGB pixels
|
||||
Vp8L.toRgba = Decode.toRgba
|
||||
|
||||
export type EncodeOptions = {
|
||||
effort: number?, -- 0..9, default 5: more = smaller and slower (0: no transforms, no LZ77 search)
|
||||
exact: boolean?, -- default false: keep the RGB of fully transparent pixels (otherwise they may be zeroed)
|
||||
alphaHint: boolean?, -- the header's "alpha is used" bit; default: any alpha < 255
|
||||
}
|
||||
|
||||
-- encode(rgba, width, height, opts?) -> a VP8L bitstream (signature + header + image stream) | nil, Err
|
||||
function Vp8L.encode(rgba: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(rgba) ~= "buffer" or type(width) ~= "number" or type(height) ~= "number" then
|
||||
return nil, Err.new(Err.ARG, "encode: needs rgba8 pixels, width, height")
|
||||
end
|
||||
if width < 1 or height < 1 or width > 16384 or height > 16384 or width % 1 ~= 0 or height % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "encode: size must be 1..16384")
|
||||
end
|
||||
if buffer.len(rgba) < width * height * 4 then
|
||||
return nil, Err.new(Err.ARG, "encode: pixel buffer too small")
|
||||
end
|
||||
local o: EncodeOptions = opts or {} :: EncodeOptions
|
||||
local effort = o.effort or 5
|
||||
if type(effort) ~= "number" or effort < 0 or effort > 9 then
|
||||
return nil, Err.new(Err.ARG, "encode: effort must be 0..9")
|
||||
end
|
||||
return Encode.encode(rgba, width, height, effort, o.exact == true, o.alphaHint, false), nil
|
||||
end
|
||||
|
||||
-- encodeAlpha(a8, width, height, opts?) -> a headerless stream of the plane in green (an ALPH payload)
|
||||
function Vp8L.encodeAlpha(a8: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(a8) ~= "buffer" or buffer.len(a8) < width * height then
|
||||
return nil, Err.new(Err.ARG, "encodeAlpha: plane too small")
|
||||
end
|
||||
local rgba = buffer.create(width * height * 4)
|
||||
for i = 0, width * height - 1 do
|
||||
buffer.writeu32(rgba, i * 4, 0xff000000 + buffer.readu8(a8, i) * 256)
|
||||
end
|
||||
local effort = opts and opts.effort or 5
|
||||
return Encode.encode(rgba, width, height, effort, true, false, true), nil
|
||||
end
|
||||
|
||||
return Vp8L
|
||||
Reference in new issue
Block a user