png: row-streaming decode through a streaming inflate (no whole inflated buffer, no IDAT concatenation); opts.maxSide / reduce (power-of-two box reduction), opts.yield / yieldRows

codecs/compress/Deflate: Inflate.raw takes an optional sink (output window: 32 KB history + a chunk) and feed (input
window over split ranges); Deflate.zlibStream(buf, ranges, sink, window?). The existing entry points are unchanged
(bench: no regression under luau -O2 or LuaJIT).
This commit is contained in:
4DBug committed 2026-11-02 22:48:27 -06:00
1 parent 89b363af78
commit e3e6273799
4 files changed
+422 -67

No files matched your search

+94 -42
View File
@@ -26,7 +26,11 @@ local Png = {
export type DecodeOptions = {
checkCrc: boolean?, -- default false
maxPixels: number?, -- default 2^26
maxPixels: number?, -- default 2^26, of the source image
maxSide: number?, -- output sides at most this: the smallest power-of-two box reduction that fits
reduce: number?, -- box reduction factor, a power of two (default 1)
yield: (() -> ())?, -- pcall'ed every yieldRows rows (default 16) and per inflate window when interlaced
yieldRows: number?,
}
export type EncodeOptions = {
level: number?, -- 0..9, default 6
@@ -107,50 +111,95 @@ type FrameControl = {
}
local DISPOSE: { [number]: "none" | "background" | "previous" } = { [0] = "none", [1] = "background", [2] = "previous" }
local function pixels(b: buffer, chunks: { { number } }, total: number, w: number, ht: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): Err.Err?
-- the inflated size: every (pass) row has a filter byte
type Reduce = { k: number, hook: (() -> ())?, every: number }
local function pixels(b: buffer, chunks: { { number } }, w: number, ht: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer, rd: Reduce): Err.Err?
local k = rd.k
local channels = Decode.CHANNELS[ct]
local expected = 0
if interlace == 0 then
expected = ht * (Decode.rowBytes(w, channels, depth) + 1)
else
for _, pass in Decode.PASSES do
local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4]
local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0
local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0
if pw > 0 and ph > 0 then
expected += ph * (Decode.rowBytes(pw, channels, depth) + 1)
end
local window = math.min(262144, ht * (Decode.rowBytes(w, channels, depth) + 1))
local sink, status = Decode.stream(w, ht, depth, ct, pal, tr, k, out, rd.hook, rd.every)
local _, zerr = Deflate.zlibStream(b, chunks, sink, window)
local y, derr = status()
if derr then
return Err.new(Err.CORRUPT, derr)
elseif zerr then
return zerr
elseif y < ht then
return Err.new(Err.CORRUPT, string.format("image data ends after %d of %d rows", y, ht))
end
return nil
end
-- Adam7: the whole inflated stream (every pass row has a filter byte), then the full image when reducing
local expected = 0
for _, pass in Decode.PASSES do
local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4]
local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0
local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0
if pw > 0 and ph > 0 then
expected += ph * (Decode.rowBytes(pw, channels, depth) + 1)
end
end
local z: buffer
if #chunks == 1 then
z = b
else
z = buffer.create(total)
local w0 = 0
for _, c in chunks do
buffer.copy(z, w0, b, c[1], c[2])
w0 += c[2]
local raw = buffer.create(expected)
local got = 0
local hook = rd.hook
local _, zerr = Deflate.zlibStream(b, chunks, function(win: buffer, from: number, to: number): number
local n = math.min(to - from, expected - got)
if n > 0 then
buffer.copy(raw, got, win, from, n)
got += n
end
end
local zo = if #chunks == 1 then chunks[1][1] else 0
local raw, zerr = Deflate.zlib(z, zo, total, expected)
if not raw then
-- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows
local loose = Deflate.zlib(z, zo, total)
if not loose or buffer.len(loose) < expected then
return zerr or Err.new(Err.CORRUPT, "bad image data")
if hook then
pcall(hook)
end
raw = loose
return 0
end, math.min(262144, expected))
if zerr then
return zerr
elseif got < expected then
return Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", got, expected))
end
local ok, derr = Decode.run(raw :: buffer, w, ht, depth, ct, interlace, pal, tr, out)
local full = if k > 1 then buffer.create(w * ht * 4) else out
local ok, derr = Decode.run(raw, w, ht, depth, ct, pal, tr, full, hook, rd.every)
if not ok then
return Err.new(Err.CORRUPT, tostring(derr))
end
if k > 1 then
Decode.reduce(full, w, ht, k, out, Decode.opaque(ct, tr, pal))
end
return nil
end
local function reduction(w: number, ht: number, opts: DecodeOptions?): (Reduce?, Err.Err?)
local o: any = opts or {}
local k = 1
if o.reduce ~= nil then
local r = o.reduce
if type(r) ~= "number" or r < 1 or r > 2 ^ 31 or r % 1 ~= 0 or bit32.band(r, r - 1) ~= 0 then
return nil, Err.new(Err.ARG, "reduce must be a power of two")
end
k = r
end
if o.maxSide ~= nil then
local m = o.maxSide
if type(m) ~= "number" or not (m >= 1) then
return nil, Err.new(Err.ARG, "maxSide must be at least 1")
end
while (w + k - 1) // k > m or (ht + k - 1) // k > m do
k *= 2
end
end
local hook = o.yield
if hook ~= nil and type(hook) ~= "function" then
return nil, Err.new(Err.ARG, "yield must be a function")
end
local every = o.yieldRows or 16
if type(every) ~= "number" or not (every >= 1) or every % 1 ~= 0 then
return nil, Err.new(Err.ARG, "yieldRows must be a positive integer")
end
return { k = k, hook = hook, every = every }, nil
end
function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local checkCrc = opts and opts.checkCrc or false
local maxPixels = opts and opts.maxPixels or 2 ^ 26
@@ -162,6 +211,11 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if w * ht > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels))
end
local rd, rerr = reduction(w, ht, opts)
if not rd then
return nil, rerr
end
local k = rd.k
local b, n = r.buf, r.limit
local pal = buffer.create(1024)
for i = 0, 255 do
@@ -170,7 +224,6 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
local palCount = 0
local tr = -1
local idat: { { number } } = {}
local idatLen = 0
local text: { [string]: string } = {}
local iccCompressed: buffer? = nil
-- APNG: acTL, then fcTL (+ IDAT for frame 1 when it is the default image) / fdAT, one sequence counter
@@ -224,7 +277,6 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
end
elseif typ == "IDAT" then
table.insert(idat, { d, len })
idatLen += len
if #fctls == 1 and #idat == 1 then
idatInAnim = true
end
@@ -302,8 +354,8 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if ct == 3 and palCount == 0 then
return nil, Err.new(Err.CORRUPT, "palette image without PLTE")
end
local img = Types.Image.new(w, ht, "rgba8")
local ierr = pixels(b, idat, idatLen, w, ht, h.bitDepth, ct, h.interlace, pal, tr, img.pixels)
local img = Types.Image.new((w + k - 1) // k, (ht + k - 1) // k, "rgba8")
local ierr = pixels(b, idat, w, ht, h.bitDepth, ct, h.interlace, pal, tr, img.pixels, rd)
if ierr then
return nil, ierr
end
@@ -316,14 +368,14 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
for i, f in fctls do
local fimg: Types.Image
if i == 1 and idatInAnim then
fimg = Types.Image.new(w, ht, "rgba8")
fimg = Types.Image.new(img.width, img.height, "rgba8")
buffer.copy(fimg.pixels, 0, img.pixels)
else
if #f.chunks == 0 then
return nil, Err.new(Err.CORRUPT, "APNG frame " .. i .. " has no data")
end
fimg = Types.Image.new(f.width, f.height, "rgba8")
local ferr = pixels(b, f.chunks, f.len, f.width, f.height, h.bitDepth, ct, h.interlace, pal, tr, fimg.pixels)
fimg = Types.Image.new((f.width + k - 1) // k, (f.height + k - 1) // k, "rgba8")
local ferr = pixels(b, f.chunks, f.width, f.height, h.bitDepth, ct, h.interlace, pal, tr, fimg.pixels, rd)
if ferr then
ferr.message = "frame " .. i .. ": " .. ferr.message
return nil, ferr
@@ -332,8 +384,8 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
frames[i] = {
image = fimg,
delay = f.num / (if f.den == 0 then 100 else f.den),
x = f.x,
y = f.y,
x = f.x // k,
y = f.y // k,
dispose = DISPOSE[f.dispose] :: any,
blend = if f.blend == 1 then "over" :: "over" else "source" :: "source",
}
@@ -353,7 +405,7 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
img.meta.text = text
end
img.meta.iccCompressed = iccCompressed
img.meta.source = { format = "png", bitDepth = depth, colorType = COLOR_NAMES[ct], interlace = h.interlace }
img.meta.source = { format = "png", bitDepth = depth, colorType = COLOR_NAMES[ct], interlace = h.interlace, width = w, height = ht, reduce = k }
return img, nil
end