ws-game: image/blp (BLP1 JPEG / palette, BLP2 palette + alpha planes / DXT1-5 via codecs/image/Bcn / BGRA read; BLP2 BGRA write); codecs/image/Jpeg: opts.raw (components without colour conversion, 4th as alpha; additive)
This commit is contained in:
1 parent
e5c0873a79
commit
7a86e357ed
8 files changed
+547
No files matched your search
@@ -5,6 +5,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
|
||||
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|
||||
|---|---|---|---|---|---|---|
|
||||
| image | blp | .blp | yes | yes | alpha: true, variants: "blp1", "blp2", compressions: "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" | `tests/image/blp.luau` |
|
||||
| image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` |
|
||||
| image | gif | .gif | yes | yes | animation: true, alpha: true, palette: true, depths: 1, 2, 4, 8 | `tests/image/gif.luau` |
|
||||
| image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` |
|
||||
|
||||
@@ -14,6 +14,18 @@ export type Entry = {
|
||||
}
|
||||
|
||||
local list: { Entry } = {
|
||||
{
|
||||
name = "blp",
|
||||
category = "image",
|
||||
path = "image/blp",
|
||||
extensions = { "blp" },
|
||||
mime = { "image/x-blp" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" },
|
||||
caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } },
|
||||
load = function()
|
||||
return require("@formats/image/blp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "bmp",
|
||||
category = "image",
|
||||
|
||||
@@ -31,6 +31,7 @@ Color.RGB = 2
|
||||
Color.CMYK = 3
|
||||
Color.YCCK = 4
|
||||
Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted
|
||||
Color.RAW = 6 -- no conversion: components 1..4 as R, G, B, A (opts.raw: BLP1's BGRA JPEGs, ...)
|
||||
|
||||
export type Comp = {
|
||||
plane: buffer, -- u16 samples, stride per row
|
||||
@@ -177,6 +178,19 @@ function Color.run(P: Params)
|
||||
if nc >= 4 then
|
||||
s3, b3 = fetch(comps[4], y, outW)
|
||||
end
|
||||
if space == 6 then
|
||||
for x = 0, outW - 1 do
|
||||
local i = x * 2
|
||||
local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i)
|
||||
local c3 = if nc >= 4 then readu16(s3, b3 + i) else maxv
|
||||
if toByte then
|
||||
c0, c1, c2, c3 = readu8(toByte, c0), readu8(toByte, c1), readu8(toByte, c2), readu8(toByte, c3)
|
||||
end
|
||||
writeu32(out, o, c0 + c1 * 256 + c2 * 65536 + c3 * 16777216)
|
||||
o += 4
|
||||
end
|
||||
continue
|
||||
end
|
||||
if space == 1 and not toByte then
|
||||
-- the common case: 8-bit YCbCr
|
||||
for x = 0, outW - 1 do
|
||||
|
||||
@@ -228,6 +228,7 @@ export type State = {
|
||||
icc: buffer?,
|
||||
comments: { string },
|
||||
truncated: boolean,
|
||||
raw: boolean, -- opts.raw: no colour conversion
|
||||
scale: number,
|
||||
avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back)
|
||||
endPos: number, -- the byte after the EOI marker (or the end of the data)
|
||||
@@ -259,6 +260,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
|
||||
icc = nil,
|
||||
comments = {},
|
||||
truncated = false,
|
||||
raw = opts ~= nil and opts.raw == true,
|
||||
scale = scale,
|
||||
avi1 = nil,
|
||||
endPos = n,
|
||||
@@ -644,6 +646,9 @@ function Decode.output(st: State): (number?, any, any, string?)
|
||||
if space == "cmyk" and st.adobe == nil then
|
||||
spaceId = Color.CMYK_PLAIN
|
||||
end
|
||||
if st.raw then
|
||||
spaceId = Color.RAW
|
||||
end
|
||||
local t = yccTables(maxv)
|
||||
local tb = nil
|
||||
if maxv == 4095 then
|
||||
|
||||
@@ -43,6 +43,7 @@ export type DecodeOptions = {
|
||||
native: boolean?, -- grey files decode to gray8 (default false: rgba8)
|
||||
yuv: boolean?, -- 8-bit YCbCr / grey frames decode to yuv420p (default false); see the header for the layouts
|
||||
fields: boolean?, -- two JPEGs back to back are two fields of one frame (default: when the AVI1 segment says so)
|
||||
raw: boolean?, -- no colour conversion: 3 / 4 components as R, G, B (, A) bytes (default false; BLP1 BGRA JPEGs)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
--!strict
|
||||
-- image/blp: Blizzard BLP textures (Warcraft III: BLP1; World of Warcraft: BLP2), read, and BLP2 written
|
||||
-- (uncompressed BGRA). Written from the wowdev.wiki BLP page; no code taken.
|
||||
-- Decode, mip 0 (meta.source.mips counts the levels) to rgba8:
|
||||
-- BLP1 JPEG: the shared JPEG header + the mip's data through codecs/image/Jpeg; 4-component files (the usual
|
||||
-- Warcraft III layout) are BGRA without colour conversion, 3-component ones YCbCr -> BGR (R and B swapped back);
|
||||
-- BLP1 palette: 8-bit indexes into a BGRA palette, then an 8-bit alpha plane when alphaBits is 8 (else opaque);
|
||||
-- BLP2 palette: indexes + a 1 / 4 / 8-bit alpha plane (LSB first), DXT1 / DXT3 / DXT5 (codecs/image/Bcn: alpha
|
||||
-- type 0 / 1 / 7), uncompressed BGRA.
|
||||
-- Encode: BLP2 uncompressed BGRA with 8-bit alpha (opts.mips = true adds the box-filtered mip chain).
|
||||
-- Not supported: BLP0 (external .b00 mip files), BLP2 JPEG (never used by the games).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Jpeg = require("@formats/codecs/image/Jpeg")
|
||||
local Bcn = require("@formats/codecs/image/Bcn")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Blp = {
|
||||
name = "blp",
|
||||
category = "image",
|
||||
extensions = { "blp" },
|
||||
mime = { "image/x-blp" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" },
|
||||
caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = { maxPixels: number? } -- default 2^26
|
||||
export type EncodeOptions = { mips: boolean? } -- write the mip chain (default false)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Blp.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
return if m == "BLP1" or m == "BLP2" then 1 elseif m == "BLP0" then 0.8 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- BGRA u32 (b at the lowest address) -> RGBA u32 with the given alpha
|
||||
local function swap(v: number, a: number): number
|
||||
local b, g, r = v % 256, (v // 256) % 256, (v // 65536) % 256
|
||||
return r + g * 256 + b * 65536 + a * 16777216
|
||||
end
|
||||
|
||||
-- alpha of pixel i from a packed plane at p of depth bits
|
||||
local function alphaAt(b: buffer, p: number, depth: number, i: number): number
|
||||
if depth == 8 then
|
||||
return readu8(b, p + i)
|
||||
elseif depth == 4 then
|
||||
local v = readu8(b, p + i // 2)
|
||||
local n = if i % 2 == 0 then v % 16 else v // 16
|
||||
return n * 17
|
||||
elseif depth == 1 then
|
||||
local v = readu8(b, p + i // 8)
|
||||
return if bit32.band(v, bit32.lshift(1, i % 8)) ~= 0 then 255 else 0
|
||||
end
|
||||
return 255
|
||||
end
|
||||
|
||||
function Blp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local size = r.limit - r.base
|
||||
local b, base = r.buf, r.base
|
||||
local magic = r:peek(4)
|
||||
if magic == "BLP0" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "BLP0 (mips in external files)", 0)
|
||||
end
|
||||
if magic ~= "BLP1" and magic ~= "BLP2" then
|
||||
return nil, Err.new(if size < 4 then Err.TRUNCATED else Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local v2 = magic == "BLP2"
|
||||
local headerSize = if v2 then 20 + 128 + 1024 else 28 + 128
|
||||
if size < headerSize then
|
||||
return nil, Err.new(Err.TRUNCATED, "header", 0)
|
||||
end
|
||||
local kind = readu32(b, base + 4) -- BLP1: 0 = JPEG, 1 = palette; BLP2: 1 (0 = JPEG)
|
||||
local compression = if v2 then readu8(b, base + 8) elseif kind == 0 then 0 else 1
|
||||
local alphaDepth = if v2 then readu8(b, base + 9) else readu32(b, base + 8)
|
||||
local alphaType = if v2 then readu8(b, base + 10) else 0
|
||||
local w, h = readu32(b, base + 12), readu32(b, base + 16)
|
||||
local mipsAt = if v2 then 20 else 28
|
||||
if w == 0 or h == 0 or w > 65535 or h > 65535 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad size " .. w .. " x " .. h, 12)
|
||||
end
|
||||
if w * h > (opts and opts.maxPixels or 2 ^ 26) then
|
||||
return nil, Err.new(Err.LIMIT, "image too big")
|
||||
end
|
||||
local offs: { number }, lens: { number } = {}, {}
|
||||
local mips = 0
|
||||
for i = 0, 15 do
|
||||
offs[i + 1] = readu32(b, base + mipsAt + i * 4)
|
||||
lens[i + 1] = readu32(b, base + mipsAt + 64 + i * 4)
|
||||
if offs[i + 1] ~= 0 and lens[i + 1] ~= 0 then
|
||||
mips += 1
|
||||
end
|
||||
end
|
||||
local at, len = offs[1], lens[1]
|
||||
if at + len > size or len == 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "mip 0 past the end", mipsAt)
|
||||
end
|
||||
local img = Types.Image.new(w, h)
|
||||
local px = img.pixels
|
||||
local n = w * h
|
||||
local src = base + at
|
||||
local name: string
|
||||
if (not v2 and kind == 0) or (v2 and kind == 0) then
|
||||
if v2 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "BLP2 JPEG")
|
||||
end
|
||||
-- the JPEG header shared by the mips, then the mip's own data
|
||||
if size < headerSize + 4 then
|
||||
return nil, Err.new(Err.TRUNCATED, "JPEG header size", headerSize)
|
||||
end
|
||||
local hs = readu32(b, base + headerSize)
|
||||
if hs > 0x10000 or headerSize + 4 + hs > size then
|
||||
return nil, Err.new(Err.CORRUPT, "bad JPEG header size", headerSize)
|
||||
end
|
||||
local jpg = buffer.create(hs + len)
|
||||
buffer.copy(jpg, 0, b, base + headerSize + 4, hs)
|
||||
buffer.copy(jpg, hs, b, src, len)
|
||||
local info = Jpeg.info(jpg)
|
||||
local four = info ~= nil and (info :: any).components == 4
|
||||
local dec, err = Jpeg.decode(jpg, 0, nil, { raw = four, maxPixels = opts and opts.maxPixels })
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local dw, dh = math.min(dec.width, w), math.min(dec.height, h)
|
||||
for y = 0, dh - 1 do
|
||||
for x = 0, dw - 1 do
|
||||
local v = readu32(dec.pixels, (y * dec.width + x) * 4)
|
||||
local a = if four and alphaDepth > 0 then v // 16777216 else 255
|
||||
writeu32(px, (y * w + x) * 4, swap(v, a))
|
||||
end
|
||||
end
|
||||
name = "jpeg"
|
||||
elseif compression == 1 then
|
||||
local palAt = base + (if v2 then 148 else headerSize)
|
||||
local dataAt = src
|
||||
if not v2 then
|
||||
-- BLP1: the palette follows the header; the mip offsets point past it
|
||||
if headerSize + 1024 > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "palette", headerSize)
|
||||
end
|
||||
end
|
||||
local depth = if v2 then alphaDepth else (if alphaDepth >= 8 then 8 else 0)
|
||||
local need = n + (if depth == 8 then n elseif depth == 4 then (n + 1) // 2 elseif depth == 1 then (n + 7) // 8 else 0)
|
||||
if at + need > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "palette mip past the end", at)
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
local e = readu32(b, palAt + readu8(b, dataAt + i) * 4)
|
||||
writeu32(px, i * 4, swap(e, if depth > 0 then alphaAt(b, dataAt + n, depth, i) else 255))
|
||||
end
|
||||
name = "palette"
|
||||
elseif compression == 2 then
|
||||
local kindName = if alphaType == 7 then "bc3" elseif alphaType == 1 then "bc2" else "bc1"
|
||||
local want: number = Bcn.size(kindName, w, h) or 0
|
||||
if len < want then
|
||||
return nil, Err.new(Err.TRUNCATED, "DXT mip shorter than " .. want .. " bytes", mipsAt + 64)
|
||||
end
|
||||
local dec, err = Bcn.decode(kindName, b, src, w, h)
|
||||
if not dec then
|
||||
return nil, Err.from(err)
|
||||
end
|
||||
buffer.copy(px, 0, dec, 0, n * 4)
|
||||
if kindName == "bc1" and alphaDepth == 0 then
|
||||
for i = 0, n - 1 do
|
||||
writeu8(px, i * 4 + 3, 255)
|
||||
end
|
||||
end
|
||||
name = ({ bc1 = "dxt1", bc2 = "dxt3", bc3 = "dxt5" } :: { [string]: string })[kindName]
|
||||
elseif compression == 3 then
|
||||
if len < n * 4 then
|
||||
return nil, Err.new(Err.TRUNCATED, "BGRA mip too short", mipsAt + 64)
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
local v = readu32(b, src + i * 4)
|
||||
writeu32(px, i * 4, swap(v, v // 16777216))
|
||||
end
|
||||
name = "bgra"
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, "compression " .. tostring(compression))
|
||||
end
|
||||
img.meta.source = { format = "blp", version = if v2 then 2 else 1, compression = name, alphaDepth = alphaDepth, alphaType = alphaType, mips = mips }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- halve(px, w, h) -> the next mip (2 x 2 box filter; odd edges repeat)
|
||||
local function halve(px: buffer, w: number, h: number): (buffer, number, number)
|
||||
local nw, nh = math.max(1, w // 2), math.max(1, h // 2)
|
||||
local out = buffer.create(nw * nh * 4)
|
||||
for y = 0, nh - 1 do
|
||||
for x = 0, nw - 1 do
|
||||
for c = 0, 3 do
|
||||
local s = 0
|
||||
for dy = 0, 1 do
|
||||
for dx = 0, 1 do
|
||||
local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1)
|
||||
s += readu8(px, (sy * w + sx) * 4 + c)
|
||||
end
|
||||
end
|
||||
writeu8(out, (y * nw + x) * 4 + c, (s + 2) // 4)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, nw, nh
|
||||
end
|
||||
|
||||
function Blp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "expected an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 then
|
||||
return nil, Err.new(Err.ARG, "bad size")
|
||||
end
|
||||
local levels: { buffer } = { img.pixels }
|
||||
local sizes: { { number } } = { { w, h } }
|
||||
if opts and opts.mips then
|
||||
local p, cw, ch = img.pixels, w, h
|
||||
while (cw > 1 or ch > 1) and #levels < 16 do
|
||||
p, cw, ch = halve(p, cw, ch)
|
||||
table.insert(levels, p)
|
||||
table.insert(sizes, { cw, ch })
|
||||
end
|
||||
end
|
||||
local out = Bytes.writer(1172 + w * h * 6)
|
||||
out:string("BLP2")
|
||||
out:u32le(1)
|
||||
out:u8(3) -- uncompressed BGRA
|
||||
out:u8(8) -- alpha depth
|
||||
out:u8(8) -- alpha type
|
||||
out:u8(if #levels > 1 then 1 else 0)
|
||||
out:u32le(w)
|
||||
out:u32le(h)
|
||||
local at = 1172
|
||||
for i = 1, 16 do
|
||||
local l = levels[i]
|
||||
out:u32le(if l then at else 0)
|
||||
if l then
|
||||
at += buffer.len(l)
|
||||
end
|
||||
end
|
||||
for i = 1, 16 do
|
||||
local l = levels[i]
|
||||
out:u32le(if l then buffer.len(l) else 0)
|
||||
end
|
||||
out:fill(0, 1024)
|
||||
for _, l in levels do
|
||||
local p = out:reserve(buffer.len(l))
|
||||
local o = out.buf
|
||||
for i = 0, buffer.len(l) // 4 - 1 do
|
||||
local v = readu32(l, i * 4)
|
||||
writeu32(o, p + i * 4, swap(v, v // 16777216))
|
||||
end
|
||||
out.pos = p + buffer.len(l)
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Blp
|
||||
@@ -0,0 +1,89 @@
|
||||
-- image/blp tests: BLP1 / BLP2 palette files written by Pillow and DXT1 / DXT3 / DXT5 / palette-with-alpha files
|
||||
-- written by tools/fixtures/blp.py decode to Pillow's RGBA; BLP1 JPEG (3 components) to Pillow's, 4 components (BGRA)
|
||||
-- within a PSNR of the source; BLP2 BGRA and BLP1 palette + alpha against the writer; our BLP2 writer round-trips
|
||||
-- (with mips); errors; the fuzz pass. Fixtures: tools/fixtures/blp.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Blp = require("@formats/image/blp")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Fx = require("@tests/gen/blp")
|
||||
|
||||
local t = T.suite("blp")
|
||||
t:eq(Blp.name, "blp", "name")
|
||||
|
||||
local function psnr(a: buffer, b: string): number
|
||||
local se = 0
|
||||
for i = 0, #b - 1 do
|
||||
local d = buffer.readu8(a, i) - string.byte(b, i + 1)
|
||||
se += d * d
|
||||
end
|
||||
if se == 0 then
|
||||
return math.huge
|
||||
end
|
||||
return 10 * math.log10(255 * 255 / (se / #b))
|
||||
end
|
||||
|
||||
for _, c in Fx do
|
||||
local img, err = Blp.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
t:eq(F.detect(c.data), "blp", c.name .. ": F.detect")
|
||||
t:check(img.width == c.width and img.height == c.height, c.name .. ": size")
|
||||
if c.crc then
|
||||
t:eq(Crc32.of(img.pixels), c.crc, c.name .. ": pixels against Pillow")
|
||||
elseif c.ref then
|
||||
local worst, alpha = 0, true
|
||||
for i = 0, #c.ref - 1 do
|
||||
local d = math.abs(buffer.readu8(img.pixels, i) - string.byte(c.ref, i + 1))
|
||||
if i % 4 == 3 then
|
||||
alpha = alpha and d == 0
|
||||
else
|
||||
worst = math.max(worst, d)
|
||||
end
|
||||
end
|
||||
t:check(worst <= c.tol, c.name .. ": colours within " .. c.tol .. " of Pillow (worst " .. worst .. ")")
|
||||
t:check(alpha, c.name .. ": alpha equal to Pillow's")
|
||||
elseif c.rgbref then
|
||||
local ok = true
|
||||
for i = 0, img.width * img.height - 1 do
|
||||
for k = 0, 2 do
|
||||
ok = ok and buffer.readu8(img.pixels, i * 4 + k) == string.byte(c.rgbref, i * 4 + k + 1)
|
||||
end
|
||||
ok = ok and buffer.readu8(img.pixels, i * 4 + 3) == string.byte(c.alpha, i + 1)
|
||||
end
|
||||
t:check(ok, c.name .. ": RGB against Pillow, alpha plane against the writer")
|
||||
elseif c.psnr then
|
||||
local p = psnr(img.pixels, c.rgba)
|
||||
t:check(p >= c.psnr, string.format("%s: PSNR %.1f dB", c.name, p))
|
||||
t:note("%s: PSNR %.1f dB against the source", c.name, p)
|
||||
else
|
||||
t:check(buffer.tostring(img.pixels) == c.rgba, c.name .. ": pixels against the writer")
|
||||
end
|
||||
-- our writer: BLP2 BGRA, lossless
|
||||
local enc = Blp.encode(img, { mips = true }) :: buffer
|
||||
local back = Blp.decode(Bytes.reader(enc)) :: any
|
||||
t:eq(Crc32.of(back.pixels), Crc32.of(img.pixels), c.name .. ": BLP2 BGRA round trip")
|
||||
t:check(back.meta.source.mips > 1 or (img.width == 1 and img.height == 1), c.name .. ": mips written")
|
||||
end
|
||||
|
||||
do
|
||||
local _, e1 = Blp.decode(Bytes.reader(buffer.fromstring(string.sub(Fx[3].data, 1, 1200))))
|
||||
t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
|
||||
local _, e2 = Blp.decode(Bytes.reader(buffer.fromstring("BLP0" .. string.rep("\0", 200))))
|
||||
t:check(e2 and e2.code == Err.UNSUPPORTED, "BLP0")
|
||||
local _, e3 = Blp.encode({ format = "rgba16" } :: any)
|
||||
t:check(e3 and e3.code == Err.ARG, "encode needs rgba8")
|
||||
local one = Types.Image.new(1, 1)
|
||||
t:check(Blp.decode(Bytes.reader(Blp.encode(one) :: buffer)) ~= nil, "1 x 1")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Blp.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 40 })
|
||||
t:done()
|
||||
@@ -0,0 +1,159 @@
|
||||
# Blizzard BLP fixtures (tools/fixtures.py). Pillow (nix python3 pillow) is the reference decoder: it writes BLP2
|
||||
# palette files itself (not BLP1: Pillow 12 writes BLP1 mip offsets as if the header were BLP2's, 8 bytes short), and decodes the files written here from the wowdev.wiki layout: BLP2 DXT1 / DXT3 / DXT5
|
||||
# (random blocks), palette with 1 / 4 / 8-bit alpha planes, mip chains, and BLP1 JPEG (a Pillow
|
||||
# JPEG split into the shared header and the mip data). Pillow's RGBA -> CRC-32. Two cases Pillow reads differently
|
||||
# from the games (or not at all) are checked against this writer instead: uncompressed BGRA (Pillow 12 has no
|
||||
# encoding 3), BLP1 palette files with an 8-bit alpha plane, and BLP1
|
||||
# JPEGs of 4 components (BGRA without colour conversion: CMYK written inverted by Pillow, its Adobe marker removed)
|
||||
# whose reference is the source pixels (PSNR).
|
||||
# tests/gen/blp.luau { { name, data, width, height, crc?, rgba?, psnr? } }
|
||||
import io, json, struct, zlib
|
||||
|
||||
CODE = r"""
|
||||
import io, json, sys, zlib, random, struct
|
||||
from PIL import Image
|
||||
args = json.loads(sys.stdin.read())
|
||||
rng = random.Random(args["seed"])
|
||||
out = {}
|
||||
|
||||
def rgba_crc(im):
|
||||
return zlib.crc32(im.convert("RGBA").tobytes())
|
||||
|
||||
# 1. Pillow-written palette BLPs
|
||||
pal_img = Image.new("P", (13, 7))
|
||||
pal_img.putpalette(bytes(rng.randrange(256) for _ in range(768)))
|
||||
pal_img.putdata([rng.randrange(256) for _ in range(13 * 7)])
|
||||
for v in ("BLP2",):
|
||||
b = io.BytesIO()
|
||||
pal_img.save(b, "BLP", blp_version=v)
|
||||
data = b.getvalue()
|
||||
out["pillow-" + v.lower()] = {"data": data.hex(), "crc": rgba_crc(Image.open(io.BytesIO(data))), "w": 13, "h": 7}
|
||||
|
||||
# 2. Pillow decodes the hand-made files
|
||||
for name, hexdata in args["files"].items():
|
||||
try:
|
||||
im = Image.open(io.BytesIO(bytes.fromhex(hexdata)))
|
||||
im.load()
|
||||
out[name] = {"crc": rgba_crc(im), "w": im.size[0], "h": im.size[1], "rgba": im.convert("RGBA").tobytes().hex()}
|
||||
except Exception as e:
|
||||
out[name] = {"failed": str(e)}
|
||||
|
||||
# 3. JPEGs for BLP1: a 3-component one and a 4-component (CMYK) one
|
||||
src = Image.new("RGB", (24, 16))
|
||||
src.putdata([(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(24 * 16)])
|
||||
src = src.resize((24, 16))
|
||||
b = io.BytesIO(); src.save(b, "JPEG", quality=95)
|
||||
out["jpeg3"] = b.getvalue().hex()
|
||||
# smooth RGBA source pixels for the 4-component file, stored as B, G, R, A components
|
||||
px = [((x * 10) % 256, (y * 15) % 256, ((x + y) * 7) % 256, (255 - x * 8) % 256) for y in range(16) for x in range(24)]
|
||||
cm = Image.new("CMYK", (24, 16))
|
||||
# Pillow stores CMYK inverted: write 255 - (b, g, r, a) so the stored components are B, G, R, A
|
||||
cm.putdata([(255 - p[2], 255 - p[1], 255 - p[0], 255 - p[3]) for p in px])
|
||||
b = io.BytesIO(); cm.save(b, "JPEG", quality=98)
|
||||
out["jpeg4"] = b.getvalue().hex()
|
||||
out["jpeg4src"] = bytes(c for p in px for c in p).hex()
|
||||
print(json.dumps(out))
|
||||
"""
|
||||
|
||||
|
||||
def blp2(kind, comp, adepth, atype, w, h, mips, palette=b"\0" * 1024):
|
||||
offs, lens, at = [], [], 1172
|
||||
for m in mips:
|
||||
offs.append(at)
|
||||
lens.append(len(m))
|
||||
at += len(m)
|
||||
offs += [0] * (16 - len(mips))
|
||||
lens += [0] * (16 - len(mips))
|
||||
head = b"BLP2" + struct.pack("<IBBBBII", kind, comp, adepth, atype, 1 if len(mips) > 1 else 0, w, h)
|
||||
return head + struct.pack("<16I", *offs) + struct.pack("<16I", *lens) + palette + b"".join(mips)
|
||||
|
||||
|
||||
def blp1(comp, adepth, w, h, mips, extra=b""):
|
||||
base = 156 + len(extra)
|
||||
offs, lens, at = [], [], base
|
||||
for m in mips:
|
||||
offs.append(at)
|
||||
lens.append(len(m))
|
||||
at += len(m)
|
||||
offs += [0] * (16 - len(mips))
|
||||
lens += [0] * (16 - len(mips))
|
||||
return b"BLP1" + struct.pack("<6I", comp, adepth, w, h, 4, 1 if len(mips) > 1 else 0) + struct.pack("<16I", *offs) + struct.pack("<16I", *lens) + extra + b"".join(mips)
|
||||
|
||||
|
||||
def split_jpeg(j):
|
||||
# the shared header: everything before the first SOS marker
|
||||
k = j.index(b"\xff\xda")
|
||||
return j[:k], j[k:]
|
||||
|
||||
|
||||
def strip_adobe(j):
|
||||
i = j.find(b"\xff\xee")
|
||||
if i < 0:
|
||||
return j
|
||||
n = struct.unpack(">H", j[i + 2:i + 4])[0]
|
||||
return j[:i] + j[i + 2 + n:]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(121)
|
||||
w, h = 16, 12
|
||||
files = {}
|
||||
for name, atype, bs in (("dxt1", 0, 8), ("dxt3", 1, 16), ("dxt5", 7, 16)):
|
||||
blocks = rng.randbytes((w // 4) * (h // 4) * bs)
|
||||
files[name] = blp2(1, 2, 1 if name == "dxt1" else 8, atype, w, h, [blocks, rng.randbytes(2 * 2 * bs)]) # mip 1: 8 x 6
|
||||
bgra = rng.randbytes(w * h * 4)
|
||||
own = [{"name": "bgra", "data": blp2(1, 3, 8, 8, w, h, [bgra]), "width": w, "height": h,
|
||||
"rgba": b"".join(bytes((bgra[i + 2], bgra[i + 1], bgra[i], bgra[i + 3])) for i in range(0, len(bgra), 4))}]
|
||||
pal = bytes(rng.randrange(256) for _ in range(1024))
|
||||
alphas = {}
|
||||
for depth in (0, 1, 4, 8):
|
||||
idx = rng.randbytes(w * h)
|
||||
alpha = rng.randbytes({0: 0, 1: w * h // 8, 4: w * h // 2, 8: w * h}[depth])
|
||||
files["palette-a%d" % depth] = blp2(1, 1, depth, 0, w, h, [idx + alpha], pal)
|
||||
# the alpha plane (LSB first), expanded to 8 bits
|
||||
if depth == 1:
|
||||
alphas[depth] = bytes(255 if alpha[i // 8] >> (i % 8) & 1 else 0 for i in range(w * h))
|
||||
elif depth == 4:
|
||||
alphas[depth] = bytes(((alpha[i // 2] >> (4 * (i % 2))) & 15) * 17 for i in range(w * h))
|
||||
elif depth == 8:
|
||||
alphas[depth] = alpha
|
||||
res = json.loads(ctx.python(["pillow"], CODE, input=json.dumps({"seed": 5, "files": {k: v.hex() for k, v in files.items()}}).encode()))
|
||||
out = []
|
||||
for name in ("pillow-blp2",):
|
||||
r = res[name]
|
||||
out.append({"name": name, "data": bytes.fromhex(r["data"]), "width": r["w"], "height": r["h"], "crc": r["crc"]})
|
||||
for name, data in files.items():
|
||||
r = res[name]
|
||||
if "failed" in r:
|
||||
raise SystemExit("blp: Pillow cannot read %s: %s" % (name, r["failed"]))
|
||||
e = {"name": name, "data": data, "width": r["w"], "height": r["h"]}
|
||||
if name.startswith("dxt"):
|
||||
# Pillow's own DXT decoder expands the 5 / 6-bit endpoints by shifting only (r << 3), the D3D rule
|
||||
# replicates the top bits (r << 3 | r >> 2), and divides by 3 without rounding: colours compared within
|
||||
# 8, alpha exactly
|
||||
e["ref"], e["tol"] = bytes.fromhex(r["rgba"]), 8
|
||||
elif name.startswith("palette-a") and name != "palette-a0":
|
||||
# Pillow ignores the alpha plane (it takes the palette's alpha): RGB from Pillow, alpha from the writer
|
||||
e["rgbref"], e["alpha"] = bytes.fromhex(r["rgba"]), alphas[int(name[-1])]
|
||||
else:
|
||||
e["crc"] = r["crc"]
|
||||
out.append(e)
|
||||
out += own
|
||||
# BLP1 JPEG, 3 components: Pillow decodes it (YCbCr -> RGB, then R / B swapped)
|
||||
j3 = bytes.fromhex(res["jpeg3"])
|
||||
hd, body = split_jpeg(j3)
|
||||
d = blp1(0, 0, 24, 16, [body], struct.pack("<I", len(hd)) + hd)
|
||||
r = json.loads(ctx.python(["pillow"], CODE.split("# 1.")[0] + "im = Image.open(io.BytesIO(bytes.fromhex(args['d'])))\nprint(json.dumps({'crc': rgba_crc(im)}))\n", input=json.dumps({"seed": 1, "d": d.hex()}).encode()))
|
||||
out.append({"name": "blp1-jpeg3", "data": d, "width": 24, "height": 16, "crc": r["crc"]})
|
||||
# BLP1 JPEG, 4 components (BGRA)
|
||||
j4 = strip_adobe(bytes.fromhex(res["jpeg4"]))
|
||||
hd, body = split_jpeg(j4)
|
||||
d = blp1(0, 8, 24, 16, [body], struct.pack("<I", len(hd)) + hd)
|
||||
out.append({"name": "blp1-jpeg4", "data": d, "width": 24, "height": 16, "rgba": bytes.fromhex(res["jpeg4src"]), "psnr": 30})
|
||||
# BLP1 palette with an 8-bit alpha plane: indexes then alpha
|
||||
idx = rng.randbytes(w * h)
|
||||
alpha = rng.randbytes(w * h)
|
||||
d = blp1(1, 8, w, h, [idx + alpha], pal)
|
||||
rgba = b"".join(bytes((pal[i * 4 + 2], pal[i * 4 + 1], pal[i * 4], alpha[k])) for k, i in enumerate(idx))
|
||||
out.append({"name": "blp1-palette-a8", "data": d, "width": w, "height": h, "rgba": rgba})
|
||||
ctx.emit("blp", out)
|
||||
Reference in new issue
Block a user