diff --git a/docs/FORMATS.md b/docs/FORMATS.md
index 181230b..71d3140 100644
--- a/docs/FORMATS.md
+++ b/docs/FORMATS.md
@@ -6,7 +6,10 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|---|---|---|---|---|---|---|
| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
+| image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` |
Codecs (layer 1, shared by formats; not loadable on their own):
- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
+- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
+- codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau
index ba09f70..b5ea13f 100644
--- a/src/Formats/Registry.luau
+++ b/src/Formats/Registry.luau
@@ -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
diff --git a/src/Formats/codecs/Vp8L/Encode.luau b/src/Formats/codecs/Vp8L/Encode.luau
index 3733130..5c4fe3f 100644
--- a/src/Formats/codecs/Vp8L/Encode.luau
+++ b/src/Formats/codecs/Vp8L/Encode.luau
@@ -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
diff --git a/src/Formats/image/webp/Alpha.luau b/src/Formats/image/webp/Alpha.luau
new file mode 100644
index 0000000..4742d47
--- /dev/null
+++ b/src/Formats/image/webp/Alpha.luau
@@ -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
diff --git a/src/Formats/image/webp/Anim.luau b/src/Formats/image/webp/Anim.luau
new file mode 100644
index 0000000..559202d
--- /dev/null
+++ b/src/Formats/image/webp/Anim.luau
@@ -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
diff --git a/src/Formats/image/webp/Riff.luau b/src/Formats/image/webp/Riff.luau
new file mode 100644
index 0000000..6a93aef
--- /dev/null
+++ b/src/Formats/image/webp/Riff.luau
@@ -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
diff --git a/src/Formats/image/webp/init.luau b/src/Formats/image/webp/init.luau
new file mode 100644
index 0000000..d17928a
--- /dev/null
+++ b/src/Formats/image/webp/init.luau
@@ -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
diff --git a/tests/image/webp.luau b/tests/image/webp.luau
new file mode 100644
index 0000000..bf76303
--- /dev/null
+++ b/tests/image/webp.luau
@@ -0,0 +1,246 @@
+-- image/webp tests: every still file of tools/fixtures/webp.py (cwebp lossless / lossy / alpha variants, libvpx key
+-- frames with token partitions, metadata) against dwebp (-pam, -nofancy -pam, -yuv: bit-exact), animations (img2webp,
+-- gif2webp, webpmux) against Pillow's WebPAnimDecoder frames (bit-exact), our encoder (round trips at every effort,
+-- dwebp / Pillow decoding our files at fixture time, metadata, animations), error codes, and the fuzz no-throw pass.
+-- Fixtures: tools/fixtures/webp.py.
+local T = require("@tests/T")
+local Webp = require("@formats/image/webp")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Cases = require("@tests/gen/webp_cases")
+local Anims = require("@tests/gen/webp_anim")
+local Src = require("@tests/gen/webp_src")
+local Enc = require("@tests/gen/webp_enc")
+
+local t = T.suite("webp")
+
+local function decode(data: any, opts: any?): (any, any)
+ local b = if type(data) == "string" then buffer.fromstring(data) else data
+ return Webp.decode(Bytes.reader(b), opts)
+end
+
+-- the contract
+t:eq(Webp.name, "webp", "name")
+t:eq(Webp.category, "image", "category")
+t:check(table.find(Webp.extensions, "webp") ~= nil, "extensions")
+t:check(Webp.caps.decode and Webp.caps.encode and Webp.caps.animation and Webp.caps.alpha, "caps")
+
+-- still files, bit-exact with dwebp
+do
+ local lossy, lossless, alpha = 0, 0, 0
+ for _, c in Cases do
+ local img, err = decode(c.data)
+ t:check(img, c.name .. ": " .. tostring(err))
+ t:check(img.kind == "image" and img.format == "rgba8" and img.width == c.width and img.height == c.height, c.name .. ": size")
+ local crc = Crc32.of(img.pixels)
+ t:check(crc == c.crc, string.format("%s: pixels crc %08x, dwebp %08x", c.name, crc, c.crc))
+ t:eq(img.meta.source.format, "webp", c.name .. ": meta.source")
+ t:eq(img.meta.source.lossless, not c.lossy, c.name .. ": lossless flag")
+ if c.lossy then
+ lossy += 1
+ local nf = decode(c.data, { upsampling = "nearest" })
+ t:check(Crc32.of(nf.pixels) == c.nofancy, c.name .. ": -nofancy")
+ if not c.alpha then
+ local y = decode(c.data, { native = true })
+ t:check(y.format == "yuv420p" and Crc32.of(y.pixels) == c.yuv, c.name .. ": yuv420p planes (dwebp -yuv)")
+ end
+ else
+ lossless += 1
+ end
+ if c.alpha then
+ alpha += 1
+ end
+ if c.icc then
+ t:check(img.meta.icc and Crc32.of(img.meta.icc) == c.icc, c.name .. ": ICC profile")
+ end
+ if c.exif then
+ t:check(img.meta.exif and Crc32.of(img.meta.exif) == c.exif, c.name .. ": EXIF")
+ t:check(img.meta.xmp and buffer.tostring(img.meta.xmp) == c.xmp, c.name .. ": XMP")
+ end
+ end
+ -- inside a bigger buffer (the Reader's range)
+ local c = Cases[3]
+ local big = buffer.create(#c.data + 11)
+ buffer.writestring(big, 5, c.data)
+ local img = Webp.decode(Bytes.reader(big, 5, #c.data))
+ t:check(img and Crc32.of(img.pixels) == c.crc, "decode from a sub-range")
+ t:note("%d lossless and %d lossy files (%d with alpha) match dwebp", lossless, lossy, alpha)
+end
+
+-- animations, bit-exact with Pillow (libwebp WebPAnimDecoder)
+local function opaque(px: buffer, n: number): buffer
+ local b = buffer.create(n * 4)
+ buffer.copy(b, 0, px, 0, n * 4)
+ for i = 0, n - 1 do
+ buffer.writeu8(b, i * 4 + 3, 255)
+ end
+ return b
+end
+local function checkAnim(a: any, label: string)
+ local img, err = decode(a.data, { coalesce = true })
+ t:check(img and img.frames, label .. ": " .. tostring(err))
+ t:eq(#img.frames, #a.frames, label .. ": frame count")
+ t:eq(img.loops, a.loops, label .. ": loops")
+ local n = img.width * img.height
+ for i, f in img.frames do
+ local px = if a.rgba == false then opaque(f.image.pixels, n) else f.image.pixels
+ t:check(Crc32.of(px) == a.frames[i].crc, string.format("%s: frame %d", label, i))
+ t:eq(math.floor(f.delay * 1000 + 0.5), a.frames[i].ms, label .. ": duration")
+ t:check(f.x == 0 and f.y == 0 and f.dispose == "none" and f.blend == "source", label .. ": coalesced frame fields")
+ end
+ t:check(buffer.tostring(img.pixels) == buffer.tostring(img.frames[1].image.pixels), label .. ": pixels = first canvas")
+ -- the frames as stored, then composited by Webp.coalesce: the same canvases
+ local raw = decode(a.data)
+ local canv = Webp.coalesce(raw) :: { buffer }
+ for i, c in canv do
+ local px = if a.rgba == false then opaque(c, n) else c
+ t:check(Crc32.of(px) == a.frames[i].crc, string.format("%s: Webp.coalesce frame %d", label, i))
+ end
+ local only = decode(a.data, { frames = false })
+ t:check(only.frames == nil and buffer.tostring(only.pixels) == buffer.tostring(img.pixels), label .. ": frames = false")
+ return raw
+end
+for _, a in Anims do
+ local raw = checkAnim(a, a.name)
+ t:check(raw.meta.source.animated and raw.frames[1].image.meta.source.codec ~= nil, a.name .. ": meta")
+ if a.name == "anim_mux_icc.webp" then
+ t:check(raw.meta.icc ~= nil, a.name .. ": ICC")
+ t:check(raw.meta.background[1] == 1 and raw.meta.background[2] == 2 and raw.meta.background[3] == 3 and raw.meta.background[4] == 255, a.name .. ": background colour")
+ t:check(raw.frames[2].x == 10 and raw.frames[2].y == 6 and raw.frames[2].dispose == "background" and raw.frames[2].blend == "over", a.name .. ": frame placement")
+ end
+end
+t:note("%d animations match Pillow", #Anims)
+
+-- the encoder: round trips, the fixture-time dwebp / Pillow checks of our files, metadata, animations
+local function image(s: any): Types.Image
+ local img = Types.Image.new(s.width, s.height)
+ img.pixels = buffer.fromstring(s.rgba)
+ return img
+end
+do
+ local rt = 0
+ for _, s in Src do
+ local img = image(s)
+ for _, effort in { 0, 2, 5, 7 } do
+ local out, err = Webp.encode(img, { effort = effort, exact = true })
+ t:check(out, s.name .. ": encode: " .. tostring(err))
+ local back = decode(out)
+ t:check(back and buffer.tostring(back.pixels) == s.rgba, string.format("%s effort %d: lossless round trip", s.name, effort))
+ rt += 1
+ end
+ -- without exact, fully transparent pixels may change, nothing else
+ local back = decode(Webp.encode(img))
+ local same = true
+ for i = 0, s.width * s.height - 1 do
+ local a = buffer.readu8(img.pixels, i * 4 + 3)
+ if a ~= 0 and buffer.readu32(back.pixels, i * 4) ~= buffer.readu32(img.pixels, i * 4) then
+ same = false
+ elseif a == 0 and buffer.readu8(back.pixels, i * 4 + 3) ~= 0 then
+ same = false
+ end
+ end
+ t:check(same, s.name .. ": default (not exact) round trip")
+ end
+ local ok, ours, cwebp = 0, 0, 0
+ for _, e in Enc.still do
+ t:check(e.ok, string.format("dwebp decodes our %s (effort %d%s)", e.name, e.effort, if e.exact then ", exact" else ""))
+ ok += 1
+ if e.effort == 9 and e.exact then
+ ours += e.size
+ cwebp += e.cwebp
+ end
+ end
+ t:note("%d round trips; dwebp reads our %d files; effort 9: %d bytes, cwebp -lossless: %d bytes", rt, ok, ours, cwebp)
+ for _, a in Enc.anim do
+ t:check(a.ok, a.name .. ": Pillow composites our animation as its input frames")
+ checkAnim({ data = a.data, frames = (function()
+ local f = {}
+ for i, c in a.frames do
+ f[i] = { crc = c, ms = a.ms[i] }
+ end
+ return f
+ end)(), loops = a.loops, rgba = true }, "our " .. a.name)
+ end
+ -- metadata chunks
+ local img = image(Src[1])
+ img.meta.icc = buffer.fromstring("icc profile bytes")
+ img.meta.exif = buffer.fromstring("Exif\0\0MM")
+ img.meta.xmp = ""
+ local back = decode(Webp.encode(img))
+ t:check(back.meta.icc and buffer.tostring(back.meta.icc) == "icc profile bytes", "ICC round trip")
+ t:check(back.meta.exif and buffer.tostring(back.meta.exif) == "Exif\0\0MM", "EXIF round trip")
+ t:check(back.meta.xmp and buffer.tostring(back.meta.xmp) == "", "XMP round trip")
+ t:check(back.meta.source.extended and buffer.tostring(back.pixels) == Src[1].rgba, "VP8X still round trip")
+ -- an animation round trip through our own decoder (frame fields kept)
+ local anim = Types.Image.new(8, 6)
+ local f1 = Types.Image.new(8, 6)
+ buffer.fill(f1.pixels, 0, 200)
+ local f2 = Types.Image.new(4, 2)
+ buffer.fill(f2.pixels, 0, 77)
+ anim.frames = {
+ { image = f1, delay = 0.25, x = 0, y = 0, dispose = "none", blend = "source" },
+ { image = f2, delay = 1.5, x = 2, y = 4, dispose = "background", blend = "over" },
+ }
+ anim.loops = 7
+ local ab = decode(Webp.encode(anim, { background = { 10, 20, 30, 40 } }))
+ t:check(ab.frames and #ab.frames == 2 and ab.loops == 7, "animation round trip: frames, loops")
+ t:check(ab.frames[2].x == 2 and ab.frames[2].y == 4 and ab.frames[2].dispose == "background" and ab.frames[2].blend == "over" and ab.frames[2].delay == 1.5, "animation round trip: frame fields")
+ t:check(buffer.tostring(ab.frames[2].image.pixels) == buffer.tostring(f2.pixels), "animation round trip: frame pixels")
+ t:check(ab.meta.background[1] == 10 and ab.meta.background[4] == 40, "animation round trip: background")
+ -- bad arguments
+ local _, e1 = Webp.encode({} :: any)
+ t:check(e1 and e1.code == Err.ARG, "encode a non-image: ARG")
+ local _, e2 = Webp.encode(img, { lossless = false })
+ t:check(e2 and e2.code == Err.UNSUPPORTED, "lossy encode: UNSUPPORTED")
+ local _, e3 = Webp.encode(img, { effort = 11 })
+ t:check(e3 and e3.code == Err.ARG, "bad effort: ARG")
+ anim.frames[2].x = 6
+ local _, e4 = Webp.encode(anim)
+ t:check(e4 and e4.code == Err.ARG, "frame outside the canvas: ARG")
+end
+
+-- sniff, info, errors
+do
+ local c = Cases[1]
+ t:eq(Webp.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff WebP")
+ t:eq(Webp.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0WAVEfmt "))), 0, "sniff WAV")
+ t:eq(Webp.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing")
+ local r = Bytes.reader(buffer.fromstring(c.data))
+ local info = Webp.info(r)
+ t:check(info and info.width == c.width and info.height == c.height and info.frames == 1, "info")
+ local ai = Webp.info(Bytes.reader(buffer.fromstring(Anims[1].data)))
+ t:check(ai and ai.animated and ai.frames == #Anims[1].frames, "info of an animation")
+ local _, e1 = decode("RIFF\4\0\0\0WEBP")
+ t:check(e1 and e1.code == Err.CORRUPT, "RIFF size too small: " .. tostring(e1))
+ local _, e2 = decode(string.sub(c.data, 1, #c.data - 5))
+ t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2))
+ local _, e3 = decode(c.data, { maxPixels = 10 })
+ t:check(e3 and e3.code == Err.LIMIT, "maxPixels: " .. tostring(e3))
+ local _, e4 = decode("not a webp file at all")
+ t:check(e4 and e4.code == Err.CORRUPT, "junk: " .. tostring(e4))
+end
+
+-- fuzz: truncations, mutations and garbage never throw
+do
+ local samples = {}
+ for i, c in Cases do
+ if i % 7 == 0 and #c.data < 20000 then
+ table.insert(samples, c.data)
+ end
+ end
+ for _, a in Anims do
+ if #a.data < 40000 then
+ table.insert(samples, a.data)
+ end
+ end
+ t:fuzz("decode", function(b: buffer)
+ return Webp.decode(Bytes.reader(b), { maxPixels = 2 ^ 20 })
+ end, samples, { mutations = 6 })
+ t:fuzz("decode coalesce", function(b: buffer)
+ return Webp.decode(Bytes.reader(b), { maxPixels = 2 ^ 20, coalesce = true, upsampling = "nearest" })
+ end, samples, { mutations = 3, keepHeader = 30, garbage = 20 })
+end
+
+t:done()
diff --git a/tools/fixtures/_webp_encode.luau b/tools/fixtures/_webp_encode.luau
new file mode 100644
index 0000000..c7c9b3c
--- /dev/null
+++ b/tools/fixtures/_webp_encode.luau
@@ -0,0 +1,95 @@
+-- tools/fixtures/_webp_encode: run by tools/fixtures/webp.py (luau CLI, repo root). Encodes the WebP fixture sources
+-- (tests/gen/webp_src) with image/webp at several efforts and two animations, and prints one line per file:
+-- " " (stills: _e_) or "anim:,,... " with the CRC-32 of each
+-- canvas the input frames composite to (image/webp/Anim.composite), for dwebp / Pillow to check.
+local Webp = require("@formats/image/webp")
+local Anim = require("@formats/image/webp/Anim")
+local Types = require("@formats/Types")
+local Crc32 = require("@formats/core/Crc32")
+local Src = require("@tests/gen/webp_src")
+
+local HEX = {}
+for i = 0, 255 do
+ HEX[i] = string.format("%02x", i)
+end
+local function hex(b: buffer): string
+ local t = table.create(buffer.len(b))
+ for i = 0, buffer.len(b) - 1 do
+ t[i + 1] = HEX[buffer.readu8(b, i)]
+ end
+ return table.concat(t)
+end
+
+local function image(s: any): Types.Image
+ local img = Types.Image.new(s.width, s.height)
+ img.pixels = buffer.fromstring(s.rgba)
+ return img
+end
+
+local bySrc = {}
+for _, s in Src do
+ bySrc[s.name] = s
+ for _, effort in { 0, 3, 5, 9 } do
+ local out = assert(Webp.encode(image(s), { effort = effort, exact = true }))
+ print(string.format("%s_e%d_exact %s", s.name, effort, hex(out)))
+ end
+ local out = assert(Webp.encode(image(s), { effort = 5 }))
+ print(string.format("%s_e5_loose %s", s.name, hex(out)))
+end
+
+-- crop(src, x, y, w, h) -> an rgba8 Image
+local function crop(s: any, x: number, y: number, w: number, h: number): Types.Image
+ local img = Types.Image.new(w, h)
+ local px = buffer.fromstring(s.rgba)
+ for j = 0, h - 1 do
+ buffer.copy(img.pixels, j * w * 4, px, ((y + j) * s.width + x) * 4, w * 4)
+ end
+ return img
+end
+
+local function animation(cw: number, ch: number, frames: { Types.Frame }): Types.Image
+ local img = Types.Image.new(cw, ch)
+ img.frames = frames
+ img.loops = 2
+ return img
+end
+
+local rose, rosea, grad = bySrc.rose, bySrc.rose_a, bySrc.grad
+local anims = {
+ -- stored as they are: even offsets, blending, dispose to background
+ animation(70, 46, {
+ { image = crop(rose, 0, 0, 70, 46), delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" },
+ { image = crop(rosea, 10, 4, 30, 20), delay = 0.05, x = 10, y = 4, dispose = "background", blend = "over" },
+ { image = crop(rosea, 20, 10, 40, 30), delay = 0.2, x = 20, y = 10, dispose = "none", blend = "over" },
+ { image = crop(grad, 0, 0, 24, 16), delay = 0.033, x = 46, y = 30, dispose = "none", blend = "source" },
+ }),
+ -- flattened: odd offsets and dispose "previous"
+ animation(70, 46, {
+ { image = crop(rosea, 0, 0, 70, 46), delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" },
+ { image = crop(grad, 3, 3, 21, 13), delay = 0.1, x = 5, y = 7, dispose = "previous", blend = "over" },
+ { image = crop(rose, 1, 1, 9, 9), delay = 0.1, x = 33, y = 21, dispose = "background", blend = "over" },
+ { image = crop(grad, 0, 0, 10, 10), delay = 0.1, x = 60, y = 36, dispose = "none", blend = "over" },
+ }),
+}
+for k, img in anims do
+ local list = {}
+ for _, f in img.frames :: { Types.Frame } 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",
+ disposePrev = f.dispose == "previous",
+ hasAlpha = true,
+ })
+ end
+ local crcs = {}
+ for _, c in Anim.composite(img.width, img.height, list) do
+ table.insert(crcs, tostring(Crc32.of(c)))
+ end
+ local out = assert(Webp.encode(img, { effort = 5, exact = true }))
+ print(string.format("anim%d:%s %s", k, table.concat(crcs, ","), hex(out)))
+end
diff --git a/tools/fixtures/webp.py b/tools/fixtures/webp.py
new file mode 100644
index 0000000..2f4ba62
--- /dev/null
+++ b/tools/fixtures/webp.py
@@ -0,0 +1,298 @@
+# WebP fixtures (tools/fixtures.py). Reference tools: libwebp 1.6 (cwebp, dwebp, img2webp, gif2webp, webpmux),
+# ImageMagick (built-in test images, an animated GIF), ffmpeg's libvpx (VP8 key frames from a second encoder, with
+# token partitions and loop filter deltas, wrapped in a RIFF here) and Pillow (WebPAnimDecoder: composited frames).
+# tests/gen/webp_src.luau the source images: { name, width, height, rgba }
+# tests/gen/webp_cases.luau still files: { name, data, width, height, crc (dwebp -pam), lossy, yuv (dwebp -yuv),
+# nofancy (dwebp -nofancy -pam), alpha, meta }
+# tests/gen/webp_anim.luau animations: { name, data, width, height, loops, frames = { crc, ms } (Pillow) }
+# tests/gen/webp_enc.luau our encoder's output checked by dwebp / Pillow (tools/fixtures/_webp_encode.luau):
+# { name, effort, crc, ok, size, cwebp }, animations { name, crc, frames }
+# tests/gen/webp_bench.luau bigger lossy / lossless files for tools/bench.luau
+import json, os, random, shutil, struct, subprocess, tempfile, zlib
+
+INPUTS = ["tools/fixtures/_webp_encode.luau", "src/Formats/codecs/Vp8L", "src/Formats/image/webp"]
+
+TOOLS = ["libwebp", "imagemagick", "ffmpeg"]
+
+
+def run(tmp, script):
+ path = os.path.join(tmp, "run.sh")
+ with open(path, "w") as f:
+ f.write("set -e\n" + script)
+ cmd = ["nix", "shell"] + ["nixpkgs#" + t for t in TOOLS] + ["-c", "bash", path]
+ subprocess.run(cmd, cwd=tmp, check=True, capture_output=True)
+
+
+def pam_write(path, w, h, rgba):
+ with open(path, "wb") as f:
+ f.write(b"P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n" % (w, h) + bytes(rgba))
+
+
+def pam_read(data):
+ end = data.index(b"ENDHDR\n") + 7
+ hdr = dict(l.split(b" ", 1) for l in data[:end].split(b"\n")[1:] if b" " in l)
+ w, h, d = int(hdr[b"WIDTH"]), int(hdr[b"HEIGHT"]), int(hdr[b"DEPTH"])
+ px = data[end:end + w * h * d]
+ if d == 4:
+ return w, h, px
+ out = bytearray(w * h * 4)
+ for i in range(w * h):
+ if d == 3:
+ out[i * 4:i * 4 + 3] = px[i * 3:i * 3 + 3]
+ else:
+ out[i * 4:i * 4 + 3] = bytes([px[i * d]]) * 3
+ out[i * 4 + 3] = 255 if d < 2 or d == 3 else px[i * d + 1]
+ return w, h, bytes(out)
+
+
+def synthetic(rng):
+ out = []
+
+ def img(name, w, h, f):
+ px = bytearray()
+ for y in range(h):
+ for x in range(w):
+ px += bytes(f(x, y))
+ out.append((name, w, h, bytes(px)))
+
+ img("tiny", 1, 1, lambda x, y: (200, 10, 30, 255))
+ img("odd", 3, 7, lambda x, y: (rng.randrange(256), rng.randrange(256), rng.randrange(256), 255))
+ img("strip", 257, 3, lambda x, y: ((x * 7) & 255, (x + y * 50) & 255, (x * x) & 255, 255))
+ two = [(0, 0, 0, 255), (255, 255, 255, 255)]
+ img("pal2", 33, 17, lambda x, y: two[(x * 3 + y * 5) % 7 < 3])
+ three = [(255, 0, 0, 255), (0, 255, 0, 128), (0, 0, 255, 0)]
+ img("pal3", 40, 9, lambda x, y: three[(x // 3 + y) % 3])
+ five = [(rng.randrange(256), rng.randrange(256), rng.randrange(256), 255) for _ in range(5)]
+ img("pal5", 25, 25, lambda x, y: five[(x * y + x) % 5])
+ p16 = [(rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.choice([255, 255, 90])) for _ in range(16)]
+ img("pal16", 64, 40, lambda x, y: p16[((x // 4) * 3 + y // 5) % 16])
+ p17 = [(i * 15, 255 - i * 15, (i * 77) & 255, 255) for i in range(17)]
+ img("pal17", 51, 30, lambda x, y: p17[(x + y) % 17])
+ p256 = [(i, (i * 3) & 255, (i * 7) & 255, 255 if i % 9 else 128) for i in range(256)]
+ img("pal256", 64, 64, lambda x, y: p256[(x * 64 + y * 5 + x * y) % 256])
+ img("noise", 48, 48, lambda x, y: (rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.randrange(256)))
+ img("grad", 100, 60, lambda x, y: (x * 255 // 99, y * 255 // 59, (x + y) * 255 // 158, min(255, x * 3 + y)))
+ img("trans", 50, 50, lambda x, y: (rng.randrange(256), rng.randrange(256), rng.randrange(256), 0 if (x - 25) ** 2 + (y - 25) ** 2 > 300 else 255))
+ return out
+
+
+def add_alpha(name, w, h, px, kind):
+ out = bytearray(px)
+ for y in range(h):
+ for x in range(w):
+ i = (y * w + x) * 4 + 3
+ if kind == "ramp":
+ out[i] = 0 if x < w // 6 else min(255, (x * 255) // max(1, w - 1) + 20)
+ else:
+ out[i] = 255 if (x // 8 + y // 8) % 3 else (x * y) & 255
+ return name, w, h, bytes(out)
+
+
+LOSSLESS = [("z0", "-lossless -z 0"), ("z3", "-lossless -z 3"), ("z6", "-lossless -z 6"), ("z9", "-lossless -z 9"),
+ ("exact", "-lossless -exact -m 6 -q 100"), ("near", "-lossless -near_lossless 40")]
+LOSSY = [("q5", "-q 5"), ("q50", "-q 50"), ("q90", "-q 90 -m 6"), ("simple", "-q 75 -nostrong -sharpness 5"),
+ ("seg1", "-q 30 -f 100 -segments 1"), ("nofilter", "-q 60 -sns 0 -f 0"), ("sharpyuv", "-q 80 -sharp_yuv -af")]
+ALPHA = [("araw", "-q 70 -alpha_method 0"), ("afnone", "-q 70 -alpha_filter none"), ("affast", "-q 70 -alpha_filter fast"),
+ ("afbest", "-q 70 -alpha_filter best -exact"), ("aq30", "-q 70 -alpha_q 30")]
+FULL = {"rose", "plasma", "rose_a", "pal16", "grad", "odd"} # every lossless / lossy variant; others get a few
+
+
+def ivf_frames(data):
+ frames, p = [], 32
+ while p + 12 <= len(data):
+ n = struct.unpack_from(" meta.icc && head -c 100 /dev/urandom > meta.exif && printf '' > meta.xmp")
+ lines.append("webpmux -set icc meta.icc meta_base.webp -o meta1.webp")
+ lines.append("webpmux -set exif meta.exif meta1.webp -o meta2.webp")
+ lines.append("webpmux -set xmp meta.xmp meta2.webp -o meta_all.webp")
+ lines.append("cwebp -quiet -lossless -metadata all rose.pam -o meta_ll.webp && webpmux -set icc meta.icc meta_ll.webp -o meta_ll_icc.webp")
+ files.append(("meta_all.webp", {"lossy": True, "meta": True}))
+ files.append(("meta_ll_icc.webp", {"lossy": False, "meta": True}))
+ run(tmp, "\n".join(lines))
+ for n in ["rose", "granite", "plasma", "wizard"]:
+ for k in range(4):
+ data = open(os.path.join(tmp, "%s_vpx%d.ivf" % (n, k)), "rb").read()
+ frame = ivf_frames(data)[0]
+ name = "%s_vpx%d.webp" % (n, k)
+ open(os.path.join(tmp, name), "wb").write(riff([(b"VP8 ", frame)]))
+ files.append((name, {"lossy": True}))
+ # references
+ lines = []
+ for name, info in files:
+ lines.append("dwebp -quiet %s -pam -o %s.pam" % (name, name))
+ if info["lossy"]:
+ lines.append("dwebp -quiet %s -nofancy -pam -o %s.nf.pam" % (name, name))
+ lines.append("dwebp -quiet %s -yuv -o %s.yuv" % (name, name))
+ run(tmp, "\n".join(lines))
+ cases = []
+ for name, info in files:
+ data = open(os.path.join(tmp, name), "rb").read()
+ w, h, px = pam_read(open(os.path.join(tmp, name + ".pam"), "rb").read())
+ c = {"name": name, "data": data, "width": w, "height": h, "crc": zlib.crc32(px), "lossy": info["lossy"],
+ "alpha": any(px[i] != 255 for i in range(3, len(px), 4))}
+ if info["lossy"]:
+ c["nofancy"] = zlib.crc32(pam_read(open(os.path.join(tmp, name + ".nf.pam"), "rb").read())[2])
+ c["yuv"] = zlib.crc32(open(os.path.join(tmp, name + ".yuv"), "rb").read())
+ if info.get("meta"):
+ c["icc"] = zlib.crc32(open(os.path.join(tmp, "meta.icc"), "rb").read())
+ if name == "meta_all.webp":
+ c["exif"] = zlib.crc32(open(os.path.join(tmp, "meta.exif"), "rb").read())
+ c["xmp"] = ""
+ cases.append(c)
+ ctx.emit("webp_cases", cases)
+
+ # 3. animations: img2webp (sub-rectangles, blending, mixed lossy / lossless), gif2webp, webpmux frames
+ lines = []
+ # frames of one canvas size: rose-sized crops of the sources
+ for i, (n, w, h, px) in enumerate([s for s in sources if s[0] in ("plasma", "plasma_a", "wizard", "grad", "noise", "netscape")]):
+ lines.append("magick %s.pam -resize 70x46! -depth 8 PAM:af%d.pam" % (n, i))
+ lines.append("magick rose.pam -fill red -draw 'rectangle 10,10 30,20' PAM:af6.pam")
+ lines.append("magick rose.pam -fill blue -draw 'rectangle 40,20 60,40' PAM:af7.pam")
+ lines.append("magick rose.pam -alpha on -channel A -evaluate set 50%% +channel PAM:af8.pam")
+ lines.append("img2webp -loop 3 -lossless rose.pam -d 80 af6.pam -d 120 af7.pam af8.pam -lossy -q 60 af0.pam -o anim_mixed.webp")
+ lines.append("img2webp -min_size -lossless af1.pam af3.pam -d 40 af4.pam af8.pam -o anim_alpha.webp")
+ lines.append("img2webp -kmax 2 -lossy -q 40 af0.pam af2.pam af5.pam -mixed af6.pam af7.pam -o anim_lossy.webp")
+ lines.append("magick -dispose background -delay 10 -size 60x40 xc:none -fill red -draw 'circle 20,20 30,20' "
+ "-dispose previous -delay 20 -size 60x40 xc:none -fill blue -draw 'rectangle 5,5 25,30' "
+ "-dispose none -delay 30 -size 60x40 xc:none -fill green -draw 'rectangle 30,10 55,35' "
+ "-loop 0 anim.gif")
+ lines.append("gif2webp -quiet anim.gif -o anim_gif.webp")
+ lines.append("gif2webp -quiet -lossy -q 50 anim.gif -o anim_gif_lossy.webp")
+ lines.append("cwebp -quiet -lossless af6.pam -o fr1.webp && cwebp -quiet -q 50 af7.pam -o fr2.webp")
+ lines.append("webpmux -frame fr1.webp +100+0+0+0-b -frame fr2.webp +50+10+6+1+b -loop 1 -bgcolor 255,1,2,3 -o anim_mux.webp")
+ lines.append("webpmux -set icc meta.icc anim_mux.webp -o anim_mux_icc.webp")
+ run(tmp, "\n".join(lines))
+ anims = ["anim_mixed.webp", "anim_alpha.webp", "anim_lossy.webp", "anim_gif.webp", "anim_gif_lossy.webp", "anim_mux_icc.webp"]
+ ref = pillow_frames(ctx, [os.path.join(tmp, a) for a in anims])
+ out = []
+ for a, r in zip(anims, ref):
+ out.append({"name": a, "data": open(os.path.join(tmp, a), "rb").read(), "width": r["w"], "height": r["h"],
+ "loops": r["loop"], "rgba": r["mode"] == "RGBA", "frames": [{"crc": c, "ms": d} for c, d in r["frames"]]})
+ ctx.emit("webp_anim", out)
+
+ # 4. our encoder, checked by dwebp (still) and Pillow (animations)
+ res = subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_webp_encode.luau"],
+ cwd=ctx.root, check=True, capture_output=True).stdout.decode()
+ ours = []
+ for line in res.split("\n"):
+ if line.strip():
+ name, hexdata = line.split(" ")
+ path = os.path.join(tmp, "ours_" + name.split(":")[0] + ".webp")
+ open(path, "wb").write(bytes.fromhex(hexdata))
+ ours.append((name, path))
+ run(tmp, "\n".join("dwebp -quiet %s -pam -o %s.pam" % (p, p) for n, p in ours if not n.startswith("anim")) + "\n" +
+ "\n".join("cwebp -quiet -lossless -exact %s.pam -o cw_%s.webp" % (n, n) for n, w, h, px in sources))
+ src = {n: (w, h, px) for n, w, h, px in sources}
+ enc = []
+ anim_paths = [(n, p) for n, p in ours if n.startswith("anim")]
+ aref = pillow_frames(ctx, [p for n, p in anim_paths])
+ for name, path in ours:
+ if name.startswith("anim"):
+ continue
+ sname, effort, mode = name.rsplit("_", 2)
+ w, h, px = src[sname]
+ _, _, got = pam_read(open(path + ".pam", "rb").read())
+ want = px if mode == "exact" else bytes(b if px[(i // 4) * 4 + 3] else 0 for i, b in enumerate(px))
+ enc.append({"name": sname, "effort": int(effort[1:]), "exact": mode == "exact", "ok": got == want,
+ "size": os.path.getsize(path), "cwebp": os.path.getsize(os.path.join(tmp, "cw_%s.webp" % sname))})
+ anim_out = []
+ for (n, p), r in zip(anim_paths, aref):
+ aname, want = n.split(":")
+ got = [c for c, d in r["frames"]]
+ anim_out.append({"name": aname, "data": open(p, "rb").read(), "frames": got, "ms": [d for c, d in r["frames"]],
+ "loops": r["loop"], "ok": got == [int(c) for c in want.split(",")]})
+ ctx.emit("webp_enc", {"still": enc, "anim": anim_out})
+
+ # 5. bench: a 512 x 512 lossy and lossless file
+ run(tmp, "cwebp -quiet -q 80 bench.pam -o bench_lossy.webp\ncwebp -quiet -lossless bench.pam -o bench_ll.webp")
+ w, h, px = pam_read(open(os.path.join(tmp, "bench.pam"), "rb").read())
+ ctx.emit("webp_bench", {"width": w, "height": h, "rgba": px,
+ "lossy": open(os.path.join(tmp, "bench_lossy.webp"), "rb").read(),
+ "lossless": open(os.path.join(tmp, "bench_ll.webp"), "rb").read()})
+
+
+PILLOW = r"""
+import json, sys, zlib
+from PIL import Image
+out = []
+for path in sys.argv[1:]:
+ im = Image.open(path)
+ frames = []
+ for i in range(getattr(im, "n_frames", 1)):
+ im.seek(i)
+ frames.append([zlib.crc32(im.convert("RGBA").tobytes()), im.info.get("duration", 0)])
+ out.append({"w": im.width, "h": im.height, "mode": im.mode, "loop": im.info.get("loop", 0), "frames": frames})
+print(json.dumps(out))
+"""
+
+
+def pillow_frames(ctx, paths):
+ expr = "with import {}; python3.withPackages (p: [p.pillow])"
+ cmd = ["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", PILLOW] + paths
+ return json.loads(subprocess.run(cmd, capture_output=True, check=True).stdout)