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

+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