ws-webp: image/webp (VP8 / VP8L / ALPH / VP8X / animation / metadata decode, lossless + animated encode), codecs/Vp8L encoder, fixtures vs dwebp / Pillow / libvpx, tests
This commit is contained in:
1 parent
5bad752d91
commit
7c3d4b75ec
10 files changed
+2449
-3
No files matched your search
@@ -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:
|
||||
-- "<name> <hex>" (stills: <source>_e<effort>_<exact|loose>) or "anim<k>:<crc>,<crc>,... <hex>" 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
|
||||
@@ -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("<I", data, p)[0]
|
||||
frames.append(data[p + 12:p + 12 + n])
|
||||
p += 12 + n
|
||||
return frames
|
||||
|
||||
|
||||
def riff(chunks):
|
||||
body = b"WEBP"
|
||||
for fourcc, payload in chunks:
|
||||
body += fourcc + struct.pack("<I", len(payload)) + payload + (b"\0" if len(payload) % 2 else b"")
|
||||
return b"RIFF" + struct.pack("<I", len(body)) + body
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="webp_fx_")
|
||||
try:
|
||||
_generate(ctx, tmp)
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
def _generate(ctx, tmp):
|
||||
rng = ctx.rng(20260)
|
||||
# 1. sources: ImageMagick's built-in images (resized) + synthetic ones
|
||||
run(tmp, "\n".join([
|
||||
"magick rose: -alpha off PAM:rose.pam",
|
||||
"magick granite: -alpha off PAM:granite.pam",
|
||||
"magick netscape: -alpha off PAM:netscape.pam",
|
||||
"magick wizard: -resize 120x160 -alpha off PAM:wizard.pam",
|
||||
"magick logo: -resize 160x120 -alpha off PAM:logo.pam",
|
||||
"magick -seed 7 -size 200x150 plasma:fractal -depth 8 -alpha off PAM:plasma.pam",
|
||||
"magick wizard: -resize 512x512! -alpha off PAM:bench.pam",
|
||||
]))
|
||||
sources = []
|
||||
for n in ["rose", "granite", "netscape", "wizard", "logo", "plasma"]:
|
||||
w, h, px = pam_read(open(os.path.join(tmp, n + ".pam"), "rb").read())
|
||||
sources.append((n, w, h, px))
|
||||
base = {s[0]: s for s in sources}
|
||||
sources.append(add_alpha("rose_a", *base["rose"][1:], "ramp"))
|
||||
sources.append(add_alpha("plasma_a", *base["plasma"][1:], "blocks"))
|
||||
sources += synthetic(rng)
|
||||
for n, w, h, px in sources:
|
||||
pam_write(os.path.join(tmp, n + ".pam"), w, h, px)
|
||||
ctx.emit("webp_src", [{"name": n, "width": w, "height": h, "rgba": px} for n, w, h, px in sources])
|
||||
|
||||
# 2. still files: cwebp lossless / lossy / alpha variants, libvpx key frames, metadata
|
||||
files = [] # (name, extra info)
|
||||
lines = []
|
||||
for n, w, h, px in sources:
|
||||
has_alpha = any(px[i] != 255 for i in range(3, len(px), 4))
|
||||
full = n in FULL
|
||||
for tag, args in LOSSLESS if full else LOSSLESS[2:3]:
|
||||
lines.append("cwebp -quiet %s %s.pam -o %s_%s.webp" % (args, n, n, tag))
|
||||
files.append(("%s_%s.webp" % (n, tag), {"lossy": False}))
|
||||
for tag, args in LOSSY if full else LOSSY[1:2]:
|
||||
lines.append("cwebp -quiet %s %s.pam -o %s_%s.webp" % (args, n, n, tag))
|
||||
files.append(("%s_%s.webp" % (n, tag), {"lossy": True}))
|
||||
if has_alpha:
|
||||
for tag, args in ALPHA if full or n == "plasma_a" else ALPHA[1:2]:
|
||||
lines.append("cwebp -quiet %s %s.pam -o %s_%s.webp" % (args, n, n, tag))
|
||||
files.append(("%s_%s.webp" % (n, tag), {"lossy": True}))
|
||||
for n in ["rose", "granite", "plasma", "wizard"]:
|
||||
for k, (slices, q) in enumerate([(1, 10), (2, 30), (4, 50), (8, 63)]):
|
||||
lines.append("magick %s.pam -alpha off PNG24:%s_vpx.png" % (n, n))
|
||||
lines.append("ffmpeg -loglevel error -y -i %s_vpx.png -c:v libvpx -slices %d -qmin %d -qmax %d -b:v 1M -sharpness %d -f ivf %s_vpx%d.ivf"
|
||||
% (n, slices, q, q, k, n, k))
|
||||
lines.append("cwebp -quiet -q 60 rose_a.pam -o meta_base.webp")
|
||||
lines.append("head -c 600 /dev/urandom > meta.icc && head -c 100 /dev/urandom > meta.exif && printf '<x:xmpmeta/>' > 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"] = "<x:xmpmeta/>"
|
||||
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 <nixpkgs> {}; 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)
|
||||
Reference in new issue
Block a user