ws-webp: image/webp (VP8 / VP8L / ALPH / VP8X / animation / metadata decode, lossless + animated encode), codecs/Vp8L encoder, fixtures vs dwebp / Pillow / libvpx, tests

This commit is contained in:
4DBug committed 2026-10-31 08:55:49 -05:00
1 parent 5bad752d91
commit 7c3d4b75ec
10 files changed
+2449 -3

No files matched your search

+12
View File
@@ -26,6 +26,18 @@ local list: { Entry } = {
return require("@formats/image/png")
end,
},
{
name = "webp",
category = "image",
path = "image/webp",
extensions = { "webp" },
mime = { "image/webp" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Vp8", "codecs/Vp8L" },
caps = { decode = true, encode = true, animation = true, alpha = true, lossy = true, lossless = true, depths = { 8 } },
load = function()
return require("@formats/image/webp")
end,
},
}
return list
+931 -3
View File
@@ -1,8 +1,936 @@
--!strict
--!native
-- codecs/Vp8L/Encode: stub
--!optimize 2
-- codecs/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 (core/Huffman) and run-length coded.
-- Never throws (the init module validates the arguments).
local Huffman = require("@formats/core/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 = {}
function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact: boolean, alphaHint: boolean?, headerless: boolean): buffer
return buffer.create(0)
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/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
-- encode(rgba, w, h, effort, exact, alphaHint?, headerless) -> the VP8L bitstream (headerless: the image stream only,
-- as an ALPH chunk stores it)
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 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 xs = w
local sub = math.min(effort, 3)
local pal = if effort > 0 then palette(px, n) else nil
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 effort > 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 = if effort >= 5 then 4 else 5
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 effort >= 3 then
local cbits = if effort >= 6 then 4 else 5
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)
return finish(bw)
end
return Encode
+75
View File
@@ -0,0 +1,75 @@
--!strict
--!native
-- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2): header byte (compression, filter, pre-processing),
-- raw or VP8L-compressed alpha (the green channel of a headerless VP8L stream), and the horizontal / vertical /
-- gradient unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Never throws.
local Vp8L = require("@formats/codecs/Vp8L")
local readu8, writeu8 = buffer.readu8, buffer.writeu8
local Alpha = {}
local function unfilter(a: buffer, w: number, h: number, filter: number)
if filter == 0 then
return
end
for y = 0, h - 1 do
local row = y * w
local prev = row - w
if y == 0 or filter == 1 then
-- horizontal (also the first row of the other filters): the left pixel, the first one from above
local pred = if y == 0 then 0 else readu8(a, prev)
for i = row, row + w - 1 do
pred = (pred + readu8(a, i)) % 256
writeu8(a, i, pred)
end
elseif filter == 2 then
for i = 0, w - 1 do
writeu8(a, row + i, (readu8(a, prev + i) + readu8(a, row + i)) % 256)
end
else
local top = readu8(a, prev)
local topLeft, left = top, top
for i = 0, w - 1 do
top = readu8(a, prev + i)
local g = left + top - topLeft
g = if g < 0 then 0 elseif g > 255 then 255 else g
left = (readu8(a, row + i) + g) % 256
topLeft = top
writeu8(a, row + i, left)
end
end
end
end
-- decode(buf, off, len, w, h) -> w * h alpha bytes, header info | nil, message
function Alpha.decode(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, any)
if len <= 1 then
return nil, "truncated: ALPH chunk"
end
local hb = readu8(buf, off)
local method = hb % 4
local filter = (hb // 4) % 4
local pre = (hb // 16) % 4
if method > 1 or pre > 1 or hb >= 64 then
return nil, "bad ALPH header"
end
local a: buffer
if method == 0 then
if len - 1 < w * h then
return nil, "truncated: raw alpha"
end
a = buffer.create(w * h)
buffer.copy(a, 0, buf, off + 1, w * h)
else
local d, err = Vp8L.decodeAlpha(buf, off + 1, len - 1, w, h)
if not d then
return nil, if err.code == "TRUNCATED" then "truncated: alpha " .. err.message else "alpha: " .. err.message
end
a = d
end
unfilter(a, w, h, filter)
return a, { method = method, filter = filter, preprocessing = pre }
end
return Alpha
+162
View File
@@ -0,0 +1,162 @@
--!strict
--!native
-- image/webp/Anim: animation compositing. coalesce() reproduces libwebp's WebPAnimDecoder (src/demux/anim_decode.c,
-- BSD-3-Clause, licenses/libwebp-LICENSE.txt) exactly: key frame detection, transparent canvas (the background colour
-- is ignored, as the spec recommends and libwebp does), non-premultiplied "over" blending of the pixels with alpha
-- < 255, dispose to background. composite() is the generic Types.Frame model (also dispose "previous") used by the
-- encoder to flatten frames WebP cannot store as they are. Pixels are rgba8; never throws.
local band, rshift = bit32.band, bit32.rshift
local readu32, writeu32 = buffer.readu32, buffer.writeu32
local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill
local Anim = {}
export type Frame = {
rgba: buffer, -- w * h rgba8
x: number,
y: number,
w: number,
h: number,
blend: boolean, -- alpha-blend over the canvas (false: overwrite)
disposeBg: boolean, -- after display, clear the rectangle to transparent
disposePrev: boolean?, -- after display, restore the canvas as it was before the frame (composite() only)
hasAlpha: boolean,
}
-- blend(src, dst) -> src over dst, both non-premultiplied 0xAABBGGRR (libwebp BlendPixelNonPremult)
local function blendPixel(src: number, dst: number): number
local sa = rshift(src, 24)
if sa == 0 then
return dst
end
local da = rshift(dst, 24)
local dfa = rshift(da * (256 - sa), 8)
local ba = sa + dfa
local scale = 16777216 // ba
local r = ((band(src, 255) * sa + band(dst, 255) * dfa) * scale) // 16777216
local g = ((band(rshift(src, 8), 255) * sa + band(rshift(dst, 8), 255) * dfa) * scale) // 16777216
local b = ((band(rshift(src, 16), 255) * sa + band(rshift(dst, 16), 255) * dfa) * scale) // 16777216
return r + g * 256 + b * 65536 + ba * 16777216
end
Anim.blendPixel = blendPixel
-- blendRow(cur, prev, offset, n): pixels of cur with alpha < 255 blended over prev (pixel offsets)
local function blendRow(cur: buffer, prev: buffer, o: number, n: number)
for i = o, o + n - 1 do
local s = readu32(cur, i * 4)
if s < 0xff000000 then
writeu32(cur, i * 4, blendPixel(s, readu32(prev, i * 4)))
end
end
end
-- draw(canvas, cw, f): copy the frame rectangle into the canvas
local function draw(canvas: buffer, cw: number, f: Frame)
for j = 0, f.h - 1 do
bcopy(canvas, ((f.y + j) * cw + f.x) * 4, f.rgba, j * f.w * 4, f.w * 4)
end
end
local function clearRect(canvas: buffer, cw: number, x: number, y: number, w: number, h: number)
for j = 0, h - 1 do
bfill(canvas, ((y + j) * cw + x) * 4, 0, w * 4)
end
end
-- coalesce(cw, ch, frames) -> one full canvas (rgba8) per frame, as WebPAnimDecoder returns them
function Anim.coalesce(cw: number, ch: number, frames: { Frame }): { buffer }
local size = cw * ch * 4
local out: { buffer } = {}
local disposed = bcreate(size)
local prev: Frame? = nil
local prevKey = false
for n, f in frames do
local full = f.w == cw and f.h == ch
local key
if n == 1 then
key = true
elseif (not f.hasAlpha or not f.blend) and full then
key = true
else
local p = prev :: Frame
key = p.disposeBg and ((p.w == cw and p.h == ch) or prevKey)
end
local cur = bcreate(size)
if not key then
bcopy(cur, 0, disposed, 0, size)
end
draw(cur, cw, f)
if n > 1 and f.blend and not key then
local p = prev :: Frame
if not p.disposeBg then
for j = 0, f.h - 1 do
blendRow(cur, disposed, (f.y + j) * cw + f.x, f.w)
end
else
-- the previous rectangle was cleared: blending with transparent there is a no-op for libwebp
local pmx, pmy = p.x + p.w, p.y + p.h
local smx = f.x + f.w
for j = 0, f.h - 1 do
local cy = f.y + j
if cy < p.y or cy >= pmy or f.x >= pmx or smx <= p.x then
blendRow(cur, disposed, cy * cw + f.x, f.w)
else
if f.x < p.x then
blendRow(cur, disposed, cy * cw + f.x, p.x - f.x)
end
if smx > pmx then
blendRow(cur, disposed, cy * cw + pmx, smx - pmx)
end
end
end
end
end
table.insert(out, cur)
prev = f
prevKey = key
bcopy(disposed, 0, cur, 0, size)
if f.disposeBg then
clearRect(disposed, cw, f.x, f.y, f.w, f.h)
end
end
return out
end
-- composite(cw, ch, frames) -> one full canvas per frame in the generic model: start transparent, draw (blend or
-- overwrite; "over" a fully transparent pixel copies it), show, then dispose (background: clear the rectangle;
-- previous: restore)
function Anim.composite(cw: number, ch: number, frames: { Frame }): { buffer }
local size = cw * ch * 4
local canvas = bcreate(size)
local out: { buffer } = {}
for _, f in frames do
local saved: buffer? = nil
if f.disposePrev then
saved = bcreate(size)
bcopy(saved :: buffer, 0, canvas, 0, size)
end
if f.blend then
for j = 0, f.h - 1 do
local co = (f.y + j) * cw + f.x
for i = 0, f.w - 1 do
local s = readu32(f.rgba, (j * f.w + i) * 4)
local d = readu32(canvas, (co + i) * 4)
writeu32(canvas, (co + i) * 4, if s >= 0xff000000 or d < 0x01000000 then s else blendPixel(s, d))
end
end
else
draw(canvas, cw, f)
end
local shown = bcreate(size)
bcopy(shown, 0, canvas, 0, size)
table.insert(out, shown)
if saved then
canvas = saved
elseif f.disposeBg then
clearRect(canvas, cw, f.x, f.y, f.w, f.h)
end
end
return out
end
return Anim
+59
View File
@@ -0,0 +1,59 @@
--!strict
-- image/webp/Riff: a small private RIFF chunk reader for WebP files (RFC 9649 section 2.4: "RIFF" size "WEBP", then
-- chunks of FourCC + u32le size + payload padded to even). TODO: switch to containers/Riff when ws-absorb lands it.
-- Never throws.
local Riff = {}
export type Chunk = { id: string, off: number, size: number } -- off: absolute offset of the payload
-- chunks(buf, base, limit) -> the chunks of the RIFF "WEBP" form inside [base, limit) | nil, message
-- (messages start with "truncated: " when the data ends early). Bytes after the RIFF size are ignored, as libwebp does.
function Riff.chunks(buf: buffer, base: number, limit: number): ({ Chunk }?, string?)
if limit - base < 12 then
return nil, "truncated: RIFF header"
end
if buffer.readstring(buf, base, 4) ~= "RIFF" or buffer.readstring(buf, base + 8, 4) ~= "WEBP" then
return nil, "not a RIFF WEBP file"
end
local riffSize = buffer.readu32(buf, base + 4)
if riffSize < 12 then
return nil, "RIFF size too small"
end
local stop = base + 8 + riffSize
if stop > limit then
return nil, "truncated: RIFF size runs past the end of the data"
end
return Riff.list(buf, base + 12, stop)
end
-- list(buf, p, stop) -> the chunks in [p, stop) | nil, message
function Riff.list(buf: buffer, p: number, stop: number): ({ Chunk }?, string?)
local out: { Chunk } = {}
while p < stop do
if p + 8 > stop then
return nil, "truncated: chunk header"
end
local id = buffer.readstring(buf, p, 4)
local size = buffer.readu32(buf, p + 4)
if p + 8 + size > stop then
return nil, "truncated: chunk '" .. id .. "' runs past the end"
end
table.insert(out, { id = id, off = p + 8, size = size })
p += 8 + size + size % 2
end
return out, nil
end
-- chunk(w, id, payload, off?, len?): append one chunk (header, payload, pad byte) to a core/Bytes Writer
function Riff.write(w: any, id: string, payload: buffer, off: number?, len: number?)
local o = off or 0
local n = len or (buffer.len(payload) - o)
w:string(id)
w:u32le(n)
w:bytes(payload, o, n)
if n % 2 == 1 then
w:u8(0)
end
end
return Riff
+568
View File
@@ -0,0 +1,568 @@
--!strict
-- image/webp: WebP (RFC 9649; Google's "WebP Container Specification"). New code: the bitstreams are ports of libwebp 1.6
-- (codecs/Vp8, codecs/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the container and the compositing follow
-- libwebp's demux / WebPAnimDecoder.
-- Supports: decode of lossy (VP8 key frames: bit-exact with dwebp, fancy or point chroma upsampling, or the raw
-- yuv420p planes with opts.native), lossless (VP8L, bit-exact), alpha (ALPH raw or lossless, every filter), the
-- extended format (VP8X), animation (ANIM / ANMF: frames as their own rectangles plus the composited first frame, or
-- every frame composited exactly as WebPAnimDecoder with opts.coalesce), ICC / EXIF / XMP into meta.icc / meta.exif
-- / meta.xmp; encode of rgba8 images and animations as lossless VP8L (VP8X / ANIM / ANMF for animations and
-- metadata).
-- Not supported: lossy encoding (UNSUPPORTED), the VP8 horizontal / vertical scale fields (ignored, as dwebp does),
-- alpha dithering / premultiplied output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Vp8 = require("@formats/codecs/Vp8")
local Vp8L = require("@formats/codecs/Vp8L")
local Riff = require("@formats/image/webp/Riff")
local Alpha = require("@formats/image/webp/Alpha")
local Anim = require("@formats/image/webp/Anim")
-- ------------------------------------------------------------------------------------------------ contract
local Webp = {
name = "webp",
category = "image",
extensions = { "webp" },
mime = { "image/webp" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Vp8", "codecs/Vp8L" },
caps = { decode = true, encode = true, animation = true, alpha = true, lossy = true, lossless = true, depths = { 8 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26)
native: boolean?, -- a still lossy image without alpha decodes to its yuv420p planes (default false: rgba8)
upsampling: ("fancy" | "nearest")?, -- lossy chroma upsampling, default "fancy" (libwebp's default; "nearest" =
-- dwebp -nofancy)
coalesce: boolean?, -- animations: every frame is the full composited canvas (x = y = 0, dispose "none",
-- blend "source"), exactly what WebPAnimDecoder returns (default false: each frame's own rectangle)
frames: boolean?, -- animations: decode every frame (default true; false: only the first canvas)
}
export type EncodeOptions = {
lossless: boolean?, -- must be true or nil (lossy encoding is not supported)
effort: number?, -- 0..9, default 5: VP8L encoder effort (more = smaller, slower)
exact: boolean?, -- keep the RGB of fully transparent pixels (default false: they may be changed)
loops: number?, -- animations: loop count (default img.loops; 0 = forever)
background: { number }?, -- animations: ANIM background colour { r, g, b, a } (default meta.background or 0)
}
-- ------------------------------------------------------------------------------------------------ constants
local DEFAULT_MAX_PIXELS = 2 ^ 26
local FLAG_ANIM, FLAG_XMP, FLAG_EXIF, FLAG_ALPHA, FLAG_ICC = 0x02, 0x04, 0x08, 0x10, 0x20
local readu8 = buffer.readu8
local function u24(buf: buffer, p: number): number
return readu8(buf, p) + readu8(buf, p + 1) * 256 + readu8(buf, p + 2) * 65536
end
local function corrupt(msg: string, offset: number?): (nil, Err.Err)
return nil, Err.new(Err.CORRUPT, msg, offset)
end
-- an Err from a submodule message ("truncated: ...", "limit: ...", "unsupported: ...", else CORRUPT)
local function fromMessage(msg: any, offset: number?): Err.Err
if Err.is(msg) then
return msg
end
local m = tostring(msg)
for _, k in { { "truncated: ", Err.TRUNCATED }, { "limit: ", Err.LIMIT }, { "unsupported: ", Err.UNSUPPORTED } } do
if string.sub(m, 1, #k[1]) == k[1] then
return Err.new(k[2], string.sub(m, #k[1] + 1), offset)
end
end
return Err.new(Err.CORRUPT, m, offset)
end
-- ------------------------------------------------------------------------------------------------ sniff
function Webp.sniff(r: Bytes.Reader): number
if r:peek(4) == "RIFF" and r:peek(4, 8) == "WEBP" then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Bitstream = { rgba: buffer?, yuv: Types.Image?, w: number, h: number, hasAlpha: boolean, source: { [string]: any } }
-- the image chunks of a still image or an ANMF frame: the first ALPH (if any) and the first VP8 / VP8L chunk
local function findImage(chunks: { Riff.Chunk }, from: number): (Riff.Chunk?, Riff.Chunk?)
local alph: Riff.Chunk? = nil
for i = from, #chunks do
local c = chunks[i]
if c.id == "ALPH" and not alph then
alph = c
elseif c.id == "VP8 " or c.id == "VP8L" then
return c, alph
elseif c.id == "ANMF" then
break
end
end
return nil, nil
end
local function decodeBitstream(buf: buffer, c: Riff.Chunk, alph: Riff.Chunk?, opts: DecodeOptions, allowNative: boolean): (Bitstream?, Err.Err?)
local maxPixels = opts.maxPixels or DEFAULT_MAX_PIXELS
if c.id == "VP8L" then
local rgba, w, h, alphaHint = Vp8L.decode(buf, c.off, c.size, maxPixels)
if not rgba then
return nil, w
end
return { rgba = rgba, w = w, h = h :: number, hasAlpha = alphaHint == true, source = { codec = "vp8l", lossless = true } }, nil
end
local y, u, v, w, h = Vp8.decodePlanes(buf, c.off, c.size, { maxPixels = maxPixels })
if not y then
return nil, u
end
local fw, fh = w :: number, h :: number
local source: { [string]: any } = { codec = "vp8", lossless = false }
if allowNative and opts.native and not alph then
local img = Types.Image.new(fw, fh, "yuv420p")
local ny, nc = fw * fh, buffer.len(v :: buffer)
buffer.copy(img.pixels, 0, y, 0, ny)
buffer.copy(img.pixels, ny, u, 0, nc)
buffer.copy(img.pixels, ny + nc, v :: buffer, 0, nc)
return { yuv = img, w = fw, h = fh, hasAlpha = false, source = source }, nil
end
local rgba = Vp8.yuvToRgba(y, u, v :: buffer, fw, fh, opts.upsampling ~= "nearest")
if alph then
local a, info = Alpha.decode(buf, alph.off, alph.size, fw, fh)
if not a then
return nil, fromMessage(info, alph.off)
end
Vp8.setAlpha(rgba, a, fw * fh)
source.alpha = info
end
return { rgba = rgba, w = fw, h = fh, hasAlpha = alph ~= nil, source = source }, nil
end
local function collectMeta(buf: buffer, chunks: { Riff.Chunk }, meta: Types.ImageMeta)
for _, c in chunks do
local key = if c.id == "ICCP" then "icc" elseif c.id == "EXIF" then "exif" elseif c.id == "XMP " then "xmp" else nil
if key and meta[key] == nil then
local b = buffer.create(c.size)
buffer.copy(b, 0, buf, c.off, c.size)
meta[key] = b
end
end
end
function Webp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local o: DecodeOptions = opts or {}
local maxPixels = o.maxPixels or DEFAULT_MAX_PIXELS
local buf = r.buf
local chunks, cerr = Riff.chunks(buf, r.base, r.limit)
if not chunks then
return nil, fromMessage(cerr, r.base)
end
local first = chunks[1]
if not first then
return corrupt("no chunks", r.base + 12)
end
if first.id == "VP8 " or first.id == "VP8L" then
local bs, err = decodeBitstream(buf, first, nil, o, true)
if not bs then
return nil, err
end
local img = bs.yuv or Types.Image.new(bs.w, bs.h, "rgba8")
if bs.rgba then
img.pixels = bs.rgba
end
bs.source.format = "webp"
bs.source.bitDepth = 8
bs.source.extended = false
img.meta.source = bs.source
return img, nil
end
if first.id ~= "VP8X" then
return corrupt("the first chunk is '" .. first.id .. "', not VP8, VP8L or VP8X", first.off - 8)
end
if first.size < 10 then
return nil, Err.new(Err.TRUNCATED, "VP8X chunk too small", first.off)
end
local flags = readu8(buf, first.off)
local cw = u24(buf, first.off + 4) + 1
local ch = u24(buf, first.off + 7) + 1
if cw * ch > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d canvas is over the %d pixel limit", cw, ch, maxPixels))
end
local meta: Types.ImageMeta = {}
collectMeta(buf, chunks, meta)
if bit32.band(flags, FLAG_ANIM) == 0 then
local c, alph = findImage(chunks, 2)
if not c then
return corrupt("no VP8 / VP8L image chunk")
end
local bs, err = decodeBitstream(buf, c, if c.id == "VP8 " then alph else nil, o, true)
if not bs then
return nil, err
end
if bs.w ~= cw or bs.h ~= ch then
return corrupt(string.format("image %d x %d does not match the %d x %d canvas", bs.w, bs.h, cw, ch), c.off)
end
local img = bs.yuv or Types.Image.new(cw, ch, "rgba8")
if bs.rgba then
img.pixels = bs.rgba
end
for k, v in meta do
img.meta[k] = v
end
bs.source.format = "webp"
bs.source.bitDepth = 8
bs.source.extended = true
bs.source.flags = flags
img.meta.source = bs.source
return img, nil
end
-- animation: ANIM then ANMF frames
local bg, loops = 0, 0
local haveAnim = false
local frames: { Anim.Frame } = {}
local sources: { any } = {}
local delays: { number } = {}
local wantAll = o.frames ~= false
for i = 2, #chunks do
local c = chunks[i]
if c.id == "ANIM" then
if c.size < 6 then
return nil, Err.new(Err.TRUNCATED, "ANIM chunk too small", c.off)
end
bg = buffer.readu32(buf, c.off)
loops = buffer.readu16(buf, c.off + 4)
haveAnim = true
elseif c.id == "ANMF" then
if not haveAnim then
return corrupt("ANMF before ANIM", c.off)
end
if c.size < 16 then
return nil, Err.new(Err.TRUNCATED, "ANMF chunk too small", c.off)
end
local fx = u24(buf, c.off) * 2
local fy = u24(buf, c.off + 3) * 2
local fw = u24(buf, c.off + 6) + 1
local fh = u24(buf, c.off + 9) + 1
local dur = u24(buf, c.off + 12)
local fl = readu8(buf, c.off + 15)
if fx + fw > cw or fy + fh > ch then
return corrupt("frame " .. (#frames + 1) .. " lies outside the canvas", c.off)
end
local sub, serr = Riff.list(buf, c.off + 16, c.off + c.size)
if not sub then
return nil, fromMessage(serr, c.off + 16)
end
local img, alph = findImage(sub, 1)
if not img then
return corrupt("frame " .. (#frames + 1) .. " has no image data", c.off)
end
local bs, err = decodeBitstream(buf, img, if img.id == "VP8 " then alph else nil, o, false)
if not bs then
return nil, err
end
if bs.w ~= fw or bs.h ~= fh then
return corrupt(string.format("frame %d: image %d x %d does not match its ANMF size %d x %d", #frames + 1, bs.w, bs.h, fw, fh), c.off)
end
table.insert(frames, {
rgba = bs.rgba :: buffer,
x = fx,
y = fy,
w = fw,
h = fh,
blend = bit32.band(fl, 2) == 0,
disposeBg = bit32.band(fl, 1) == 1,
hasAlpha = bs.hasAlpha,
})
bs.source.hasAlpha = bs.hasAlpha
table.insert(sources, bs.source)
table.insert(delays, dur)
if not wantAll then
break
end
end
end
if #frames == 0 then
return corrupt("animation without frames")
end
local canvases = Anim.coalesce(cw, ch, frames)
local img = Types.Image.new(cw, ch, "rgba8")
img.pixels = canvases[1]
img.loops = loops
for k, v in meta do
img.meta[k] = v
end
img.meta.background = { bit32.band(bit32.rshift(bg, 16), 255), bit32.band(bit32.rshift(bg, 8), 255), bit32.band(bg, 255), bit32.rshift(bg, 24) }
img.meta.source = { format = "webp", bitDepth = 8, extended = true, flags = flags, animated = true, codec = sources[1].codec, lossless = sources[1].lossless }
if wantAll then
local list: { Types.Frame } = {}
for i, f in frames do
local fi: Types.Image
if o.coalesce then
fi = Types.Image.new(cw, ch, "rgba8")
fi.pixels = canvases[i]
else
fi = Types.Image.new(f.w, f.h, "rgba8")
fi.pixels = f.rgba
end
fi.meta.source = sources[i]
fi.meta.duration = delays[i]
list[i] = {
image = fi,
delay = delays[i] / 1000,
x = if o.coalesce then 0 else f.x,
y = if o.coalesce then 0 else f.y,
dispose = if not o.coalesce and f.disposeBg then "background" else "none",
blend = if not o.coalesce and f.blend then "over" else "source",
}
end
img.frames = list
end
return img, nil
end
-- info(r) -> { width, height, animated, alpha, lossless, frames? } from the headers only | nil, Err
function Webp.info(r: Bytes.Reader): (any, Err.Err?)
local chunks, cerr = Riff.chunks(r.buf, r.base, r.limit)
if not chunks then
return nil, fromMessage(cerr, r.base)
end
local first = chunks[1]
if not first then
return corrupt("no chunks")
end
local buf = r.buf
if first.id == "VP8X" and first.size >= 10 then
local flags = readu8(buf, first.off)
local n = 0
for _, c in chunks do
if c.id == "ANMF" then
n += 1
end
end
return {
width = u24(buf, first.off + 4) + 1,
height = u24(buf, first.off + 7) + 1,
animated = bit32.band(flags, FLAG_ANIM) ~= 0,
alpha = bit32.band(flags, FLAG_ALPHA) ~= 0,
frames = if n > 0 then n else 1,
}, nil
elseif first.id == "VP8L" then
local i, err = Vp8L.info(buf, first.off, first.size)
if not i then
return nil, err
end
return { width = i.width, height = i.height, animated = false, alpha = i.alpha, lossless = true, frames = 1 }, nil
elseif first.id == "VP8 " then
local h, err = Vp8.info(buf, first.off, first.size)
if not h then
return nil, err
end
return { width = h.width, height = h.height, animated = false, alpha = false, lossless = false, frames = 1 }, nil
end
return corrupt("the first chunk is '" .. first.id .. "', not VP8, VP8L or VP8X")
end
-- ------------------------------------------------------------------------------------------------ encode
local function hasAlpha(px: buffer, n: number): boolean
for i = 0, n - 1 do
if readu8(px, i * 4 + 3) ~= 255 then
return true
end
end
return false
end
local function validImage(img: any): boolean
return type(img) == "table" and img.format == "rgba8" and type(img.pixels) == "buffer" and type(img.width) == "number" and type(img.height) == "number" and img.width >= 1 and img.height >= 1 and img.width <= 16384 and img.height <= 16384 and img.width % 1 == 0 and img.height % 1 == 0 and buffer.len(img.pixels) >= img.width * img.height * 4
end
local function finishRiff(body: Bytes.Writer): buffer
local out = Bytes.writer(body:tell() + 12)
out:string("RIFF")
out:u32le(body:tell() + 4)
out:string("WEBP")
out:bytes(body.buf, 0, body:tell())
return out:finish()
end
local function writeVp8x(body: Bytes.Writer, flags: number, w: number, h: number)
body:string("VP8X")
body:u32le(10)
body:u8(flags)
body:u24le(0)
body:u24le(w - 1)
body:u24le(h - 1)
end
local function metaChunk(meta: any, key: string): buffer?
local v = meta and meta[key]
if type(v) == "buffer" and buffer.len(v) > 0 then
return v
elseif type(v) == "string" and #v > 0 then
return buffer.fromstring(v)
end
return nil
end
function Webp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
if o.lossless == false then
return nil, Err.new(Err.UNSUPPORTED, "lossy WebP encoding is not supported (use lossless)")
end
if not validImage(img) then
return nil, Err.new(Err.ARG, "needs an rgba8 Image (1..16384 pixels a side)")
end
local effort = o.effort or 5
if type(effort) ~= "number" or effort < 0 or effort > 9 then
return nil, Err.new(Err.ARG, "effort must be 0..9")
end
local vopts = { effort = effort, exact = o.exact }
local w, h = img.width, img.height
local icc, exif, xmp = metaChunk(img.meta, "icc"), metaChunk(img.meta, "exif"), metaChunk(img.meta, "xmp")
local frames = img.frames
local body = Bytes.writer(w * h + 1024)
if not frames or #frames == 0 then
local bits, err = Vp8L.encode(img.pixels, w, h, vopts)
if not bits then
return nil, err
end
if icc or exif or xmp then
local flags = (if icc then FLAG_ICC else 0) + (if exif then FLAG_EXIF else 0) + (if xmp then FLAG_XMP else 0)
if hasAlpha(img.pixels, w * h) then
flags += FLAG_ALPHA
end
writeVp8x(body, flags, w, h)
if icc then
Riff.write(body, "ICCP", icc)
end
Riff.write(body, "VP8L", bits)
if exif then
Riff.write(body, "EXIF", exif)
end
if xmp then
Riff.write(body, "XMP ", xmp)
end
else
Riff.write(body, "VP8L", bits)
end
return finishRiff(body), nil
end
-- animation: frames as they are when WebP can store them (even offsets, dispose none / background), else every
-- frame flattened to a full canvas
local list: { Anim.Frame } = {}
local direct = true
for i, f in frames do
if type(f) ~= "table" or not validImage(f.image) then
return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image")
end
local fx, fy = f.x or 0, f.y or 0
local fw, fh = f.image.width, f.image.height
if type(fx) ~= "number" or type(fy) ~= "number" or fx < 0 or fy < 0 or fx % 1 ~= 0 or fy % 1 ~= 0 or fx + fw > w or fy + fh > h then
return nil, Err.new(Err.ARG, "frame " .. i .. ": rectangle outside the canvas")
end
local dispose = f.dispose or "none"
if dispose ~= "none" and dispose ~= "background" and dispose ~= "previous" then
return nil, Err.new(Err.ARG, "frame " .. i .. ": bad dispose " .. tostring(dispose))
end
if dispose == "previous" or fx % 2 == 1 or fy % 2 == 1 then
direct = false
end
table.insert(list, {
rgba = f.image.pixels,
x = fx,
y = fy,
w = fw,
h = fh,
blend = f.blend == "over",
disposeBg = dispose == "background",
disposePrev = dispose == "previous",
hasAlpha = true,
})
end
if not direct then
local canvases = Anim.composite(w, h, list)
for i, c in canvases do
list[i] = { rgba = c, x = 0, y = 0, w = w, h = h, blend = false, disposeBg = false, hasAlpha = true }
end
end
local anyAlpha = false
for _, f in list do
if hasAlpha(f.rgba, f.w * f.h) then
anyAlpha = true
break
end
end
local flags = FLAG_ANIM + (if anyAlpha then FLAG_ALPHA else 0) + (if icc then FLAG_ICC else 0) + (if exif then FLAG_EXIF else 0) + (if xmp then FLAG_XMP else 0)
writeVp8x(body, flags, w, h)
if icc then
Riff.write(body, "ICCP", icc)
end
local loops = o.loops or img.loops or 0
if type(loops) ~= "number" or loops < 0 or loops > 65535 then
return nil, Err.new(Err.ARG, "loops must be 0..65535")
end
local bgc = o.background or (img.meta and img.meta.background) or { 0, 0, 0, 0 }
local anim = buffer.create(6)
-- the background colour is stored as B, G, R, A
buffer.writeu8(anim, 0, bgc[3] or 0)
buffer.writeu8(anim, 1, bgc[2] or 0)
buffer.writeu8(anim, 2, bgc[1] or 0)
buffer.writeu8(anim, 3, bgc[4] or 0)
buffer.writeu16(anim, 4, loops)
Riff.write(body, "ANIM", anim)
for i, f in list do
local bits, err = Vp8L.encode(f.rgba, f.w, f.h, vopts)
if not bits then
return nil, err
end
local delay = frames[i].delay or 0.1
local ms = math.clamp(math.floor(delay * 1000 + 0.5), 0, 0xffffff)
local hdr = Bytes.writer(16 + buffer.len(bits) + 9)
hdr:u24le(f.x // 2)
hdr:u24le(f.y // 2)
hdr:u24le(f.w - 1)
hdr:u24le(f.h - 1)
hdr:u24le(ms)
hdr:u8((if f.blend then 0 else 2) + (if f.disposeBg then 1 else 0))
Riff.write(hdr, "VP8L", bits)
Riff.write(body, "ANMF", hdr.buf, 0, hdr:tell())
end
if exif then
Riff.write(body, "EXIF", exif)
end
if xmp then
Riff.write(body, "XMP ", xmp)
end
return finishRiff(body), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- coalesce(img) -> the full composited canvases of a decoded animation's frames ({ buffer }, rgba8), the way
-- WebPAnimDecoder composites them (nil for a still image)
function Webp.coalesce(img: Types.Image): { buffer }?
if not img.frames then
return nil
end
local list: { Anim.Frame } = {}
for _, f in img.frames do
table.insert(list, {
rgba = f.image.pixels,
x = f.x,
y = f.y,
w = f.image.width,
h = f.image.height,
blend = f.blend == "over",
disposeBg = f.dispose == "background",
hasAlpha = not (f.image.meta.source and f.image.meta.source.hasAlpha == false),
})
end
return Anim.coalesce(img.width, img.height, list)
end
return Webp