From e3e6273799c23c09cbd64a6da7e5b3d3ca855dcd Mon Sep 17 00:00:00 2001 From: 4DBug Date: Mon, 2 Nov 2026 22:48:27 -0600 Subject: [PATCH] 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). --- .../codecs/compress/Deflate/Inflate.luau | 88 ++++++++- src/Rosetta/codecs/compress/Deflate/init.luau | 87 +++++++++ src/Rosetta/image/png/Decode.luau | 178 ++++++++++++++++-- src/Rosetta/image/png/init.luau | 136 ++++++++----- 4 files changed, 422 insertions(+), 67 deletions(-) diff --git a/src/Rosetta/codecs/compress/Deflate/Inflate.luau b/src/Rosetta/codecs/compress/Deflate/Inflate.luau index cd80046..2f99993 100644 --- a/src/Rosetta/codecs/compress/Deflate/Inflate.luau +++ b/src/Rosetta/codecs/compress/Deflate/Inflate.luau @@ -54,7 +54,7 @@ do FDISTS = Huffman.buildLsbMap(d, 0, 30, FDIST, DISTBITS, DMAP) end --- scratch tables for dynamic blocks, shared by every call (raw never yields) +-- scratch tables for dynamic blocks, shared by every call that has no sink (only a sink may yield) local SLIT, SDIST, SCL, SLENS = bcreate(LITCAP * 4), bcreate(DISTCAP * 4), bcreate(CLCAP * 4), bcreate(320) local Inflate = {} @@ -66,7 +66,26 @@ local function grow(out: buffer, op: number, need: number): (buffer, number) return nb, cap end -function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?) +-- streaming: sink(out, from, to) takes the new bytes [from, to) and returns how many bytes before to it has not +-- consumed yet (< 0 aborts); out keeps those and 32 KB of history. feed(pos) slides the input window: it keeps 8 bytes +-- before pos (the bit buffer's) and returns the new pos and endpos. +local function drain(out: buffer, op: number, seen: number, need: number, sink: (buffer, number, number) -> number): (buffer, number) + local pending = sink(out, seen, op) + if pending < 0 then + return out, -1 + end + local from = op - math.max(math.min(pending, op), 32768) + if from > 0 then + bcopy(out, 0, out, from, op - from) + op -= from + end + if op + need > blen(out) then + out = grow(out, op, op + need) + end + return out, op +end + +function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?, sink: ((buffer, number, number) -> number)?, feed: ((number) -> (number, number))?): (buffer?, any, number?) local op = 0 if dict then op = blen(dict) @@ -78,9 +97,12 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex end local pos = start local bitbuf, bitcnt, over = 0, 0, 0 - local lt, dt = SLIT, SDIST - local clt = SCL - local lens = SLENS + local slit, sdist, clt, lens = SLIT, SDIST, SCL, SLENS + if sink then + slit, sdist, clt, lens = bcreate(LITCAP * 4), bcreate(DISTCAP * 4), bcreate(CLCAP * 4), bcreate(320) + end + local lt, dt = slit, sdist + local seen = 0 local final = 0 repeat -- block header (3 bits); also up to 14 bits of a dynamic header @@ -91,6 +113,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex pos += nb bitcnt += nb * 8 else + if feed then + pos, endpos = feed(pos) + end while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) @@ -119,6 +144,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex end pos -= real bitbuf, bitcnt, over = 0, 0, 0 + if feed and pos + 65540 > endpos then + pos, endpos = feed(pos) + end if pos + 4 > endpos then return nil, "truncated input" end @@ -137,7 +165,15 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex end return nil, "output larger than expected" end - out, cap = grow(out, op, op + n) + if sink then + out, op = drain(out, op, seen, n, sink) + if op < 0 then + return nil, "aborted" + end + seen, cap = op, blen(out) + else + out, cap = grow(out, op, op + n) + end end bcopy(out, op, src, pos, n) op += n @@ -149,7 +185,7 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex lt, dt = FLIT, FDIST lsub, dsub = FLITS, FDISTS elseif btype == 2 then - lt, dt = SLIT, SDIST + lt, dt = slit, sdist local hlit = band(bitbuf, 31) + 257 local hdist = band(rshift(bitbuf, 5), 31) + 1 local hclen = band(rshift(bitbuf, 10), 15) + 4 @@ -167,6 +203,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex pos += nb bitcnt += nb * 8 else + if feed then + pos, endpos = feed(pos) + end while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) @@ -198,6 +237,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex pos += nb bitcnt += nb * 8 else + if feed then + pos, endpos = feed(pos) + end while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) @@ -272,6 +314,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex pos += nb bitcnt += nb * 8 else + if feed then + pos, endpos = feed(pos) + end while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) @@ -309,7 +354,15 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex end return nil, "output larger than expected" end - out, cap = grow(out, op, op + 1) + if sink then + out, op = drain(out, op, seen, 1, sink) + if op < 0 then + return nil, "aborted" + end + seen, cap = op, blen(out) + else + out, cap = grow(out, op, op + 1) + end end writeu8(out, op, sym) op += 1 @@ -326,6 +379,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex pos += nb bitcnt += nb * 8 else + if feed then + pos, endpos = feed(pos) + end while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) @@ -372,6 +428,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex pos += nb bitcnt += nb * 8 else + if feed then + pos, endpos = feed(pos) + end while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) @@ -400,7 +459,15 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex end return nil, "output larger than expected" end - out, cap = grow(out, op, op + len) + if sink then + out, op = drain(out, op, seen, len, sink) + if op < 0 then + return nil, "aborted" + end + seen, cap = op, blen(out) + else + out, cap = grow(out, op, op + len) + end end local s = op - dist if dist >= len then @@ -440,6 +507,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex if consumed > endpos then return nil, "truncated input" end + if sink and sink(out, seen, op) < 0 then + return nil, "aborted" + end return out, op, consumed end diff --git a/src/Rosetta/codecs/compress/Deflate/init.luau b/src/Rosetta/codecs/compress/Deflate/init.luau index 7f315e0..94d0120 100644 --- a/src/Rosetta/codecs/compress/Deflate/init.luau +++ b/src/Rosetta/codecs/compress/Deflate/init.luau @@ -97,6 +97,93 @@ function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, ex return out, consumed + 4 end +-- A zlib stream split over byte ranges of buf (PNG IDAT / fdAT payloads), inflated through a window of 32 KB of history +-- plus `window` bytes (default 256 KB): sink(out, from, to) gets each run of new bytes out[from, to) and returns how many +-- bytes before `to` it has not consumed yet (they are handed back before the next run); a negative return aborts. The +-- input is read through a 128 KB window when there is more than one range. Returns the inflated size. +local INWIN = 131072 + +function Deflate.zlibStream(buf: buffer, ranges: { { number } }, sink: (buffer, number, number) -> number, window: number?): (number?, Err.Err?) + if type(buf) ~= "buffer" or type(ranges) ~= "table" or #ranges == 0 or type(sink) ~= "function" then + return nil, Err.new(Err.ARG, "Deflate.zlibStream: expected a buffer, a list of { offset, length } and a sink") + end + local total = 0 + for _, r in ranges do + if type(r[1]) ~= "number" or type(r[2]) ~= "number" or r[1] < 0 or r[2] < 0 or r[1] + r[2] > buffer.len(buf) then + return nil, Err.new(Err.ARG, "Deflate.zlibStream: range out of bounds") + end + total += r[2] + end + if total < 6 then + return nil, Err.new(Err.TRUNCATED, "zlib: truncated header", ranges[1][1]) + end + local src, pos, endpos = buf, ranges[1][1], ranges[1][1] + ranges[1][2] + local feed: ((number) -> (number, number))? = nil + if #ranges > 1 then + local win = buffer.create(INWIN) + local ri, ro, fill = 1, 0, 0 + feed = function(at: number): (number, number) + local keep = math.max(at - 8, 0) + if keep > 0 then + buffer.copy(win, 0, win, keep, fill - keep) + fill -= keep + end + while fill < INWIN and ri <= #ranges do + local r = ranges[ri] + local k = math.min(r[2] - ro, INWIN - fill) + buffer.copy(win, fill, buf, r[1] + ro, k) + fill += k + ro += k + if ro >= r[2] then + ri += 1 + ro = 0 + end + end + return at - keep, fill + end + src = win + pos, endpos = (feed :: any)(0) + end + if endpos - pos < 2 then + return nil, Err.new(Err.TRUNCATED, "zlib: truncated header", ranges[1][1]) + end + local cmf, flg = buffer.readu8(src, pos), buffer.readu8(src, pos + 1) + if cmf % 16 ~= 8 or cmf // 16 > 7 then + return nil, Err.new(Err.CORRUPT, "zlib: not a deflate stream (CMF " .. cmf .. ")", ranges[1][1]) + end + if (cmf * 256 + flg) % 31 ~= 0 then + return nil, Err.new(Err.CORRUPT, "zlib: header check failed", ranges[1][1]) + end + if bit32.band(flg, 0x20) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "zlib: preset dictionaries are not supported", ranges[1][1]) + end + local adler, size = 1, 0 + local function counted(out: buffer, from: number, to: number): number + adler = Adler32.raw(out, from, to - from, adler) + size += to - from + return sink(out, from, to) + end + local out, n, consumed = Inflate.raw(src, pos + 2, endpos, 32768 + (window or 262144), false, false, nil, counted, feed) + if not out then + if n == "aborted" then + return nil, Err.new(Err.CORRUPT, "inflate: aborted by the sink") + end + return nil, inflateErr(tostring(n)) + end + local at = consumed :: number + if feed and at + 4 > endpos then + at, endpos = feed(at) + end + if at + 4 > endpos then + return nil, Err.new(Err.TRUNCATED, "zlib: missing Adler-32") + end + local want = bit32.byteswap(buffer.readu32(src, at)) + if adler ~= want then + return nil, Err.new(Err.CHECKSUM, string.format("zlib: Adler-32 mismatch (%08x, expected %08x)", adler, want)) + end + return size, nil +end + local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?) local flg = buffer.readu8(b, p + 3) if flg >= 0x20 then diff --git a/src/Rosetta/image/png/Decode.luau b/src/Rosetta/image/png/Decode.luau index 59bc272..acd187b 100644 --- a/src/Rosetta/image/png/Decode.luau +++ b/src/Rosetta/image/png/Decode.luau @@ -120,10 +120,10 @@ local function paeth1(raw: buffer, cur: number, e: number, stride: number, pt: b end end -local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number): (boolean, number) +-- top = 0: the first row has no previous row; 1: the row before p is its previous row +local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number, pt: buffer?, top: number): (boolean, number) local stride = rb + 1 - local pt = paethFor(ph * rb) - for r = 0, ph - 1 do + for r = top, top + ph - 1 do local f = readu8(raw, p) local cur = p + 1 local e = cur + rb @@ -333,34 +333,180 @@ local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: num end end -function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): (boolean, string?) +-- the k x k box reduction (k a power of two; edge blocks are smaller): the alpha-weighted mean, colour = +-- round(sum(c * a) / sum(a)) and alpha = round(sum(a) / n), halves up; a fully transparent block is 0, 0, 0, 0. sums +-- holds sum(c * a) and sum(a) per output pixel, or plain sums of r, g, b when the image is opaque (the same result). +local function accumRgba(row: buffer, ro: number, w: number, k: number, sums: { number }, opaque: boolean) + local i = 1 + for x0 = 0, w - 1, k do + local e = ro + (math.min(x0 + k, w) - 1) * 4 + local r, g, b, a = 0, 0, 0, 0 + if opaque then + for q = ro + x0 * 4, e, 4 do + local v = readu32(row, q) + r += band(v, 255) + g += band(rshift(v, 8), 255) + b += band(rshift(v, 16), 255) + end + else + for q = ro + x0 * 4, e, 4 do + local v = readu32(row, q) + local al = rshift(v, 24) + r += band(v, 255) * al + g += band(rshift(v, 8), 255) * al + b += band(rshift(v, 16), 255) * al + a += al + end + end + sums[i] += r + sums[i + 1] += g + sums[i + 2] += b + sums[i + 3] += a + i += 4 + end +end + +-- truecolour without tRNS, straight from the unfiltered row (16-bit samples: the high byte, as convert does) +local function accumRgb(raw: buffer, ro: number, w: number, k: number, sums: { number }, depth: number) + local step = if depth == 16 then 6 else 3 + local go = step // 3 + local bo = go * 2 + local i = 1 + for x0 = 0, w - 1, k do + local r, g, b = 0, 0, 0 + for q = ro + x0 * step, ro + (math.min(x0 + k, w) - 1) * step, step do + r += readu8(raw, q) + g += readu8(raw, q + go) + b += readu8(raw, q + bo) + end + sums[i] += r + sums[i + 1] += g + sums[i + 2] += b + i += 4 + end +end + +local function emit(sums: { number }, out: buffer, oo: number, w: number, k: number, bh: number, opaque: boolean) + local i = 1 + for x0 = 0, w - 1, k do + local n = (math.min(x0 + k, w) - x0) * bh + local r, g, b, a = sums[i], sums[i + 1], sums[i + 2], sums[i + 3] + local v = 0 + if opaque then + local hn = n // 2 + v = (r + hn) // n + (g + hn) // n * 256 + (b + hn) // n * 65536 + 0xFF000000 + elseif a > 0 then + local ha = a // 2 + v = (r + ha) // a + (g + ha) // a * 256 + (b + ha) // a * 65536 + (a + n // 2) // n * 16777216 + end + writeu32(out, oo, v) + oo += 4 + sums[i], sums[i + 1], sums[i + 2], sums[i + 3] = 0, 0, 0, 0 + i += 4 + end +end + +function Decode.opaque(ct: number, tr: number, pal: buffer): boolean + if ct == 4 or ct == 6 then + return false + elseif ct == 3 then + for i = 3, 1023, 4 do + if readu8(pal, i) ~= 255 then + return false + end + end + return true + end + return tr < 0 +end + +function Decode.reduce(src: buffer, w: number, h: number, k: number, out: buffer, opaque: boolean) + local ow = (w + k - 1) // k + local sums = table.create(ow * 4, 0) + for y = 0, h - 1 do + accumRgba(src, y * w * 4, w, k, sums, opaque) + if (y + 1) % k == 0 or y == h - 1 then + emit(sums, out, (y // k) * ow * 4, w, k, y % k + 1, opaque) + end + end +end + +-- a row-streaming decoder of a non-interlaced image for a streaming inflate sink: unfilters each row against the +-- previous one, writes it (k = 1) or box-reduces it into out; hook is called every `every` rows +function Decode.stream(w: number, h: number, depth: number, ct: number, pal: buffer, tr: number, k: number, out: buffer, hook: (() -> ())?, every: number): ((buffer, number, number) -> number, () -> (number, string?)) + local channels = CHANNELS[ct] + local bpp = math.max(1, (channels * depth) // 8) + local rb = Decode.rowBytes(w, channels, depth) + local stride = rb + 1 + local pt = paethFor(h * rb) + local scratch = buffer.create(stride * 2) + local row = buffer.create(if k > 1 then w * 4 else 0) + local ow = (w + k - 1) // k + local sums = table.create(if k > 1 then ow * 4 else 0, 0) + local opaque = Decode.opaque(ct, tr, pal) + local direct = ct == 2 and tr < 0 + local y, pending = 0, 0 + local err: string? = nil + local function sink(win: buffer, from: number, to: number): number + local p = from - pending + while y < h and to - p >= stride do + bcopy(scratch, stride, win, p, stride) + local ok, f = unfilter(scratch, stride, 1, rb, bpp, pt, if y == 0 then 0 else 1) + if not ok then + err = "bad filter type " .. f + return -1 + end + if k == 1 then + convert(scratch, stride + 1, w, out, y * w * 4, 4, ct, depth, pal, tr) + else + if direct then + accumRgb(scratch, stride + 1, w, k, sums, depth) + else + convert(scratch, stride + 1, w, row, 0, 4, ct, depth, pal, tr) + accumRgba(row, 0, w, k, sums, opaque) + end + if (y + 1) % k == 0 or y == h - 1 then + emit(sums, out, (y // k) * ow * 4, w, k, y % k + 1, opaque) + end + end + bcopy(scratch, 0, scratch, stride, stride) + y += 1 + p += stride + if hook and y % every == 0 then + pcall(hook) + end + end + pending = if y < h then to - p else 0 + return pending + end + return sink, function(): (number, string?) + return y, err + end +end + +-- Adam7 (the whole inflated stream in raw) +function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, pal: buffer, tr: number, out: buffer, hook: (() -> ())?, every: number): (boolean, string?) local channels = CHANNELS[ct] local bpp = math.max(1, (channels * depth) // 8) local p = 0 - if interlace == 0 then - local rb = Decode.rowBytes(w, channels, depth) - local ok, f = unfilter(raw, 0, h, rb, bpp) - if not ok then - return false, "bad filter type " .. f - end - for y = 0, h - 1 do - convert(raw, y * (rb + 1) + 1, w, out, y * w * 4, 4, ct, depth, pal, tr) - end - return true, nil - end + local rows = 0 for _, pass in 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 h > y0 then (h - y0 + dy - 1) // dy else 0 if pw > 0 and ph > 0 then local rb = Decode.rowBytes(pw, channels, depth) - local ok, f = unfilter(raw, p, ph, rb, bpp) + local ok, f = unfilter(raw, p, ph, rb, bpp, paethFor(ph * rb), 0) if not ok then return false, "bad filter type " .. f end for r = 0, ph - 1 do local y = y0 + r * dy convert(raw, p + r * (rb + 1) + 1, pw, out, (y * w + x0) * 4, dx * 4, ct, depth, pal, tr) + rows += 1 + if hook and rows % every == 0 then + pcall(hook) + end end p += ph * (rb + 1) end diff --git a/src/Rosetta/image/png/init.luau b/src/Rosetta/image/png/init.luau index aa33e33..388e0e6 100644 --- a/src/Rosetta/image/png/init.luau +++ b/src/Rosetta/image/png/init.luau @@ -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