merge ws/downscale

This commit is contained in:
4DBug committed 2026-11-02 23:41:47 -06:00
commit f1d98ec904
24 files changed
+3432 -1340

No files matched your search

@@ -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,16 @@ 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 = op
cap = blen(out)
else
out, cap = grow(out, op, op + n)
end
end
bcopy(out, op, src, pos, n)
op += n
@@ -149,7 +186,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 +204,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 +238,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 +315,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 +355,16 @@ 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 = op
cap = blen(out)
else
out, cap = grow(out, op, op + 1)
end
end
writeu8(out, op, sym)
op += 1
@@ -326,6 +381,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 +430,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 +461,16 @@ 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 = op
cap = blen(out)
else
out, cap = grow(out, op, op + len)
end
end
local s = op - dist
if dist >= len then
@@ -440,6 +510,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
@@ -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
+1 -1
View File
@@ -510,7 +510,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
clean = buffer.create(n - base + Scan.PAD)
end
local cb = clean :: buffer
local nextPos, cleanLen, nrst = Scan.destuff(b, pos, n, cb, rst)
local nextPos, cleanLen, nrst = Scan.destuff(b, pos, n, cb, rst, st.hook)
if nextPos >= n then
st.truncated = true -- no EOI
end
+34 -26
View File
@@ -100,37 +100,45 @@ function Scan.buildTable(counts: { number }, symbols: { number }): buffer
return t
end
function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }): (number, number, number)
function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }, hook: (() -> ())?): (number, number, number)
local o, nr = 0, 0
while pos < n do
local b = readu8(src, pos)
if b ~= 0xFF then
writeu8(dst, o, b)
o += 1
pos += 1
else
local q = pos + 1
while q < n and readu8(src, q) == 0xFF do
q += 1
end
if q >= n then
pos = n
break
end
local m = readu8(src, q)
if m == 0 then
writeu8(dst, o, 0xFF)
local done = false
while not done and pos < n do
local lim = if hook then math.min(n, pos + 65536) else n
while pos < lim do
local b = readu8(src, pos)
if b ~= 0xFF then
writeu8(dst, o, b)
o += 1
pos = q + 1
elseif m >= 0xD0 and m <= 0xD7 then
nr += 1
rst[nr] = o
pos = q + 1
pos += 1
else
pos = q - 1
break
local q = pos + 1
while q < n and readu8(src, q) == 0xFF do
q += 1
end
if q >= n then
pos = n
break
end
local m = readu8(src, q)
if m == 0 then
writeu8(dst, o, 0xFF)
o += 1
pos = q + 1
elseif m >= 0xD0 and m <= 0xD7 then
nr += 1
rst[nr] = o
pos = q + 1
else
pos = q - 1
done = true
break
end
end
end
if hook and not done and pos < n then
pcall(hook)
end
end
buffer.fill(dst, o, 0, Scan.PAD)
return pos, o, nr
+24 -1
View File
@@ -22,9 +22,11 @@ local Jpeg = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
scale: number?, -- 1 (default), 2, 4 or 8
maxSide: number?, -- the smallest scale (up to 8) whose output sides are at most this
orient: boolean?, -- default false
native: boolean?, -- default false
maxPixels: number?, -- default 2^26
yield: (() -> ())?, -- pcall'ed every MCU row of each Huffman scan, every block row of the IDCT, every 8 output rows
}
export type EncodeOptions = {
quality: number?, -- 1..100, default 90 (libjpeg scaling of the T.81 annex K tables)
@@ -55,12 +57,33 @@ function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.
return nil, Err.new(Err.ARG, "options must be a table")
end
local o = opts or {} :: DecodeOptions
local scale = o.scale
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
local info, ierr = Codec.info(r.buf, r.base, r.limit - r.base)
if not info then
return nil, ierr
end
-- the output side at scale s is ceil(side / s) (libjpeg-turbo jdmaster.c)
local s = if type(scale) == "number" then scale else 1
while s < 8 and ((info.width + s - 1) // s > m or (info.height + s - 1) // s > m) do
s *= 2
end
scale = s
end
if o.yield ~= nil and type(o.yield) ~= "function" then
return nil, Err.new(Err.ARG, "yield must be a function")
end
-- two JPEGs back to back are an image and a preview, as in MPF
return Codec.decode(r.buf, r.base, r.limit - r.base, {
scale = o.scale,
scale = scale,
orient = o.orient,
native = o.native,
maxPixels = o.maxPixels,
yield = o.yield,
fields = false,
})
end
+188 -16
View File
@@ -102,6 +102,30 @@ local function paeth3(raw: buffer, cur: number, e: number, stride: number, pt: b
end
end
-- 16-bit RGB: two three-byte lanes carried as in paeth3
local function paeth6(raw: buffer, cur: number, e: number, stride: number, pt: buffer)
local a0, a1, a2, a3, a4, a5 = readu8(raw, cur), readu8(raw, cur + 1), readu8(raw, cur + 2), readu8(raw, cur + 3), readu8(raw, cur + 4), readu8(raw, cur + 5)
local u = cur - stride
local c0, c1, c2, c3, c4, c5 = readu8(raw, u), readu8(raw, u + 1), readu8(raw, u + 2), readu8(raw, u + 3), readu8(raw, u + 4), readu8(raw, u + 5)
for i = cur + 6, e - 6, 6 do
local j = i - stride
local b0, b1, b2, b3, b4, b5 = readu8(raw, j), readu8(raw, j + 1), readu8(raw, j + 2), readu8(raw, j + 3), readu8(raw, j + 4), readu8(raw, j + 5)
a0 = (readu8(raw, i) + c0 + readi16(pt, (a0 * 511 + b0 - c0 * 512) * 2 + 261120)) % 256
a1 = (readu8(raw, i + 1) + c1 + readi16(pt, (a1 * 511 + b1 - c1 * 512) * 2 + 261120)) % 256
a2 = (readu8(raw, i + 2) + c2 + readi16(pt, (a2 * 511 + b2 - c2 * 512) * 2 + 261120)) % 256
a3 = (readu8(raw, i + 3) + c3 + readi16(pt, (a3 * 511 + b3 - c3 * 512) * 2 + 261120)) % 256
a4 = (readu8(raw, i + 4) + c4 + readi16(pt, (a4 * 511 + b4 - c4 * 512) * 2 + 261120)) % 256
a5 = (readu8(raw, i + 5) + c5 + readi16(pt, (a5 * 511 + b5 - c5 * 512) * 2 + 261120)) % 256
writeu8(raw, i, a0)
writeu8(raw, i + 1, a1)
writeu8(raw, i + 2, a2)
writeu8(raw, i + 3, a3)
writeu8(raw, i + 4, a4)
writeu8(raw, i + 5, a5)
c0, c1, c2, c3, c4, c5 = b0, b1, b2, b3, b4, b5
end
end
-- any bpp: the left byte is the one written bpp bytes earlier
local function paethN(raw: buffer, cur: number, e: number, stride: number, bpp: number, pt: buffer)
for i = cur + bpp, e - 1 do
@@ -120,10 +144,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
@@ -213,6 +237,8 @@ local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: num
paeth4(raw, cur, e, stride, pt)
elseif bpp == 3 then
paeth3(raw, cur, e, stride, pt)
elseif bpp == 6 then
paeth6(raw, cur, e, stride, pt)
elseif bpp == 1 then
paeth1(raw, cur, e, stride, pt)
else
@@ -333,34 +359,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
+99 -44
View File
@@ -1,7 +1,8 @@
--!strict
-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.) and APNG 1.0; from png-luau 1.0.0 (same author). Supports: every
-- colour type and bit depth, tRNS, Adam7, tEXt, acTL / fcTL / fdAT; writes RGBA / RGB / grey(+alpha) and APNG. Not
-- supported: colour management (iCCP kept raw), palette / 16-bit / interlaced output.
-- colour type and bit depth, tRNS, Adam7, tEXt, acTL / fcTL / fdAT, row-streaming decode with power-of-two box
-- reduction; writes RGBA / RGB / grey(+alpha) and APNG. Not supported: colour management (iCCP kept raw), palette /
-- 16-bit / interlaced output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -26,7 +27,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, and per 64 KB inflated when interlaced
yieldRows: number?, -- default: about 64 KB of row data
}
export type EncodeOptions = {
level: number?, -- 0..9, default 6
@@ -107,50 +112,97 @@ 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 stride = Decode.rowBytes(w, channels, depth) + 1
local window = math.min(if rd.hook then 65536 else 262144, ht * stride)
local every = if rd.every > 0 then rd.every else math.max(1, 65536 // stride)
local sink, status = Decode.stream(w, ht, depth, ct, pal, tr, k, out, rd.hook, 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(if hook then 65536 else 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, if rd.every > 0 then rd.every else math.max(1, 65536 // (w * 4)))
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 0
if type(every) ~= "number" or not (every >= 0) 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 +214,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 +227,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 +280,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 +357,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 +371,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 +387,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 +408,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
+1 -1
View File
@@ -853,7 +853,7 @@ F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: E
data = resolve(tex.uri)
end
if data ~= nil then
local img, err = F.load(data, { category = "image", name = tex.uri, data = true })
local img, err = F.load(data, { category = "image", name = tex.uri, data = true, maxSide = opts and opts.maxSide, yield = opts and opts.yield, yieldRows = opts and opts.yieldRows, maxPixels = opts and opts.maxPixels })
if img then
tex.image = img
elseif err then