--!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 chunks go through containers/Riff, the -- container rules 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. -- Speed (one Zen 5 core, 512 x 512, tools/bench.luau): lossy decode ~50 MB/s of rgba8 out (luau --codegen) / ~38 MB/s -- (LuaJIT), lossless decode ~43 / ~73 MB/s, lossless encode ~6 / ~8 MB/s at effort 5 (~15 / ~18 MB/s at effort 1). -- Encoded size: within ~4 % of cwebp -lossless on photos at effort 9, smaller on some synthetic images. -- ------------------------------------------------------------------------------------------------ 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/containers/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", "containers/Riff" }, 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 Chunk = { id: string, off: number, size: number } -- off: absolute offset of the payload local function convert(list: { Riff.Chunk }): ({ Chunk }?, Err.Err?) local out: { Chunk } = {} for _, c in list do if c.truncated then return nil, Err.new(Err.TRUNCATED, "chunk '" .. c.id .. "' runs past the end", c.offset) end table.insert(out, { id = c.id, off = c.offset, size = c.size }) end return out, nil end -- readChunks(r) -> the chunks of a RIFF "WEBP" file, the containers/Riff File | nil, Err. As libwebp: the RIFF size -- must fit the data (TRUNCATED) and bytes after it are ignored. local function readChunks(r: Bytes.Reader): ({ Chunk }?, any) local buf, base, limit = r.buf, r.base, r.limit if limit - base < 12 then return nil, Err.new(Err.TRUNCATED, "RIFF header", base) end if buffer.readstring(buf, base, 4) ~= "RIFF" or buffer.readstring(buf, base + 8, 4) ~= "WEBP" then return nil, Err.new(Err.CORRUPT, "not a RIFF WEBP file", base) end local size = buffer.readu32(buf, base + 4) if size < 12 then return nil, Err.new(Err.CORRUPT, "RIFF size too small", base + 4) end if 8 + size > limit - base then return nil, Err.new(Err.TRUNCATED, "the RIFF size runs past the end of the data", base + 4) end local f, err = Riff.read(Bytes.reader(buf, base, 8 + size)) if not f then return nil, err end local list, cerr = convert(f.chunks) if not list then return nil, cerr end return list, f end -- subChunks(f, c) -> the chunks inside an ANMF payload (after its 16-byte header) local function subChunks(f: Riff.File, c: Chunk): ({ Chunk }?, Err.Err?) local n = c.size - 12 return convert(Riff.list(f, { id = c.id, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false })) end 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: { Chunk }, from: number): (Chunk?, Chunk?) local alph: 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: Chunk, alph: 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: { 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, file = readChunks(r) if not chunks then return nil, file 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 = subChunks(file, c) if not sub then return nil, serr 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 = readChunks(r) if not chunks then return nil, cerr 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 vp8x(flags: number, w: number, h: number): buffer local b = Bytes.writer(10) b:u8(flags) b:u24le(0) b:u24le(w - 1) b:u24le(h - 1) return b:finish() 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: Vp8L.EncodeOptions = { 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 = Riff.writer("WEBP", { rf64 = false }) 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 body:chunk("VP8X", vp8x(flags, w, h)) if icc then body:chunk("ICCP", icc) end body:chunk("VP8L", bits) if exif then body:chunk("EXIF", exif) end if xmp then body:chunk("XMP ", xmp) end else body:chunk("VP8L", bits) end return body:finish() 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) body:chunk("VP8X", vp8x(flags, w, h)) if icc then body:chunk("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 } if type(bgc) ~= "table" then return nil, Err.new(Err.ARG, "background must be { r, g, b, a }") end for k = 1, 4 do local v = bgc[k] if v ~= nil and (type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0) then return nil, Err.new(Err.ARG, "background must be { r, g, b, a } with 0..255 integers") end end 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) body:chunk("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 local ms = if type(delay) == "number" and delay == delay then math.clamp(math.floor(delay * 1000 + 0.5), 0, 0xffffff) else 100 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)) local nb = buffer.len(bits) hdr:string("VP8L") hdr:u32le(nb) hdr:bytes(bits) if nb % 2 == 1 then hdr:u8(0) end body:chunk("ANMF", hdr.buf, 0, hdr:tell()) end if exif then body:chunk("EXIF", exif) end if xmp then body:chunk("XMP ", xmp) end return body:finish() 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 or frames that do not fit the canvas) function Webp.coalesce(img: Types.Image): { buffer }? if type(img) ~= "table" or type(img.frames) ~= "table" or type(img.width) ~= "number" or type(img.height) ~= "number" then return nil end local list: { Anim.Frame } = {} for _, f in img.frames :: { Types.Frame } do if type(f) ~= "table" or not validImage(f.image) or type(f.x) ~= "number" or type(f.y) ~= "number" or f.x < 0 or f.y < 0 or f.x % 1 ~= 0 or f.y % 1 ~= 0 or f.x + f.image.width > img.width or f.y + f.image.height > img.height then return nil end 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