From e0629b12a309e3ee97b7cae35b061ba381713319 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:39:56 -0500 Subject: [PATCH] vec: layered/psd (PSD/PSB read: all modes/depths, RLE/ZIP, groups, masks, clipping; write: 8-bit RGB layers + merged), codecs/Blend (blend modes, layer-tree compositing), ops/LayerOps (flatten, frames, leaves); Types: Layer gains optional children/clip/mask + Layered.layer/group constructors (backward compatible). Tests vs psd-tools incl. psd-tools reading our PSD --- docs/FORMATS.md | 2 + src/Formats/Registry.luau | 12 + src/Formats/Types.luau | 18 +- src/Formats/codecs/Blend.luau | 371 +++++++++++++ src/Formats/layered/psd/Channels.luau | 383 +++++++++++++ src/Formats/layered/psd/init.luau | 758 ++++++++++++++++++++++++++ src/Formats/ops/LayerOps.luau | 101 ++++ tests/layered/psd.luau | 184 +++++++ tests/ops/layerops.luau | 144 +++++ tools/fixtures/_ours.luau | 102 ++++ tools/fixtures/psd.py | 389 +++++++++++++ 11 files changed, 2461 insertions(+), 3 deletions(-) create mode 100644 src/Formats/codecs/Blend.luau create mode 100644 src/Formats/layered/psd/Channels.luau create mode 100644 src/Formats/layered/psd/init.luau create mode 100644 src/Formats/ops/LayerOps.luau create mode 100644 tests/layered/psd.luau create mode 100644 tests/ops/layerops.luau create mode 100644 tools/fixtures/_ours.luau create mode 100644 tools/fixtures/psd.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 634a40c..5f33ef3 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,10 +6,12 @@ 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` | +| layered | psd | .psd .psb | yes | yes | layers: true, groups: true, depths: 1, 8, 16, 32 | `tests/layered/psd.luau` | | subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` | | subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` | | subtitle | vtt | .vtt .webvtt | yes | yes | styles: true | `tests/subtitle/vtt.luau` | Codecs (layer 1, shared by formats; not loadable on their own): +- codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 18eb359..cef9c24 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 = "psd", + category = "layered", + path = "layered/psd", + extensions = { "psd", "psb" }, + mime = { "image/vnd.adobe.photoshop" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Blend", "codecs/Deflate" }, + caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } }, + load = function() + return require("@formats/layered/psd") + end, + }, { name = "ass", category = "subtitle", diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 9f37bd1..ea12b0c 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -376,19 +376,31 @@ end Types.Vector = Vector -- ------------------------------------------------------------------------------------------------ Layered (PSD, Aseprite) -export type Layer = { name: string, image: Image, x: number, y: number, opacity: number, blend: string, visible: boolean } +-- blend: a codecs/Blend mode name ("normal", "multiply", ...; groups also "passThrough"). Optional: children (a group: +-- its layers bottom to top; its image is 0 x 0), clip (clipped to the alpha of the layer below), mask (a grey mask in +-- canvas coordinates; outside its rectangle the mask is `default`). +export type LayerMask = { image: Image, x: number, y: number, default: number, disabled: boolean? } +export type Layer = { name: string, image: Image, x: number, y: number, opacity: number, blend: string, visible: boolean, children: { Layer }?, clip: boolean?, mask: LayerMask? } export type Layered = { kind: "layered", width: number, height: number, - layers: { Layer }, -- bottom to top - frames: { { layers: { Layer }, delay: number } }?, + layers: { Layer }, -- bottom to top (a tree: groups have children); animations: frame 1's layers + frames: { { layers: { Layer }, delay: number } }?, -- animations (Aseprite): every frame's layers, delay in seconds meta: { [string]: any }, } local Layered = {} function Layered.new(width: number, height: number): Layered return { kind = "layered", width = width, height = height, layers = {}, frames = nil, meta = {} } end +-- layer(name, image, x?, y?) -> a visible normal layer at full opacity +function Layered.layer(name: string, image: Image, x: number?, y: number?): Layer + return { name = name, image = image, x = x or 0, y = y or 0, opacity = 1, blend = "normal", visible = true } +end +-- group(name, children) -> a pass-through group layer +function Layered.group(name: string, children: { Layer }): Layer + return { name = name, image = Image.new(0, 0), x = 0, y = 0, opacity = 1, blend = "passThrough", visible = true, children = children } +end Types.Layered = Layered -- ------------------------------------------------------------------------------------------------ TileMap (Tiled) diff --git a/src/Formats/codecs/Blend.luau b/src/Formats/codecs/Blend.luau new file mode 100644 index 0000000..a3db2a9 --- /dev/null +++ b/src/Formats/codecs/Blend.luau @@ -0,0 +1,371 @@ +--!strict +--!native +-- codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable +-- blend modes of the W3C Compositing and Blending Level 1 spec (the Photoshop / Aseprite set), opacity, a grey layer +-- mask, clipping (source-atop: the backdrop keeps its alpha) and dissolve. Shared by ops/LayerOps (flatten) and the +-- layered formats that must write a composite (layered/psd). Never throws: rectangles are clipped to both buffers. +-- +-- Blend.composite(dst, dw, dh, src, sw, sh, x, y, opacity, "multiply", { clip = false, mask = m }) +-- Blend.MODES.multiply -> true +-- +-- Mode names: normal dissolve darken multiply colorBurn linearBurn darkerColor lighten screen colorDodge linearDodge +-- (= add) lighterColor overlay softLight hardLight vividLight linearLight pinLight hardMix difference exclusion +-- subtract divide hue saturation color luminosity. Unknown names composite as normal. +local Blend = {} + +local readu8, writeu8, readu32, writeu32, blen = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32, buffer.len +local min, max, floor, sqrt, abs = math.min, math.max, math.floor, math.sqrt, math.abs + +local IDS: { [string]: number } = { + normal = 0, + dissolve = 1, + darken = 2, + multiply = 3, + colorBurn = 4, + linearBurn = 5, + darkerColor = 6, + lighten = 7, + screen = 8, + colorDodge = 9, + linearDodge = 10, + add = 10, + lighterColor = 11, + overlay = 12, + softLight = 13, + hardLight = 14, + vividLight = 15, + linearLight = 16, + pinLight = 17, + hardMix = 18, + difference = 19, + exclusion = 20, + subtract = 21, + divide = 22, + hue = 23, + saturation = 24, + color = 25, + luminosity = 26, +} +local MODES: { [string]: boolean } = {} +for k in IDS do + MODES[k] = true +end +Blend.MODES = table.freeze(MODES) + +local function burn(cb: number, cs: number): number + if cb >= 1 then + return 1 + elseif cs <= 0 then + return 0 + end + return 1 - min(1, (1 - cb) / cs) +end +local function dodge(cb: number, cs: number): number + if cb <= 0 then + return 0 + elseif cs >= 1 then + return 1 + end + return min(1, cb / (1 - cs)) +end + +-- B(cb, cs) of a separable mode +local function sep(m: number, cb: number, cs: number): number + if m == 3 then + return cb * cs + elseif m == 8 then + return cb + cs - cb * cs + elseif m == 2 then + return min(cb, cs) + elseif m == 7 then + return max(cb, cs) + elseif m == 12 then -- overlay = hardLight(cs, cb) + if cb <= 0.5 then + return 2 * cb * cs + end + local c = 2 * cb - 1 + return cs + c - cs * c + elseif m == 14 then + if cs <= 0.5 then + return 2 * cb * cs + end + local c = 2 * cs - 1 + return cb + c - cb * c + elseif m == 13 then + if cs <= 0.5 then + return cb - (1 - 2 * cs) * cb * (1 - cb) + end + local d = if cb <= 0.25 then ((16 * cb - 12) * cb + 4) * cb else sqrt(cb) + return cb + (2 * cs - 1) * (d - cb) + elseif m == 9 then + return dodge(cb, cs) + elseif m == 4 then + return burn(cb, cs) + elseif m == 5 then + return max(0, cb + cs - 1) + elseif m == 10 then + return min(1, cb + cs) + elseif m == 15 then + if cs <= 0.5 then + return burn(cb, 2 * cs) + end + return dodge(cb, 2 * cs - 1) + elseif m == 16 then + return max(0, min(1, cb + 2 * cs - 1)) + elseif m == 17 then + if cs <= 0.5 then + return min(cb, 2 * cs) + end + return max(cb, 2 * cs - 1) + elseif m == 18 then + return if cb + cs >= 1 then 1 else 0 + elseif m == 19 then + return abs(cb - cs) + elseif m == 20 then + return cb + cs - 2 * cb * cs + elseif m == 21 then + return max(0, cb - cs) + elseif m == 22 then + if cs <= 0 then + return if cb <= 0 then 0 else 1 + end + return min(1, cb / cs) + end + return cs +end + +-- non-separable helpers (W3C): lum, clip, setLum, sat, setSat +local function lum(r: number, g: number, b: number): number + return 0.3 * r + 0.59 * g + 0.11 * b +end +local function clipColor(r: number, g: number, b: number): (number, number, number) + local l = lum(r, g, b) + local n = min(r, g, b) + local x = max(r, g, b) + if n < 0 and l - n > 1e-12 then + r, g, b = l + (r - l) * l / (l - n), l + (g - l) * l / (l - n), l + (b - l) * l / (l - n) + end + if x > 1 and x - l > 1e-12 then + r, g, b = l + (r - l) * (1 - l) / (x - l), l + (g - l) * (1 - l) / (x - l), l + (b - l) * (1 - l) / (x - l) + end + return r, g, b +end +local function setLum(r: number, g: number, b: number, l: number): (number, number, number) + local d = l - lum(r, g, b) + return clipColor(r + d, g + d, b + d) +end +local function setSat(r: number, g: number, b: number, s: number): (number, number, number) + local mx = max(r, g, b) + local mn = min(r, g, b) + if mx - mn <= 1e-12 then + return 0, 0, 0 + end + local k = s / (mx - mn) + return (r - mn) * k, (g - mn) * k, (b - mn) * k +end + +-- composite(dst, dw, dh, src, sw, sh, x, y, opacity, mode, opts?): blends the sw x sh rgba8 src onto the dw x dh rgba8 +-- dst with its top-left at (x, y). opacity 0..1. opts.clip: keep the backdrop's alpha (clipping masks). opts.mask: +-- { pixels: buffer (1 byte per pixel), width, height, x, y, default: 0..255 } in dst coordinates (outside it: default). +local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: number, sh: number, x: number, y: number, opacity: number, mode: string?, opts: { clip: boolean?, mask: any? }?) + x, y = floor(x), floor(y) + if opacity <= 0 or dw <= 0 or dh <= 0 or sw <= 0 or sh <= 0 then + return + end + if blen(dst) < dw * dh * 4 or blen(src) < sw * sh * 4 then + return + end + local op = min(1, opacity) + local m = IDS[mode or "normal"] or 0 + local clip = opts ~= nil and opts.clip == true + local mask = if opts ~= nil then opts.mask else nil + local mbuf: buffer? = nil + local mx0, my0, mw, mh, mdef = 0, 0, 0, 0, 1 + if type(mask) == "table" and type(mask.pixels) == "buffer" and type(mask.width) == "number" and type(mask.height) == "number" then + mw, mh = floor(mask.width), floor(mask.height) + if mw > 0 and mh > 0 and blen(mask.pixels) >= mw * mh then + mbuf = mask.pixels + end + mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) + mdef = (tonumber(mask.default) or 255) / 255 + elseif type(mask) == "table" then + mdef = (tonumber(mask.default) or 255) / 255 + end + local x0, y0 = max(0, x), max(0, y) + local x1, y1 = min(dw, x + sw), min(dh, y + sh) + for py = y0, y1 - 1 do + local so = ((py - y) * sw + (x0 - x)) * 4 + local do_ = (py * dw + x0) * 4 + for px = x0, x1 - 1 do + local sa8 = readu8(src, so + 3) + if sa8 ~= 0 then + local sa = sa8 / 255 * op + if mbuf ~= nil or mdef ~= 1 then + local mv = mdef + local mxx, myy = px - mx0, py - my0 + if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then + mv = readu8(mbuf, myy * mw + mxx) / 255 + end + sa *= mv + end + if m == 1 then -- dissolve: a hash threshold per pixel, full alpha where it shows + local h = (px * 73856093 + py * 19349663) % 65536 / 65536 + sa = if h < sa then 1 else 0 + end + local ba8 = readu8(dst, do_ + 3) + if sa > 0 and not (clip and ba8 == 0) then + local sr, sg, sb = readu8(src, so) / 255, readu8(src, so + 1) / 255, readu8(src, so + 2) / 255 + if ba8 == 0 then + -- empty backdrop: the source as it is (alpha scaled) + writeu32(dst, do_, readu32(src, so)) + writeu8(dst, do_ + 3, floor(sa * 255 + 0.5)) + else + local ba = ba8 / 255 + local br, bg, bb = readu8(dst, do_) / 255, readu8(dst, do_ + 1) / 255, readu8(dst, do_ + 2) / 255 + local mr, mg, mb = sr, sg, sb + if m >= 2 and m ~= 6 and m ~= 11 and m < 23 then + mr, mg, mb = sep(m, br, sr), sep(m, bg, sg), sep(m, bb, sb) + elseif m == 6 then + if lum(sr, sg, sb) >= lum(br, bg, bb) then + mr, mg, mb = br, bg, bb + end + elseif m == 11 then + if lum(sr, sg, sb) < lum(br, bg, bb) then + mr, mg, mb = br, bg, bb + end + elseif m == 23 then + local s = max(br, bg, bb) - min(br, bg, bb) + local r1, g1, b1 = setSat(sr, sg, sb, s) + mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb)) + elseif m == 24 then + local s = max(sr, sg, sb) - min(sr, sg, sb) + local r1, g1, b1 = setSat(br, bg, bb, s) + mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb)) + elseif m == 25 then + mr, mg, mb = setLum(sr, sg, sb, lum(br, bg, bb)) + elseif m == 26 then + mr, mg, mb = setLum(br, bg, bb, lum(sr, sg, sb)) + end + local orr, og, ob, oa + if clip then + -- source-atop: the backdrop's alpha; the mixed colour where the backdrop is opaque + orr = sa * mr + (1 - sa) * br + og = sa * mg + (1 - sa) * bg + ob = sa * mb + (1 - sa) * bb + oa = ba + else + oa = sa + ba * (1 - sa) + local ws, wm, wb = sa * (1 - ba), sa * ba, (1 - sa) * ba + orr = (ws * sr + wm * mr + wb * br) / oa + og = (ws * sg + wm * mg + wb * bg) / oa + ob = (ws * sb + wm * mb + wb * bb) / oa + end + writeu8(dst, do_, floor(max(0, min(1, orr)) * 255 + 0.5)) + writeu8(dst, do_ + 1, floor(max(0, min(1, og)) * 255 + 0.5)) + writeu8(dst, do_ + 2, floor(max(0, min(1, ob)) * 255 + 0.5)) + writeu8(dst, do_ + 3, floor(max(0, min(1, oa)) * 255 + 0.5)) + end + end + end + so += 4 + do_ += 4 + end + end +end + +-- lerp(dst, from, t, n): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity) +local function lerp(dst: buffer, from: buffer, t: number, n: number) + if blen(dst) < n * 4 or blen(from) < n * 4 then + return + end + for i = 0, n * 4 - 1 do + local a = readu8(from, i) + writeu8(dst, i, floor(a + (readu8(dst, i) - a) * t + 0.5)) + end +end +Blend.composite = composite +Blend.lerp = lerp + +-- ------------------------------------------------------------------------------------------------ layer trees +local function isImage(v: any): boolean + return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and buffer.len(v.pixels) >= v.width * v.height * 4 +end + +local function maskOf(l: any): any + local m = l.mask + if type(m) ~= "table" or m.disabled or type(m.image) ~= "table" or type(m.image.pixels) ~= "buffer" then + return nil + end + local img = m.image + local px = img.pixels + if img.format == "rgba8" then -- use the red channel + local n = img.width * img.height + local g = buffer.create(n) + for i = 0, n - 1 do + buffer.writeu8(g, i, buffer.readu8(px, i * 4)) + end + px = g + end + return { pixels = px, width = img.width, height = img.height, x = m.x or 0, y = m.y or 0, default = m.default or 255 } +end + +local function compose(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) + local i = 1 + while i <= #layers do + local l = layers[i] + i += 1 + if type(l) ~= "table" or (l.visible == false and not hidden) then + -- clipped layers above a hidden base are hidden too + while i <= #layers and type(layers[i]) == "table" and layers[i].clip do + i += 1 + end + continue + end + local opacity = (tonumber(l.opacity) or 1) * (tonumber(l.fillOpacity) or 1) + local mode = if type(l.blend) == "string" then l.blend else "normal" + -- the layer's own pixels, as an isolated w x h buffer + local src: buffer? = nil + if type(l.children) == "table" then + if mode == "passThrough" then + local before = buffer.create(w * h * 4) + buffer.copy(before, 0, canvas, 0, w * h * 4) + compose(l.children, canvas, w, h, hidden) + if opacity < 1 then + lerp(canvas, before, opacity, w * h) + end + continue + end + src = buffer.create(w * h * 4) + compose(l.children, src :: buffer, w, h, hidden) + elseif isImage(l.image) then + if l.image.width > 0 and l.image.height > 0 then + local b = buffer.create(w * h * 4) + composite(b, w, h, l.image.pixels, l.image.width, l.image.height, tonumber(l.x) or 0, tonumber(l.y) or 0, 1, "normal") + src = b + end + end + -- clipping layers above this one: composited onto it with their alpha limited to it + while i <= #layers and type(layers[i]) == "table" and layers[i].clip do + local c = layers[i] + i += 1 + if src and (c.visible ~= false or hidden) and isImage(c.image) then + composite(src :: buffer, w, h, c.image.pixels, c.image.width, c.image.height, tonumber(c.x) or 0, tonumber(c.y) or 0, (tonumber(c.opacity) or 1) * (tonumber(c.fillOpacity) or 1), c.blend, { clip = true, mask = maskOf(c) }) + end + end + if src then + composite(canvas, w, h, src :: buffer, w, h, 0, 0, opacity, mode, { mask = maskOf(l) }) + end + end +end + +-- flatten(layers, canvas, w, h, hidden): composites a Types.Layer tree (bottom to top) onto the w x h rgba8 canvas: +-- blend modes, opacity x fillOpacity, groups (isolated, or "passThrough": blended straight onto the canvas, the group +-- opacity then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks. +-- hidden = true includes invisible layers. +function Blend.flatten(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) + if blen(canvas) >= w * h * 4 then + compose(layers, canvas, w, h, hidden) + end +end + +return Blend diff --git a/src/Formats/layered/psd/Channels.luau b/src/Formats/layered/psd/Channels.luau new file mode 100644 index 0000000..4b68fdd --- /dev/null +++ b/src/Formats/layered/psd/Channels.luau @@ -0,0 +1,383 @@ +--!strict +--!native +-- layered/psd/Channels: PSD / PSB channel data. Decodes one channel (raw, PackBits RLE, ZIP, ZIP with prediction) to a +-- plane of big-endian samples, converts planes to rgba8 for every colour mode, and PackBits-encodes rows for the +-- writer. Adobe Photoshop File Formats Specification (2016), "Channel image data" / "Image data section". +-- Never throws: every read is range-checked first; failures return nil, "message". +local Deflate = require("@formats/codecs/Deflate") + +local Channels = {} + +local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32 +local readf32, writef32, bcreate, bcopy, blen, bfill = buffer.readf32, buffer.writef32, buffer.create, buffer.copy, buffer.len, buffer.fill +local floor, min, max = math.floor, math.min, math.max +local byteswap = bit32.byteswap + +-- rowBytes(w, depth) -> bytes per row of one channel +function Channels.rowBytes(w: number, depth: number): number + if depth == 1 then + return (w + 7) // 8 + end + return w * (depth // 8) +end + +-- packbits(src, p, limit, dst, d, n) -> the source offset after decoding n bytes into dst at d | nil +local function packbits(src: buffer, p: number, limit: number, dst: buffer, d: number, n: number): number? + local e = d + n + while d < e do + if p >= limit then + return nil + end + local h = readu8(src, p) + p += 1 + if h < 128 then + local c = h + 1 + if p + c > limit or d + c > e then + return nil + end + bcopy(dst, d, src, p, c) + p += c + d += c + elseif h > 128 then + local c = 257 - h + if p >= limit or d + c > e then + return nil + end + bfill(dst, d, readu8(src, p), c) + p += 1 + d += c + end + end + return p +end + +-- rleCounts(src, p, limit, rows, psb) -> { counts }, offset after them | nil +function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, psb: boolean): ({ number }?, number) + local size = if psb then 4 else 2 + if rows < 0 or p + rows * size > limit then + return nil, p + end + local counts = table.create(rows) + for i = 1, rows do + if psb then + counts[i] = byteswap(readu32(src, p)) + else + counts[i] = readu8(src, p) * 256 + readu8(src, p + 1) + end + p += size + end + return counts, p +end + +-- rle(src, p, limit, counts, first, rows, rowBytes, dst, d) -> offset after the rows | nil, message +function Channels.rle(src: buffer, p: number, limit: number, counts: { number }, first: number, rows: number, rowBytes: number, dst: buffer, d: number): (number?, string?) + for i = 0, rows - 1 do + local c = counts[first + i] or 0 + if p + c > limit then + return nil, "RLE row past the end" + end + local q = packbits(src, p, p + c, dst, d + i * rowBytes, rowBytes) + if q == nil then + -- a short or overlong row: keep what decoded, zero the rest (Photoshop is lenient too) + return nil, "bad RLE row" + end + p += c + end + return p, nil +end + +-- unpredict(plane, w, h, depth): undo ZIP-with-prediction deltas in place +local function unpredict(plane: buffer, w: number, h: number, depth: number) + if depth == 8 then + for y = 0, h - 1 do + local o = y * w + local acc = readu8(plane, o) + for x = 1, w - 1 do + acc = (acc + readu8(plane, o + x)) % 256 + writeu8(plane, o + x, acc) + end + end + elseif depth == 16 then + for y = 0, h - 1 do + local o = y * w * 2 + local acc = readu8(plane, o) * 256 + readu8(plane, o + 1) + for x = 1, w - 1 do + local q = o + x * 2 + acc = (acc + readu8(plane, q) * 256 + readu8(plane, q + 1)) % 65536 + writeu8(plane, q, acc // 256) + writeu8(plane, q + 1, acc % 256) + end + end + elseif depth == 32 then + -- byte deltas over the row, then the row is 4 byte planes (all high bytes first) + local rb = w * 4 + local tmp = bcreate(rb) + for y = 0, h - 1 do + local o = y * rb + local acc = readu8(plane, o) + for x = 1, rb - 1 do + acc = (acc + readu8(plane, o + x)) % 256 + writeu8(plane, o + x, acc) + end + for x = 0, w - 1 do + writeu8(tmp, x * 4, readu8(plane, o + x)) + writeu8(tmp, x * 4 + 1, readu8(plane, o + w + x)) + writeu8(tmp, x * 4 + 2, readu8(plane, o + 2 * w + x)) + writeu8(tmp, x * 4 + 3, readu8(plane, o + 3 * w + x)) + end + bcopy(plane, o, tmp, 0, rb) + end + end +end + +-- channel(src, p, limit, w, h, depth, psb) -> plane (h rows of rowBytes) | nil, message. src[p, limit) holds the +-- 2-byte compression code and the data of one layer channel. +function Channels.channel(src: buffer, p: number, limit: number, w: number, h: number, depth: number, psb: boolean): (buffer?, string?) + local rb = Channels.rowBytes(w, depth) + local plane = bcreate(rb * h) + if w == 0 or h == 0 then + return plane, nil + end + if p + 2 > limit then + return nil, "channel data past the end" + end + local comp = readu8(src, p) * 256 + readu8(src, p + 1) + p += 2 + if comp == 0 then + if p + rb * h > limit then + return nil, "raw channel data past the end" + end + bcopy(plane, 0, src, p, rb * h) + elseif comp == 1 then + local counts, q = Channels.rleCounts(src, p, limit, h, psb) + if not counts then + return nil, "RLE row counts past the end" + end + local ok, err = Channels.rle(src, q, limit, counts, 1, h, rb, plane, 0) + if not ok then + return nil, err + end + elseif comp == 2 or comp == 3 then + local out, err = Deflate.zlib(src, p, limit - p, rb * h) + if not out then + return nil, "ZIP channel: " .. tostring(err) + end + plane = out + if comp == 3 then + unpredict(plane, w, h, depth) + end + else + return nil, "unknown channel compression " .. comp + end + return plane, nil +end + +-- sample8(plane, i, depth) -> sample i as 0..255 +local function sample8(plane: buffer, i: number, depth: number): number + if depth == 8 then + return readu8(plane, i) + elseif depth == 16 then + return floor((readu8(plane, i * 2) * 256 + readu8(plane, i * 2 + 1)) / 257 + 0.5) + elseif depth == 32 then + local f = readf32(plane, i * 4) -- the plane holds big-endian floats: swapped by the caller + if f ~= f then + return 0 + end + return floor(max(0, min(1, f)) * 255 + 0.5) + end + -- 1-bit (rows are padded, so this is only right for whole-byte widths; toRGBA reads bitmaps itself): 1 = black + return if readu8(plane, i // 8) // 2 ^ (7 - i % 8) % 2 == 1 then 0 else 255 +end + +-- swap32(plane): big-endian f32 samples to native order, in place +function Channels.swap32(plane: buffer) + for i = 0, blen(plane) // 4 - 1 do + writeu32(plane, i * 4, byteswap(readu32(plane, i * 4))) + end +end + +-- lab(L, a, b) 0..255 each (PSD Lab) -> sRGB r, g, b 0..255 (D50 -> D65 approximated by D65 white) +local function srgb(c: number): number + c = if c <= 0.0031308 then 12.92 * c else 1.055 * c ^ (1 / 2.4) - 0.055 + return floor(max(0, min(1, c)) * 255 + 0.5) +end +local function lab(l8: number, a8: number, b8: number): (number, number, number) + local L = l8 * 100 / 255 + local a, b = a8 - 128, b8 - 128 + local fy = (L + 16) / 116 + local fx = fy + a / 500 + local fz = fy - b / 200 + local function f(t: number): number + return if t > 6 / 29 then t * t * t else 3 * (6 / 29) ^ 2 * (t - 4 / 29) + end + local X, Y, Z = 0.95047 * f(fx), f(fy), 1.08883 * f(fz) + local r = 3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z + local g = -0.969266 * X + 1.8760108 * Y + 0.041556 * Z + local bl = 0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z + return srgb(r), srgb(g), srgb(bl) +end + +-- toRGBA(planes, w, h, depth, mode, palette?, dst?) -> rgba8 buffer. planes: { [1..k] = colour planes, alpha = plane? } +-- mode: PSD colour mode (0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab) +function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: number, mode: number, palette: buffer?): buffer + local n = w * h + local out = bcreate(n * 4) + local c1, c2, c3, c4 = planes[1], planes[2], planes[3], planes[4] + local alpha = planes.alpha + local bitmapW = (w + 7) // 8 + for i = 0, n - 1 do + local r, g, b = 0, 0, 0 + if mode == 3 then + r = if c1 then sample8(c1, i, depth) else 0 + g = if c2 then sample8(c2, i, depth) else r + b = if c3 then sample8(c3, i, depth) else r + elseif mode == 4 then + local cc = if c1 then sample8(c1, i, depth) else 255 + local mm = if c2 then sample8(c2, i, depth) else 255 + local yy = if c3 then sample8(c3, i, depth) else 255 + local kk = if c4 then sample8(c4, i, depth) else 255 + r, g, b = floor(cc * kk / 255 + 0.5), floor(mm * kk / 255 + 0.5), floor(yy * kk / 255 + 0.5) + elseif mode == 2 then + local k = if c1 then readu8(c1, i) else 0 + if palette and blen(palette) >= 768 then + r, g, b = readu8(palette, k), readu8(palette, 256 + k), readu8(palette, 512 + k) + else + r, g, b = k, k, k + end + elseif mode == 0 then + local y, x = i // w, i % w + local bit = if c1 then readu8(c1, y * bitmapW + x // 8) // 2 ^ (7 - x % 8) % 2 else 0 + r = if bit == 1 then 0 else 255 + g, b = r, r + elseif mode == 9 then + local L = if c1 then sample8(c1, i, depth) else 0 + local A = if c2 then sample8(c2, i, depth) else 128 + local B = if c3 then sample8(c3, i, depth) else 128 + r, g, b = lab(L, A, B) + else -- grey, duotone, multichannel: the first channel as grey + r = if c1 then sample8(c1, i, depth) else 0 + g, b = r, r + end + local a = if alpha then sample8(alpha, i, depth) else 255 + writeu32(out, i * 4, r + g * 256 + b * 65536 + a * 16777216) + end + return out +end + +-- gray8(plane, w, h, depth) -> 1 byte per pixel +function Channels.gray8(plane: buffer, w: number, h: number, depth: number): buffer + local n = w * h + local out = bcreate(n) + for i = 0, n - 1 do + writeu8(out, i, sample8(plane, i, depth)) + end + return out +end + +-- unmatte(rgba, n): Photoshop stores a transparent merged image matted with white (C * a + 255 * (1 - a)): undo it +function Channels.unmatte(rgba: buffer, n: number) + for i = 0, n - 1 do + local o = i * 4 + local a = readu8(rgba, o + 3) + if a == 0 then + writeu32(rgba, o, 0) + elseif a < 255 then + local f = a / 255 + for k = 0, 2 do + local v = (readu8(rgba, o + k) - 255 * (1 - f)) / f + writeu8(rgba, o + k, floor(max(0, min(255, v)) + 1e-6)) + end + end + end +end + +-- matte(rgba, n) -> a copy matted with white (the writer's merged image) +function Channels.matte(rgba: buffer, n: number): buffer + local out = bcreate(n * 4) + bcopy(out, 0, rgba, 0, n * 4) + for i = 0, n - 1 do + local o = i * 4 + local a = readu8(out, o + 3) + if a < 255 then + local f = a / 255 + for k = 0, 2 do + writeu8(out, o + k, floor(readu8(out, o + k) * f + 255 * (1 - f) + 0.5)) + end + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ writer helpers +-- packRow(src, o, n, out, d) -> bytes written: PackBits of src[o, o + n) into out at d (out needs n + n // 128 + 1) +function Channels.packRow(src: buffer, o: number, n: number, out: buffer, d: number): number + local start = d + local i = 0 + while i < n do + -- a run of at least 3 equal bytes? + local v = readu8(src, o + i) + local run = 1 + while i + run < n and run < 128 and readu8(src, o + i + run) == v do + run += 1 + end + if run >= 3 then + writeu8(out, d, 257 - run) + writeu8(out, d + 1, v) + d += 2 + i += run + else + -- literals up to the next run of 3 + local j = i + while j < n and j - i < 128 do + if j + 2 < n and readu8(src, o + j) == readu8(src, o + j + 1) and readu8(src, o + j) == readu8(src, o + j + 2) then + break + end + j += 1 + end + local c = j - i + writeu8(out, d, c - 1) + bcopy(out, d + 1, src, o + i, c) + d += c + 1 + i = j + end + end + return d - start +end + +-- planes8(rgba, w, h) -> r, g, b, a planes (1 byte per pixel each) +function Channels.planes8(rgba: buffer, w: number, h: number): (buffer, buffer, buffer, buffer) + local n = w * h + local r, g, b, a = bcreate(n), bcreate(n), bcreate(n), bcreate(n) + if blen(rgba) < n * 4 then + return r, g, b, a + end + for i = 0, n - 1 do + local v = readu32(rgba, i * 4) + writeu8(r, i, v % 256) + writeu8(g, i, v // 256 % 256) + writeu8(b, i, v // 65536 % 256) + writeu8(a, i, v // 16777216) + end + return r, g, b, a +end + +-- rleChannel(plane, w, h, psb) -> the RLE data of one channel (counts, then rows), without the compression code +function Channels.rleChannel(plane: buffer, w: number, h: number, psb: boolean): buffer + local cs = if psb then 4 else 2 + local out = bcreate(h * cs + h * (w + w // 128 + 2)) + local d = h * cs + for y = 0, h - 1 do + local n = Channels.packRow(plane, y * w, w, out, d) + if psb then + writeu32(out, y * 4, byteswap(n)) + else + writeu16(out, y * 2, byteswap(n) // 65536) + end + d += n + end + local res = bcreate(d) + bcopy(res, 0, out, 0, d) + return res +end + +return Channels diff --git a/src/Formats/layered/psd/init.luau b/src/Formats/layered/psd/init.luau new file mode 100644 index 0000000..af510e7 --- /dev/null +++ b/src/Formats/layered/psd/init.luau @@ -0,0 +1,758 @@ +--!strict +-- layered/psd: Adobe Photoshop PSD and PSB (Adobe Photoshop File Formats Specification, 2016). Supports: decode of +-- bitmap, greyscale, indexed, RGB, CMYK, Lab, duotone and multichannel documents at 1 / 8 / 16 / 32 bits; layers +-- (raw, PackBits RLE, ZIP and ZIP-with-prediction channels; 16 / 32-bit layers in Lr16 / Lr32), their blend mode, +-- opacity, fill opacity (iOpa), visibility, clipping, Unicode names (luni), user masks (as grey masks), groups (lsct / +-- lsdk section dividers -> group layers with children; pass-through kept as the "passThrough" blend); the merged image +-- (meta.composite); image resources (meta.resources, ICC profile in meta.icc). Everything converts to rgba8. +-- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/Blend +-- flattens the tree, or opts.composite) and every layer as RLE RGBA channels, groups as section dividers, masks, +-- clipping, opacity / fill, hidden flags and Unicode names. +-- Not supported: adjustment / fill / type / smart-object layer contents (their pixels, if any, are used), layer +-- effects, vector masks, colour management, 16 / 32-bit or non-RGB output. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Blend = require("@formats/codecs/Blend") +local Channels = require("@formats/layered/psd/Channels") + +-- ------------------------------------------------------------------------------------------------ contract +local Psd = { + name = "psd", + category = "layered", + extensions = { "psd", "psb" }, + mime = { "image/vnd.adobe.photoshop" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Blend", "codecs/Deflate" }, + caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } }, +} + +export type DecodeOptions = { + layers: boolean?, -- read the layers (default true; false reads only the merged image) + maxPixels: number?, -- refuse documents / layers larger than this (default 2^26) + maxLayers: number?, -- default 10000 +} +export type EncodeOptions = { + composite: Types.Image?, -- the merged image to store (default: the layers flattened with codecs/Blend) +} + +-- ------------------------------------------------------------------------------------------------ constants +local BLEND_KEYS: { [string]: string } = { + norm = "normal", + diss = "dissolve", + dark = "darken", + ["mul "] = "multiply", + idiv = "colorBurn", + lbrn = "linearBurn", + dkCl = "darkerColor", + lite = "lighten", + scrn = "screen", + ["div "] = "colorDodge", + lddg = "linearDodge", + lgCl = "lighterColor", + over = "overlay", + sLit = "softLight", + hLit = "hardLight", + vLit = "vividLight", + lLit = "linearLight", + pLit = "pinLight", + hMix = "hardMix", + diff = "difference", + smud = "exclusion", + fsub = "subtract", + fdiv = "divide", + ["hue "] = "hue", + ["sat "] = "saturation", + colr = "color", + ["lum "] = "luminosity", + pass = "passThrough", +} +local BLEND_NAMES: { [string]: string } = {} +for k, v in BLEND_KEYS do + BLEND_NAMES[v] = k +end +BLEND_NAMES.add = "lddg" + +-- colour channels per mode (the rest are alpha / spot channels) +local COLOR_CHANNELS = { [0] = 1, [1] = 1, [2] = 1, [3] = 3, [4] = 4, [7] = 1, [8] = 1, [9] = 3 } +local MODE_NAMES = { [0] = "bitmap", [1] = "gray", [2] = "indexed", [3] = "rgb", [4] = "cmyk", [7] = "multichannel", [8] = "duotone", [9] = "lab" } +-- additional layer info keys with 8-byte lengths in PSB +local LONG_KEYS = { LMsk = true, Lr16 = true, Lr32 = true, Layr = true, Mt16 = true, Mt32 = true, Mtrn = true, Alph = true, FMsk = true, lnk2 = true, FEid = true, FXid = true, PxSD = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Psd.sniff(r: Bytes.Reader): number + local h = r:peek(6) + if string.sub(h, 1, 4) == "8BPS" and (string.sub(h, 5, 6) == "\0\1" or string.sub(h, 5, 6) == "\0\2") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Ctx = { psb: boolean, depth: number, mode: number, maxPixels: number, maxLayers: number } + +local function len(r: Bytes.Reader, psb: boolean): number + return if psb then r:u64be() else r:u32be() +end + +local function utf16be(s: string): string + local out = {} + local i = 1 + while i + 1 <= #s do + local c = string.byte(s, i) * 256 + string.byte(s, i + 1) + i += 2 + if c >= 0xD800 and c < 0xDC00 and i + 1 <= #s then + local c2 = string.byte(s, i) * 256 + string.byte(s, i + 1) + if c2 >= 0xDC00 and c2 < 0xE000 then + c = 0x10000 + (c - 0xD800) * 1024 + (c2 - 0xDC00) + i += 2 + end + end + if c ~= 0 then + table.insert(out, utf8.char(c)) + end + end + return table.concat(out) +end + +-- the layer records + channel data at r (a Reader over the layer info, after its length): flat records | nil, Err +local function layerRecords(r: Bytes.Reader, c: Ctx): ({ any }?, boolean, Err.Err?) + local count = r:i16be() + local absAlpha = count < 0 + count = math.abs(count) + if r.err then + return nil, absAlpha, r.err + end + if count > c.maxLayers then + return nil, absAlpha, Err.new(Err.LIMIT, "over " .. c.maxLayers .. " layers") + end + local recs = {} + for li = 1, count do + local top, left, bottom, right = r:i32be(), r:i32be(), r:i32be(), r:i32be() + local nch = r:u16be() + if r.err then + return nil, absAlpha, r.err + end + if nch > 56 then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": " .. nch .. " channels", r.pos) + end + local chans = {} + for k = 1, nch do + chans[k] = { id = r:i16be(), size = len(r, c.psb) } + end + if r:string(4) ~= "8BIM" and not r.err then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad blend mode signature", r.pos - 4) + end + local key = r:string(4) + local opacity, clipping, flags = r:u8(), r:u8(), r:u8() + r:skip(1) + local extraLen = r:u32be() + if r.err then + return nil, absAlpha, r.err + end + local ex = r:slice(extraLen) + local rec: { [string]: any } = { + top = top, + left = left, + bottom = bottom, + right = right, + chans = chans, + blend = BLEND_KEYS[key] or "normal", + blendKey = key, + opacity = opacity / 255, + clip = clipping ~= 0, + hidden = bit32.band(flags, 2) ~= 0, + flags = flags, + } + -- mask data + local ml = ex:u32be() + if ml > 0 then + local mr = ex:slice(ml) + if ml >= 18 then + rec.mask = { top = mr:i32be(), left = mr:i32be(), bottom = mr:i32be(), right = mr:i32be(), default = mr:u8(), flags = mr:u8() } + end + end + -- blending ranges + ex:skip(ex:u32be()) + -- name: Pascal string padded to 4 + local nl = ex:u8() + rec.name = ex:string(nl) + ex:skip((4 - (nl + 1) % 4) % 4) + -- additional layer info + while ex:remaining() >= 12 do + local sig = ex:string(4) + if sig ~= "8BIM" and sig ~= "8B64" then + break + end + local k = ex:string(4) + local l = if c.psb and LONG_KEYS[k] then ex:u64be() else ex:u32be() + if ex.err then + break + end + local d = ex:slice(l) + if k == "luni" then + local n = d:u32be() + local s = d:string(math.min(n * 2, d:remaining())) + rec.name = utf16be(s) + elseif k == "lsct" or k == "lsdk" then + rec.section = d:u32be() + if d:remaining() >= 8 and d:string(4) == "8BIM" then + rec.sectionBlend = d:string(4) + end + elseif k == "iOpa" then + rec.fill = d:u8() / 255 + elseif k == "lyid" then + rec.id = d:u32be() + end + end + if r.err then + return nil, absAlpha, r.err + end + recs[li] = rec + end + -- channel image data + local b = r.buf + for li, rec in recs do + local w, h = rec.right - rec.left, rec.bottom - rec.top + if w < 0 or h < 0 or w > 300000 or h > 300000 then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad bounds", r.pos) + end + if w * h > c.maxPixels then + return nil, absAlpha, Err.new(Err.LIMIT, string.format("layer %d: %d x %d is over the pixel limit", li, w, h)) + end + local planes: { [any]: buffer } = {} + for _, ch in rec.chans do + local p = r.pos + if ch.size < 0 or p + ch.size > r.limit then + return nil, absAlpha, Err.new(Err.TRUNCATED, "layer " .. li .. ": channel data past the end", p) + end + r.pos = p + ch.size + local cw, chh = w, h + if ch.id == -2 or ch.id == -3 then + local m = rec.mask + if not m then + continue + end + cw, chh = m.right - m.left, m.bottom - m.top + if cw < 0 or chh < 0 or cw * chh > c.maxPixels then + continue + end + end + if ch.size < 2 then + continue -- an empty channel + end + local plane, perr = Channels.channel(b, p, p + ch.size, cw, chh, c.depth, c.psb) + if not plane then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. " channel " .. ch.id .. ": " .. tostring(perr), p) + end + if c.depth == 32 then + Channels.swap32(plane) + end + if ch.id == -1 then + planes.alpha = plane + elseif ch.id == -2 then + rec.maskPlane = Channels.gray8(plane, cw, chh, c.depth) + elseif ch.id >= 0 and ch.id < 56 then + planes[ch.id + 1] = plane + end + end + local img = Types.Image.new(w, h) + if w > 0 and h > 0 then + img.pixels = Channels.toRGBA(planes, w, h, c.depth, c.mode, nil) + end + rec.image = img + end + return recs, absAlpha, nil +end + +-- records (bottom to top) -> a layer tree +local function tree(recs: { any }): { Types.Layer } + local root: { Types.Layer } = {} + local stack: { { Types.Layer } } = {} + local cur = root + local function layerOf(rec: any): Types.Layer + local l: any = { + name = rec.name, + image = rec.image, + x = rec.left, + y = rec.top, + opacity = rec.opacity, + blend = rec.blend, + visible = not rec.hidden, + } + if rec.clip then + l.clip = true + end + if rec.fill and rec.fill < 1 then + l.fillOpacity = rec.fill + end + if rec.id then + l.id = rec.id + end + if rec.mask and rec.maskPlane then + local m = rec.mask + local mi = Types.Image.new(m.right - m.left, m.bottom - m.top, "gray8") + mi.pixels = rec.maskPlane + l.mask = { image = mi, x = m.left, y = m.top, default = m.default, disabled = bit32.band(m.flags, 2) ~= 0 } + end + return l + end + for _, rec in recs do + local s = rec.section + if s == 3 then + table.insert(stack, cur) + cur = {} + elseif s == 1 or s == 2 then + local g = layerOf(rec) + g.image = Types.Image.new(0, 0) + g.children = cur + if rec.sectionBlend and BLEND_KEYS[rec.sectionBlend] then + g.blend = BLEND_KEYS[rec.sectionBlend] + end + ;(g :: any).collapsed = s == 2 + cur = table.remove(stack) or root + table.insert(cur, g) + else + table.insert(cur, layerOf(rec)) + end + end + -- unbalanced dividers: splice the open groups' layers back in + while #stack > 0 do + local parent = table.remove(stack) :: { Types.Layer } + for _, l in cur do + table.insert(parent, l) + end + cur = parent + end + return cur +end + +function Psd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?) + local o: DecodeOptions = opts or {} + local c: Ctx = { psb = false, depth = 8, mode = 3, maxPixels = o.maxPixels or 2 ^ 26, maxLayers = o.maxLayers or 10000 } + if Psd.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a PSD (bad signature)", r.pos) + end + r:skip(4) + local version = r:u16be() + r:skip(6) + local nch, h, w, depth, mode = r:u16be(), r:u32be(), r:u32be(), r:u16be(), r:u16be() + if r.err then + return nil, r.err + end + c.psb, c.depth, c.mode = version == 2, depth, mode + if nch < 1 or nch > 56 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. nch) + end + local maxSide = if c.psb then 300000 else 30000 + if w < 1 or h < 1 or w > maxSide or h > maxSide then + return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h)) + end + if not (depth == 1 or depth == 8 or depth == 16 or depth == 32) then + return nil, Err.new(Err.CORRUPT, "bad depth " .. depth) + end + if COLOR_CHANNELS[mode] == nil then + return nil, Err.new(Err.CORRUPT, "bad colour mode " .. mode) + end + if (mode == 0) ~= (depth == 1) then + return nil, Err.new(Err.UNSUPPORTED, "1-bit data outside bitmap mode") + end + if w * h > c.maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, c.maxPixels)) + end + local layered = Types.Layered.new(w, h) + -- colour mode data + local cm = r:slice(r:u32be()) + local palette: buffer? = nil + if mode == 2 and cm:size() >= 768 then + palette = cm:bytes(768) + local pal = {} + for i = 0, 255 do + pal[i + 1] = { buffer.readu8(palette :: buffer, i), buffer.readu8(palette :: buffer, 256 + i), buffer.readu8(palette :: buffer, 512 + i), 255 } + end + layered.meta.palette = pal + end + -- image resources + local rr = r:slice(r:u32be()) + if r.err then + return nil, r.err + end + local resources = {} + while rr:remaining() >= 12 and rr:string(4) == "8BIM" do + local id = rr:u16be() + local nl = rr:u8() + local name = rr:string(nl) + rr:skip((nl + 1) % 2) + local size = rr:u32be() + if rr.err or size > rr:remaining() then + break + end + local data = rr:bytes(size) + rr:skip(size % 2) + table.insert(resources, { id = id, name = name, data = data }) + if id == 0x040F then + layered.meta.icc = data + end + end + layered.meta.resources = resources + -- layer and mask information + local lm = r:slice(len(r, c.psb)) + if r.err then + return nil, r.err + end + local recs: { any }? = nil + local absAlpha = false + if o.layers ~= false and lm:size() > 0 then + local liLen = len(lm, c.psb) + local li = lm:slice(liLen) + if lm.err then + return nil, lm.err + end + if liLen > 0 then + local list, aa, lerr = layerRecords(li, c) + if not list then + return nil, lerr + end + recs, absAlpha = list, aa + end + -- global layer mask info, then additional info (16 / 32-bit layers live in Lr16 / Lr32) + lm:skip(lm:u32be()) + while not lm.err and lm:remaining() >= 12 do + local sig = lm:string(4) + if sig ~= "8BIM" and sig ~= "8B64" then + break + end + local k = lm:string(4) + local l = if c.psb and LONG_KEYS[k] then lm:u64be() else lm:u32be() + if lm.err then + break + end + local d = lm:slice(l) + if (k == "Lr16" or k == "Lr32" or k == "Layr") and recs == nil then + local list, aa, lerr = layerRecords(d, c) + if not list then + return nil, lerr + end + recs, absAlpha = list, aa + end + lm:align(4) + end + end + if recs then + layered.layers = tree(recs) + end + -- the merged image + local comp = r:u16be() + if r.err then + return nil, r.err + end + local cc = COLOR_CHANNELS[mode] + if mode == 7 then + cc = math.min(nch, 3) + end + local useAlpha = nch > cc and (absAlpha or recs == nil) and mode ~= 7 + local nread = math.min(nch, cc + (if useAlpha then 1 else 0)) + local rb = Channels.rowBytes(w, depth) + local planes: { [any]: buffer } = {} + local b = r.buf + if comp == 0 then + for k = 1, nread do + local p = r.pos + (k - 1) * rb * h + if p + rb * h > r.limit then + return nil, Err.new(Err.TRUNCATED, "merged image past the end", p) + end + local plane = buffer.create(rb * h) + buffer.copy(plane, 0, b, p, rb * h) + planes[k] = plane + end + elseif comp == 1 then + local counts, q = Channels.rleCounts(b, r.pos, r.limit, h * nch, c.psb) + if not counts then + return nil, Err.new(Err.TRUNCATED, "merged image row counts past the end", r.pos) + end + local p: number = q + for k = 1, nread do + local plane = buffer.create(rb * h) + local np, perr = Channels.rle(b, p, r.limit, counts, (k - 1) * h + 1, h, rb, plane, 0) + if not np then + return nil, Err.new(Err.CORRUPT, "merged image: " .. tostring(perr), p) + end + p = np + planes[k] = plane + end + elseif comp == 2 or comp == 3 then + -- one zlib stream per channel would be Channels.channel; Photoshop writes all channels in one stream + local all = Channels.channel(b, r.pos - 2, r.limit, w, h * nread, depth, c.psb) + if not all then + return nil, Err.new(Err.CORRUPT, "merged image: bad ZIP data", r.pos) + end + for k = 1, nread do + local plane = buffer.create(rb * h) + buffer.copy(plane, 0, all, (k - 1) * rb * h, rb * h) + planes[k] = plane + end + else + return nil, Err.new(Err.CORRUPT, "bad merged image compression " .. comp) + end + if useAlpha then + planes.alpha = planes[cc + 1] + planes[cc + 1] = nil :: any + end + if depth == 32 then + for _, p in planes do + Channels.swap32(p) + end + end + local composite = Types.Image.new(w, h) + composite.pixels = Channels.toRGBA(planes, w, h, depth, mode, palette) + if planes.alpha then + Channels.unmatte(composite.pixels, w * h) + end + composite.meta.source = { format = "psd", bitDepth = depth, colorType = MODE_NAMES[mode] } + layered.meta.composite = composite + layered.meta.source = { format = "psd", version = version, bitDepth = depth, colorMode = MODE_NAMES[mode], channels = nch, psb = c.psb } + return layered, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +type Rec = { layer: any, section: number?, name: string } + +local function isImage(v: any): boolean + return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and v.width >= 0 and v.height >= 0 and buffer.len(v.pixels) >= v.width * v.height * 4 +end + +local function pascal(name: string): string + local s = string.gsub(name, "[\128-\255]", "?") + s = string.sub(s, 1, 255) + local pad = (4 - (#s + 1) % 4) % 4 + return string.char(#s) .. s .. string.rep("\0", pad) +end + +local function block(w: Bytes.Writer, key: string, data: string) + w:string("8BIM") + w:string(key) + local pad = (4 - #data % 4) % 4 -- additional info is padded to 4 + w:u32be(#data + pad) + w:string(data) + w:fill(0, pad) +end + +local function u32s(v: number): string + return string.char(v // 16777216 % 256, v // 65536 % 256, v // 256 % 256, v % 256) +end + +local function luni(name: string): string + local out = {} + local n = 0 + for _, cp in utf8.codes(name) do + if cp >= 0x10000 then + local v = cp - 0x10000 + local hi, lo = 0xD800 + v // 1024, 0xDC00 + v % 1024 + table.insert(out, string.char(hi // 256, hi % 256, lo // 256, lo % 256)) + n += 2 + else + table.insert(out, string.char(cp // 256, cp % 256)) + n += 1 + end + end + return u32s(n) .. table.concat(out) +end + +function Psd.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" then + return nil, Err.new(Err.ARG, "needs a Layered value") + end + local W, H = math.floor(layered.width), math.floor(layered.height) + if W < 1 or H < 1 or W > 300000 or H > 300000 then + return nil, Err.new(Err.ARG, "bad document size") + end + local psb = W > 30000 or H > 30000 + -- the records, bottom to top + local recs: { Rec } = {} + local bad: string? = nil + local function walk(list: { any }, depth: number) + for _, l in list do + if type(l) ~= "table" then + bad = "a layer is not a table" + return + end + if type(l.children) == "table" then + if depth > 64 then + bad = "groups nested too deep" + return + end + table.insert(recs, { layer = l, section = 3, name = "" }) + walk(l.children, depth + 1) + table.insert(recs, { layer = l, section = if l.collapsed then 2 else 1, name = tostring(l.name or "Group") }) + else + if not isImage(l.image) then + bad = "layer " .. tostring(l.name) .. ": needs an rgba8 image" + return + end + table.insert(recs, { layer = l, name = tostring(l.name or "Layer") }) + end + end + end + walk(layered.layers, 0) + if bad then + return nil, Err.new(Err.ARG, bad :: string) + end + if #recs > 32767 then + return nil, Err.new(Err.ARG, "too many layers") + end + local function lenW(w: Bytes.Writer, v: number) + if psb then + w:u64be(v) + else + w:u32be(v) + end + end + -- layer records and channel data + local info = Bytes.writer(4096) + local data = Bytes.writer(65536) + info:i16be(-#recs) -- negative: the merged image's first alpha channel is its transparency + for _, rec in recs do + local l = rec.layer + local img = if rec.section then nil else l.image + local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0) + local w, h = if img then img.width else 0, if img then img.height else 0 + if rec.section then + x, y = 0, 0 + end + info:i32be(y) + info:i32be(x) + info:i32be(y + h) + info:i32be(x + w) + local chans: { { id: number, data: buffer } } = {} + if img and w > 0 and h > 0 then + local pr, pg, pb, pa = Channels.planes8(img.pixels, w, h) + chans = { + { id = -1, data = Channels.rleChannel(pa, w, h, psb) }, + { id = 0, data = Channels.rleChannel(pr, w, h, psb) }, + { id = 1, data = Channels.rleChannel(pg, w, h, psb) }, + { id = 2, data = Channels.rleChannel(pb, w, h, psb) }, + } + else + chans = { { id = -1, data = buffer.create(0) }, { id = 0, data = buffer.create(0) }, { id = 1, data = buffer.create(0) }, { id = 2, data = buffer.create(0) } } + end + -- the mask + local m = if rec.section == nil and type(l.mask) == "table" and type(l.mask.image) == "table" and type(l.mask.image.pixels) == "buffer" then l.mask else nil + local mw, mh = 0, 0 + if m then + local mi = m.image + mw, mh = mi.width, mi.height + local plane = mi.pixels + if mi.format == "rgba8" then + plane = (Channels.planes8(mi.pixels, mw, mh)) + elseif mi.format ~= "gray8" and mi.format ~= "alpha8" then + return nil, Err.new(Err.ARG, "mask images are gray8 / alpha8 / rgba8") + end + if buffer.len(plane) < mw * mh then + return nil, Err.new(Err.ARG, "bad mask image") + end + table.insert(chans, { id = -2, data = Channels.rleChannel(plane, mw, mh, psb) }) + end + info:u16be(#chans) + for _, ch in chans do + info:i16be(ch.id) + lenW(info, buffer.len(ch.data) + 2) + data:u16be(if buffer.len(ch.data) > 0 then 1 else 0) + data:bytes(ch.data) + end + info:string("8BIM") + local blend = if type(l.blend) == "string" then l.blend else "normal" + local key = BLEND_NAMES[blend] or "norm" + if rec.section and rec.section ~= 3 then + key = if blend == "passThrough" then "pass" else key + end + info:string(key) + info:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255)) + info:u8(if l.clip and rec.section == nil then 1 else 0) + local flags = 8 -- bit 3: bit 4 is meaningful + if l.visible == false and rec.section ~= 3 then + flags += 2 + end + if rec.section then + flags += 16 -- pixel data irrelevant to the appearance + end + info:u8(flags) + info:u8(0) + local ex = Bytes.writer(256) + if m then + ex:u32be(20) + local mx, my = math.floor(tonumber(m.x) or 0), math.floor(tonumber(m.y) or 0) + ex:i32be(my) + ex:i32be(mx) + ex:i32be(my + mh) + ex:i32be(mx + mw) + ex:u8(math.clamp(math.floor(tonumber(m.default) or 0), 0, 255)) + ex:u8(if m.disabled then 2 else 0) + ex:u16be(0) + else + ex:u32be(0) + end + ex:u32be(0) -- blending ranges + ex:string(pascal(rec.name)) + block(ex, "luni", luni(rec.name)) + if rec.section then + block(ex, "lsct", u32s(rec.section) .. (if rec.section ~= 3 then "8BIM" .. key else "")) + end + local fill = tonumber(l.fillOpacity) + if fill and fill < 1 and rec.section == nil then + block(ex, "iOpa", string.char(math.clamp(math.floor(fill * 255 + 0.5), 0, 255)) .. "\0\0\0") + end + local exb = ex:finish() + info:u32be(buffer.len(exb)) + info:bytes(exb) + end + info:bytes(data:finish()) + if info:tell() % 2 == 1 then + info:u8(0) + end + local infoB = info:finish() + -- the merged image + local comp: Types.Image? = opts and opts.composite + if comp ~= nil and (not isImage(comp) or comp.width ~= W or comp.height ~= H) then + return nil, Err.new(Err.ARG, "opts.composite must be a " .. W .. " x " .. H .. " rgba8 Image") + end + local merged: buffer + if comp then + merged = comp.pixels + else + merged = buffer.create(W * H * 4) + Blend.flatten(layered.layers, merged, W, H, false) + end + local out = Bytes.writer(buffer.len(infoB) + W * H * 4 + 1024) + out:string("8BPS") + out:u16be(if psb then 2 else 1) + out:fill(0, 6) + out:u16be(4) + out:u32be(H) + out:u32be(W) + out:u16be(8) + out:u16be(3) + out:u32be(0) -- colour mode data + out:u32be(0) -- image resources + local lmLen = (if psb then 8 else 4) + buffer.len(infoB) + 4 + lenW(out, lmLen) + lenW(out, buffer.len(infoB)) + out:bytes(infoB) + out:u32be(0) -- global layer mask info + -- merged: RLE, all row counts first + out:u16be(1) + local pr, pg, pb, pa = Channels.planes8(Channels.matte(merged, W * H), W, H) + local cs = if psb then 4 else 2 + local parts = {} + for k, plane in { pr, pg, pb, pa } do + local ch = Channels.rleChannel(plane, W, H, psb) + parts[k] = ch + out:bytes(ch, 0, H * cs) + end + for k = 1, 4 do + out:bytes(parts[k], H * cs) + end + return out:finish(), nil +end + +return Psd diff --git a/src/Formats/ops/LayerOps.luau b/src/Formats/ops/LayerOps.luau new file mode 100644 index 0000000..bf4b242 --- /dev/null +++ b/src/Formats/ops/LayerOps.luau @@ -0,0 +1,101 @@ +--!strict +-- ops/LayerOps: editing on the Layered type (PSD, Aseprite): flatten a layer tree (or one animation frame) to an +-- rgba8 Image with the blend modes of codecs/Blend, opacity, groups (isolated, or pass-through), clipping layers and +-- grey layer masks; every frame as an animated Image; walking the leaves. +-- +-- local LayerOps = require("@formats/ops/LayerOps") +-- local img = LayerOps.flatten(layered) -- frame 1 / the layers +-- local img3 = LayerOps.flatten(layered, { frame = 3 }) +-- local anim = LayerOps.flattenFrames(layered) -- an Image with frames (delays from the Layered frames) +-- for layer, depth in LayerOps.leaves(layered.layers) do ... end +-- +-- Never throws: bad values return nil, Err.ARG. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Blend = require("@formats/codecs/Blend") + +local LayerOps = {} + +export type FlattenOptions = { + frame: number?, -- 1-based animation frame (default: layered.layers, which is frame 1) + hidden: boolean?, -- include hidden layers (default false) + background: { number }?, -- r, g, b, a 0..255 under everything (default transparent) +} + +-- flatten(layered, opts?) -> rgba8 Image (layered.width x layered.height) | nil, Err +function LayerOps.flatten(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?) + if type(layered) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" or type(layered.layers) ~= "table" then + return nil, Err.new(Err.ARG, "flatten: needs a Layered value") + end + local o: FlattenOptions = opts or {} + local w, h = math.floor(layered.width), math.floor(layered.height) + if w < 0 or h < 0 or w * h > 2 ^ 28 then + return nil, Err.new(Err.ARG, "flatten: bad size") + end + local layers = layered.layers + if o.frame then + local f = if type(layered.frames) == "table" then layered.frames[o.frame] else nil + if f == nil and o.frame ~= 1 then + return nil, Err.new(Err.ARG, "flatten: no frame " .. tostring(o.frame)) + end + if f then + layers = f.layers + end + end + local img = Types.Image.new(w, h) + local bg = o.background + if type(bg) == "table" then + local v = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216 + for i = 0, w * h - 1 do + buffer.writeu32(img.pixels, i * 4, v) + end + end + Blend.flatten(layers, img.pixels, w, h, o.hidden == true) + return img, nil +end + +-- flattenFrames(layered, opts?) -> an rgba8 Image whose frames are every flattened frame (frame 1 is the image) +function LayerOps.flattenFrames(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?) + local first, err = LayerOps.flatten(layered, opts) + if not first then + return nil, err + end + local frames = if type(layered.frames) == "table" then layered.frames else {} + if #frames == 0 then + return first, nil + end + local list: { Types.Frame } = {} + for i, f in frames do + local o: FlattenOptions = table.clone(opts or {}) :: any + o.frame = i + local img = if i == 1 then first else LayerOps.flatten(layered, o) + if not img then + return nil, Err.new(Err.ARG, "flatten: frame " .. i) + end + list[i] = { image = img, delay = tonumber(f.delay) or 0.1, x = 0, y = 0, dispose = "none", blend = "source" } + end + first.frames = list + return first, nil +end + +-- leaves(layers) -> iterator of (layer, depth) over the non-group layers of a tree, bottom to top +function LayerOps.leaves(layers: { Types.Layer }): () -> (Types.Layer?, number?) + local stack: { { any } } = { { layers, 0, 0 } } + return function(): (Types.Layer?, number?) + while #stack > 0 do + local top = stack[#stack] + top[2] += 1 + local l = top[1][top[2]] + if l == nil then + table.remove(stack) + elseif type(l.children) == "table" then + table.insert(stack, { l.children, 0, top[3] + 1 }) + else + return l, top[3] + end + end + return nil, nil + end +end + +return LayerOps diff --git a/tests/layered/psd.luau b/tests/layered/psd.luau new file mode 100644 index 0000000..5d3227a --- /dev/null +++ b/tests/layered/psd.luau @@ -0,0 +1,184 @@ +-- layered/psd tests: PSD / PSB files of every colour mode and depth, compression, groups, pass-through, clipping, +-- masks, fill opacity and blend mode (written by tools/fixtures/psd.py) plus an ImageMagick PSD, against psd-tools: +-- the merged image and every layer's pixels exact (8-bit; 16 / 32-bit within rounding), our flatten (ops/LayerOps) +-- against psd-tools' composite by PSNR; our encoder's PSD read back by psd-tools (tools/fixtures/_ours.luau), round +-- trips, the contract and the fuzz pass. Fixtures: tools/fixtures/psd.py. +local T = require("@tests/T") +local Psd = require("@formats/layered/psd") +local LayerOps = require("@formats/ops/LayerOps") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/psd") +local Ours = require("@tests/gen/psd_ours") + +local t = T.suite("psd") + +local function decode(s: string | buffer, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Psd.decode(Bytes.reader(b), opts) +end +-- PSNR of two rgba8 buffers, colours premultiplied by alpha (the colour of a transparent pixel does not matter); +-- identical -> 99 +local function psnr(a: buffer, b: string, opaque: boolean?): number + local n = math.min(buffer.len(a), #b) + local se = 0 + for i = 0, n - 1, 4 do + local aa, ab = buffer.readu8(a, i + 3), string.byte(b, i + 4) + if opaque then + aa, ab = 255, 255 + end + for k = 0, 2 do + local d = (buffer.readu8(a, i + k) * aa - string.byte(b, i + k + 1) * ab) / 255 + se += d * d + end + se += (aa - ab) * (aa - ab) + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 / (se / n)) +end +local function leaves(layers: any): { any } + local out = {} + for l in LayerOps.leaves(layers) do + table.insert(out, l) + end + return out +end + +t:eq(Psd.name, "psd", "name") +t:eq(Psd.category, "layered", "category") +t:check(Psd.caps.decode and Psd.caps.encode, "caps") + +-- PSNR floors for our flatten vs psd-tools' composite: blend modes where psd-tools' formulas differ from the W3C ones +-- (Photoshop's own differ from both) get a lower bar +local LOW = { ["blend-diss"] = 8, ["blend-hMix"] = 15, ["blend-sLit"] = 30, ["blend-vLit"] = 25, ["blend-lLit"] = 30, ["blend-pLit"] = 30, ["blend-div"] = 30, ["blend-idiv"] = 30, ["blend-fdiv"] = 25, ["blend-hue"] = 25, ["blend-sat"] = 25, ["blend-colr"] = 25, ["blend-lum"] = 25 } +local samples = {} +for _, c in Fx.cases do + local doc, err = decode(c.data) + t:check(doc, c.name .. ": " .. tostring(err)) + t:eq(doc.kind, "layered", c.name .. ": kind") + t:check(doc.width == c.width and doc.height == c.height, c.name .. ": size") + local comp = doc.meta.composite + if #c.composite > 0 then + local src = doc.meta.source + local exact = (src.bitDepth == 8 or src.bitDepth == 1) and src.colorMode ~= "lab" and src.colorMode ~= "cmyk" + if exact then + t:check(buffer.tostring(comp.pixels) == c.composite, c.name .. ": merged image = psd-tools") + else + -- (PIL turns Lab into RGBA with alpha 0: compare the colours only) + local p = psnr(comp.pixels, c.composite, src.colorMode == "lab") + -- 16 / 32 bits: rounding; CMYK / Lab: different conversions (ours: naive CMYK, D65 Lab) + local floor = if src.colorMode == "lab" then 20 elseif src.colorMode == "cmyk" then 30 else 45 + t:check(p > floor, string.format("%s: merged image PSNR %.1f", c.name, p)) + t:note("%s: merged image vs psd-tools %.1f dB", c.name, p) + end + end + -- layers, in order, against psd-tools + local ours = leaves(doc.layers) + local ref = {} + for _, l in c.layers do + if not l.group then + table.insert(ref, l) + end + end + t:eq(#ours, #ref, c.name .. ": leaf count") + for i, r in ref do + local l = ours[i] + t:eq(l.name, r.name, c.name .. ": layer name") + if r.width > 0 then + t:check(l.x == r.left and l.y == r.top and l.image.width == r.width and l.image.height == r.height, c.name .. ": " .. r.name .. ": bounds") + end + if r.crc and doc.meta.source.bitDepth == 8 then + t:eq(Crc32.of(l.image.pixels), r.crc, c.name .. ": " .. r.name .. ": pixels") + end + end + -- our flatten vs psd-tools' composite + if c.flat and #ours > 0 then + local flat = LayerOps.flatten(doc) :: any + local p = psnr(flat.pixels, c.flat) + local floor = LOW[c.name] or 38 + t:check(p >= floor, string.format("%s: flatten PSNR %.1f dB (floor %d)", c.name, p, floor)) + if p < 99 then + t:note("%s: flatten vs psd-tools %.1f dB", c.name, p) + end + end + if #samples < 8 and (c.name == "rgb-layers" or c.name == "psb" or c.name == "rgb16-lr16" or c.name == "gray" or c.name == "indexed" or c.name == "bitmap" or c.name == "rgb32" or c.name == "cmyk") then + table.insert(samples, c.data) + end +end + +-- the full document's structure +do + local doc + for _, c in Fx.cases do + if c.name == "rgb-layers" then + doc = decode(c.data) + end + end + local L = doc.layers + t:eq(#L, 8, "top level: bg, multiply, isolated, pass, base, clipped, masked, fill") + t:eq(L[2].blend, "multiply", "blend") + t:eq(math.floor(L[2].opacity * 255 + 0.5), 200, "opacity") + t:eq(L[3].name, "Isolated", "group name") + t:eq(L[3].blend, "normal", "isolated group blend") + t:eq(#L[3].children, 2, "group children") + t:eq(L[4].blend, "passThrough", "pass-through group") + t:eq(L[4].children[1].name, "Diff \u{e9}\u{65e5}", "unicode name (luni)") + t:eq(L[4].children[2].visible, false, "hidden layer") + t:eq(L[6].clip, true, "clipping layer") + t:check(L[7].mask and L[7].mask.image.format == "gray8" and L[7].mask.x == 8 and L[7].mask.y == 5, "mask") + t:eq(math.floor(L[8].fillOpacity * 255 + 0.5), 128, "fill opacity") + local only = decode(Fx.cases[1].data, { layers = false }) + t:check(only and #only.layers == 0 and only.meta.composite, "layers = false: merged image only") + + -- round trip: our PSD of the decoded document decodes to the same layers, and its merged image is our flatten + local out, eerr = Psd.encode(doc) + t:check(out, "encode: " .. tostring(eerr)) + local back = decode(out :: buffer) + t:check(back, "decode our PSD") + local a, b = leaves(doc.layers), leaves(back.layers) + t:eq(#b, #a, "round trip: leaves") + for i, l in a do + t:eq(b[i].name, l.name, "rt name") + t:check(buffer.tostring(b[i].image.pixels) == buffer.tostring(l.image.pixels), "rt pixels " .. l.name) + t:check(b[i].x == l.x and b[i].y == l.y, "rt position") + t:eq(b[i].blend, l.blend, "rt blend") + t:eq(b[i].visible, l.visible, "rt visible") + t:eq(b[i].clip, l.clip, "rt clip") + t:eq(b[i].opacity, l.opacity, "rt opacity") + end + t:eq(back.layers[4].blend, "passThrough", "rt pass-through group") + t:check(back.layers[7].mask and buffer.tostring(back.layers[7].mask.image.pixels) == buffer.tostring(L[7].mask.image.pixels), "rt mask") + local flat = LayerOps.flatten(doc) :: any + -- the merged image is stored matted with white (as Photoshop does): exact where opaque, rounding elsewhere + local p = psnr(back.meta.composite.pixels, buffer.tostring(flat.pixels)) + t:check(p > 45, string.format("rt merged = flatten (%.1f dB)", p)) + table.insert(samples, buffer.tostring(out :: buffer)) +end + +-- psd-tools reads our encoder's PSD (checked when the fixtures were made) +for _, c in Ours.checks do + t:check(c.ok, "psd-tools on our PSD: " .. c.label) +end +t:note("psd-tools agrees with our PSD on %d facts", #Ours.checks) + +-- errors +do + local _, e = decode("8BPS\0\1\0\0\0\0\0\0\0\3\0\0\0\10\0\0\0\10\0\8\0\3") + t:check(e and e.code == Err.TRUNCATED, "truncated after the header: " .. tostring(e)) + local _, e2 = decode("8BPS\0\1\0\0\0\0\0\0\0\3\0\0\0\10\0\0\0\10\0\7\0\3") + t:check(e2 and e2.code == Err.CORRUPT, "bad depth: " .. tostring(e2)) + local _, e3 = decode(Fx.cases[1].data, { maxPixels = 100 }) + t:check(e3 and e3.code == Err.LIMIT, "maxPixels") + t:eq(Psd.sniff(Bytes.reader(buffer.fromstring("8BPS\0\1"))), 1, "sniff") + t:eq(Psd.sniff(Bytes.reader(buffer.fromstring("8BPS\0\3"))), 0, "sniff version 3") + local _, e4 = Psd.encode({ width = 4, height = 4, layers = { { name = "x" } } } :: any) + t:check(e4 and e4.code == Err.ARG, "encode: layer without an image") +end + +t:fuzz("decode", function(b: buffer) + return Psd.decode(Bytes.reader(b)) +end, samples, { mutations = 30, keepHeader = 4 }) +t:done() diff --git a/tests/ops/layerops.luau b/tests/ops/layerops.luau new file mode 100644 index 0000000..94f4692 --- /dev/null +++ b/tests/ops/layerops.luau @@ -0,0 +1,144 @@ +-- ops/LayerOps + codecs/Blend tests: blend mode formulas on single pixels against hand-computed W3C values, opacity, +-- masks, clipping, isolated vs pass-through groups, hidden layers, frames, leaves, bad arguments. (Whole-document +-- flattening against psd-tools is in tests/layered/psd.luau.) +local T = require("@tests/T") +local LayerOps = require("@formats/ops/LayerOps") +local Blend = require("@formats/codecs/Blend") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") + +local t = T.suite("layerops") + +local function px(r: number, g: number, b: number, a: number): Types.Image + local img = Types.Image.new(1, 1) + buffer.writeu8(img.pixels, 0, r) + buffer.writeu8(img.pixels, 1, g) + buffer.writeu8(img.pixels, 2, b) + buffer.writeu8(img.pixels, 3, a) + return img +end +local function get(img: any): (number, number, number, number) + local p = img.pixels + return buffer.readu8(p, 0), buffer.readu8(p, 1), buffer.readu8(p, 2), buffer.readu8(p, 3) +end +local function doc(layers: { any }): any + local d = Types.Layered.new(1, 1) + d.layers = layers + return d +end +local L = Types.Layered.layer + +-- separable modes on opaque pixels: backdrop (200, 100, 50), source (100, 150, 250); values from the W3C formulas +local cases = { + normal = { 100, 150, 250 }, + multiply = { 78, 59, 49 }, + screen = { 222, 191, 251 }, + darken = { 100, 100, 50 }, + lighten = { 200, 150, 250 }, + difference = { 100, 50, 200 }, + exclusion = { 143, 132, 202 }, + linearDodge = { 255, 250, 255 }, + linearBurn = { 45, 0, 45 }, + subtract = { 100, 0, 0 }, + overlay = { 188, 118, 98 }, + hardLight = { 157, 127, 247 }, + colorDodge = { 255, 243, 255 }, + colorBurn = { 115, 0, 46 }, + hardMix = { 255, 0, 255 }, +} +for mode, want in cases do + local top = L("top", px(100, 150, 250, 255)) + top.blend = mode + local img = LayerOps.flatten(doc({ L("bottom", px(200, 100, 50, 255)), top })) :: any + local r, g, b, a = get(img) + t:check(math.abs(r - want[1]) <= 1 and math.abs(g - want[2]) <= 1 and math.abs(b - want[3]) <= 1 and a == 255, string.format("%s: got %d %d %d, want %d %d %d", mode, r, g, b, want[1], want[2], want[3])) +end +-- non-separable: luminosity of the source on the backdrop's hue +do + local top = L("top", px(255, 255, 255, 255)) + top.blend = "luminosity" + local r, g, b = get(LayerOps.flatten(doc({ L("bottom", px(255, 0, 0, 255)), top }))) + t:check(r == 255 and g == 255 and b == 255, "luminosity of white") + top.blend = "color" + local r2, g2, b2 = get(LayerOps.flatten(doc({ L("bottom", px(128, 128, 128, 255)), top }))) + t:check(r2 == g2 and g2 == b2 and math.abs(r2 - 128) <= 1, "colour of a grey source keeps the grey") +end +-- opacity and alpha: 50% red over opaque blue +do + local top = L("top", px(255, 0, 0, 255)) + top.opacity = 0.5 + local r, g, b, a = get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top }))) + t:check(math.abs(r - 128) <= 1 and g == 0 and math.abs(b - 128) <= 1 and a == 255, "opacity mix") + local r2, _, _, a2 = get(LayerOps.flatten(doc({ top }))) + t:check(r2 == 255 and math.abs(a2 - 128) <= 1, "over transparent: alpha scales") +end +-- hidden layers, masks, clipping +do + local top = L("top", px(255, 0, 0, 255)) + top.visible = false + local r = get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top }))) + t:eq(r, 0, "hidden layer skipped") + local r2 = get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top }), { hidden = true })) + t:eq(r2, 255, "hidden = true includes it") + top.visible = true + local m = Types.Image.new(1, 1, "gray8") + top.mask = { image = m, x = 0, y = 0, default = 255 } + t:eq((get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top })))), 0, "black mask hides") + top.mask = { image = m, x = 5, y = 5, default = 255 } + t:eq((get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top })))), 255, "outside the mask: default white") + top.mask = nil + local base = L("base", px(0, 255, 0, 0)) -- transparent base: the clipped layer shows nowhere + top.clip = true + local r3, g3, b3, a3 = get(LayerOps.flatten(doc({ base, top }))) + t:check(a3 == 0, "clipped to a transparent base: " .. r3 .. g3 .. b3 .. a3) + base = L("base", px(0, 255, 0, 255)) + local r4, g4 = get(LayerOps.flatten(doc({ base, top }))) + t:check(r4 == 255 and g4 == 0, "clipped to an opaque base") +end +-- groups: an isolated multiply group multiplies its composite; pass-through multiplies each child onto the backdrop +do + local child = L("child", px(128, 128, 128, 255)) + child.blend = "multiply" + local g = Types.Layered.group("g", { child }) + local bottom = L("bottom", px(200, 200, 200, 255)) + local r = get(LayerOps.flatten(doc({ bottom, g }))) + t:check(math.abs(r - 100) <= 1, "pass-through: child multiplies the backdrop: " .. r) + g.blend = "normal" + local r2 = get(LayerOps.flatten(doc({ bottom, g }))) + t:eq(r2, 128, "isolated group: the child multiplies nothing") + g.blend = "passThrough" + g.opacity = 0.5 + local r3 = get(LayerOps.flatten(doc({ bottom, g }))) + t:check(math.abs(r3 - 150) <= 1, "pass-through opacity mixes before / after: " .. r3) +end +-- frames, leaves, flattenFrames +do + local d = doc({ L("a", px(1, 2, 3, 255)) }) + d.frames = { { layers = d.layers, delay = 0.1 }, { layers = { L("b", px(9, 8, 7, 255)) }, delay = 0.2 } } + t:eq((get(LayerOps.flatten(d, { frame = 2 }))), 9, "frame 2") + local anim = LayerOps.flattenFrames(d) :: any + t:check(anim.frames and #anim.frames == 2 and anim.frames[2].delay == 0.2, "flattenFrames") + local _, e = LayerOps.flatten(d, { frame = 5 }) + t:check(e and e.code == Err.ARG, "missing frame") + local names = {} + for l, depth in LayerOps.leaves({ L("x", px(0, 0, 0, 0)), Types.Layered.group("g", { L("y", px(0, 0, 0, 0)), Types.Layered.group("h", { L("z", px(0, 0, 0, 0)) }) }) }) do + table.insert(names, (l :: any).name .. depth) + end + t:eq(table.concat(names, " "), "x0 y1 z2", "leaves with depth") + local _, e2 = LayerOps.flatten(5 :: any) + t:check(e2 and e2.code == Err.ARG, "flatten of a non-Layered") +end +-- Blend.composite clips its rectangles (no throw, nothing outside) +do + local dst = buffer.create(4 * 4 * 4) + local src = buffer.create(3 * 3 * 4) + buffer.fill(src, 0, 255) + for _, pos in { { -2, -2 }, { 3, 3 }, { -10, 0 }, { 100, 100 } } do + Blend.composite(dst, 4, 4, src, 3, 3, pos[1], pos[2], 1, "multiply") + end + Blend.composite(dst, 4, 4, src, 3, 3, 0, 0, 1, "nope") + Blend.composite(dst, 4, 4, src, 30, 30, 0, 0, 1, "normal") -- src too short: ignored + t:eq(buffer.readu8(dst, 0), 255, "composite clipping") + t:check(Blend.MODES.softLight and not Blend.MODES.nope, "MODES") +end +t:done() diff --git a/tools/fixtures/_ours.luau b/tools/fixtures/_ours.luau new file mode 100644 index 0000000..37be39b --- /dev/null +++ b/tools/fixtures/_ours.luau @@ -0,0 +1,102 @@ +-- tools/fixtures/_ours.luau: our encoders' output for the reference tools to read (run by tools/fixtures/*.py through +-- `luau tools/fixtures/_ours.luau -a `). Prints one JSON object: { "data": hex of the encoded file, ... the +-- facts the python side checks the reference's reading against }. +local Types = require("@formats/Types") +local Crc32 = require("@formats/core/Crc32") +local LayerOps = require("@formats/ops/LayerOps") + +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(t) +end + +local function json(v: any): string + if type(v) == "table" then + if #v > 0 or next(v) == nil then + local t = {} + for i, x in v do + t[i] = json(x) + end + return "[" .. table.concat(t, ",") .. "]" + end + local t = {} + for k, x in v do + table.insert(t, string.format("%q", k) .. ":" .. json(x)) + end + return "{" .. table.concat(t, ",") .. "}" + elseif type(v) == "string" then + return string.format("%q", v) + elseif type(v) == "boolean" then + return if v then "true" else "false" + end + return tostring(v) +end + +-- a deterministic rgba8 image +local function image(w: number, h: number, seed: number, alpha: boolean?): Types.Image + local img = Types.Image.new(w, h) + for y = 0, h - 1 do + for x = 0, w - 1 do + local o = (y * w + x) * 4 + buffer.writeu8(img.pixels, o, (x * (seed + 3) * 7 + y * 5) % 256) + buffer.writeu8(img.pixels, o + 1, (y * (seed + 1) * 9 + x) % 256) + buffer.writeu8(img.pixels, o + 2, ((x + seed) * (y + 1) * 3) % 256) + buffer.writeu8(img.pixels, o + 3, if alpha and (x + y) % 3 == 0 then (x * 40 + seed) % 256 else 255) + end + end + return img +end +local function gray(w: number, h: number): Types.Image + local img = Types.Image.new(w, h, "gray8") + for i = 0, w * h - 1 do + buffer.writeu8(img.pixels, i, (i * 13) % 256) + end + return img +end + +-- the Layered document tests/layered/psd.luau also builds (keep them in step) +local function psdDoc(): Types.Layered + local L = Types.Layered + local doc = L.new(36, 24) + local bg = L.layer("Background", image(36, 24, 1)) + local mul = L.layer("Multiply", image(20, 12, 2, true), 4, 3) + mul.blend = "multiply" + mul.opacity = 200 / 255 + local scr = L.layer("Screen", image(18, 18, 3, true), 12, 4) + scr.blend = "screen" + local iso = L.group("Isolated", { scr }) + iso.blend = "normal" + iso.opacity = 180 / 255 + local hid = L.layer("Hidden", image(8, 8, 4), 1, 1) + hid.visible = false + local diff = L.layer("Diff \u{e9}\u{65e5}", image(14, 10, 5, true), 18, 12) + diff.blend = "difference" + local pass = L.group("Pass", { hid, diff }) + local base = L.layer("Base", image(10, 8, 6), 24, 14) + local clip = L.layer("Clipped", image(14, 12, 7, true), 20, 10) + clip.clip = true + local masked = L.layer("Masked", image(16, 10, 8), 2, 12) + masked.mask = { image = gray(12, 8), x = 4, y = 13, default = 0 } + local fill = L.layer("Fill", image(8, 24, 9, true), 28, 0) + fill.fillOpacity = 128 / 255 + fill.blend = "lighten" + doc.layers = { bg, mul, iso, pass, base, clip, masked, fill } + return doc +end + +local which = ... +if which == "psd" then + local Psd = require("@formats/layered/psd") + local doc = psdDoc() + local data = Psd.encode(doc) :: buffer + local flat = LayerOps.flatten(doc) :: Types.Image + local layers = {} + for l, depth in LayerOps.leaves(doc.layers) do + local lay = l :: any + table.insert(layers, { name = lay.name, crc = Crc32.of(lay.image.pixels), left = lay.x, top = lay.y, width = lay.image.width, height = lay.image.height, blend = lay.blend, visible = lay.visible, clip = lay.clip == true, opacity = math.floor(lay.opacity * 255 + 0.5), depth = depth }) + end + print(json({ data = hex(data), composite = Crc32.of(flat.pixels), layers = layers })) +end diff --git a/tools/fixtures/psd.py b/tools/fixtures/psd.py new file mode 100644 index 0000000..d134b70 --- /dev/null +++ b/tools/fixtures/psd.py @@ -0,0 +1,389 @@ +# PSD fixtures (tools/fixtures.py): PSD / PSB files written here (a small writer below: every colour mode, 1/8/16/32 +# bits, raw / RLE / ZIP / ZIP-with-prediction channels, groups, pass-through, clipping, masks, fill opacity, hidden +# layers, Unicode names, every blend mode) and one written by ImageMagick, all read by psd-tools (the reference): +# tests/gen/psd.luau { cases = { { name, data, width, height, composite (RGBA of psd-tools' merged image), +# layers = { { name, left, top, width, height, crc (RGBA of psd-tools' layer.topil()) } }, +# flat (psd-tools' composite of the layers, RGBA) } } } +# tests/gen/psd_ours.luau { checks = { { label, ok } } }: our encoder's PSD (tools/fixtures/_ours.luau, run with +# luau) read by psd-tools, compared with the layers and the flattened image we wrote. +import json, os, random, shutil, struct, subprocess, tempfile, zlib + +INPUTS = ["src/Formats/layered/psd", "src/Formats/codecs/Blend.luau", "src/Formats/ops/LayerOps.luau", "tools/fixtures/_ours.luau"] + +BLEND = ["norm", "diss", "dark", "mul ", "idiv", "lbrn", "dkCl", "lite", "scrn", "div ", "lddg", "lgCl", "over", "sLit", + "hLit", "vLit", "lLit", "pLit", "hMix", "diff", "smud", "fsub", "fdiv", "hue ", "sat ", "colr", "lum "] + + +def packbits(row): + out, i, n = bytearray(), 0, len(row) + while i < n: + j = i + while j + 1 < n and row[j + 1] == row[i] and j - i < 127: + j += 1 + if j - i >= 2: + out += bytes([257 - (j - i + 1), row[i]]) + i = j + 1 + else: + k = i + while k < n and k - i < 128 and not (k + 2 < n and row[k] == row[k + 1] == row[k + 2]): + k += 1 + out += bytes([k - i - 1]) + row[i:k] + i = k + return bytes(out) + + +def bytes_per(depth): + return {8: 1, 16: 2, 32: 4}[depth] + + +def channel_data(plane, w, h, depth, comp, psb=False): + """plane: bytes (rows of w samples, big endian) -> compression code + data""" + rb = w * bytes_per(depth) + if w == 0 or h == 0: + return struct.pack(">H", 0) + if comp == 0: + return struct.pack(">H", 0) + plane + if comp == 1: + rows = [packbits(plane[y * rb:(y + 1) * rb]) for y in range(h)] + fmt = ">I" if psb else ">H" + return struct.pack(">H", 1) + b"".join(struct.pack(fmt, len(r)) for r in rows) + b"".join(rows) + if comp == 2: + return struct.pack(">H", 2) + zlib.compress(plane) + # zip with prediction + out = bytearray() + for y in range(h): + row = plane[y * rb:(y + 1) * rb] + if depth == 8: + out += bytes([row[0]] + [(row[x] - row[x - 1]) & 255 for x in range(1, w)]) + elif depth == 16: + vals = struct.unpack(">%dH" % w, row) + out += struct.pack(">%dH" % w, *([vals[0]] + [(vals[x] - vals[x - 1]) & 0xFFFF for x in range(1, w)])) + else: + planes = bytes(row[x * 4 + k] for k in range(4) for x in range(w)) + out += bytes([planes[0]] + [(planes[x] - planes[x - 1]) & 255 for x in range(1, len(planes))]) + return struct.pack(">H", 3) + zlib.compress(bytes(out)) + + +def pascal(name, pad=4): + b = name.encode("latin-1", "replace")[:255] + s = bytes([len(b)]) + b + while len(s) % pad: + s += b"\0" + return s + + +def block(key, data, psb=False): + while len(data) % 4: + data += b"\0" + return b"8BIM" + key + (struct.pack(">Q", len(data)) if psb and key in (b"Lr16", b"Lr32", b"Layr") else struct.pack(">I", len(data))) + data + + +def luni(name): + u = name.encode("utf-16-be") + return struct.pack(">I", len(u) // 2) + u + + +class Layer: + def __init__(self, name, left, top, w, h, chans, blend="norm", opacity=255, clip=0, hidden=False, section=None, + section_blend=None, fill=None, mask=None, comp=1): + self.__dict__.update(locals()) + + +def layer_info(layers, depth, psb, neg): + recs, data = bytearray(), bytearray() + for L in layers: + recs += struct.pack(">iiii", L.top, L.left, L.top + L.h, L.left + L.w) + chans = list(L.chans.items()) + if L.mask: + chans.append((-2, L.mask["plane"])) + recs += struct.pack(">H", len(chans)) + for cid, plane in chans: + if cid == -2: + m = L.mask + cd = channel_data(plane, m["w"], m["h"], depth, 1, psb) + else: + cd = channel_data(plane, L.w, L.h, depth, L.comp, psb) + recs += struct.pack(">h", cid) + (struct.pack(">Q", len(cd)) if psb else struct.pack(">I", len(cd))) + data += cd + flags = 8 | (2 if L.hidden else 0) | (16 if L.section else 0) + recs += b"8BIM" + L.blend.encode() + bytes([L.opacity, L.clip, flags, 0]) + ex = bytearray() + if L.mask: + m = L.mask + ex += struct.pack(">IiiiiBBH", 20, m["top"], m["left"], m["top"] + m["h"], m["left"] + m["w"], m["default"], m.get("flags", 0), 0) + else: + ex += struct.pack(">I", 0) + ex += struct.pack(">I", 0) + ex += pascal(L.name) + ex += block(b"luni", luni(L.name)) + if L.section is not None: + ex += block(b"lsct", struct.pack(">I", L.section) + (b"8BIM" + L.section_blend.encode() if L.section_blend else b"")) + if L.fill is not None: + ex += block(b"iOpa", bytes([L.fill, 0, 0, 0])) + recs += struct.pack(">I", len(ex)) + ex + body = struct.pack(">h", -len(layers) if neg else len(layers)) + recs + data + if len(body) % 2: + body += b"\0" + return body + + +def psd(w, h, mode, depth, nch, merged_planes, layers=None, psb=False, comp=1, palette=None, lr16=False, neg=True, resources=b""): + out = b"8BPS" + struct.pack(">H", 2 if psb else 1) + b"\0" * 6 + struct.pack(">HIIHH", nch, h, w, depth, mode) + cm = palette or b"" + out += struct.pack(">I", len(cm)) + cm + out += struct.pack(">I", len(resources)) + resources + L = lambda n: struct.pack(">Q", n) if psb else struct.pack(">I", n) + if layers: + li = layer_info(layers, depth, psb, neg) + if lr16: + lm = L(0) + struct.pack(">I", 0) + block(b"Lr16" if depth == 16 else b"Lr32", li, psb) + else: + lm = L(len(li)) + li + struct.pack(">I", 0) + out += L(len(lm)) + lm + else: + out += L(0) + rb = (w + 7) // 8 if depth == 1 else w * bytes_per(depth) + if comp == 0: + out += struct.pack(">H", 0) + b"".join(merged_planes) + elif comp == 1: + rows = [packbits(p[y * rb:(y + 1) * rb]) for p in merged_planes for y in range(h)] + fmt = ">I" if psb else ">H" + out += struct.pack(">H", 1) + b"".join(struct.pack(fmt, len(r)) for r in rows) + b"".join(rows) + else: + out += struct.pack(">H", 2) + zlib.compress(b"".join(merged_planes)) + return out + + +def plane8(w, h, f): + return bytes(f(x, y) & 255 for y in range(h) for x in range(w)) + + +def plane16(w, h, f): + return b"".join(struct.pack(">H", f(x, y) & 0xFFFF) for y in range(h) for x in range(w)) + + +def plane32(w, h, f): + return b"".join(struct.pack(">f", f(x, y)) for y in range(h) for x in range(w)) + + +def rgba_layer(name, left, top, w, h, seed, **kw): + rng = random.Random(seed) + k = [rng.randrange(1, 9) for _ in range(8)] + chans = { + 0: plane8(w, h, lambda x, y: x * k[0] * 7 + y * k[1]), + 1: plane8(w, h, lambda x, y: y * k[2] * 9 + x * k[3]), + 2: plane8(w, h, lambda x, y: (x ^ y) * k[4] * 5), + -1: plane8(w, h, lambda x, y: 255 if (x + y) % 5 else 90 + (x * k[5] * 13) % 160), + } + return Layer(name, left, top, w, h, chans, **kw) + + +def divider(): + return Layer("", 0, 0, 0, 0, {0: b"", 1: b"", 2: b"", -1: b""}, section=3) + + +def group(name, blend="pass", opacity=255, hidden=False): + return Layer(name, 0, 0, 0, 0, {0: b"", 1: b"", 2: b"", -1: b""}, blend=blend, opacity=opacity, section=1, section_blend=blend, hidden=hidden) + + +def merged_rgb(w, h, alpha=True): + ps = [plane8(w, h, lambda x, y, c=c: x * 5 + y * 3 + c * 70) for c in range(3)] + if alpha: + ps.append(plane8(w, h, lambda x, y: 255 - x)) + return ps + + +def cases(): + W, H = 40, 30 + out = [] + # 1. a full RGB document: groups, pass-through, clipping, masks, fill, hidden, every compression + mask = {"top": 5, "left": 8, "w": 20, "h": 12, "default": 0, "plane": plane8(20, 12, lambda x, y: x * 12)} + layers = [ + rgba_layer("Background", 0, 0, W, H, 1, comp=0), + rgba_layer("Multiply", 5, 4, 20, 15, 2, blend="mul ", opacity=200), + divider(), + rgba_layer("Screen", -3, 10, 25, 25, 3, blend="scrn", comp=2), + rgba_layer("Overlay", 15, 2, 30, 12, 4, blend="over", comp=3), + group("Isolated", blend="norm", opacity=180), + divider(), + rgba_layer("Diff é日", 10, 10, 20, 15, 5, blend="diff"), + rgba_layer("Hidden", 0, 0, 10, 10, 6, hidden=True), + group("Pass"), + rgba_layer("Base", 20, 15, 15, 10, 7), + rgba_layer("Clipped", 15, 12, 20, 14, 8, clip=1, blend="mul "), + rgba_layer("Masked", 2, 2, 30, 20, 9, mask=mask), + rgba_layer("Fill", 25, 0, 15, 30, 10, fill=128, blend="lite"), + ] + out.append(("rgb-layers", psd(W, H, 3, 8, 4, merged_rgb(W, H), layers))) + # 2. every blend mode on its own (two layers) + for key in BLEND: + ls = [rgba_layer("Bottom", 0, 0, 24, 16, 11, comp=0), rgba_layer("Top " + key, 4, 2, 18, 12, 12, blend=key, opacity=230)] + out.append(("blend-" + key.strip(), psd(24, 16, 3, 8, 4, merged_rgb(24, 16), ls))) + # 3. 16-bit RGB with the layers in Lr16, ZIP with prediction + ch16 = lambda s: {0: plane16(12, 9, lambda x, y: x * 5000 + y * 31 + s), 1: plane16(12, 9, lambda x, y: y * 7000 + s), 2: plane16(12, 9, lambda x, y: (x * y * 997) + s), -1: plane16(12, 9, lambda x, y: 65535 - x * 3000)} + l16 = [Layer("L16a", 0, 0, 12, 9, ch16(1), comp=3), Layer("L16b", 3, 2, 12, 9, ch16(77), comp=1, blend="mul ")] + m16 = [plane16(16, 12, lambda x, y, c=c: x * 4000 + y * 100 + c * 9000) for c in range(3)] + [plane16(16, 12, lambda x, y: 65535)] + out.append(("rgb16-lr16", psd(16, 12, 3, 16, 4, m16, l16, lr16=True))) + # 4. 32-bit: merged only (floats) and a layer in Lr32 + m32 = [plane32(10, 7, lambda x, y, c=c: (x + c) / 12.0) for c in range(3)] + l32 = [Layer("F", 1, 1, 6, 5, {0: plane32(6, 5, lambda x, y: x / 6.0), 1: plane32(6, 5, lambda x, y: y / 5.0), 2: plane32(6, 5, lambda x, y: 0.5), -1: plane32(6, 5, lambda x, y: 1.0)}, comp=3)] + out.append(("rgb32", psd(10, 7, 3, 32, 3, m32, l32, lr16=True, comp=0))) + # 5. greyscale with layers, raw merged + gl = [Layer("G1", 0, 0, 20, 10, {0: plane8(20, 10, lambda x, y: x * 12), -1: plane8(20, 10, lambda x, y: 255)}), + Layer("G2", 5, 3, 10, 6, {0: plane8(10, 6, lambda x, y: 200 - y * 20), -1: plane8(10, 6, lambda x, y: 128 + x * 10)}, blend="scrn")] + out.append(("gray", psd(20, 10, 1, 8, 2, [plane8(20, 10, lambda x, y: x * 12 + y), plane8(20, 10, lambda x, y: 255)], gl, comp=0))) + # 6. CMYK, merged + a layer + cm = [plane8(14, 8, lambda x, y, c=c: 255 - (x * 15 + c * 40) % 256) for c in range(4)] + cl = [Layer("C", 2, 1, 8, 5, {0: plane8(8, 5, lambda x, y: 200), 1: plane8(8, 5, lambda x, y: 40 * x), 2: plane8(8, 5, lambda x, y: 255), 3: plane8(8, 5, lambda x, y: 220 + y), -1: plane8(8, 5, lambda x, y: 255)})] + out.append(("cmyk", psd(14, 8, 4, 8, 4, cm, cl))) + # 7. indexed (merged only), 8. bitmap (merged only), 9. Lab + pal = bytes(range(256)) + bytes((i * 3) % 256 for i in range(256)) + bytes(255 - i for i in range(256)) + out.append(("indexed", psd(17, 9, 2, 8, 1, [plane8(17, 9, lambda x, y: x * 15 + y)], palette=pal, comp=1))) + out.append(("bitmap", psd(24, 7, 0, 1, 1, [bytes((x * 37 + y * 11) & 255 for y in range(7) for x in range(3))], comp=0))) + out.append(("lab", psd(9, 5, 9, 8, 3, [plane8(9, 5, lambda x, y: x * 28), plane8(9, 5, lambda x, y: 100 + y * 10), plane8(9, 5, lambda x, y: 150)], comp=1))) + # 10. PSB with layers (8-byte lengths, 4-byte RLE counts) + out.append(("psb", psd(W, H, 3, 8, 4, merged_rgb(W, H), [rgba_layer("A", 0, 0, W, H, 21), rgba_layer("B", 3, 3, 10, 10, 22, blend="mul ")], psb=True))) + # 11. no alpha in the merged image, positive layer count + out.append(("rgb-noalpha", psd(W, H, 3, 8, 3, merged_rgb(W, H, False), [rgba_layer("Only", 0, 0, W, H, 31)], neg=False))) + return out + + +REF = r''' +import json, os, sys, zlib +from psd_tools import PSDImage +d = %r +res = [] +for name in sorted(os.listdir(d)): + if not name.endswith(".psd"): + continue + psd = PSDImage.open(os.path.join(d, name)) + c = {"name": name[:-4], "width": psd.width, "height": psd.height} + try: + im = psd.topil() + c["composite"] = im.convert("RGBA").tobytes().hex() if im is not None else "" + except Exception as e: + c["composite"] = "" + layers = [] + for l in psd.descendants(): + if l.is_group(): + layers.append({"name": l.name, "group": True}) + continue + e = {"name": l.name, "left": l.left, "top": l.top, "width": l.width, "height": l.height} + try: + im = l.topil() + if im is not None: + e["crc"] = zlib.crc32(im.convert("RGBA").tobytes()) + except Exception: + pass + layers.append(e) + c["layers"] = layers + try: + f = psd.composite(force=True, color=0.0, alpha=0.0) + c["flat"] = f.convert("RGBA").tobytes().hex() + except Exception as e: + c["flaterr"] = str(e) + res.append(c) +print(json.dumps(res)) +''' + + +def pyrun(ctx, code): + try: + return ctx.python(["psd-tools", "numpy", "pillow"], code) + except subprocess.CalledProcessError as e: + raise RuntimeError("psd-tools failed:\n" + e.stderr.decode(errors="replace")) + + +def reference(ctx, files): + with tempfile.TemporaryDirectory() as d: + for name, data in files: + open(os.path.join(d, name + ".psd"), "wb").write(data) + res = json.loads(pyrun(ctx, REF % d)) + by = {r["name"]: r for r in res} + out = [] + for name, data in files: + r = by[name] + case = {"name": name, "data": data, "width": r["width"], "height": r["height"], "composite": bytes.fromhex(r["composite"])} + if "flat" in r: + case["flat"] = bytes.fromhex(r["flat"]) + case["layers"] = r["layers"] + out.append(case) + return out + + +def imagemagick(ctx): + # image 0 is the merged image, the rest are layers (ImageMagick 7.1 writes the blend key of some layers byte-reversed + # ("mron"), which psd-tools refuses: these layers avoid it) + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "im.psd") + argv = ["magick", "-size", "32x24", "gradient:red-blue", "(", "-clone", "0", ")", + "(", "-size", "8x8", "radial-gradient:yellow-none", "-repage", "+20+10", ")", p] + try: + subprocess.run(argv, check=True, capture_output=True) + except (OSError, subprocess.CalledProcessError): + ctx.nix("imagemagick", argv) + return open(p, "rb").read() + + +def generate(ctx): + files = cases() + files.append(("imagemagick", imagemagick(ctx))) + ctx.emit("psd", {"cases": reference(ctx, files)}) + ctx.emit("psd_ours", {"checks": ours(ctx)}) + + +def run_ours(ctx, fmt): + """our encoder's output and facts, from tools/fixtures/_ours.luau""" + script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau") + argv = [shutil.which("luau") or "luau", script, "-a", fmt] + if shutil.which("luau"): + out = subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout + else: + out = subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt], check=True, capture_output=True, cwd=ctx.root).stdout + return json.loads(out) + + +OURS = r''' +import json, sys, zlib +from psd_tools import PSDImage +psd = PSDImage.open(%r) +res = {"width": psd.width, "height": psd.height, "composite": zlib.crc32(psd.topil().convert("RGBA").tobytes()), "layers": []} +for l in psd.descendants(): + if l.is_group(): + res["layers"].append({"group": True, "name": l.name, "blend": str(l.blend_mode), "opacity": l.opacity, "visible": l.visible}) + continue + res["layers"].append({"name": l.name, "left": l.left, "top": l.top, "width": l.width, "height": l.height, + "crc": zlib.crc32(l.topil().convert("RGBA").tobytes()), "blend": str(l.blend_mode), "opacity": l.opacity, + "visible": l.visible, "clip": bool(l.clipping_layer), "mask": l.has_mask()}) +print(json.dumps(res)) +''' + +PSD_BLEND = {"normal": "NORMAL", "multiply": "MULTIPLY", "screen": "SCREEN", "difference": "DIFFERENCE", "lighten": "LIGHTEN"} + + +def ours(ctx): + o = run_ours(ctx, "psd") + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "ours.psd") + open(p, "wb").write(bytes.fromhex(o["data"])) + ref = json.loads(pyrun(ctx, OURS % p)) + checks = [] + def check(label, ok): + checks.append({"label": label, "ok": bool(ok)}) + check("psd-tools: composite = our flatten", ref["composite"] == o["composite"]) + leaves = [l for l in ref["layers"] if not l.get("group")] + check("psd-tools: leaf count", len(leaves) == len(o["layers"])) + for want, got in zip(o["layers"], leaves): + n = want["name"] + check(n + ": name", got["name"] == n) + check(n + ": pixels", got["crc"] == want["crc"]) + check(n + ": bounds", (got["left"], got["top"], got["width"], got["height"]) == (want["left"], want["top"], want["width"], want["height"])) + check(n + ": blend", got["blend"].endswith(PSD_BLEND.get(want["blend"], "?"))) + check(n + ": opacity", got["opacity"] == want["opacity"]) + check(n + ": visible", got["visible"] == want["visible"]) + check(n + ": clip", got["clip"] == want["clip"]) + groups = [l for l in ref["layers"] if l.get("group")] + check("psd-tools: two groups", [g["name"] for g in groups] == ["Isolated", "Pass"]) + check("psd-tools: pass-through group", len(groups) == 2 and groups[1]["blend"].endswith("PASS_THROUGH") and groups[0]["blend"].endswith("NORMAL")) + check("psd-tools: masked layer has a mask", any(l.get("mask") for l in leaves if l["name"] == "Masked")) + return checks