From 4ffb8cd6bd1dec21848a9adc86f1b33b7acba1b0 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:39:26 -0500 Subject: [PATCH 1/6] ws-webp: codecs/Vp8L decoder (libwebp port) and codecs/Vp8 key frame decoder + libwebp YUV->RGB (fancy / point upsampling); bit-exact on first samples --- licenses/libwebp-LICENSE.txt | 55 ++ src/Formats/codecs/Vp8/Decode.luau | 1248 +++++++++++++++++++++++++++ src/Formats/codecs/Vp8/Tables.luau | 180 ++++ src/Formats/codecs/Vp8/Yuv.luau | 123 +++ src/Formats/codecs/Vp8/init.luau | 142 +++ src/Formats/codecs/Vp8L/Decode.luau | 873 +++++++++++++++++++ src/Formats/codecs/Vp8L/Encode.luau | 8 + src/Formats/codecs/Vp8L/init.luau | 120 +++ 8 files changed, 2749 insertions(+) create mode 100644 licenses/libwebp-LICENSE.txt create mode 100644 src/Formats/codecs/Vp8/Decode.luau create mode 100644 src/Formats/codecs/Vp8/Tables.luau create mode 100644 src/Formats/codecs/Vp8/Yuv.luau create mode 100644 src/Formats/codecs/Vp8/init.luau create mode 100644 src/Formats/codecs/Vp8L/Decode.luau create mode 100644 src/Formats/codecs/Vp8L/Encode.luau create mode 100644 src/Formats/codecs/Vp8L/init.luau diff --git a/licenses/libwebp-LICENSE.txt b/licenses/libwebp-LICENSE.txt new file mode 100644 index 0000000..b6de3f0 --- /dev/null +++ b/licenses/libwebp-LICENSE.txt @@ -0,0 +1,55 @@ +Copyright (c) 2010, Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of Google nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Additional IP Rights Grant (Patents): +Additional IP Rights Grant (Patents) +------------------------------------ + +"These implementations" means the copyrightable works that implement the WebM +codecs distributed by Google as part of the WebM Project. + +Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge, +royalty-free, irrevocable (except as stated in this section) patent license to +make, have made, use, offer to sell, sell, import, transfer, and otherwise +run, modify and propagate the contents of these implementations of WebM, where +such license applies only to those patent claims, both currently owned by +Google and acquired in the future, licensable by Google that are necessarily +infringed by these implementations of WebM. This grant does not include claims +that would be infringed only as a consequence of further modification of these +implementations. If you or your agent or exclusive licensee institute or order +or agree to the institution of patent litigation or any other patent +enforcement activity against any entity (including a cross-claim or +counterclaim in a lawsuit) alleging that any of these implementations of WebM +or any code incorporated within any of these implementations of WebM +constitute direct or contributory patent infringement, or inducement of +patent infringement, then any patent rights granted to you under this License +for these implementations of WebM shall terminate as of the date such +litigation is filed. diff --git a/src/Formats/codecs/Vp8/Decode.luau b/src/Formats/codecs/Vp8/Decode.luau new file mode 100644 index 0000000..8f019fe --- /dev/null +++ b/src/Formats/codecs/Vp8/Decode.luau @@ -0,0 +1,1248 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Vp8/Decode: the VP8 key frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter / +-- quantizer headers, token probability updates, intra modes, residual tokens, the inverse WHT and DCT, intra +-- prediction (16x16, 4x4, chroma), and the normal and simple loop filters. A port of libwebp 1.6 src/dec/vp8_dec.c, +-- tree_dec.c, quant_dec.c, frame_dec.c, src/dsp/dec.c and src/utils/bit_reader* (BSD-3-Clause, +-- licenses/libwebp-LICENSE.txt), bit-exact with it (libwebp is deterministic; so is this). +-- +-- The decoder state (Decode.new) keeps what persists between frames (token probabilities, segment and filter +-- headers) so inter frames can be added later for WebM: decodeFrame() returns UNSUPPORTED for them today. +-- Never throws: bad data returns nil, "message" ("truncated: ..." when the data ends early). +local Tables = require("@formats/codecs/Vp8/Tables") + +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift +local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16 +local bfill, bcopy, bcreate = buffer.fill, buffer.copy, buffer.create +local abs = math.abs + +local COEFF_PROBA0 = Tables.COEFF_PROBA0 +local COEFF_UPDATE_PROBA = Tables.COEFF_UPDATE_PROBA +local BMODES_PROBA = Tables.BMODES_PROBA +local DC_TABLE, AC_TABLE = Tables.DC_TABLE, Tables.AC_TABLE +local BANDS, ZIGZAG = Tables.BANDS, Tables.ZIGZAG +local CAT = { Tables.CAT3, Tables.CAT4, Tables.CAT5, Tables.CAT6 } + +local Decode = {} + +-- ------------------------------------------------------------------------------------------------ boolean decoder +-- libwebp's VP8BitReader: `range` is the range minus one (127..254), `value` holds the unread bits, `bits` is the +-- position of the 8-bit window in `value` (< 0: load more). Bytes past the end read as zero once and set eof. +type Br = { buf: buffer, pos: number, limit: number, value: number, bits: number, range: number, eof: boolean } + +-- SHIFT[r + 1]: the normalisation shift of a range r (1..255) = 7 - floor(log2 r) +local SHIFT = table.create(256, 0) +for r = 1, 255 do + local s, v = 0, r + while v < 128 do + v *= 2 + s += 1 + end + SHIFT[r + 1] = s +end + +local function load(br: Br) + local p = br.pos + if p + 3 <= br.limit then + local b = br.buf + br.value = br.value * 16777216 + readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) + br.pos = p + 3 + br.bits += 24 + elseif p < br.limit then + br.value = br.value * 256 + readu8(br.buf, p) + br.pos = p + 1 + br.bits += 8 + elseif not br.eof then + br.value *= 256 + br.bits += 8 + br.eof = true + else + br.bits = 0 + end +end + +local function newBr(buf: buffer, off: number, len: number): Br + local br = { buf = buf, pos = off, limit = off + len, value = 0, bits = -8, range = 254, eof = false } + load(br) + return br +end + +local function getBit(br: Br, prob: number): number + if br.bits < 0 then + load(br) + end + local range = br.range + local pos = br.bits + local split = rshift(range * prob, 8) + local bit = 0 + if rshift(br.value, pos) > split then + range -= split + br.value -= (split + 1) * 2 ^ pos + bit = 1 + else + range = split + 1 + end + local shift = SHIFT[range + 1] + br.range = lshift(range, shift) - 1 + br.bits = pos - shift + return bit +end + +local function getValue(br: Br, n: number): number + local v = 0 + for i = n - 1, 0, -1 do + v += getBit(br, 0x80) * 2 ^ i + end + return v +end + +local function getSignedValue(br: Br, n: number): number + local v = getValue(br, n) + return if getBit(br, 0x80) == 1 then -v else v +end + +-- ------------------------------------------------------------------------------------------------ state +export type Quant = { y1dc: number, y1ac: number, y2dc: number, y2ac: number, uvdc: number, uvac: number } + +export type State = { + -- persistent between frames (inter frames: TODO) + proba: { number }, -- 4 * 8 * 3 * 11 token probabilities + segProba: { number }, -- 3 + useSegment: boolean, + updateMap: boolean, + absoluteDelta: boolean, + segQuant: { number }, -- 4 + segFilter: { number }, -- 4 + refLfDelta: { number }, -- 4 + modeLfDelta: { number }, -- 4 + width: number, + height: number, +} + +function Decode.new(): State + return { + proba = table.clone(COEFF_PROBA0), + segProba = { 255, 255, 255 }, + useSegment = false, + updateMap = false, + absoluteDelta = true, + segQuant = { 0, 0, 0, 0 }, + segFilter = { 0, 0, 0, 0 }, + refLfDelta = { 0, 0, 0, 0 }, + modeLfDelta = { 0, 0, 0, 0 }, + width = 0, + height = 0, + } +end + +-- header(buf, off, len) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, msg +function Decode.header(buf: buffer, off: number, len: number): (any, string?) + if len < 3 then + return nil, "truncated: frame tag" + end + local bits = readu8(buf, off) + readu8(buf, off + 1) * 256 + readu8(buf, off + 2) * 65536 + local h = { + keyFrame = band(bits, 1) == 0, + profile = band(rshift(bits, 1), 7), + show = band(rshift(bits, 4), 1) == 1, + partitionLength = rshift(bits, 5), + width = 0, + height = 0, + xscale = 0, + yscale = 0, + } + if h.profile > 3 then + return nil, "bad profile " .. h.profile + end + if h.keyFrame then + if len < 10 then + return nil, "truncated: key frame header" + end + if readu8(buf, off + 3) ~= 0x9d or readu8(buf, off + 4) ~= 0x01 or readu8(buf, off + 5) ~= 0x2a then + return nil, "bad VP8 start code" + end + local w = readu8(buf, off + 6) + readu8(buf, off + 7) * 256 + local ht = readu8(buf, off + 8) + readu8(buf, off + 9) * 256 + h.width, h.xscale = band(w, 0x3fff), rshift(w, 14) + h.height, h.yscale = band(ht, 0x3fff), rshift(ht, 14) + end + return h, nil +end + +-- ------------------------------------------------------------------------------------------------ residuals +local function getLargeValue(br: Br, P: { number }, p: number): number + local v + if getBit(br, P[p + 4]) == 0 then + if getBit(br, P[p + 5]) == 0 then + v = 2 + else + v = 3 + getBit(br, P[p + 6]) + end + else + if getBit(br, P[p + 7]) == 0 then + if getBit(br, P[p + 8]) == 0 then + v = 5 + getBit(br, 159) + else + v = 7 + 2 * getBit(br, 165) + v += getBit(br, 145) + end + else + local bit1 = getBit(br, P[p + 9]) + local bit0 = getBit(br, P[p + 10 + bit1]) + local cat = 2 * bit1 + bit0 + v = 0 + for _, pr in CAT[cat + 1] do + v = v + v + getBit(br, pr) + end + v += 3 + lshift(8, cat) + end + end + return v +end + +-- getCoeffs(br, P, t, ctx, dqDc, dqAc, n, out, o) -> the position of the last non-zero coefficient + 1. Writes the +-- dequantized coefficients (int16, as libwebp stores them) into out at byte offset o, in raster order. +local function getCoeffs(br: Br, P: { number }, t: number, ctx: number, dqDc: number, dqAc: number, n: number, out: buffer, o: number): number + local tb = t * 8 + local p = ((tb + BANDS[n + 1]) * 3 + ctx) * 11 + while n < 16 do + if getBit(br, P[p + 1]) == 0 then + return n + end + while getBit(br, P[p + 2]) == 0 do + n += 1 + if n == 16 then + return 16 + end + p = (tb + BANDS[n + 1]) * 33 + end + local nb = (tb + BANDS[n + 2]) * 3 + local v + if getBit(br, P[p + 3]) == 0 then + v = 1 + p = (nb + 1) * 11 + else + v = getLargeValue(br, P, p) + p = (nb + 2) * 11 + end + if getBit(br, 0x80) == 1 then + v = -v + end + writei16(out, o + ZIGZAG[n + 1] * 2, v * (if n > 0 then dqAc else dqDc)) + n += 1 + end + return 16 +end + +local function nzCode(acc: number, nz: number, dcNz: number): number + return acc * 4 + (if nz > 3 then 3 elseif nz > 1 then 2 else dcNz) +end + +-- the inverse Walsh-Hadamard transform of the 16 Y2 coefficients into the DC of the 16 luma blocks +local whtTmp = table.create(16, 0) +local function transformWHT(inp: buffer, out: buffer, o: number) + for i = 0, 3 do + local i0, i4, i8, i12 = readi16(inp, i * 2), readi16(inp, (4 + i) * 2), readi16(inp, (8 + i) * 2), readi16(inp, (12 + i) * 2) + local a0 = i0 + i12 + local a1 = i4 + i8 + local a2 = i4 - i8 + local a3 = i0 - i12 + whtTmp[1 + i] = a0 + a1 + whtTmp[9 + i] = a0 - a1 + whtTmp[5 + i] = a3 + a2 + whtTmp[13 + i] = a3 - a2 + end + for i = 0, 3 do + local dc = whtTmp[1 + i * 4] + 3 + local a0 = dc + whtTmp[4 + i * 4] + local a1 = whtTmp[2 + i * 4] + whtTmp[3 + i * 4] + local a2 = whtTmp[2 + i * 4] - whtTmp[3 + i * 4] + local a3 = dc - whtTmp[4 + i * 4] + local base = o + i * 128 + writei16(out, base, (a0 + a1) // 8) + writei16(out, base + 32, (a3 + a2) // 8) + writei16(out, base + 64, (a0 - a1) // 8) + writei16(out, base + 96, (a3 - a2) // 8) + end +end + +-- ------------------------------------------------------------------------------------------------ reconstruction +-- the work buffer of libwebp (yuv_b): BPS = 32, Y at row 1 column 8, U and V below it side by side +local BPS = 32 +local Y_OFF = BPS + 8 +local U_OFF = Y_OFF + BPS * 16 + BPS +local V_OFF = U_OFF + 16 +local YUV_SIZE = BPS * 17 + BPS * 9 + +local function clip8(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +-- the inverse DCT of one block (libwebp TransformOne) added to dst +local C1, C2 = 20091, 35468 +local idctTmp = table.create(16, 0) +local function mul1(a: number): number + return ((a * C1) // 65536) + a +end +local function mul2(a: number): number + return (a * C2) // 65536 +end +local function transformOne(c: buffer, o: number, b: buffer, dst: number) + for i = 0, 3 do + local i0, i4, i8, i12 = readi16(c, o + i * 2), readi16(c, o + (4 + i) * 2), readi16(c, o + (8 + i) * 2), readi16(c, o + (12 + i) * 2) + local a = i0 + i8 + local bb = i0 - i8 + local cc = mul2(i4) - mul1(i12) + local d = mul1(i4) + mul2(i12) + idctTmp[i * 4 + 1] = a + d + idctTmp[i * 4 + 2] = bb + cc + idctTmp[i * 4 + 3] = bb - cc + idctTmp[i * 4 + 4] = a - d + end + for i = 0, 3 do + local dc = idctTmp[i + 1] + 4 + local a = dc + idctTmp[i + 9] + local bb = dc - idctTmp[i + 9] + local cc = mul2(idctTmp[i + 5]) - mul1(idctTmp[i + 13]) + local d = mul1(idctTmp[i + 5]) + mul2(idctTmp[i + 13]) + local row = dst + i * BPS + writeu8(b, row, clip8(readu8(b, row) + (a + d) // 8)) + writeu8(b, row + 1, clip8(readu8(b, row + 1) + (bb + cc) // 8)) + writeu8(b, row + 2, clip8(readu8(b, row + 2) + (bb - cc) // 8)) + writeu8(b, row + 3, clip8(readu8(b, row + 3) + (a - d) // 8)) + end +end + +local function transformDC(c: buffer, o: number, b: buffer, dst: number) + local dc = (readi16(c, o) + 4) // 8 + for j = 0, 3 do + local row = dst + j * BPS + for i = row, row + 3 do + writeu8(b, i, clip8(readu8(b, i) + dc)) + end + end +end + +-- code: 3 = full transform, 2 = only the first three coefficients (the same result as the full one), 1 = DC only +local function doTransform(code: number, c: buffer, o: number, b: buffer, dst: number) + if code >= 2 then + transformOne(c, o, b, dst) + elseif code == 1 then + transformDC(c, o, b, dst) + end +end + +local function doUVTransform(bits: number, c: buffer, o: number, b: buffer, dst: number) + if band(bits, 0xff) ~= 0 then + if band(bits, 0xaa) ~= 0 then + transformOne(c, o, b, dst) + transformOne(c, o + 32, b, dst + 4) + transformOne(c, o + 64, b, dst + 4 * BPS) + transformOne(c, o + 96, b, dst + 4 * BPS + 4) + else + if readi16(c, o) ~= 0 then + transformDC(c, o, b, dst) + end + if readi16(c, o + 32) ~= 0 then + transformDC(c, o + 32, b, dst + 4) + end + if readi16(c, o + 64) ~= 0 then + transformDC(c, o + 64, b, dst + 4 * BPS) + end + if readi16(c, o + 96) ~= 0 then + transformDC(c, o + 96, b, dst + 4 * BPS + 4) + end + end + end +end + +-- prediction: modes 0 DC, 1 TM, 2 VE, 3 HE; 4 DC no top, 5 DC no left, 6 DC no top-left (16x16 and chroma) +local function fill(b: buffer, dst: number, size: number, v: number) + for j = 0, size - 1 do + bfill(b, dst + j * BPS, v, size) + end +end + +local function trueMotion(b: buffer, dst: number, size: number) + local tl = readu8(b, dst - BPS - 1) + for y = 0, size - 1 do + local row = dst + y * BPS + local l = readu8(b, row - 1) - tl + for x = 0, size - 1 do + writeu8(b, row + x, clip8(readu8(b, dst - BPS + x) + l)) + end + end +end + +local function predictBlock(b: buffer, dst: number, size: number, mode: number) + local shift = if size == 16 then 5 else 4 + if mode == 0 then + local dc = size + for j = 0, size - 1 do + dc += readu8(b, dst - 1 + j * BPS) + readu8(b, dst + j - BPS) + end + fill(b, dst, size, rshift(dc, shift)) + elseif mode == 1 then + trueMotion(b, dst, size) + elseif mode == 2 then + for j = 0, size - 1 do + bcopy(b, dst + j * BPS, b, dst - BPS, size) + end + elseif mode == 3 then + for j = 0, size - 1 do + bfill(b, dst + j * BPS, readu8(b, dst + j * BPS - 1), size) + end + elseif mode == 4 then -- no top: left samples + local dc = size // 2 + for j = 0, size - 1 do + dc += readu8(b, dst - 1 + j * BPS) + end + fill(b, dst, size, rshift(dc, shift - 1)) + elseif mode == 5 then -- no left: top samples + local dc = size // 2 + for j = 0, size - 1 do + dc += readu8(b, dst + j - BPS) + end + fill(b, dst, size, rshift(dc, shift - 1)) + else + fill(b, dst, size, 0x80) + end +end + +local function avg3(a: number, b: number, c: number): number + return rshift(a + 2 * b + c + 2, 2) +end +local function avg2(a: number, b: number): number + return rshift(a + b + 1, 1) +end + +-- 4x4 prediction (libwebp VP8PredLuma4): 0 DC, 1 TM, 2 VE, 3 HE, 4 RD, 5 VR, 6 LD, 7 VL, 8 HD, 9 HU +local function predict4(b: buffer, dst: number, mode: number) + local function put(x: number, y: number, v: number) + writeu8(b, dst + x + y * BPS, v) + end + if mode == 0 then + local dc = 4 + for i = 0, 3 do + dc += readu8(b, dst + i - BPS) + readu8(b, dst - 1 + i * BPS) + end + fill(b, dst, 4, rshift(dc, 3)) + elseif mode == 1 then + trueMotion(b, dst, 4) + elseif mode == 2 then + local t = dst - BPS + local x, a, bb, c, d, e = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3), readu8(b, t + 4) + local v0, v1, v2, v3 = avg3(x, a, bb), avg3(a, bb, c), avg3(bb, c, d), avg3(c, d, e) + for j = 0, 3 do + put(0, j, v0) + put(1, j, v1) + put(2, j, v2) + put(3, j, v3) + end + elseif mode == 3 then + local A, B, C, D = readu8(b, dst - 1 - BPS), readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS) + local E = readu8(b, dst - 1 + 3 * BPS) + bfill(b, dst, avg3(A, B, C), 4) + bfill(b, dst + BPS, avg3(B, C, D), 4) + bfill(b, dst + 2 * BPS, avg3(C, D, E), 4) + bfill(b, dst + 3 * BPS, avg3(D, E, E), 4) + else + local I, J, K, L = readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS), readu8(b, dst - 1 + 3 * BPS) + local t = dst - BPS + local X, A, B, C, D = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3) + local E, F, G, H = readu8(b, t + 4), readu8(b, t + 5), readu8(b, t + 6), readu8(b, t + 7) + if mode == 4 then -- RD + put(0, 3, avg3(J, K, L)) + local v = avg3(I, J, K) + put(1, 3, v) + put(0, 2, v) + v = avg3(X, I, J) + put(2, 3, v) + put(1, 2, v) + put(0, 1, v) + v = avg3(A, X, I) + put(3, 3, v) + put(2, 2, v) + put(1, 1, v) + put(0, 0, v) + v = avg3(B, A, X) + put(3, 2, v) + put(2, 1, v) + put(1, 0, v) + v = avg3(C, B, A) + put(3, 1, v) + put(2, 0, v) + put(3, 0, avg3(D, C, B)) + elseif mode == 5 then -- VR + local v = avg2(X, A) + put(0, 0, v) + put(1, 2, v) + v = avg2(A, B) + put(1, 0, v) + put(2, 2, v) + v = avg2(B, C) + put(2, 0, v) + put(3, 2, v) + put(3, 0, avg2(C, D)) + put(0, 3, avg3(K, J, I)) + put(0, 2, avg3(J, I, X)) + v = avg3(I, X, A) + put(0, 1, v) + put(1, 3, v) + v = avg3(X, A, B) + put(1, 1, v) + put(2, 3, v) + v = avg3(A, B, C) + put(2, 1, v) + put(3, 3, v) + put(3, 1, avg3(B, C, D)) + elseif mode == 6 then -- LD + put(0, 0, avg3(A, B, C)) + local v = avg3(B, C, D) + put(1, 0, v) + put(0, 1, v) + v = avg3(C, D, E) + put(2, 0, v) + put(1, 1, v) + put(0, 2, v) + v = avg3(D, E, F) + put(3, 0, v) + put(2, 1, v) + put(1, 2, v) + put(0, 3, v) + v = avg3(E, F, G) + put(3, 1, v) + put(2, 2, v) + put(1, 3, v) + v = avg3(F, G, H) + put(3, 2, v) + put(2, 3, v) + put(3, 3, avg3(G, H, H)) + elseif mode == 7 then -- VL + put(0, 0, avg2(A, B)) + local v = avg2(B, C) + put(1, 0, v) + put(0, 2, v) + v = avg2(C, D) + put(2, 0, v) + put(1, 2, v) + v = avg2(D, E) + put(3, 0, v) + put(2, 2, v) + put(0, 1, avg3(A, B, C)) + v = avg3(B, C, D) + put(1, 1, v) + put(0, 3, v) + v = avg3(C, D, E) + put(2, 1, v) + put(1, 3, v) + v = avg3(D, E, F) + put(3, 1, v) + put(2, 3, v) + put(3, 2, avg3(E, F, G)) + put(3, 3, avg3(F, G, H)) + elseif mode == 8 then -- HD + local v = avg2(I, X) + put(0, 0, v) + put(2, 1, v) + v = avg2(J, I) + put(0, 1, v) + put(2, 2, v) + v = avg2(K, J) + put(0, 2, v) + put(2, 3, v) + put(0, 3, avg2(L, K)) + put(3, 0, avg3(A, B, C)) + put(2, 0, avg3(X, A, B)) + v = avg3(I, X, A) + put(1, 0, v) + put(3, 1, v) + v = avg3(J, I, X) + put(1, 1, v) + put(3, 2, v) + v = avg3(K, J, I) + put(1, 2, v) + put(3, 3, v) + put(1, 3, avg3(L, K, J)) + else -- HU + put(0, 0, avg2(I, J)) + local v = avg2(J, K) + put(2, 0, v) + put(0, 1, v) + v = avg2(K, L) + put(2, 1, v) + put(0, 2, v) + put(1, 0, avg3(I, J, K)) + v = avg3(J, K, L) + put(3, 0, v) + put(1, 1, v) + v = avg3(K, L, L) + put(3, 1, v) + put(1, 2, v) + put(3, 2, L) + put(2, 2, L) + put(0, 3, L) + put(1, 3, L) + put(2, 3, L) + put(3, 3, L) + end + end +end + +local function checkMode(mbx: number, mby: number, mode: number): number + if mode == 0 then + if mbx == 0 then + return if mby == 0 then 6 else 5 + end + return if mby == 0 then 4 else 0 + end + return mode +end + +-- ------------------------------------------------------------------------------------------------ loop filter +local function sclip1(v: number): number + return if v < -128 then -128 elseif v > 127 then 127 else v +end +local function sclip2(v: number): number + return if v < -16 then -16 elseif v > 15 then 15 else v +end + +local function doFilter2(b: buffer, p: number, step: number) + local p1, p0, q0, q1 = readu8(b, p - 2 * step), readu8(b, p - step), readu8(b, p), readu8(b, p + step) + local a = 3 * (q0 - p0) + sclip1(p1 - q1) + local a1 = sclip2((a + 4) // 8) + local a2 = sclip2((a + 3) // 8) + writeu8(b, p - step, clip8(p0 + a2)) + writeu8(b, p, clip8(q0 - a1)) +end + +local function doFilter4(b: buffer, p: number, step: number) + local p1, p0, q0, q1 = readu8(b, p - 2 * step), readu8(b, p - step), readu8(b, p), readu8(b, p + step) + local a = 3 * (q0 - p0) + local a1 = sclip2((a + 4) // 8) + local a2 = sclip2((a + 3) // 8) + local a3 = (a1 + 1) // 2 + writeu8(b, p - 2 * step, clip8(p1 + a3)) + writeu8(b, p - step, clip8(p0 + a2)) + writeu8(b, p, clip8(q0 - a1)) + writeu8(b, p + step, clip8(q1 - a3)) +end + +local function doFilter6(b: buffer, p: number, step: number) + local p2, p1, p0 = readu8(b, p - 3 * step), readu8(b, p - 2 * step), readu8(b, p - step) + local q0, q1, q2 = readu8(b, p), readu8(b, p + step), readu8(b, p + 2 * step) + local a = sclip1(3 * (q0 - p0) + sclip1(p1 - q1)) + local a1 = (27 * a + 63) // 128 + local a2 = (18 * a + 63) // 128 + local a3 = (9 * a + 63) // 128 + writeu8(b, p - 3 * step, clip8(p2 + a3)) + writeu8(b, p - 2 * step, clip8(p1 + a2)) + writeu8(b, p - step, clip8(p0 + a1)) + writeu8(b, p, clip8(q0 - a1)) + writeu8(b, p + step, clip8(q1 - a2)) + writeu8(b, p + 2 * step, clip8(q2 - a3)) +end + +local function simpleFilter(b: buffer, p: number, step: number, along: number, thresh: number) + local t2 = 2 * thresh + 1 + for i = 0, 15 do + local q = p + i * along + local p1, p0, q0, q1 = readu8(b, q - 2 * step), readu8(b, q - step), readu8(b, q), readu8(b, q + step) + if 4 * abs(p0 - q0) + abs(p1 - q1) <= t2 then + doFilter2(b, q, step) + end + end +end + +-- filterLoop(b, p, hstride, vstride, size, thresh, ithresh, hevThresh, six): FilterLoop26 (six) / FilterLoop24 +local function filterLoop(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number, six: boolean) + local t2 = 2 * thresh + 1 + for _ = 1, size do + local p3, p2, p1, p0 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs), readu8(b, p - 2 * hs), readu8(b, p - hs) + local q0, q1, q2, q3 = readu8(b, p), readu8(b, p + hs), readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) + if 4 * abs(p0 - q0) + abs(p1 - q1) <= t2 and abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(p1 - p0) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it and abs(q1 - q0) <= it then + if abs(p1 - p0) > hevT or abs(q1 - q0) > hevT then + doFilter2(b, p, hs) + elseif six then + doFilter6(b, p, hs) + else + doFilter4(b, p, hs) + end + end + p += vs + end +end + +-- ------------------------------------------------------------------------------------------------ frame +export type Frame = { + width: number, + height: number, + y: buffer, -- width * height + u: buffer, -- ceil(w / 2) * ceil(h / 2) + v: buffer, + header: any, +} + +-- decodeFrame(state, buf, off, len, maxPixels) -> Frame | nil, message +function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, maxPixels: number): (Frame?, string?) + local hdr, herr = Decode.header(buf, off, len) + if not hdr then + return nil, herr + end + if not hdr.keyFrame then + return nil, "unsupported: inter frames" + end + if not hdr.show then + return nil, "unsupported: invisible frame" + end + local width, height = hdr.width, hdr.height + if width == 0 or height == 0 then + return nil, "zero frame size" + end + if width * height > maxPixels then + return nil, "limit: " .. width .. " x " .. height .. " is over maxPixels" + end + st.width, st.height = width, height + local p = off + 10 + local left = len - 10 + if hdr.partitionLength > left then + return nil, "truncated: first partition" + end + -- key frame: reset the probabilities and the segment header + st.segProba = { 255, 255, 255 } + st.useSegment, st.updateMap, st.absoluteDelta = false, false, true + st.segQuant = { 0, 0, 0, 0 } + st.segFilter = { 0, 0, 0, 0 } + local br = newBr(buf, p, hdr.partitionLength) + p += hdr.partitionLength + left -= hdr.partitionLength + getValue(br, 1) -- colour space + getValue(br, 1) -- clamping type + -- segment header + st.useSegment = getValue(br, 1) == 1 + if st.useSegment then + st.updateMap = getValue(br, 1) == 1 + if getValue(br, 1) == 1 then + st.absoluteDelta = getValue(br, 1) == 1 + for s = 1, 4 do + st.segQuant[s] = if getValue(br, 1) == 1 then getSignedValue(br, 7) else 0 + end + for s = 1, 4 do + st.segFilter[s] = if getValue(br, 1) == 1 then getSignedValue(br, 6) else 0 + end + end + if st.updateMap then + for s = 1, 3 do + st.segProba[s] = if getValue(br, 1) == 1 then getValue(br, 8) else 255 + end + end + else + st.updateMap = false + end + if br.eof then + return nil, "truncated: segment header" + end + -- filter header + local simple = getValue(br, 1) == 1 + local level = getValue(br, 6) + local sharpness = getValue(br, 3) + local useLfDelta = getValue(br, 1) == 1 + if useLfDelta then + if getValue(br, 1) == 1 then + for i = 1, 4 do + if getValue(br, 1) == 1 then + st.refLfDelta[i] = getSignedValue(br, 6) + end + end + for i = 1, 4 do + if getValue(br, 1) == 1 then + st.modeLfDelta[i] = getSignedValue(br, 6) + end + end + end + end + local filterType = if level == 0 then 0 elseif simple then 1 else 2 + if br.eof then + return nil, "truncated: filter header" + end + -- partitions + local numParts = lshift(1, getValue(br, 2)) + local lastPart = numParts - 1 + if left < 3 * lastPart then + return nil, "truncated: partition sizes" + end + local parts: { Br } = {} + local partStart = p + lastPart * 3 + local sizeLeft = left - lastPart * 3 + for k = 0, lastPart - 1 do + local q = p + k * 3 + local psize = readu8(buf, q) + readu8(buf, q + 1) * 256 + readu8(buf, q + 2) * 65536 + if psize > sizeLeft then + psize = sizeLeft + end + parts[k + 1] = newBr(buf, partStart, psize) + partStart += psize + sizeLeft -= psize + end + parts[numParts] = newBr(buf, partStart, sizeLeft) + if partStart >= off + len then + return nil, "truncated: partitions" + end + -- quantizers + local baseQ = getValue(br, 7) + local dqy1dc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local dqy2dc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local dqy2ac = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local dquvdc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local dquvac = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local quants: { Quant } = {} + for s = 1, 4 do + local q + if st.useSegment then + q = st.segQuant[s] + if not st.absoluteDelta then + q += baseQ + end + else + q = baseQ + end + local function cq(v: number, m: number): number + return if v < 0 then 0 elseif v > m then m else v + end + local y2ac = (AC_TABLE[cq(q + dqy2ac, 127) + 1] * 101581) // 65536 + if y2ac < 8 then + y2ac = 8 + end + quants[s] = { + y1dc = DC_TABLE[cq(q + dqy1dc, 127) + 1], + y1ac = AC_TABLE[cq(q, 127) + 1], + y2dc = DC_TABLE[cq(q + dqy2dc, 127) + 1] * 2, + y2ac = y2ac, + uvdc = DC_TABLE[cq(q + dquvdc, 117) + 1], + uvac = AC_TABLE[cq(q + dquvac, 127) + 1], + } + end + getValue(br, 1) -- refresh entropy probabilities (ignored, as libwebp does) + -- token probabilities + local P = st.proba + for i = 1, 1056 do + P[i] = if getBit(br, COEFF_UPDATE_PROBA[i]) == 1 then getValue(br, 8) else COEFF_PROBA0[i] + end + local useSkip = getValue(br, 1) == 1 + local skipP = if useSkip then getValue(br, 8) else 0 + if br.eof then + return nil, "truncated: frame header" + end + + -- filter strengths per segment and i4x4: { limit, ilevel, hevThresh } + local fstr: { { number } } = {} + for s = 1, 4 do + local base + if st.useSegment then + base = st.segFilter[s] + if not st.absoluteDelta then + base += level + end + else + base = level + end + for i4 = 0, 1 do + local lv = base + if useLfDelta then + lv += st.refLfDelta[1] + if i4 == 1 then + lv += st.modeLfDelta[1] + end + end + lv = if lv < 0 then 0 elseif lv > 63 then 63 else lv + local e = { 0, 0, 0 } + if lv > 0 then + local il = lv + if sharpness > 0 then + if sharpness > 4 then + il = rshift(il, 2) + else + il = rshift(il, 1) + end + if il > 9 - sharpness then + il = 9 - sharpness + end + end + if il < 1 then + il = 1 + end + e[1] = 2 * lv + il + e[2] = il + e[3] = if lv >= 40 then 2 elseif lv >= 15 then 1 else 0 + end + fstr[(s - 1) * 2 + i4 + 1] = e + end + end + + -- the frame, macroblock aligned + local mbw, mbh = (width + 15) // 16, (height + 15) // 16 + local ys, uvs = mbw * 16, mbw * 8 + local Y = bcreate(ys * mbh * 16) + local U = bcreate(uvs * mbh * 8) + local V = bcreate(uvs * mbh * 8) + local topY, topU, topV = bcreate(ys), bcreate(uvs), bcreate(uvs) + local yuv = bcreate(YUV_SIZE) + local coeffs = bcreate(mbw * 768) + local dcb = bcreate(32) + -- per macroblock column / row state + local intraT = table.create(mbw * 4, 0) + local intraL = table.create(4, 0) + local topNz = table.create(mbw, 0) + local topNzDc = table.create(mbw, 0) + local mbI4 = table.create(mbw, false) + local mbModes = table.create(mbw * 16, 0) + local mbUv = table.create(mbw, 0) + local mbSeg = table.create(mbw, 0) + local mbSkip = table.create(mbw, 0) + local mbNzY = table.create(mbw, 0) + local mbNzUv = table.create(mbw, 0) + -- filter info for the whole frame: limit, ilevel, inner, hev per macroblock + local fLimit = table.create(mbw * mbh, 0) + local fIlevel = table.create(mbw * mbh, 0) + local fInner = table.create(mbw * mbh, 0) + local fHev = table.create(mbw * mbh, 0) + local segProba = st.segProba + + for mby = 0, mbh - 1 do + local tbr = parts[band(mby, lastPart) + 1] + -- intra modes of the row (first partition) + for k = 1, 4 do + intraL[k] = 0 + end + for mbx = 0, mbw - 1 do + local seg = 0 + if st.updateMap then + if getBit(br, segProba[1]) == 0 then + seg = getBit(br, segProba[2]) + else + seg = getBit(br, segProba[3]) + 2 + end + end + mbSeg[mbx + 1] = seg + mbSkip[mbx + 1] = if useSkip then getBit(br, skipP) else 0 + local i4 = getBit(br, 145) == 0 + mbI4[mbx + 1] = i4 + local t0 = mbx * 4 + if not i4 then + local ymode + if getBit(br, 156) == 1 then + ymode = if getBit(br, 128) == 1 then 1 else 3 + else + ymode = if getBit(br, 163) == 1 then 2 else 0 + end + mbModes[mbx * 16 + 1] = ymode + for k = 1, 4 do + intraT[t0 + k] = ymode + intraL[k] = ymode + end + else + for y = 0, 3 do + local ymode = intraL[y + 1] + for x = 0, 3 do + local pr = (intraT[t0 + x + 1] * 10 + ymode) * 9 + if getBit(br, BMODES_PROBA[pr + 1]) == 0 then + ymode = 0 + elseif getBit(br, BMODES_PROBA[pr + 2]) == 0 then + ymode = 1 + elseif getBit(br, BMODES_PROBA[pr + 3]) == 0 then + ymode = 2 + elseif getBit(br, BMODES_PROBA[pr + 4]) == 0 then + if getBit(br, BMODES_PROBA[pr + 5]) == 0 then + ymode = 3 + elseif getBit(br, BMODES_PROBA[pr + 6]) == 0 then + ymode = 4 + else + ymode = 5 + end + elseif getBit(br, BMODES_PROBA[pr + 7]) == 0 then + ymode = 6 + elseif getBit(br, BMODES_PROBA[pr + 8]) == 0 then + ymode = 7 + elseif getBit(br, BMODES_PROBA[pr + 9]) == 0 then + ymode = 8 + else + ymode = 9 + end + intraT[t0 + x + 1] = ymode + mbModes[mbx * 16 + y * 4 + x + 1] = ymode + end + intraL[y + 1] = ymode + end + end + if getBit(br, 142) == 0 then + mbUv[mbx + 1] = 0 + elseif getBit(br, 114) == 0 then + mbUv[mbx + 1] = 2 + else + mbUv[mbx + 1] = if getBit(br, 183) == 1 then 1 else 3 + end + end + if br.eof then + return nil, "truncated: first partition (intra modes)" + end + + -- residuals (token partition) + local leftNz, leftNzDc = 0, 0 + for mbx = 0, mbw - 1 do + local x1 = mbx + 1 + local q = quants[mbSeg[x1] + 1] + local skip = mbSkip[x1] + local i4 = mbI4[x1] + if skip == 0 then + local co = mbx * 768 + bfill(coeffs, co, 0, 768) + local first, acType + if not i4 then + bfill(dcb, 0, 0, 32) + local ctx = topNzDc[x1] + leftNzDc + local nz = getCoeffs(tbr, P, 1, ctx, q.y2dc, q.y2ac, 0, dcb, 0) + local f = if nz > 0 then 1 else 0 + topNzDc[x1] = f + leftNzDc = f + if nz > 1 then + transformWHT(dcb, coeffs, co) + else + local dc0 = (readi16(dcb, 0) + 3) // 8 + for i = 0, 15 do + writei16(coeffs, co + i * 32, dc0) + end + end + first, acType = 1, 0 + else + first, acType = 0, 3 + end + local tnz = band(topNz[x1], 0x0f) + local lnz = band(leftNz, 0x0f) + local nzY = 0 + local dst = co + for _ = 0, 3 do + local l = band(lnz, 1) + local acc = 0 + for _ = 0, 3 do + local ctx = l + band(tnz, 1) + local nz = getCoeffs(tbr, P, acType, ctx, q.y1dc, q.y1ac, first, coeffs, dst) + l = if nz > first then 1 else 0 + tnz = bor(rshift(tnz, 1), l * 128) + acc = nzCode(acc, nz, if readi16(coeffs, dst) ~= 0 then 1 else 0) + dst += 32 + end + tnz = rshift(tnz, 4) + lnz = bor(rshift(lnz, 1), l * 128) + nzY = nzY * 256 + acc + end + local outT = tnz + local outL = rshift(lnz, 4) + local nzUv = 0 + for ch = 0, 2, 2 do + local acc = 0 + tnz = band(rshift(topNz[x1], 4 + ch), 255) + lnz = band(rshift(leftNz, 4 + ch), 255) + for _ = 0, 1 do + local l = band(lnz, 1) + for _ = 0, 1 do + local ctx = l + band(tnz, 1) + local nz = getCoeffs(tbr, P, 2, ctx, q.uvdc, q.uvac, 0, coeffs, dst) + l = if nz > 0 then 1 else 0 + tnz = bor(rshift(tnz, 1), l * 8) + acc = nzCode(acc, nz, if readi16(coeffs, dst) ~= 0 then 1 else 0) + dst += 32 + end + tnz = rshift(tnz, 2) + lnz = bor(rshift(lnz, 1), l * 32) + end + nzUv = bor(nzUv, lshift(acc, 4 * ch)) + outT = bor(outT, lshift(lshift(tnz, 4), ch)) + outL = bor(outL, lshift(band(lnz, 0xf0), ch)) + end + topNz[x1] = band(outT, 255) + leftNz = band(outL, 255) + mbNzY[x1] = nzY + mbNzUv[x1] = nzUv + skip = if nzY == 0 and nzUv == 0 then 1 else 0 + else + topNz[x1] = 0 + leftNz = 0 + if not i4 then + topNzDc[x1] = 0 + leftNzDc = 0 + end + mbNzY[x1] = 0 + mbNzUv[x1] = 0 + end + if filterType > 0 then + local e = fstr[mbSeg[x1] * 2 + (if i4 then 1 else 0) + 1] + local fi = mby * mbw + x1 + fLimit[fi] = e[1] + fIlevel[fi] = e[2] + fHev[fi] = e[3] + fInner[fi] = if i4 or skip == 0 then 1 else 0 + end + if tbr.eof then + return nil, "truncated: token partition" + end + end + + -- reconstruct the row (libwebp ReconstructRow) + for j = 0, 15 do + writeu8(yuv, Y_OFF + j * BPS - 1, 129) + end + for j = 0, 7 do + writeu8(yuv, U_OFF + j * BPS - 1, 129) + writeu8(yuv, V_OFF + j * BPS - 1, 129) + end + if mby > 0 then + writeu8(yuv, Y_OFF - 1 - BPS, 129) + writeu8(yuv, U_OFF - 1 - BPS, 129) + writeu8(yuv, V_OFF - 1 - BPS, 129) + else + bfill(yuv, Y_OFF - BPS - 1, 127, 16 + 4 + 1) + bfill(yuv, U_OFF - BPS - 1, 127, 8 + 1) + bfill(yuv, V_OFF - BPS - 1, 127, 8 + 1) + end + for mbx = 0, mbw - 1 do + local x1 = mbx + 1 + if mbx > 0 then + for j = -1, 15 do + bcopy(yuv, Y_OFF + j * BPS - 4, yuv, Y_OFF + j * BPS + 12, 4) + end + for j = -1, 7 do + bcopy(yuv, U_OFF + j * BPS - 4, yuv, U_OFF + j * BPS + 4, 4) + bcopy(yuv, V_OFF + j * BPS - 4, yuv, V_OFF + j * BPS + 4, 4) + end + end + if mby > 0 then + bcopy(yuv, Y_OFF - BPS, topY, mbx * 16, 16) + bcopy(yuv, U_OFF - BPS, topU, mbx * 8, 8) + bcopy(yuv, V_OFF - BPS, topV, mbx * 8, 8) + end + local co = mbx * 768 + local bits = mbNzY[x1] + if mbI4[x1] then + local tr = Y_OFF - BPS + 16 + if mby > 0 then + if mbx >= mbw - 1 then + bfill(yuv, tr, readu8(topY, mbx * 16 + 15), 4) + else + bcopy(yuv, tr, topY, mbx * 16 + 16, 4) + end + end + bcopy(yuv, tr + 4 * BPS, yuv, tr, 4) + bcopy(yuv, tr + 8 * BPS, yuv, tr, 4) + bcopy(yuv, tr + 12 * BPS, yuv, tr, 4) + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS + predict4(yuv, dst, mbModes[mbx * 16 + n + 1]) + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + else + predictBlock(yuv, Y_OFF, 16, checkMode(mbx, mby, mbModes[mbx * 16 + 1])) + if bits ~= 0 then + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + end + end + local uvm = checkMode(mbx, mby, mbUv[x1]) + predictBlock(yuv, U_OFF, 8, uvm) + predictBlock(yuv, V_OFF, 8, uvm) + local buv = mbNzUv[x1] + doUVTransform(buv, coeffs, co + 16 * 32, yuv, U_OFF) + doUVTransform(rshift(buv, 8), coeffs, co + 20 * 32, yuv, V_OFF) + if mby < mbh - 1 then + bcopy(topY, mbx * 16, yuv, Y_OFF + 15 * BPS, 16) + bcopy(topU, mbx * 8, yuv, U_OFF + 7 * BPS, 8) + bcopy(topV, mbx * 8, yuv, V_OFF + 7 * BPS, 8) + end + local yo = mby * 16 * ys + mbx * 16 + for j = 0, 15 do + bcopy(Y, yo + j * ys, yuv, Y_OFF + j * BPS, 16) + end + local uo = mby * 8 * uvs + mbx * 8 + for j = 0, 7 do + bcopy(U, uo + j * uvs, yuv, U_OFF + j * BPS, 8) + bcopy(V, uo + j * uvs, yuv, V_OFF + j * BPS, 8) + end + end + end + + -- loop filter over the whole frame, macroblocks in raster order (libwebp DoFilter) + if filterType > 0 then + for mby = 0, mbh - 1 do + for mbx = 0, mbw - 1 do + local fi = mby * mbw + mbx + 1 + local limit = fLimit[fi] + if limit ~= 0 then + local inner = fInner[fi] == 1 + local yp = mby * 16 * ys + mbx * 16 + if filterType == 1 then + if mbx > 0 then + simpleFilter(Y, yp, 1, ys, limit + 4) + end + if inner then + for k = 1, 3 do + simpleFilter(Y, yp + 4 * k, 1, ys, limit) + end + end + if mby > 0 then + simpleFilter(Y, yp, ys, 1, limit + 4) + end + if inner then + for k = 1, 3 do + simpleFilter(Y, yp + 4 * k * ys, ys, 1, limit) + end + end + else + local il, hev = fIlevel[fi], fHev[fi] + local up = mby * 8 * uvs + mbx * 8 + if mbx > 0 then + filterLoop(Y, yp, 1, ys, 16, limit + 4, il, hev, true) + filterLoop(U, up, 1, uvs, 8, limit + 4, il, hev, true) + filterLoop(V, up, 1, uvs, 8, limit + 4, il, hev, true) + end + if inner then + for k = 1, 3 do + filterLoop(Y, yp + 4 * k, 1, ys, 16, limit, il, hev, false) + end + filterLoop(U, up + 4, 1, uvs, 8, limit, il, hev, false) + filterLoop(V, up + 4, 1, uvs, 8, limit, il, hev, false) + end + if mby > 0 then + filterLoop(Y, yp, ys, 1, 16, limit + 4, il, hev, true) + filterLoop(U, up, uvs, 1, 8, limit + 4, il, hev, true) + filterLoop(V, up, uvs, 1, 8, limit + 4, il, hev, true) + end + if inner then + for k = 1, 3 do + filterLoop(Y, yp + 4 * k * ys, ys, 1, 16, limit, il, hev, false) + end + filterLoop(U, up + 4 * uvs, uvs, 1, 8, limit, il, hev, false) + filterLoop(V, up + 4 * uvs, uvs, 1, 8, limit, il, hev, false) + end + end + end + end + end + end + + -- crop to the frame size + local cw, chh = (width + 1) // 2, (height + 1) // 2 + local oy = bcreate(width * height) + for j = 0, height - 1 do + bcopy(oy, j * width, Y, j * ys, width) + end + local ou, ov = bcreate(cw * chh), bcreate(cw * chh) + for j = 0, chh - 1 do + bcopy(ou, j * cw, U, j * uvs, cw) + bcopy(ov, j * cw, V, j * uvs, cw) + end + return { width = width, height = height, y = oy, u = ou, v = ov, header = hdr }, nil +end + +return Decode diff --git a/src/Formats/codecs/Vp8/Tables.luau b/src/Formats/codecs/Vp8/Tables.luau new file mode 100644 index 0000000..e8a9320 --- /dev/null +++ b/src/Formats/codecs/Vp8/Tables.luau @@ -0,0 +1,180 @@ +--!strict +-- codecs/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6 +-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Flat 1-based arrays. +local Tables = {} + +-- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1 +Tables.COEFF_PROBA0 = { + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128, + 189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128, 106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128, + 1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128, 181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128, + 78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128, 1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128, + 184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128, 77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128, + 1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128, 170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128, + 37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128, 1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128, + 207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128, 102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128, + 1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128, 177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128, + 80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62, 131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1, + 68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128, 1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128, + 184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128, 81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128, + 1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128, 99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128, + 23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128, 1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128, + 109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128, 44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128, + 1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128, 94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128, + 22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128, 1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128, + 124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128, 35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128, + 1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128, 121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128, + 45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128, 1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128, + 203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128, 137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128, + 253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128, 175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128, + 73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128, 1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128, + 239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128, 155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128, + 1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128, 201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128, + 69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128, 1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128, + 223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128, 141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128, + 1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128, 190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128, + 149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128, 240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128, 213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128, + 55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255, 126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128, + 61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128, 1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128, + 166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128, 39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128, + 1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128, 124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128, + 24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128, 1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128, + 149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128, 28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128, + 1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128, 123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128, + 20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128, 1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128, + 168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128, 47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128, + 1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128, 141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128, + 42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, +} +-- token probability update probabilities, same layout +Tables.COEFF_UPDATE_PROBA = { + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255, 249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255, 234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255, 250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255, + 234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255, + 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255, 234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255, + 251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255, + 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255, + 248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, + 246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255, + 255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255, 248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255, + 253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, +} +-- 4x4 intra mode probabilities [top 10][left 10][9]: index (top * 10 + left) * 9 + i + 1 +Tables.BMODES_PROBA = { + 231, 120, 48, 89, 115, 113, 120, 152, 112, 152, 179, 64, 126, 170, 118, 46, 70, 95, 175, 69, 143, 80, + 85, 82, 72, 155, 103, 56, 58, 10, 171, 218, 189, 17, 13, 152, 114, 26, 17, 163, 44, 195, 21, 10, + 173, 121, 24, 80, 195, 26, 62, 44, 64, 85, 144, 71, 10, 38, 171, 213, 144, 34, 26, 170, 46, 55, + 19, 136, 160, 33, 206, 71, 63, 20, 8, 114, 114, 208, 12, 9, 226, 81, 40, 11, 96, 182, 84, 29, + 16, 36, 134, 183, 89, 137, 98, 101, 106, 165, 148, 72, 187, 100, 130, 157, 111, 32, 75, 80, 66, 102, + 167, 99, 74, 62, 40, 234, 128, 41, 53, 9, 178, 241, 141, 26, 8, 107, 74, 43, 26, 146, 73, 166, + 49, 23, 157, 65, 38, 105, 160, 51, 52, 31, 115, 128, 104, 79, 12, 27, 217, 255, 87, 17, 7, 87, + 68, 71, 44, 114, 51, 15, 186, 23, 47, 41, 14, 110, 182, 183, 21, 17, 194, 66, 45, 25, 102, 197, + 189, 23, 18, 22, 88, 88, 147, 150, 42, 46, 45, 196, 205, 43, 97, 183, 117, 85, 38, 35, 179, 61, + 39, 53, 200, 87, 26, 21, 43, 232, 171, 56, 34, 51, 104, 114, 102, 29, 93, 77, 39, 28, 85, 171, + 58, 165, 90, 98, 64, 34, 22, 116, 206, 23, 34, 43, 166, 73, 107, 54, 32, 26, 51, 1, 81, 43, + 31, 68, 25, 106, 22, 64, 171, 36, 225, 114, 34, 19, 21, 102, 132, 188, 16, 76, 124, 62, 18, 78, + 95, 85, 57, 50, 48, 51, 193, 101, 35, 159, 215, 111, 89, 46, 111, 60, 148, 31, 172, 219, 228, 21, + 18, 111, 112, 113, 77, 85, 179, 255, 38, 120, 114, 40, 42, 1, 196, 245, 209, 10, 25, 109, 88, 43, + 29, 140, 166, 213, 37, 43, 154, 61, 63, 30, 155, 67, 45, 68, 1, 209, 100, 80, 8, 43, 154, 1, + 51, 26, 71, 142, 78, 78, 16, 255, 128, 34, 197, 171, 41, 40, 5, 102, 211, 183, 4, 1, 221, 51, + 50, 17, 168, 209, 192, 23, 25, 82, 138, 31, 36, 171, 27, 166, 38, 44, 229, 67, 87, 58, 169, 82, + 115, 26, 59, 179, 63, 59, 90, 180, 59, 166, 93, 73, 154, 40, 40, 21, 116, 143, 209, 34, 39, 175, + 47, 15, 16, 183, 34, 223, 49, 45, 183, 46, 17, 33, 183, 6, 98, 15, 32, 183, 57, 46, 22, 24, + 128, 1, 54, 17, 37, 65, 32, 73, 115, 28, 128, 23, 128, 205, 40, 3, 9, 115, 51, 192, 18, 6, + 223, 87, 37, 9, 115, 59, 77, 64, 21, 47, 104, 55, 44, 218, 9, 54, 53, 130, 226, 64, 90, 70, + 205, 40, 41, 23, 26, 57, 54, 57, 112, 184, 5, 41, 38, 166, 213, 30, 34, 26, 133, 152, 116, 10, + 32, 134, 39, 19, 53, 221, 26, 114, 32, 73, 255, 31, 9, 65, 234, 2, 15, 1, 118, 73, 75, 32, + 12, 51, 192, 255, 160, 43, 51, 88, 31, 35, 67, 102, 85, 55, 186, 85, 56, 21, 23, 111, 59, 205, + 45, 37, 192, 55, 38, 70, 124, 73, 102, 1, 34, 98, 125, 98, 42, 88, 104, 85, 117, 175, 82, 95, + 84, 53, 89, 128, 100, 113, 101, 45, 75, 79, 123, 47, 51, 128, 81, 171, 1, 57, 17, 5, 71, 102, + 57, 53, 41, 49, 38, 33, 13, 121, 57, 73, 26, 1, 85, 41, 10, 67, 138, 77, 110, 90, 47, 114, + 115, 21, 2, 10, 102, 255, 166, 23, 6, 101, 29, 16, 10, 85, 128, 101, 196, 26, 57, 18, 10, 102, + 102, 213, 34, 20, 43, 117, 20, 15, 36, 163, 128, 68, 1, 26, 102, 61, 71, 37, 34, 53, 31, 243, + 192, 69, 60, 71, 38, 73, 119, 28, 222, 37, 68, 45, 128, 34, 1, 47, 11, 245, 171, 62, 17, 19, + 70, 146, 85, 55, 62, 70, 37, 43, 37, 154, 100, 163, 85, 160, 1, 63, 9, 92, 136, 28, 64, 32, + 201, 85, 75, 15, 9, 9, 64, 255, 184, 119, 16, 86, 6, 28, 5, 64, 255, 25, 248, 1, 56, 8, + 17, 132, 137, 255, 55, 116, 128, 58, 15, 20, 82, 135, 57, 26, 121, 40, 164, 50, 31, 137, 154, 133, + 25, 35, 218, 51, 103, 44, 131, 131, 123, 31, 6, 158, 86, 40, 64, 135, 148, 224, 45, 183, 128, 22, + 26, 17, 131, 240, 154, 14, 1, 209, 45, 16, 21, 91, 64, 222, 7, 1, 197, 56, 21, 39, 155, 60, + 138, 23, 102, 213, 83, 12, 13, 54, 192, 255, 68, 47, 28, 85, 26, 85, 85, 128, 128, 32, 146, 171, + 18, 11, 7, 63, 144, 171, 4, 4, 246, 35, 27, 10, 146, 174, 171, 12, 26, 128, 190, 80, 35, 99, + 180, 80, 126, 54, 45, 85, 126, 47, 87, 176, 51, 41, 20, 32, 101, 75, 128, 139, 118, 146, 116, 128, + 85, 56, 41, 15, 176, 236, 85, 37, 9, 62, 71, 30, 17, 119, 118, 255, 17, 18, 138, 101, 38, 60, + 138, 55, 70, 43, 26, 142, 146, 36, 19, 30, 171, 255, 97, 27, 20, 138, 45, 61, 62, 219, 1, 81, + 188, 64, 32, 41, 20, 117, 151, 142, 20, 21, 163, 112, 19, 12, 61, 195, 128, 48, 4, 24, +} +-- DC dequantization factors, index q + 1 (q 0..127) +Tables.DC_TABLE = { + 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, + 22, 22, 23, 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, + 82, 83, 84, 85, 86, 87, 88, 89, 91, 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, + 116, 118, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157, +} +-- AC dequantization factors, index q + 1 +Tables.AC_TABLE = { + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, + 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, + 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, + 205, 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284, +} +-- coefficient band of each position (with a sentinel for position 16) +Tables.BANDS = { 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0 } +-- zigzag scan: coefficient n goes to position ZIGZAG[n + 1] +Tables.ZIGZAG = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 } +-- extra bits probabilities for the DCT_CAT3..6 tokens +Tables.CAT3 = { 173, 148, 140 } +Tables.CAT4 = { 176, 155, 140, 135 } +Tables.CAT5 = { 180, 157, 141, 134, 130 } +Tables.CAT6 = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 } + +return Tables diff --git a/src/Formats/codecs/Vp8/Yuv.luau b/src/Formats/codecs/Vp8/Yuv.luau new file mode 100644 index 0000000..5668738 --- /dev/null +++ b/src/Formats/codecs/Vp8/Yuv.luau @@ -0,0 +1,123 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Vp8/Yuv: 4:2:0 Y'CbCr (BT.601, limited range) to rgba8 the way libwebp's decoder does it, bit-exact: the +-- 14-bit fixed-point VP8YuvToRgb of src/dsp/yuv.h, with either the "fancy" upsampler (src/dsp/upsampling.c: a 9-3-3-1 +-- bilinear filter on the chroma, libwebp's default) or point sampling (dwebp -nofancy). A port of libwebp 1.6 +-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt). +local rshift = bit32.rshift +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local bcreate = buffer.create + +local Yuv = {} + +local function clip(v: number): number + -- VP8Clip8: v in 14-bit fixed point + if v >= 0 and v < 16384 then + return rshift(v, 6) + end + return if v < 0 then 0 else 255 +end + +-- (v * coeff) >> 8 for non-negative v +local function mulHi(v: number, c: number): number + return rshift(v * c, 8) +end + +-- rgba(y, u, v) -> the pixel as a little-endian u32 (bytes R G B 255) +local function rgba(y: number, u: number, v: number): number + local yy = mulHi(y, 19077) + local r = clip(yy + mulHi(v, 26149) - 14234) + local g = clip(yy - mulHi(u, 6419) - mulHi(v, 13320) + 8708) + local b = clip(yy + mulHi(u, 33050) - 17685) + return r + g * 256 + b * 65536 + 0xff000000 +end +Yuv.rgba = rgba + +-- upsamplePair: libwebp UPSAMPLE_FUNC for one or two output rows. ty / by: offsets of the top / bottom luma rows +-- (by < 0: no bottom row), tu / cu: offsets of the top / current chroma rows; dt / db: output row offsets. +local function upsamplePair(Y: buffer, U: buffer, V: buffer, ty: number, by: number, tu: number, cu: number, out: buffer, dt: number, db: number, len: number) + local last = rshift(len - 1, 1) + local tlu, tlv = readu8(U, tu), readu8(V, tu) + local lu, lv = readu8(U, cu), readu8(V, cu) + do + local u0 = rshift(3 * tlu + lu + 2, 2) + local v0 = rshift(3 * tlv + lv + 2, 2) + writeu32(out, dt, rgba(readu8(Y, ty), u0, v0)) + end + if by >= 0 then + local u0 = rshift(3 * lu + tlu + 2, 2) + local v0 = rshift(3 * lv + tlv + 2, 2) + writeu32(out, db, rgba(readu8(Y, by), u0, v0)) + end + for x = 1, last do + local tu1, tv1 = readu8(U, tu + x), readu8(V, tu + x) + local u1, v1 = readu8(U, cu + x), readu8(V, cu + x) + local avgU = tlu + tu1 + lu + u1 + 8 + local avgV = tlv + tv1 + lv + v1 + 8 + local d12u = rshift(avgU + 2 * (tu1 + lu), 3) + local d03u = rshift(avgU + 2 * (tlu + u1), 3) + local d12v = rshift(avgV + 2 * (tv1 + lv), 3) + local d03v = rshift(avgV + 2 * (tlv + v1), 3) + local px = 2 * x + writeu32(out, dt + (px - 1) * 4, rgba(readu8(Y, ty + px - 1), rshift(d12u + tlu, 1), rshift(d12v + tlv, 1))) + writeu32(out, dt + px * 4, rgba(readu8(Y, ty + px), rshift(d03u + tu1, 1), rshift(d03v + tv1, 1))) + if by >= 0 then + writeu32(out, db + (px - 1) * 4, rgba(readu8(Y, by + px - 1), rshift(d03u + lu, 1), rshift(d03v + lv, 1))) + writeu32(out, db + px * 4, rgba(readu8(Y, by + px), rshift(d12u + u1, 1), rshift(d12v + v1, 1))) + end + tlu, tlv, lu, lv = tu1, tv1, u1, v1 + end + if len % 2 == 0 then + local u0 = rshift(3 * tlu + lu + 2, 2) + local v0 = rshift(3 * tlv + lv + 2, 2) + writeu32(out, dt + (len - 1) * 4, rgba(readu8(Y, ty + len - 1), u0, v0)) + if by >= 0 then + u0 = rshift(3 * lu + tlu + 2, 2) + v0 = rshift(3 * lv + tlv + 2, 2) + writeu32(out, db + (len - 1) * 4, rgba(readu8(Y, by + len - 1), u0, v0)) + end + end +end + +-- toRgba(y, u, v, w, h, fancy, out?) -> rgba8 (alpha 255). Planes are tightly packed (chroma ceil(w / 2) wide). +function Yuv.toRgba(Y: buffer, U: buffer, V: buffer, w: number, h: number, fancy: boolean, out: buffer?): buffer + local o = out or bcreate(w * h * 4) + local cw = (w + 1) // 2 + local stride = w * 4 + if fancy then + -- libwebp EmitFancyRGB over the whole picture: row 0 alone (chroma mirrored), then pairs of rows between two + -- chroma rows, then the last row of an even height alone + upsamplePair(Y, U, V, 0, -1, 0, 0, o, 0, -1, w) + local y = 1 + local cu = 0 + while y + 1 < h do + upsamplePair(Y, U, V, y * w, (y + 1) * w, cu, cu + cw, o, y * stride, (y + 1) * stride, w) + cu += cw + y += 2 + end + if h % 2 == 0 and h > 1 then + upsamplePair(Y, U, V, (h - 1) * w, -1, cu, cu, o, (h - 1) * stride, -1, w) + end + else + for y = 0, h - 1 do + local cu = (y // 2) * cw + local yo = y * w + local oo = y * stride + for x = 0, w - 1 do + local c = cu + x // 2 + writeu32(o, oo + x * 4, rgba(readu8(Y, yo + x), readu8(U, c), readu8(V, c))) + end + end + end + return o +end + +-- setAlpha(rgba, a8, n): copy an alpha plane into the A bytes +function Yuv.setAlpha(o: buffer, a: buffer, n: number) + for i = 0, n - 1 do + writeu8(o, i * 4 + 3, readu8(a, i)) + end +end + +return Yuv diff --git a/src/Formats/codecs/Vp8/init.luau b/src/Formats/codecs/Vp8/init.luau new file mode 100644 index 0000000..05f56f1 --- /dev/null +++ b/src/Formats/codecs/Vp8/init.luau @@ -0,0 +1,142 @@ +--!strict +-- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the +-- WebM / Matroska and IVF video tracks can use it too. A port of libwebp 1.6 (BSD-3-Clause, +-- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals +-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. +-- Supports: key frames (intra 16x16 / 4x4 / chroma prediction, segments, both loop filters, token partitions, +-- probability updates, skip). Not supported yet: inter frames (decodeFrame returns UNSUPPORTED; the decoder object +-- keeps the cross-frame state so they can be added), the horizontal / vertical scale bits (ignored, as libwebp does). +-- +-- local Vp8 = require("@formats/codecs/Vp8") +-- local frame, err = Vp8.decodeFrame(buf, off, len) -- a yuv420p Types.Image (+ frame.meta.source.vp8 header) +-- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling) +-- local dec = Vp8.newDecoder(); dec:decodeFrame(...) -- a stream of frames (WebM) +-- +-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Decode = require("@formats/codecs/Vp8/Decode") +local Yuv = require("@formats/codecs/Vp8/Yuv") + +local Vp8 = {} + +local DEFAULT_MAX_PIXELS = 2 ^ 28 + +export type Options = { + maxPixels: number?, -- default 2^28 +} + +local function fail(msg: string?, offset: number?): Err.Err + local m = msg or "bad data" + if string.sub(m, 1, 11) == "truncated: " then + return Err.new(Err.TRUNCATED, string.sub(m, 12), offset) + elseif string.sub(m, 1, 7) == "limit: " then + return Err.new(Err.LIMIT, string.sub(m, 8), offset) + elseif string.sub(m, 1, 13) == "unsupported: " then + return Err.new(Err.UNSUPPORTED, string.sub(m, 14), offset) + end + return Err.new(Err.CORRUPT, m, offset) +end + +local function range(buf: buffer, off: number?, len: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(off or 0, 0, n) + return o, math.clamp(len or (n - o), 0, n - o) +end + +-- info(buf, off?, len?) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, Err +function Vp8.info(buf: buffer, off: number?, len: number?): (any, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "info: expected a buffer") + end + local o, l = range(buf, off, len) + local h, err = Decode.header(buf, o, l) + if not h then + return nil, fail(err, o) + end + return h, nil +end + +local DecoderMeta = {} +DecoderMeta.__index = DecoderMeta + +export type Decoder = typeof(setmetatable({} :: { state: Decode.State }, DecoderMeta)) + +-- newDecoder() -> Decoder: decodes successive frames of one stream +function Vp8.newDecoder(): Decoder + return setmetatable({ state = Decode.new() }, DecoderMeta) +end + +-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err +function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer") + end + local o, l = range(buf, off, len) + local f, err = Decode.decodeFrame(self.state, buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS) + if not f then + return nil, fail(err, o) + end + local img = Types.Image.new(f.width, f.height, "yuv420p") + local ny = f.width * f.height + local nc = buffer.len(f.u) + buffer.copy(img.pixels, 0, f.y, 0, ny) + buffer.copy(img.pixels, ny, f.u, 0, nc) + buffer.copy(img.pixels, ny + nc, f.v, 0, nc) + img.meta.source = { format = "vp8", keyFrame = f.header.keyFrame, profile = f.header.profile } + return img, nil +end + +-- decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err (one key frame) +function Vp8.decodeFrame(buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) + return Vp8.newDecoder():decodeFrame(buf, off, len, opts) +end + +-- decodePlanes(buf, off?, len?, opts?) -> y, u, v, width, height | nil, Err: one key frame as separate planes +function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options?): (buffer?, any, buffer?, number?, number?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "decodePlanes: expected a buffer") + end + local o, l = range(buf, off, len) + local f, err = Decode.decodeFrame(Decode.new(), buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS) + if not f then + return nil, fail(err, o) + end + return f.y, f.u, f.v, f.width, f.height +end + +-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height +function Vp8.planes(img: Types.Image): (number, number, number, number, number) + local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2 + local ny = img.width * img.height + return 0, ny, ny + cw * ch, cw, ch +end + +-- toRgba(yuvImage, fancy?) -> rgba8 Image. fancy (default true): libwebp's bilinear chroma upsampling; false: point +-- sampling (dwebp -nofancy) +function Vp8.toRgba(img: Types.Image, fancy: boolean?): (Types.Image?, Err.Err?) + if type(img) ~= "table" or img.format ~= "yuv420p" then + return nil, Err.new(Err.ARG, "toRgba: needs a yuv420p Image") + end + local w, h = img.width, img.height + local _, uo, vo, cw, ch = Vp8.planes(img) + local y = buffer.create(w * h) + local u = buffer.create(cw * ch) + local v = buffer.create(cw * ch) + buffer.copy(y, 0, img.pixels, 0, w * h) + buffer.copy(u, 0, img.pixels, uo, cw * ch) + buffer.copy(v, 0, img.pixels, vo, cw * ch) + local out = Types.Image.new(w, h, "rgba8") + Yuv.toRgba(y, u, v, w, h, fancy ~= false, out.pixels) + out.meta.source = img.meta.source + return out, nil +end + +-- yuvToRgba(y, u, v, w, h, fancy?) -> rgba8 pixels from separate planes (alpha 255) +function Vp8.yuvToRgba(y: buffer, u: buffer, v: buffer, w: number, h: number, fancy: boolean?): buffer + return Yuv.toRgba(y, u, v, w, h, fancy ~= false) +end + +Vp8.setAlpha = Yuv.setAlpha + +return Vp8 diff --git a/src/Formats/codecs/Vp8L/Decode.luau b/src/Formats/codecs/Vp8L/Decode.luau new file mode 100644 index 0000000..6f88783 --- /dev/null +++ b/src/Formats/codecs/Vp8L/Decode.luau @@ -0,0 +1,873 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes, +-- LZ77 backward references with the 2-D distance map, the colour cache, and the four inverse transforms (predictor, +-- cross colour, subtract green, colour indexing with pixel bundling). A port of libwebp 1.6 src/dec/vp8l_dec.c, +-- src/utils/huffman_utils.c and src/dsp/lossless.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); bit-exact with it. +-- +-- Pixels are ARGB u32 values (0xAARRGGBB) in a buffer, 4 bytes each, rows top to bottom. Never throws: every +-- function returns nil, "message" (prefixed "truncated: " when the data ends early) on bad data. +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len + +local Decode = {} + +local ROOT_BITS = 8 +local MAX_LEN = 15 +local NUM_LITERAL = 256 +local NUM_LENGTH = 24 +local NUM_DISTANCE = 40 +local MAX_CACHE_BITS = 11 +local ARGB_BLACK = 0xff000000 + +local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } +local CODE_TO_PLANE = { + 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, + 0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, + 0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, + 0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, + 0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52, + 0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61, + 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70, +} +-- distance map (x offset 8 - (v & 15), y offset v >> 4) as a plain distance for a row width: done per image +Decode.CODE_TO_PLANE = CODE_TO_PLANE + +-- ------------------------------------------------------------------------------------------------ bit reader +-- LSB-first; bytes past the end read as zero and are counted in `over`: the stream is overrun when fewer bits are +-- left in the buffer than phantom bits were added (bitcnt < over * 8). +export type State = { + buf: buffer, + pos: number, + limit: number, + bitbuf: number, + bitcnt: number, + over: number, + -- prefix code tables (u32 entries value * 32 + bits), shared by every group of every level + tab: buffer, + tabUsed: number, + maxPixels: number, +} + +local function fill(d: State) + local bitbuf, bitcnt = d.bitbuf, d.bitcnt + while bitcnt <= 24 do + local p = d.pos + local b = 0 + if p < d.limit then + b = readu8(d.buf, p) + d.pos = p + 1 + else + d.over += 1 + end + bitbuf += lshift(b, bitcnt) + bitcnt += 8 + end + d.bitbuf, d.bitcnt = bitbuf, bitcnt +end + +-- readBits(d, n) n <= 24 +local function readBits(d: State, n: number): number + if d.bitcnt < n then + fill(d) + end + local v = band(d.bitbuf, lshift(1, n) - 1) + d.bitbuf = rshift(d.bitbuf, n) + d.bitcnt -= n + return v +end + +local function eos(d: State): boolean + return d.bitcnt < d.over * 8 +end + +-- ------------------------------------------------------------------------------------------------ prefix codes +local count = table.create(MAX_LEN + 1, 0) +local offset = table.create(MAX_LEN + 2, 0) + +local function ensure(d: State, n: number) + local cap = blen(d.tab) // 4 + if d.tabUsed + n > cap then + local nb = bcreate(math.max(cap * 2, d.tabUsed + n) * 4) + bcopy(nb, 0, d.tab, 0, d.tabUsed * 4) + d.tab = nb + end +end + +local function replicate(tab: buffer, at: number, step: number, size: number, entry: number) + local e = size + repeat + e -= step + writeu32(tab, (at + e) * 4, entry) + until e <= 0 +end + +local function nextKey(key: number, len: number): number + local step = lshift(1, len - 1) + while band(key, step) ~= 0 do + step = rshift(step, 1) + end + return if step ~= 0 then band(key, step - 1) + step else key +end + +-- build(d, lens (0-based Lua array), n) -> table offset in d.tab, or -1 for an invalid code set (libwebp +-- BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits) +local sorted = table.create(2400, 0) +local function build(d: State, lens: { number }, n: number): number + for l = 0, MAX_LEN do + count[l + 1] = 0 + end + for s = 0, n - 1 do + local l = lens[s + 1] + if l > MAX_LEN then + return -1 + end + count[l + 1] += 1 + end + if count[1] == n then + return -1 + end + offset[2] = 0 + for len = 1, MAX_LEN - 1 do + if count[len + 1] > lshift(1, len) then + return -1 + end + offset[len + 2] = offset[len + 1] + count[len + 1] + end + for s = 0, n - 1 do + local l = lens[s + 1] + if l > 0 then + sorted[offset[l + 1] + 1] = s + offset[l + 1] += 1 + end + end + local long = 0 + for len = ROOT_BITS + 1, MAX_LEN do + long += count[len + 1] + end + ensure(d, lshift(1, ROOT_BITS) + long * lshift(1, MAX_LEN - ROOT_BITS)) + local tab = d.tab + local root = d.tabUsed + local totalSize = lshift(1, ROOT_BITS) + if offset[MAX_LEN + 1] == 1 then + replicate(tab, root, 1, totalSize, sorted[1] * 32) + d.tabUsed = root + totalSize + return root + end + local key = 0 + local numNodes, numOpen = 1, 1 + local tableBits = ROOT_BITS + local tableSize = lshift(1, tableBits) + local tableAt = root + local low = -1 + local mask = totalSize - 1 + local symbol = 1 + local step = 2 + for len = 1, ROOT_BITS do + numOpen *= 2 + numNodes += numOpen + numOpen -= count[len + 1] + if numOpen < 0 then + return -1 + end + while count[len + 1] > 0 do + replicate(tab, root + key, step, tableSize, sorted[symbol] * 32 + len) + symbol += 1 + key = nextKey(key, len) + count[len + 1] -= 1 + end + step *= 2 + end + step = 2 + for len = ROOT_BITS + 1, MAX_LEN do + numOpen *= 2 + numNodes += numOpen + numOpen -= count[len + 1] + if numOpen < 0 then + return -1 + end + while count[len + 1] > 0 do + if band(key, mask) ~= low then + tableAt += tableSize + -- NextTableBitSize + local l2 = len + local left = lshift(1, l2 - ROOT_BITS) + while l2 < MAX_LEN do + left -= count[l2 + 1] + if left <= 0 then + break + end + l2 += 1 + left *= 2 + end + tableBits = l2 - ROOT_BITS + tableSize = lshift(1, tableBits) + totalSize += tableSize + low = band(key, mask) + writeu32(tab, (root + low) * 4, (tableAt - root - low) * 32 + tableBits + ROOT_BITS) + end + replicate(tab, tableAt + rshift(key, ROOT_BITS), step, tableSize, sorted[symbol] * 32 + len - ROOT_BITS) + symbol += 1 + key = nextKey(key, len) + count[len + 1] -= 1 + end + step *= 2 + end + if numNodes ~= 2 * offset[MAX_LEN + 1] - 1 then + return -1 + end + d.tabUsed = root + totalSize + return root +end + +-- readSymbol(d, at) -> symbol (the reader is refilled to >= 15 bits first) +local function readSymbol(d: State, at: number): number + if d.bitcnt < MAX_LEN then + fill(d) + end + local tab = d.tab + local bitbuf = d.bitbuf + local idx = at + band(bitbuf, 255) + local e = readu32(tab, idx * 4) + local nb = band(e, 31) + if nb > ROOT_BITS then + bitbuf = rshift(bitbuf, ROOT_BITS) + d.bitcnt -= ROOT_BITS + e = readu32(tab, (idx + rshift(e, 5) + band(bitbuf, lshift(1, nb - ROOT_BITS) - 1)) * 4) + nb = band(e, 31) + end + d.bitbuf = rshift(bitbuf, nb) + d.bitcnt -= nb + return rshift(e, 5) +end + +local codeLengths = table.create(2400, 0) +local clLens = table.create(19, 0) + +-- readCode(d, alphabetSize) -> table offset, or -1 +local function readCode(d: State, size: number): number + for i = 1, size do + codeLengths[i] = 0 + end + if readBits(d, 1) == 1 then + local numSymbols = readBits(d, 1) + 1 + local first = readBits(d, 1) + local s = readBits(d, if first == 0 then 1 else 8) + if s < size then + codeLengths[s + 1] = 1 + end + if numSymbols == 2 then + s = readBits(d, 8) + if s < size then + codeLengths[s + 1] = 1 + end + end + else + for i = 1, 19 do + clLens[i] = 0 + end + local numCodes = readBits(d, 4) + 4 + for i = 1, numCodes do + clLens[CODE_LENGTH_ORDER[i] + 1] = readBits(d, 3) + end + local mark = d.tabUsed + local clt = build(d, clLens, 19) + if clt < 0 then + return -1 + end + local maxSymbol = size + if readBits(d, 1) == 1 then + local nbits = 2 + 2 * readBits(d, 3) + maxSymbol = 2 + readBits(d, nbits) + if maxSymbol > size then + return -1 + end + end + local prev = 8 + local s = 0 + while s < size do + if maxSymbol == 0 then + break + end + maxSymbol -= 1 + local cl = readSymbol(d, clt) + if cl < 16 then + codeLengths[s + 1] = cl + s += 1 + if cl ~= 0 then + prev = cl + end + else + local rep, len + if cl == 16 then + rep, len = readBits(d, 2) + 3, prev + elseif cl == 17 then + rep, len = readBits(d, 3) + 3, 0 + else + rep, len = readBits(d, 7) + 11, 0 + end + if s + rep > size then + return -1 + end + for k = s + 1, s + rep do + codeLengths[k] = len + end + s += rep + end + end + d.tabUsed = mark -- the code length table is temporary + end + if eos(d) then + return -1 + end + return build(d, codeLengths, size) +end + +-- ------------------------------------------------------------------------------------------------ pixel data +local function subSample(size: number, bits: number): number + return rshift(size + lshift(1, bits) - 1, bits) +end +Decode.subSample = subSample + +local function cacheKey(argb: number, shift: number): number + -- (0x1e35a7bd * argb) mod 2^32 >> shift, exact in doubles + local lo = argb % 65536 + local hi = (argb - lo) / 65536 + local m = (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 + return rshift(m, shift) +end +Decode.cacheKey = cacheKey + +-- decodeData: the entropy-coded pixels of one level into `data` (w * h u32) +local function decodeData(d: State, data: buffer, w: number, h: number, cacheBits: number, groups: { number }, himg: buffer?, hbits: number, hxs: number): (boolean, string?) + local total = w * h + local cache: buffer? = if cacheBits > 0 then bcreate(lshift(1, cacheBits) * 4) else nil + local cshift = 32 - cacheBits + local lenLimit = NUM_LITERAL + NUM_LENGTH + local cacheLimit = lenLimit + (if cacheBits > 0 then lshift(1, cacheBits) else 0) + local hmask = if himg then lshift(1, hbits) - 1 else -1 + local i, col, row = 0, 0, 0 + local gG, gR, gB, gA, gD = groups[1], groups[2], groups[3], groups[4], groups[5] + local function setGroup() + if himg then + local g = readu32(himg, (hxs * rshift(row, hbits) + rshift(col, hbits)) * 4) * 5 + gG, gR, gB, gA, gD = groups[g + 1], groups[g + 2], groups[g + 3], groups[g + 4], groups[g + 5] + end + end + while i < total do + if band(col, hmask) == 0 then + setGroup() + end + local code = readSymbol(d, gG) + if code < NUM_LITERAL then + local r = readSymbol(d, gR) + local b = readSymbol(d, gB) + local a = readSymbol(d, gA) + if d.bitcnt < d.over * 8 then + break + end + local argb = a * 16777216 + r * 65536 + code * 256 + b + writeu32(data, i * 4, argb) + if cache then + writeu32(cache, cacheKey(argb, cshift) * 4, argb) + end + i += 1 + col += 1 + if col >= w then + col = 0 + row += 1 + end + elseif code < lenLimit then + local ls = code - NUM_LITERAL + local length + if ls < 4 then + length = ls + 1 + else + local eb = rshift(ls - 2, 1) + length = lshift(2 + band(ls, 1), eb) + readBits(d, eb) + 1 + end + local ds = readSymbol(d, gD) + local dc + if ds < 4 then + dc = ds + 1 + else + local eb = rshift(ds - 2, 1) + dc = lshift(2 + band(ds, 1), eb) + readBits(d, eb) + 1 + end + local dist + if dc > 120 then + dist = dc - 120 + else + local v = CODE_TO_PLANE[dc] + dist = rshift(v, 4) * w + 8 - band(v, 15) + if dist < 1 then + dist = 1 + end + end + if d.bitcnt < d.over * 8 then + break + end + if i < dist or total - i < length then + return false, "bad backward reference" + end + if dist >= length then + bcopy(data, i * 4, data, (i - dist) * 4, length * 4) + else + for k = i, i + length - 1 do + writeu32(data, k * 4, readu32(data, (k - dist) * 4)) + end + end + if cache then + for k = i, i + length - 1 do + local argb = readu32(data, k * 4) + writeu32(cache, cacheKey(argb, cshift) * 4, argb) + end + end + i += length + col += length + while col >= w do + col -= w + row += 1 + end + if band(col, hmask) ~= 0 then + setGroup() + end + elseif code < cacheLimit and cache then + if d.bitcnt < d.over * 8 then + break + end + local argb = readu32(cache, (code - lenLimit) * 4) + writeu32(data, i * 4, argb) + writeu32(cache, cacheKey(argb, cshift) * 4, argb) + i += 1 + col += 1 + if col >= w then + col = 0 + row += 1 + end + else + return false, "bad symbol" + end + end + if eos(d) then + return false, "truncated: pixel data" + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ transforms +local function addPixels(a: number, b: number): number + return band(band(a, 0xff00ff00) + band(b, 0xff00ff00), 0xff00ff00) + band(band(a, 0x00ff00ff) + band(b, 0x00ff00ff), 0x00ff00ff) +end +Decode.addPixels = addPixels + +local function average2(a: number, b: number): number + return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) +end +Decode.average2 = average2 + +local function clip255(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +local function sub3(a: number, b: number, c: number): number + local pb, pa = b - c, a - c + return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa) +end + +-- select(T, L, TL) +local function select3(a: number, b: number, c: number): number + local s = sub3(rshift(a, 24), rshift(b, 24), rshift(c, 24)) + + sub3(band(rshift(a, 16), 255), band(rshift(b, 16), 255), band(rshift(c, 16), 255)) + + sub3(band(rshift(a, 8), 255), band(rshift(b, 8), 255), band(rshift(c, 8), 255)) + + sub3(band(a, 255), band(b, 255), band(c, 255)) + return if s <= 0 then a else b +end + +local function clampedFull(c0: number, c1: number, c2: number): number + local a = clip255(rshift(c0, 24) + rshift(c1, 24) - rshift(c2, 24)) + local r = clip255(band(rshift(c0, 16), 255) + band(rshift(c1, 16), 255) - band(rshift(c2, 16), 255)) + local g = clip255(band(rshift(c0, 8), 255) + band(rshift(c1, 8), 255) - band(rshift(c2, 8), 255)) + local b = clip255(band(c0, 255) + band(c1, 255) - band(c2, 255)) + return a * 16777216 + r * 65536 + g * 256 + b +end + +local function half(a: number, b: number): number + local dd = a - b + -- C division truncates toward zero + local q = if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1) + return clip255(a + q) +end + +local function clampedHalf(c0: number, c1: number, c2: number): number + local ave = average2(c0, c1) + local a = half(rshift(ave, 24), rshift(c2, 24)) + local r = half(band(rshift(ave, 16), 255), band(rshift(c2, 16), 255)) + local g = half(band(rshift(ave, 8), 255), band(rshift(c2, 8), 255)) + local b = half(band(ave, 255), band(c2, 255)) + return a * 16777216 + r * 65536 + g * 256 + b +end + +-- predict(mode, L, T, TR, TL) -> the predicted pixel (libwebp VP8LPredictors; 14 and 15 are black) +local function predict(mode: number, L: number, T: number, TR: number, TL: number): number + if mode == 0 then + return ARGB_BLACK + elseif mode == 1 then + return L + elseif mode == 2 then + return T + elseif mode == 3 then + return TR + elseif mode == 4 then + return TL + elseif mode == 5 then + return average2(average2(L, TR), T) + elseif mode == 6 then + return average2(L, TL) + elseif mode == 7 then + return average2(L, T) + elseif mode == 8 then + return average2(TL, T) + elseif mode == 9 then + return average2(T, TR) + elseif mode == 10 then + return average2(average2(L, TL), average2(T, TR)) + elseif mode == 11 then + return select3(T, L, TL) + elseif mode == 12 then + return clampedFull(L, T, TL) + elseif mode == 13 then + return clampedHalf(L, T, TL) + end + return ARGB_BLACK +end +Decode.predict = predict + +local function inversePredictor(data: buffer, w: number, h: number, bits: number, sub: buffer) + local tw = subSample(w, bits) + -- first row: black, then L + writeu32(data, 0, addPixels(readu32(data, 0), ARGB_BLACK)) + for x = 1, w - 1 do + writeu32(data, x * 4, addPixels(readu32(data, x * 4), readu32(data, (x - 1) * 4))) + end + for y = 1, h - 1 do + local row = y * w + local up = row - w + writeu32(data, row * 4, addPixels(readu32(data, row * 4), readu32(data, up * 4))) + local trow = rshift(y, bits) * tw + local x = 1 + while x < w do + local mode = band(rshift(readu32(sub, (trow + rshift(x, bits)) * 4), 8), 15) + local xe = math.min(w, lshift(rshift(x, bits) + 1, bits)) + local L = readu32(data, (row + x - 1) * 4) + if mode == 1 then + for k = x, xe - 1 do + L = addPixels(readu32(data, (row + k) * 4), L) + writeu32(data, (row + k) * 4, L) + end + elseif mode == 2 then + for k = x, xe - 1 do + writeu32(data, (row + k) * 4, addPixels(readu32(data, (row + k) * 4), readu32(data, (up + k) * 4))) + end + else + for k = x, xe - 1 do + local p = predict(mode, L, readu32(data, (up + k) * 4), readu32(data, (up + k + 1) * 4), readu32(data, (up + k - 1) * 4)) + L = addPixels(readu32(data, (row + k) * 4), p) + writeu32(data, (row + k) * 4, L) + end + end + x = xe + end + end +end + +local function sint8(v: number): number + return if v >= 128 then v - 256 else v +end + +local function inverseCrossColor(data: buffer, w: number, h: number, bits: number, sub: buffer) + local tw = subSample(w, bits) + for y = 0, h - 1 do + local trow = rshift(y, bits) * tw + local x = 0 + while x < w do + local m = readu32(sub, (trow + rshift(x, bits)) * 4) + local g2r = sint8(band(m, 255)) + local g2b = sint8(band(rshift(m, 8), 255)) + local r2b = sint8(band(rshift(m, 16), 255)) + local xe = math.min(w, lshift(rshift(x, bits) + 1, bits)) + for k = y * w + x, y * w + xe - 1 do + local argb = readu32(data, k * 4) + local g = sint8(band(rshift(argb, 8), 255)) + local r = band(band(rshift(argb, 16), 255) + ((g2r * g) // 32), 255) + local b = band(band(argb, 255) + ((g2b * g) // 32) + ((r2b * sint8(r)) // 32), 255) + writeu32(data, k * 4, band(argb, 0xff00ff00) + r * 65536 + b) + end + x = xe + end + end +end + +local function inverseSubtractGreen(data: buffer, n: number) + for k = 0, n - 1 do + local argb = readu32(data, k * 4) + local g = band(rshift(argb, 8), 255) + writeu32(data, k * 4, band(argb, 0xff00ff00) + band(band(argb, 0x00ff00ff) + g * 65537, 0x00ff00ff)) + end +end + +-- inverseColorIndexing(src (sw x h), w, h, bits, map (2^(8 >> bits) u32)) -> w x h +local function inverseColorIndexing(src: buffer, sw: number, w: number, h: number, bits: number, map: buffer): buffer + local out = bcreate(w * h * 4) + if bits == 0 then + for k = 0, w * h - 1 do + writeu32(out, k * 4, readu32(map, band(rshift(readu32(src, k * 4), 8), 255) * 4)) + end + return out + end + local bpp = rshift(8, bits) + local cmask = lshift(1, bits) - 1 + local vmask = lshift(1, bpp) - 1 + for y = 0, h - 1 do + local packed = 0 + local s = y * sw + local o = y * w + for x = 0, w - 1 do + if band(x, cmask) == 0 then + packed = band(rshift(readu32(src, s * 4), 8), 255) + s += 1 + end + writeu32(out, (o + x) * 4, readu32(map, band(packed, vmask) * 4)) + packed = rshift(packed, bpp) + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ image stream +type Transform = { kind: number, xsize: number, bits: number, data: buffer? } + +local decodeStream: (d: State, xs: number, ys: number, level0: boolean) -> (buffer?, string?) + +-- readCodes(d, xs, ys, cacheBits, level0) -> groups (5 table offsets each), huffman image, bits, image width +local function readCodes(d: State, xs: number, ys: number, cacheBits: number, level0: boolean): ({ number }?, buffer?, number, number, string?) + local himg: buffer? = nil + local hbits, hxs = 0, 0 + local numGroups = 1 + local mapping: { number }? = nil + local numMax = 1 + if level0 and readBits(d, 1) == 1 then + hbits = readBits(d, 3) + 2 + hxs = subSample(xs, hbits) + local hys = subSample(ys, hbits) + local img, err = decodeStream(d, hxs, hys, false) + if not img then + return nil, nil, 0, 0, err + end + local n = hxs * hys + for k = 0, n - 1 do + local g = band(rshift(readu32(img, k * 4), 8), 0xffff) + writeu32(img, k * 4, g) + if g >= numMax then + numMax = g + 1 + end + end + if numMax > 1000 or numMax > xs * ys then + -- remap the used groups to [0, numGroups); unused ones are read and checked but not kept + local map: { number } = table.create(numMax, -1) + numGroups = 0 + for k = 0, n - 1 do + local g = readu32(img, k * 4) + if map[g + 1] == -1 then + map[g + 1] = numGroups + numGroups += 1 + end + writeu32(img, k * 4, map[g + 1]) + end + mapping = map + else + numGroups = numMax + end + himg = img + end + if eos(d) then + return nil, nil, 0, 0, "truncated: meta codes" + end + local groups: { number } = table.create(numGroups * 5, 0) + local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0 + for i = 0, numMax - 1 do + local slot = if mapping then mapping[i + 1] else i + local mark = d.tabUsed + for j = 0, 4 do + local size = if j == 0 then NUM_LITERAL + NUM_LENGTH + cacheSize elseif j == 4 then NUM_DISTANCE else NUM_LITERAL + local at = readCode(d, size) + if at < 0 then + return nil, nil, 0, 0, if eos(d) then "truncated: prefix code" else "bad prefix code" + end + if slot >= 0 then + groups[slot * 5 + j + 1] = at + end + end + if slot < 0 then + d.tabUsed = mark + end + end + return groups, himg, hbits, hxs, nil +end + +decodeStream = function(d: State, xs: number, ys: number, level0: boolean): (buffer?, string?) + local transforms: { Transform } = {} + local seen = 0 + local txs = xs + if level0 then + while readBits(d, 1) == 1 do + local kind = readBits(d, 2) + if band(seen, lshift(1, kind)) ~= 0 then + return nil, "repeated transform" + end + seen = bor(seen, lshift(1, kind)) + local t: Transform = { kind = kind, xsize = txs, bits = 0, data = nil } + if kind == 0 or kind == 1 then + t.bits = readBits(d, 3) + 2 + local sub, err = decodeStream(d, subSample(txs, t.bits), subSample(ys, t.bits), false) + if not sub then + return nil, err + end + t.data = sub + elseif kind == 3 then + local num = readBits(d, 8) + 1 + local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3 + t.bits = bits + local pal, err = decodeStream(d, num, 1, false) + if not pal then + return nil, err + end + local final = lshift(1, rshift(8, bits)) + local map = bcreate(final * 4) + local prev = 0 + for k = 0, num - 1 do + prev = addPixels(readu32(pal, k * 4), prev) + writeu32(map, k * 4, prev) + end + t.data = map + txs = subSample(txs, bits) + end + table.insert(transforms, t) + if eos(d) then + return nil, "truncated: transforms" + end + end + end + local cacheBits = 0 + if readBits(d, 1) == 1 then + cacheBits = readBits(d, 4) + if cacheBits < 1 or cacheBits > MAX_CACHE_BITS then + return nil, "bad colour cache size" + end + end + local mark = d.tabUsed + local groups, himg, hbits, hxs, err = readCodes(d, txs, ys, cacheBits, level0) + if not groups then + return nil, err + end + local data = bcreate(txs * ys * 4) + local ok, derr = decodeData(d, data, txs, ys, cacheBits, groups, himg, hbits, hxs) + if not ok then + return nil, derr + end + d.tabUsed = mark + -- inverse transforms, last read first + for k = #transforms, 1, -1 do + local t = transforms[k] + if t.kind == 0 then + inversePredictor(data, t.xsize, ys, t.bits, t.data :: buffer) + elseif t.kind == 1 then + inverseCrossColor(data, t.xsize, ys, t.bits, t.data :: buffer) + elseif t.kind == 2 then + inverseSubtractGreen(data, t.xsize * ys) + else + data = inverseColorIndexing(data, subSample(t.xsize, t.bits), t.xsize, ys, t.bits, t.data :: buffer) + end + end + return data, nil +end + +local function newState(buf: buffer, off: number, len: number, maxPixels: number): State + return { + buf = buf, + pos = off, + limit = off + len, + bitbuf = 0, + bitcnt = 0, + over = 0, + tab = bcreate(4096 * 4), + tabUsed = 0, + maxPixels = maxPixels, + } +end + +-- header(buf, off, len) -> width, height, alphaHint | nil, message +function Decode.header(buf: buffer, off: number, len: number): (number?, number, boolean, string?) + if len < 5 then + return nil, 0, false, "truncated: header" + end + if readu8(buf, off) ~= 0x2f then + return nil, 0, false, "bad VP8L signature" + end + local v = readu32(buf, off + 1) + local w = band(v, 0x3fff) + 1 + local h = band(rshift(v, 14), 0x3fff) + 1 + local alpha = band(rshift(v, 28), 1) == 1 + if rshift(v, 29) ~= 0 then + return nil, 0, false, "bad VP8L version" + end + return w, h, alpha, nil +end + +-- argb(buf, off, len, maxPixels) -> ARGB pixels, width, height, alphaHint | nil, message +function Decode.argb(buf: buffer, off: number, len: number, maxPixels: number): (buffer?, number, number, boolean, string?) + local w, h, alpha, err = Decode.header(buf, off, len) + if not w then + return nil, 0, 0, false, err + end + if w * h > maxPixels then + return nil, w, h, alpha, "limit: " .. w .. " x " .. h .. " is over maxPixels" + end + local d = newState(buf, off + 5, len - 5, maxPixels) + local data, derr = decodeStream(d, w, h, true) + if not data then + return nil, w, h, alpha, derr + end + return data, w, h, alpha, nil +end + +-- stream(buf, off, len, w, h) -> ARGB pixels | nil, message: a headerless image stream (the ALPH chunk's payload) +function Decode.stream(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, string?) + local d = newState(buf, off, len, w * h) + return decodeStream(d, w, h, true) +end + +-- toRgba(argb, n, out?, outOff?) -> rgba8 bytes +function Decode.toRgba(argb: buffer, n: number, out: buffer?, outOff: number?): buffer + local o = out or bcreate(n * 4) + local base = outOff or 0 + for k = 0, n - 1 do + local v = readu32(argb, k * 4) + -- 0xAARRGGBB (bytes B G R A) -> bytes R G B A + writeu32(o, base + k * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536) + end + return o +end + +-- green(argb, n) -> the green channel as bytes (alpha planes) +function Decode.green(argb: buffer, n: number): buffer + local o = bcreate(n) + for k = 0, n - 1 do + writeu8(o, k, band(rshift(readu32(argb, k * 4), 8), 255)) + end + return o +end + +return Decode diff --git a/src/Formats/codecs/Vp8L/Encode.luau b/src/Formats/codecs/Vp8L/Encode.luau new file mode 100644 index 0000000..3733130 --- /dev/null +++ b/src/Formats/codecs/Vp8L/Encode.luau @@ -0,0 +1,8 @@ +--!strict +--!native +-- codecs/Vp8L/Encode: stub +local Encode = {} +function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact: boolean, alphaHint: boolean?, headerless: boolean): buffer + return buffer.create(0) +end +return Encode diff --git a/src/Formats/codecs/Vp8L/init.luau b/src/Formats/codecs/Vp8L/init.luau new file mode 100644 index 0000000..ec5899a --- /dev/null +++ b/src/Formats/codecs/Vp8L/init.luau @@ -0,0 +1,120 @@ +--!strict +-- codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): +-- image/webp uses it for VP8L frames and for compressed ALPH planes; other containers may carry it too. +-- Decoder: a port of libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it. Encoder: new +-- (subtract green, predictor and cross-colour transforms with per-tile mode search, colour indexing with pixel +-- bundling for <= 256 colours, LZ77 with hash chains and the 2-D distance codes, a colour cache chosen by entropy, +-- one prefix code group per image or meta codes for big images). +-- +-- local Vp8L = require("@formats/codecs/Vp8L") +-- local rgba, w, h, alpha = Vp8L.decode(buf, off, len) -- a VP8L bitstream (0x2f signature) -> rgba8 +-- local a8 = Vp8L.decodeAlpha(buf, off, len, w, h) -- a headerless stream's green channel (ALPH) +-- local bits = Vp8L.encode(rgba, w, h, { effort = 4 }) -- rgba8 -> a VP8L bitstream +-- +-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / LIMIT / ARG). +local Err = require("@formats/core/Err") +local Decode = require("@formats/codecs/Vp8L/Decode") +local Encode = require("@formats/codecs/Vp8L/Encode") + +local Vp8L = {} + +local DEFAULT_MAX_PIXELS = 2 ^ 28 + +local function fail(msg: string?, offset: number?): Err.Err + local m = msg or "bad data" + if string.sub(m, 1, 11) == "truncated: " then + return Err.new(Err.TRUNCATED, string.sub(m, 12), offset) + elseif string.sub(m, 1, 7) == "limit: " then + return Err.new(Err.LIMIT, string.sub(m, 8), offset) + end + return Err.new(Err.CORRUPT, m, offset) +end +Vp8L.fail = fail + +local function range(buf: buffer, off: number?, len: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(off or 0, 0, n) + return o, math.clamp(len or (n - o), 0, n - o) +end + +-- info(buf, off?, len?) -> { width, height, alpha } | nil, Err: the 5-byte header +function Vp8L.info(buf: buffer, off: number?, len: number?): ({ width: number, height: number, alpha: boolean }?, Err.Err?) + local o, l = range(buf, off, len) + local w, h, alpha, err = Decode.header(buf, o, l) + if not w then + return nil, fail(err, o) + end + return { width = w, height = h, alpha = alpha }, nil +end + +-- decodeArgb(buf, off?, len?, maxPixels?) -> ARGB u32 pixels (0xAARRGGBB), width, height, alphaHint | nil, Err +function Vp8L.decodeArgb(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?) + local o, l = range(buf, off, len) + local px, w, h, alpha, err = Decode.argb(buf, o, l, maxPixels or DEFAULT_MAX_PIXELS) + if not px then + return nil, fail(err, o) + end + return px, w, h, alpha +end + +-- decode(buf, off?, len?, maxPixels?) -> rgba8 pixels, width, height, alphaHint | nil, Err +function Vp8L.decode(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?) + local px, w, h, alpha = Vp8L.decodeArgb(buf, off, len, maxPixels) + if not px then + return nil, w + end + return Decode.toRgba(px, w * (h :: number)), w, h, alpha +end + +-- decodeAlpha(buf, off, len, width, height) -> width * height bytes (the green channel) | nil, Err +function Vp8L.decodeAlpha(buf: buffer, off: number?, len: number?, width: number, height: number): (buffer?, Err.Err?) + local o, l = range(buf, off, len) + local px, err = Decode.stream(buf, o, l, width, height) + if not px then + return nil, fail(err, o) + end + return Decode.green(px, width * height), nil +end + +-- toRgba(argb, n) -> rgba8 bytes of n ARGB pixels +Vp8L.toRgba = Decode.toRgba + +export type EncodeOptions = { + effort: number?, -- 0..9, default 5: more = smaller and slower (0: no transforms, no LZ77 search) + exact: boolean?, -- default false: keep the RGB of fully transparent pixels (otherwise they may be zeroed) + alphaHint: boolean?, -- the header's "alpha is used" bit; default: any alpha < 255 +} + +-- encode(rgba, width, height, opts?) -> a VP8L bitstream (signature + header + image stream) | nil, Err +function Vp8L.encode(rgba: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(rgba) ~= "buffer" or type(width) ~= "number" or type(height) ~= "number" then + return nil, Err.new(Err.ARG, "encode: needs rgba8 pixels, width, height") + end + if width < 1 or height < 1 or width > 16384 or height > 16384 or width % 1 ~= 0 or height % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: size must be 1..16384") + end + if buffer.len(rgba) < width * height * 4 then + return nil, Err.new(Err.ARG, "encode: pixel buffer too small") + end + local o = opts or {} + local effort = o.effort or 5 + if type(effort) ~= "number" or effort < 0 or effort > 9 then + return nil, Err.new(Err.ARG, "encode: effort must be 0..9") + end + return Encode.encode(rgba, width, height, effort, o.exact == true, o.alphaHint, false), nil +end + +-- encodeAlpha(a8, width, height, opts?) -> a headerless stream of the plane in green (an ALPH payload) +function Vp8L.encodeAlpha(a8: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(a8) ~= "buffer" or buffer.len(a8) < width * height then + return nil, Err.new(Err.ARG, "encodeAlpha: plane too small") + end + local rgba = buffer.create(width * height * 4) + for i = 0, width * height - 1 do + buffer.writeu32(rgba, i * 4, 0xff000000 + buffer.readu8(a8, i) * 256) + end + local effort = opts and opts.effort or 5 + return Encode.encode(rgba, width, height, effort, true, false, true), nil +end + +return Vp8L From ef8262d7671c8120198b317c83b7c4b52328e647 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:55:49 -0500 Subject: [PATCH 2/6] ws-webp: image/webp (VP8 / VP8L / ALPH / VP8X / animation / metadata decode, lossless + animated encode), codecs/Vp8L encoder, fixtures vs dwebp / Pillow / libvpx, tests --- docs/FORMATS.md | 3 + src/Formats/Registry.luau | 12 + src/Formats/codecs/Vp8L/Encode.luau | 934 +++++++++++++++++++++++++++- src/Formats/image/webp/Alpha.luau | 75 +++ src/Formats/image/webp/Anim.luau | 162 +++++ src/Formats/image/webp/Riff.luau | 59 ++ src/Formats/image/webp/init.luau | 568 +++++++++++++++++ tests/image/webp.luau | 246 ++++++++ tools/fixtures/_webp_encode.luau | 95 +++ tools/fixtures/webp.py | 298 +++++++++ 10 files changed, 2449 insertions(+), 3 deletions(-) create mode 100644 src/Formats/image/webp/Alpha.luau create mode 100644 src/Formats/image/webp/Anim.luau create mode 100644 src/Formats/image/webp/Riff.luau create mode 100644 src/Formats/image/webp/init.luau create mode 100644 tests/image/webp.luau create mode 100644 tools/fixtures/_webp_encode.luau create mode 100644 tools/fixtures/webp.py 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) From ced18478df318b68d45c82d48a5772d14df210e1 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:58:17 -0500 Subject: [PATCH 3/6] ws-webp: codec tests (vp8, vp8l), bench lines, type fixes --- src/Formats/codecs/Vp8L/init.luau | 2 +- src/Formats/image/webp/Alpha.luau | 3 +- src/Formats/image/webp/init.luau | 2 +- tests/codecs/vp8.luau | 80 ++++++++++++++++++++ tests/codecs/vp8l.luau | 120 ++++++++++++++++++++++++++++++ tools/bench.luau | 22 +++++- tools/bench.sh | 2 +- 7 files changed, 226 insertions(+), 5 deletions(-) create mode 100644 tests/codecs/vp8.luau create mode 100644 tests/codecs/vp8l.luau diff --git a/src/Formats/codecs/Vp8L/init.luau b/src/Formats/codecs/Vp8L/init.luau index ec5899a..d35d7e1 100644 --- a/src/Formats/codecs/Vp8L/init.luau +++ b/src/Formats/codecs/Vp8L/init.luau @@ -96,7 +96,7 @@ function Vp8L.encode(rgba: buffer, width: number, height: number, opts: EncodeOp if buffer.len(rgba) < width * height * 4 then return nil, Err.new(Err.ARG, "encode: pixel buffer too small") end - local o = opts or {} + local o: EncodeOptions = opts or {} :: EncodeOptions local effort = o.effort or 5 if type(effort) ~= "number" or effort < 0 or effort > 9 then return nil, Err.new(Err.ARG, "encode: effort must be 0..9") diff --git a/src/Formats/image/webp/Alpha.luau b/src/Formats/image/webp/Alpha.luau index 4742d47..5da90de 100644 --- a/src/Formats/image/webp/Alpha.luau +++ b/src/Formats/image/webp/Alpha.luau @@ -64,7 +64,8 @@ function Alpha.decode(buf: buffer, off: number, len: number, w: number, h: numbe 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 + local e = err :: any + return nil, if e.code == "TRUNCATED" then "truncated: alpha " .. e.message else "alpha: " .. e.message end a = d end diff --git a/src/Formats/image/webp/init.luau b/src/Formats/image/webp/init.luau index d17928a..cbb340c 100644 --- a/src/Formats/image/webp/init.luau +++ b/src/Formats/image/webp/init.luau @@ -420,7 +420,7 @@ function Webp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err? 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 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 diff --git a/tests/codecs/vp8.luau b/tests/codecs/vp8.luau new file mode 100644 index 0000000..484c3f1 --- /dev/null +++ b/tests/codecs/vp8.luau @@ -0,0 +1,80 @@ +-- codecs/Vp8 tests: the VP8 key frames of the WebP fixtures (cwebp at many settings and libvpx through ffmpeg, with +-- 1..8 token partitions) decoded through the codec API: the yuv420p planes against dwebp -yuv, toRgba against +-- dwebp -pam (fancy upsampling) and -nofancy, the decoder object over successive frames, headers, error codes and the +-- fuzz no-throw pass on raw frames. Fixtures: tools/fixtures/webp.py. +local T = require("@tests/T") +local Vp8 = require("@formats/codecs/Vp8") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/webp_cases") + +local t = T.suite("vp8") + +local function chunk(data: string): (buffer?, number, number) + if string.sub(data, 13, 16) ~= "VP8 " then + return nil, 0, 0 + end + local b = buffer.fromstring(data) + return b, 20, buffer.readu32(b, 16) +end + +local n, vpx = 0, 0 +local frames = {} +local dec = Vp8.newDecoder() +for _, c in Cases do + local b, off, len = chunk(c.data) + if b then + local img, err = Vp8.decodeFrame(b, off, len) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.format == "yuv420p" and img.width == c.width and img.height == c.height, c.name .. ": size") + t:eq(Crc32.of(img.pixels), c.yuv, c.name .. ": yuv420p (dwebp -yuv)") + local rgba = Vp8.toRgba(img) :: any + t:eq(Crc32.of(rgba.pixels), c.crc, c.name .. ": rgba (dwebp -pam)") + local nf = Vp8.toRgba(img, false) :: any + t:eq(Crc32.of(nf.pixels), c.nofancy, c.name .. ": rgba (dwebp -nofancy -pam)") + -- the same frame through one long-lived decoder + local again = dec:decodeFrame(b, off, len) + t:check(again and Crc32.of(again.pixels) == c.yuv, c.name .. ": decoder object") + local y, u, v, w, h = Vp8.decodePlanes(b, off, len) + t:check(y and w == c.width and h == c.height and buffer.len(u) == buffer.len(v :: buffer), c.name .. ": decodePlanes") + local info = Vp8.info(b, off, len) + t:check(info and info.keyFrame and info.show and info.width == c.width, c.name .. ": info") + n += 1 + if string.find(c.name, "vpx", 1, true) then + vpx += 1 + end + if #frames < 10 and len < 6000 then + table.insert(frames, buffer.readstring(b, off, len)) + end + end +end +t:note("%d VP8 key frames (%d from libvpx) match dwebp: planes, fancy and point upsampling", n, vpx) + +-- errors +do + local f = buffer.fromstring(frames[1]) + local inter = buffer.fromstring(frames[1]) + buffer.writeu8(inter, 0, bit32.bor(buffer.readu8(inter, 0), 1)) + local _, e1 = Vp8.decodeFrame(inter) + t:check(e1 and e1.code == Err.UNSUPPORTED, "inter frame: " .. tostring(e1)) + local bad = buffer.fromstring(frames[1]) + buffer.writeu8(bad, 3, 0) + local _, e2 = Vp8.decodeFrame(bad) + t:check(e2 and e2.code == Err.CORRUPT, "bad start code: " .. tostring(e2)) + local _, e3 = Vp8.decodeFrame(f, 0, 12) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3)) + local _, e4 = Vp8.decodeFrame(f, 0, buffer.len(f), { maxPixels = 4 }) + t:check(e4 and e4.code == Err.LIMIT, "maxPixels: " .. tostring(e4)) + local _, e5 = Vp8.toRgba({} :: any) + t:check(e5 and e5.code == Err.ARG, "toRgba of a non-yuv image") +end + +-- fuzz on raw frames +t:fuzz("decodeFrame", function(b: buffer) + return Vp8.decodeFrame(b, 0, buffer.len(b), { maxPixels = 2 ^ 20 }) +end, frames, { mutations = 12, keepHeader = 10 }) +t:fuzz("decodeFrame (headers too)", function(b: buffer) + return Vp8.decodeFrame(b, 0, buffer.len(b), { maxPixels = 2 ^ 20 }) +end, frames, { mutations = 4, garbage = 100 }) + +t:done() diff --git a/tests/codecs/vp8l.luau b/tests/codecs/vp8l.luau new file mode 100644 index 0000000..b506cc2 --- /dev/null +++ b/tests/codecs/vp8l.luau @@ -0,0 +1,120 @@ +-- codecs/Vp8L tests: the VP8L bitstreams of the WebP fixtures (cwebp -z 0..9, -exact, near-lossless) decoded through +-- the codec API against dwebp, the encoder at every effort on generated images (gradients, noise, palettes of 1..300 +-- colours, odd sizes, alpha), headerless alpha streams, error codes, and the fuzz no-throw pass on raw bitstreams. +-- Fixtures: tools/fixtures/webp.py. +local T = require("@tests/T") +local Vp8L = require("@formats/codecs/Vp8L") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/webp_cases") + +local t = T.suite("vp8l") + +-- the VP8L chunk of a simple-format file +local function chunk(data: string): (buffer?, number, number) + if string.sub(data, 13, 16) ~= "VP8L" then + return nil, 0, 0 + end + local b = buffer.fromstring(data) + return b, 20, buffer.readu32(b, 16) +end + +local n = 0 +local streams = {} +for _, c in Cases do + local b, off, len = chunk(c.data) + if b then + local px, w, h = Vp8L.decode(b, off, len) + t:check(px, c.name .. ": " .. tostring(w)) + t:check(w == c.width and h == c.height, c.name .. ": size") + t:eq(Crc32.of(px :: buffer), c.crc, c.name .. ": pixels (dwebp)") + local info = Vp8L.info(b, off, len) + t:check(info and info.width == c.width and info.height == c.height and info.alpha == c.alpha, c.name .. ": info") + local argb = Vp8L.decodeArgb(b, off, len) + t:check(argb and Crc32.of(Vp8L.toRgba(argb, c.width * c.height)) == c.crc, c.name .. ": decodeArgb + toRgba") + n += 1 + if #streams < 12 and len < 8000 then + table.insert(streams, buffer.readstring(b, off, len)) + end + end +end +t:note("%d VP8L bitstreams match dwebp", n) + +-- the encoder: round trips at every effort +local rand = T.rng(5) +local function gen(w: number, h: number, kind: string): buffer + local px = buffer.create(w * h * 4) + local pal = {} + local np = if kind == "pal1" then 1 elseif kind == "pal4" then 4 elseif kind == "pal40" then 40 elseif kind == "pal300" then 300 else 0 + for i = 1, np do + pal[i] = rand(2 ^ 24) * 256 + (if i % 3 == 0 then rand(256) else 255) + end + for y = 0, h - 1 do + for x = 0, w - 1 do + local o = (y * w + x) * 4 + if np > 0 then + local v = pal[(x * 7 + y * 3 + (x * y) % 5) % np + 1] + buffer.writeu32(px, o, v) + elseif kind == "noise" then + buffer.writeu32(px, o, rand(2 ^ 16) * 65536 + rand(2 ^ 16)) + else + buffer.writeu8(px, o, (x * 4 + y) % 256) + buffer.writeu8(px, o + 1, (y * 3) % 256) + buffer.writeu8(px, o + 2, (x * y) % 256) + buffer.writeu8(px, o + 3, if kind == "alpha" then (x * 9) % 256 else 255) + end + end + end + return px +end +local count = 0 +for _, kind in { "grad", "alpha", "noise", "pal1", "pal4", "pal40", "pal300" } do + for _, size in { { 1, 1 }, { 2, 3 }, { 17, 5 }, { 64, 33 }, { 130, 2 } } do + local w, h = size[1], size[2] + local px = gen(w, h, kind) + for effort = 0, 9 do + local bits, err = Vp8L.encode(px, w, h, { effort = effort, exact = true }) + t:check(bits, kind .. ": encode: " .. tostring(err)) + local back, bw, bh = Vp8L.decode(bits :: buffer) + t:check(back and bw == w and bh == h, string.format("%s %dx%d effort %d: decode: %s", kind, w, h, effort, tostring(bw))) + t:check(buffer.tostring(back :: buffer) == buffer.tostring(px), string.format("%s %dx%d effort %d: round trip", kind, w, h, effort)) + count += 1 + end + -- a headerless alpha plane + local a = buffer.create(w * h) + for i = 0, w * h - 1 do + buffer.writeu8(a, i, buffer.readu8(px, i * 4 + 1)) + end + local s = Vp8L.encodeAlpha(a, w, h) :: buffer + local ab = Vp8L.decodeAlpha(s, 0, buffer.len(s), w, h) + t:check(ab and buffer.tostring(ab) == buffer.tostring(a), kind .. ": alpha stream round trip") + end +end +t:note("%d encoder round trips", count) + +-- errors +do + local _, e1 = Vp8L.decode(buffer.fromstring("\x2e\0\0\0\0")) + t:check(e1 and e1.code == Err.CORRUPT, "bad signature: " .. tostring(e1)) + local _, e2 = Vp8L.decode(buffer.fromstring("\x2f\0\0\0\x20")) + t:check(e2 and e2.code == Err.CORRUPT, "bad version: " .. tostring(e2)) + local _, e3 = Vp8L.decode(buffer.fromstring("\x2f\0")) + t:check(e3 and e3.code == Err.TRUNCATED, "short header: " .. tostring(e3)) + local big = Vp8L.encode(gen(64, 33, "grad"), 64, 33) :: buffer + local _, e4 = Vp8L.decode(big, 0, buffer.len(big), 100) + t:check(e4 and e4.code == Err.LIMIT, "maxPixels: " .. tostring(e4)) + local _, e5 = Vp8L.decode(big, 0, buffer.len(big) // 2) + t:check(e5 and e5.code == Err.TRUNCATED, "truncated stream: " .. tostring(e5)) + local _, e6 = Vp8L.encode(buffer.create(4), 2, 2) + t:check(e6 and e6.code == Err.ARG, "encode: short pixel buffer") +end + +-- fuzz on raw bitstreams +t:fuzz("decode", function(b: buffer) + return Vp8L.decode(b, 0, buffer.len(b), 2 ^ 20) +end, streams, { mutations = 10, keepHeader = 5 }) +t:fuzz("decodeAlpha", function(b: buffer) + return Vp8L.decodeAlpha(b, 0, buffer.len(b), 37, 11) +end, streams, { mutations = 4, garbage = 100 }) + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 9f6aef7..eca470a 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1,5 +1,6 @@ -- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs. --- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus) and tools/fixtures/png.py (1024 x 768 images). +-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images) and +-- tools/fixtures/webp.py (512 x 512 lossy and lossless files). local Deflate = require("@formats/codecs/Deflate") local Crc32 = require("@formats/core/Crc32") local Bytes = require("@formats/core/Bytes") @@ -56,3 +57,22 @@ do Png.encode(img) end) end +do + local Webp = require("@formats/image/webp") + local WB = require("@tests/gen/webp_bench") + local n = WB.width * WB.height * 4 + local lossy, lossless = buffer.fromstring(WB.lossy), buffer.fromstring(WB.lossless) + bench("webp lossy decode 512x512", 3, n, function() + Webp.decode(Bytes.reader(lossy)) + end) + bench("webp lossless decode 512x512", 3, n, function() + Webp.decode(Bytes.reader(lossless)) + end) + local img = assert(Webp.decode(Bytes.reader(lossless))) + bench("webp lossless encode (effort 5)", 1, n, function() + Webp.encode(img) + end) + bench("webp lossless encode (effort 1)", 1, n, function() + Webp.encode(img, { effort = 1 }) + end) +end diff --git a/tools/bench.sh b/tools/bench.sh index c5dea4a..1fd8e1e 100644 --- a/tools/bench.sh +++ b/tools/bench.sh @@ -3,7 +3,7 @@ cd "$(dirname "$0")/.." || exit 1 LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')} LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')} -python3 -I tools/fixtures.py deflate png > /dev/null || exit 1 +python3 -I tools/fixtures.py deflate png webp > /dev/null || exit 1 python3 -I tools/build.py luajit > /dev/null || exit 1 "$LUAU" --codegen -O2 tools/bench.luau "$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua From 709b3353744c4b140b8abaf0c34bd25f82506045 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:00:59 -0500 Subject: [PATCH 4/6] ws-webp: encoder tries several transform configurations at effort 6+ (palette vs predictor, tile sizes); argument validation in encode / coalesce; NOTICE row for the libwebp ports --- licenses/NOTICE.md | 1 + src/Formats/codecs/Vp8L/Encode.luau | 78 ++++++++++++++++++++++------- src/Formats/image/webp/init.luau | 22 ++++++-- 3 files changed, 77 insertions(+), 24 deletions(-) diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 5d28e73..3182413 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -5,6 +5,7 @@ | `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) | | `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | +| `src/Formats/codecs/Vp8/` (Decode, Yuv, Tables), `src/Formats/codecs/Vp8L/Decode.luau`, `src/Formats/image/webp/` (Alpha unfilters, Anim.coalesce) | ports of libwebp 1.6.0 (Google): src/dec, src/dsp, src/utils, src/demux/anim_decode.c | BSD-3-Clause + patent grant: [libwebp-LICENSE.txt](libwebp-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/src/Formats/codecs/Vp8L/Encode.luau b/src/Formats/codecs/Vp8L/Encode.luau index 5c4fe3f..5ab2d6a 100644 --- a/src/Formats/codecs/Vp8L/Encode.luau +++ b/src/Formats/codecs/Vp8L/Encode.luau @@ -853,23 +853,14 @@ local function palette(px: buffer, n: number): { number }? 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 +type Config = { palette: { number }?, pbits: number, cc: boolean, ccbits: number } + +-- stream(px, w, h, effort, cfg, bw): the transforms and the main image of one configuration (px is consumed) +local function stream(px: buffer, w: number, h: number, effort: number, cfg: Config, bw: W) local n = w * h - local 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 + local pal = cfg.palette if pal then local num = #pal local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3 @@ -902,7 +893,7 @@ function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact end end px = packed - elseif effort > 0 then + elseif cfg.pbits > 0 then -- subtract green put(bw, 1, 1) put(bw, 2, 2) @@ -912,15 +903,15 @@ function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact 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 pbits = cfg.pbits local modes = predictorTransform(px, w, h, pbits, effort) put(bw, 1, 1) put(bw, 0, 2) put(bw, pbits - 2, 3) writeImage(bw, modes, subSample(w, pbits), subSample(w, pbits) * subSample(h, pbits), sub, false) -- cross colour - if effort >= 3 then - local cbits = if effort >= 6 then 4 else 5 + if cfg.cc then + local cbits = cfg.ccbits local cimg = crossColorTransform(px, w, h, cbits) put(bw, 1, 1) put(bw, 1, 2) @@ -930,7 +921,56 @@ function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact end put(bw, 0, 1) -- no more transforms writeImage(bw, px, xs, xs * h, effort, true) - return finish(bw) +end + +-- encode(rgba, w, h, effort, exact, alphaHint?, headerless) -> the VP8L bitstream (headerless: the image stream only, +-- as an ALPH chunk stores it). Efforts 6+ try several transform configurations and keep the smallest. +function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact: boolean, alphaHint: boolean?, headerless: boolean): buffer + local n = w * h + local px, usesAlpha = toArgb(rgba, n, exact) + local pal = if effort > 0 then palette(px, n) else nil + local configs: { Config } = {} + if effort == 0 then + table.insert(configs, { palette = nil, pbits = 0, cc = false, ccbits = 0 }) + else + local pbits = if effort >= 5 then 4 else 5 + local plain = { palette = nil, pbits = pbits, cc = effort >= 3, ccbits = if effort >= 6 then 4 else 5 } + if pal then + table.insert(configs, { palette = pal, pbits = 0, cc = false, ccbits = 0 }) + if effort >= 6 then + table.insert(configs, plain) + end + else + table.insert(configs, plain) + end + if effort >= 9 then + table.insert(configs, { palette = nil, pbits = 3, cc = true, ccbits = 3 }) + table.insert(configs, { palette = nil, pbits = 5, cc = false, ccbits = 0 }) + end + end + local best: buffer? = nil + for k, cfg in configs do + local bw = newWriter(n + 256) + if not headerless then + put(bw, 0x2f, 8) + put(bw, w - 1, 14) + put(bw, h - 1, 14) + local hint = if alphaHint == nil then usesAlpha else alphaHint + put(bw, if hint then 1 else 0, 1) + put(bw, 0, 3) + end + local work = px + if k < #configs then + work = bcreate(n * 4) + bcopy(work, 0, px, 0, n * 4) + end + stream(work, w, h, effort, cfg, bw) + local out = finish(bw) + if not best or blen(out) < blen(best) then + best = out + end + end + return best :: buffer end return Encode diff --git a/src/Formats/image/webp/init.luau b/src/Formats/image/webp/init.luau index cbb340c..e8d78c7 100644 --- a/src/Formats/image/webp/init.luau +++ b/src/Formats/image/webp/init.luau @@ -508,6 +508,15 @@ function Webp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err? 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) @@ -521,8 +530,8 @@ function Webp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err? 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 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) @@ -544,13 +553,16 @@ 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) +-- WebPAnimDecoder composites them (nil for a still image or frames that do not fit the canvas) function Webp.coalesce(img: Types.Image): { buffer }? - if not img.frames then + 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 do + 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, From dc8fedbd625945cdb1e7f64825b8548da9125b34 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:03:02 -0500 Subject: [PATCH 5/6] ws-webp: inline the boolean decoder in the VP8 token loop, cheaper loop-filter tests, no closures in 4x4 prediction; speed notes --- src/Formats/codecs/Vp8/Decode.luau | 353 +++++++++++++++++++---------- src/Formats/image/webp/init.luau | 3 + 2 files changed, 232 insertions(+), 124 deletions(-) diff --git a/src/Formats/codecs/Vp8/Decode.luau b/src/Formats/codecs/Vp8/Decode.luau index 8f019fe..eacff53 100644 --- a/src/Formats/codecs/Vp8/Decode.luau +++ b/src/Formats/codecs/Vp8/Decode.luau @@ -202,36 +202,141 @@ local function getLargeValue(br: Br, P: { number }, p: number): number end -- getCoeffs(br, P, t, ctx, dqDc, dqAc, n, out, o) -> the position of the last non-zero coefficient + 1. Writes the --- dequantized coefficients (int16, as libwebp stores them) into out at byte offset o, in raster order. +-- dequantized coefficients (int16, as libwebp stores them) into out at byte offset o, in raster order. The boolean +-- decoder is inlined (the hot loop of lossy decoding); getLargeValue goes through br. local function getCoeffs(br: Br, P: { number }, t: number, ctx: number, dqDc: number, dqAc: number, n: number, out: buffer, o: number): number local tb = t * 8 local p = ((tb + BANDS[n + 1]) * 3 + ctx) * 11 + local buf, limit = br.buf, br.limit + local value, bits, range, pos = br.value, br.bits, br.range, br.pos while n < 16 do - if getBit(br, P[p + 1]) == 0 then - return n + do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos += 3 + bits += 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * P[p + 1], 8) + local more = rshift(value, bits) > split + if more then + range -= split + value -= lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits -= sh + if not more then + br.value, br.bits, br.range, br.pos = value, bits, range, pos + return n + end end - while getBit(br, P[p + 2]) == 0 do + while true do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos += 3 + bits += 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * P[p + 2], 8) + local nonzero = rshift(value, bits) > split + if nonzero then + range -= split + value -= lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits -= sh + if nonzero then + break + end n += 1 if n == 16 then + br.value, br.bits, br.range, br.pos = value, bits, range, pos return 16 end p = (tb + BANDS[n + 1]) * 33 end local nb = (tb + BANDS[n + 2]) * 3 local v - if getBit(br, P[p + 3]) == 0 then - v = 1 - p = (nb + 1) * 11 - else - v = getLargeValue(br, P, p) - p = (nb + 2) * 11 + do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos += 3 + bits += 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * P[p + 3], 8) + local large = rshift(value, bits) > split + if large then + range -= split + value -= lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits -= sh + if not large then + v = 1 + p = (nb + 1) * 11 + else + br.value, br.bits, br.range, br.pos = value, bits, range, pos + v = getLargeValue(br, P, p) + value, bits, range, pos = br.value, br.bits, br.range, br.pos + p = (nb + 2) * 11 + end end - if getBit(br, 0x80) == 1 then - v = -v + do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos += 3 + bits += 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * 0x80, 8) + local neg = rshift(value, bits) > split + if neg then + range -= split + value -= lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits -= sh + if neg then + v = -v + end end writei16(out, o + ZIGZAG[n + 1] * 2, v * (if n > 0 then dqAc else dqDc)) n += 1 end + br.value, br.bits, br.range, br.pos = value, bits, range, pos return 16 end @@ -419,9 +524,6 @@ end -- 4x4 prediction (libwebp VP8PredLuma4): 0 DC, 1 TM, 2 VE, 3 HE, 4 RD, 5 VR, 6 LD, 7 VL, 8 HD, 9 HU local function predict4(b: buffer, dst: number, mode: number) - local function put(x: number, y: number, v: number) - writeu8(b, dst + x + y * BPS, v) - end if mode == 0 then local dc = 4 for i = 0, 3 do @@ -435,10 +537,10 @@ local function predict4(b: buffer, dst: number, mode: number) local x, a, bb, c, d, e = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3), readu8(b, t + 4) local v0, v1, v2, v3 = avg3(x, a, bb), avg3(a, bb, c), avg3(bb, c, d), avg3(c, d, e) for j = 0, 3 do - put(0, j, v0) - put(1, j, v1) - put(2, j, v2) - put(3, j, v3) + writeu8(b, dst + j * BPS + 0, v0) + writeu8(b, dst + j * BPS + 1, v1) + writeu8(b, dst + j * BPS + 2, v2) + writeu8(b, dst + j * BPS + 3, v3) end elseif mode == 3 then local A, B, C, D = readu8(b, dst - 1 - BPS), readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS) @@ -453,139 +555,139 @@ local function predict4(b: buffer, dst: number, mode: number) local X, A, B, C, D = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3) local E, F, G, H = readu8(b, t + 4), readu8(b, t + 5), readu8(b, t + 6), readu8(b, t + 7) if mode == 4 then -- RD - put(0, 3, avg3(J, K, L)) + writeu8(b, dst + 96, avg3(J, K, L)) local v = avg3(I, J, K) - put(1, 3, v) - put(0, 2, v) + writeu8(b, dst + 97, v) + writeu8(b, dst + 64, v) v = avg3(X, I, J) - put(2, 3, v) - put(1, 2, v) - put(0, 1, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 65, v) + writeu8(b, dst + 32, v) v = avg3(A, X, I) - put(3, 3, v) - put(2, 2, v) - put(1, 1, v) - put(0, 0, v) + writeu8(b, dst + 99, v) + writeu8(b, dst + 66, v) + writeu8(b, dst + 33, v) + writeu8(b, dst + 0, v) v = avg3(B, A, X) - put(3, 2, v) - put(2, 1, v) - put(1, 0, v) + writeu8(b, dst + 67, v) + writeu8(b, dst + 34, v) + writeu8(b, dst + 1, v) v = avg3(C, B, A) - put(3, 1, v) - put(2, 0, v) - put(3, 0, avg3(D, C, B)) + writeu8(b, dst + 35, v) + writeu8(b, dst + 2, v) + writeu8(b, dst + 3, avg3(D, C, B)) elseif mode == 5 then -- VR local v = avg2(X, A) - put(0, 0, v) - put(1, 2, v) + writeu8(b, dst + 0, v) + writeu8(b, dst + 65, v) v = avg2(A, B) - put(1, 0, v) - put(2, 2, v) + writeu8(b, dst + 1, v) + writeu8(b, dst + 66, v) v = avg2(B, C) - put(2, 0, v) - put(3, 2, v) - put(3, 0, avg2(C, D)) - put(0, 3, avg3(K, J, I)) - put(0, 2, avg3(J, I, X)) + writeu8(b, dst + 2, v) + writeu8(b, dst + 67, v) + writeu8(b, dst + 3, avg2(C, D)) + writeu8(b, dst + 96, avg3(K, J, I)) + writeu8(b, dst + 64, avg3(J, I, X)) v = avg3(I, X, A) - put(0, 1, v) - put(1, 3, v) + writeu8(b, dst + 32, v) + writeu8(b, dst + 97, v) v = avg3(X, A, B) - put(1, 1, v) - put(2, 3, v) + writeu8(b, dst + 33, v) + writeu8(b, dst + 98, v) v = avg3(A, B, C) - put(2, 1, v) - put(3, 3, v) - put(3, 1, avg3(B, C, D)) + writeu8(b, dst + 34, v) + writeu8(b, dst + 99, v) + writeu8(b, dst + 35, avg3(B, C, D)) elseif mode == 6 then -- LD - put(0, 0, avg3(A, B, C)) + writeu8(b, dst + 0, avg3(A, B, C)) local v = avg3(B, C, D) - put(1, 0, v) - put(0, 1, v) + writeu8(b, dst + 1, v) + writeu8(b, dst + 32, v) v = avg3(C, D, E) - put(2, 0, v) - put(1, 1, v) - put(0, 2, v) + writeu8(b, dst + 2, v) + writeu8(b, dst + 33, v) + writeu8(b, dst + 64, v) v = avg3(D, E, F) - put(3, 0, v) - put(2, 1, v) - put(1, 2, v) - put(0, 3, v) + writeu8(b, dst + 3, v) + writeu8(b, dst + 34, v) + writeu8(b, dst + 65, v) + writeu8(b, dst + 96, v) v = avg3(E, F, G) - put(3, 1, v) - put(2, 2, v) - put(1, 3, v) + writeu8(b, dst + 35, v) + writeu8(b, dst + 66, v) + writeu8(b, dst + 97, v) v = avg3(F, G, H) - put(3, 2, v) - put(2, 3, v) - put(3, 3, avg3(G, H, H)) + writeu8(b, dst + 67, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 99, avg3(G, H, H)) elseif mode == 7 then -- VL - put(0, 0, avg2(A, B)) + writeu8(b, dst + 0, avg2(A, B)) local v = avg2(B, C) - put(1, 0, v) - put(0, 2, v) + writeu8(b, dst + 1, v) + writeu8(b, dst + 64, v) v = avg2(C, D) - put(2, 0, v) - put(1, 2, v) + writeu8(b, dst + 2, v) + writeu8(b, dst + 65, v) v = avg2(D, E) - put(3, 0, v) - put(2, 2, v) - put(0, 1, avg3(A, B, C)) + writeu8(b, dst + 3, v) + writeu8(b, dst + 66, v) + writeu8(b, dst + 32, avg3(A, B, C)) v = avg3(B, C, D) - put(1, 1, v) - put(0, 3, v) + writeu8(b, dst + 33, v) + writeu8(b, dst + 96, v) v = avg3(C, D, E) - put(2, 1, v) - put(1, 3, v) + writeu8(b, dst + 34, v) + writeu8(b, dst + 97, v) v = avg3(D, E, F) - put(3, 1, v) - put(2, 3, v) - put(3, 2, avg3(E, F, G)) - put(3, 3, avg3(F, G, H)) + writeu8(b, dst + 35, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 67, avg3(E, F, G)) + writeu8(b, dst + 99, avg3(F, G, H)) elseif mode == 8 then -- HD local v = avg2(I, X) - put(0, 0, v) - put(2, 1, v) + writeu8(b, dst + 0, v) + writeu8(b, dst + 34, v) v = avg2(J, I) - put(0, 1, v) - put(2, 2, v) + writeu8(b, dst + 32, v) + writeu8(b, dst + 66, v) v = avg2(K, J) - put(0, 2, v) - put(2, 3, v) - put(0, 3, avg2(L, K)) - put(3, 0, avg3(A, B, C)) - put(2, 0, avg3(X, A, B)) + writeu8(b, dst + 64, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 96, avg2(L, K)) + writeu8(b, dst + 3, avg3(A, B, C)) + writeu8(b, dst + 2, avg3(X, A, B)) v = avg3(I, X, A) - put(1, 0, v) - put(3, 1, v) + writeu8(b, dst + 1, v) + writeu8(b, dst + 35, v) v = avg3(J, I, X) - put(1, 1, v) - put(3, 2, v) + writeu8(b, dst + 33, v) + writeu8(b, dst + 67, v) v = avg3(K, J, I) - put(1, 2, v) - put(3, 3, v) - put(1, 3, avg3(L, K, J)) + writeu8(b, dst + 65, v) + writeu8(b, dst + 99, v) + writeu8(b, dst + 97, avg3(L, K, J)) else -- HU - put(0, 0, avg2(I, J)) + writeu8(b, dst + 0, avg2(I, J)) local v = avg2(J, K) - put(2, 0, v) - put(0, 1, v) + writeu8(b, dst + 2, v) + writeu8(b, dst + 32, v) v = avg2(K, L) - put(2, 1, v) - put(0, 2, v) - put(1, 0, avg3(I, J, K)) + writeu8(b, dst + 34, v) + writeu8(b, dst + 64, v) + writeu8(b, dst + 1, avg3(I, J, K)) v = avg3(J, K, L) - put(3, 0, v) - put(1, 1, v) + writeu8(b, dst + 3, v) + writeu8(b, dst + 33, v) v = avg3(K, L, L) - put(3, 1, v) - put(1, 2, v) - put(3, 2, L) - put(2, 2, L) - put(0, 3, L) - put(1, 3, L) - put(2, 3, L) - put(3, 3, L) + writeu8(b, dst + 35, v) + writeu8(b, dst + 65, v) + writeu8(b, dst + 67, L) + writeu8(b, dst + 66, L) + writeu8(b, dst + 96, L) + writeu8(b, dst + 97, L) + writeu8(b, dst + 98, L) + writeu8(b, dst + 99, L) end end end @@ -659,15 +761,18 @@ end local function filterLoop(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number, six: boolean) local t2 = 2 * thresh + 1 for _ = 1, size do - local p3, p2, p1, p0 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs), readu8(b, p - 2 * hs), readu8(b, p - hs) - local q0, q1, q2, q3 = readu8(b, p), readu8(b, p + hs), readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) - if 4 * abs(p0 - q0) + abs(p1 - q1) <= t2 and abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(p1 - p0) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it and abs(q1 - q0) <= it then - if abs(p1 - p0) > hevT or abs(q1 - q0) > hevT then - doFilter2(b, p, hs) - elseif six then - doFilter6(b, p, hs) - else - doFilter4(b, p, hs) + local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) + if 4 * abs(p0 - q0) + abs(p1 - q1) <= t2 and abs(p1 - p0) <= it and abs(q1 - q0) <= it then + local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs) + local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) + if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then + if abs(p1 - p0) > hevT or abs(q1 - q0) > hevT then + doFilter2(b, p, hs) + elseif six then + doFilter6(b, p, hs) + else + doFilter4(b, p, hs) + end end end p += vs diff --git a/src/Formats/image/webp/init.luau b/src/Formats/image/webp/init.luau index e8d78c7..7d5a39a 100644 --- a/src/Formats/image/webp/init.luau +++ b/src/Formats/image/webp/init.luau @@ -10,6 +10,9 @@ -- 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") From 06be7e5aa9be1c54dfa35b58f74f40f848bdefb1 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:09:35 -0500 Subject: [PATCH 6/6] ws-webp: raw ALPH fixtures with every filter (horizontal / vertical / gradient), Config type fix --- src/Formats/codecs/Vp8L/Encode.luau | 2 +- tools/fixtures/webp.py | 46 +++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/Formats/codecs/Vp8L/Encode.luau b/src/Formats/codecs/Vp8L/Encode.luau index 5ab2d6a..1eff41a 100644 --- a/src/Formats/codecs/Vp8L/Encode.luau +++ b/src/Formats/codecs/Vp8L/Encode.luau @@ -934,7 +934,7 @@ function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact table.insert(configs, { palette = nil, pbits = 0, cc = false, ccbits = 0 }) else local pbits = if effort >= 5 then 4 else 5 - local plain = { palette = nil, pbits = pbits, cc = effort >= 3, ccbits = if effort >= 6 then 4 else 5 } + local plain: Config = { palette = nil, pbits = pbits, cc = effort >= 3, ccbits = if effort >= 6 then 4 else 5 } if pal then table.insert(configs, { palette = pal, pbits = 0, cc = false, ccbits = 0 }) if effort >= 6 then diff --git a/tools/fixtures/webp.py b/tools/fixtures/webp.py index 2f4ba62..da5ea3d 100644 --- a/tools/fixtures/webp.py +++ b/tools/fixtures/webp.py @@ -113,6 +113,50 @@ def riff(chunks): return b"RIFF" + struct.pack("