merge ws/imgA: jpeg gif tiff tga qoi pnm ico hdr, codecs Dct/Lzw/Quantize, ops/ImageOps, api image hooks
This commit is contained in:
commit
ca262e19df
55 files changed
+13401
-2
No files matched your search
@@ -26,6 +26,54 @@ local list: { Entry } = {
|
||||
return require("@formats/image/bmp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "gif",
|
||||
category = "image",
|
||||
path = "image/gif",
|
||||
extensions = { "gif" },
|
||||
mime = { "image/gif" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/Lzw", "codecs/Quantize", "Types" },
|
||||
caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } },
|
||||
load = function()
|
||||
return require("@formats/image/gif")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "hdr",
|
||||
category = "image",
|
||||
path = "image/hdr",
|
||||
extensions = { "hdr", "pic", "rgbe" },
|
||||
mime = { "image/vnd.radiance", "image/x-hdr" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } },
|
||||
load = function()
|
||||
return require("@formats/image/hdr")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ico",
|
||||
category = "image",
|
||||
path = "image/ico",
|
||||
extensions = { "ico", "cur" },
|
||||
mime = { "image/vnd.microsoft.icon", "image/x-icon" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } },
|
||||
load = function()
|
||||
return require("@formats/image/ico")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "jpeg",
|
||||
category = "image",
|
||||
path = "image/jpeg",
|
||||
extensions = { "jpg", "jpeg", "jpe", "jfif" },
|
||||
mime = { "image/jpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" },
|
||||
caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
|
||||
load = function()
|
||||
return require("@formats/image/jpeg")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "png",
|
||||
category = "image",
|
||||
@@ -38,6 +86,54 @@ local list: { Entry } = {
|
||||
return require("@formats/image/png")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "pnm",
|
||||
category = "image",
|
||||
path = "image/pnm",
|
||||
extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" },
|
||||
mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true },
|
||||
load = function()
|
||||
return require("@formats/image/pnm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "qoi",
|
||||
category = "image",
|
||||
path = "image/qoi",
|
||||
extensions = { "qoi" },
|
||||
mime = { "image/qoi", "image/x-qoi" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, depths = { 8 } },
|
||||
load = function()
|
||||
return require("@formats/image/qoi")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "tga",
|
||||
category = "image",
|
||||
path = "image/tga",
|
||||
extensions = { "tga", "icb", "vda", "vst", "tpic" },
|
||||
mime = { "image/x-tga", "image/x-targa" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } },
|
||||
load = function()
|
||||
return require("@formats/image/tga")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "tiff",
|
||||
category = "image",
|
||||
path = "image/tiff",
|
||||
extensions = { "tif", "tiff" },
|
||||
mime = { "image/tiff" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "codecs/Lzw" },
|
||||
caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true },
|
||||
load = function()
|
||||
return require("@formats/image/tiff")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "flac",
|
||||
category = "audio",
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
|
||||
-- Inverse: libjpeg's islow (jidctint.c: the Loeffler-Ligtenberg-Moschytz algorithm, 13-bit constants, two passes with
|
||||
-- PASS1_BITS of scaling between them), plus the reduced 4x4 / 2x2 / 1x1 IDCTs for scaled decodes (jidctred.c); the
|
||||
-- results match libjpeg-turbo's djpeg bit for bit. Absorbed from jpeg-luau 1.0 src/Jpeg/Idct.luau (same author).
|
||||
-- Forward: libjpeg's islow (jfdctint.c) with jcdctmgr.c's rounding quantiser, so an encoder built on it produces
|
||||
-- the same coefficients as cjpeg. Both are Luau translations of IJG code (licenses/libjpeg-turbo-LICENSE.md).
|
||||
-- Values are exact integers in doubles: no overflow even on corrupt coefficients; outputs are clamped to 0..maxv.
|
||||
--
|
||||
-- Dct.idctComponent(coef, q, bpl, bpc, size, plane, p1, center, maxv) -- every block of a component
|
||||
-- Dct.idctBlock(coef, off, q, plane, out, stride, p1, center, maxv) -- one 8x8 block (u16 samples)
|
||||
-- Dct.fdctQuantize(src, stride, x, y, w, h, div, coef, off) -- one block from u8 samples
|
||||
local readi16, readu16, writeu16, readu8, writei16 = buffer.readi16, buffer.readu16, buffer.writeu16, buffer.readu8, buffer.writei16
|
||||
local clamp = math.clamp
|
||||
|
||||
local Dct = {}
|
||||
|
||||
local ws = table.create(64, 0)
|
||||
|
||||
local function idct8(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number)
|
||||
local s1 = 2 ^ (13 - p1)
|
||||
local h1 = s1 / 2
|
||||
local s2 = 2 ^ (16 + p1)
|
||||
local h2 = s2 / 2 + center * s2
|
||||
local dcm = 2 ^ p1
|
||||
for c = 0, 7 do
|
||||
local o = off + c * 2
|
||||
local qo = c * 2
|
||||
local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48)
|
||||
local c4, c5, c6, c7 = readi16(coef, o + 64), readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112)
|
||||
if c1 == 0 and c2 == 0 and c3 == 0 and c4 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then
|
||||
local dc = readi16(coef, o) * readu16(q, qo) * dcm
|
||||
ws[c + 1] = dc
|
||||
ws[c + 9] = dc
|
||||
ws[c + 17] = dc
|
||||
ws[c + 25] = dc
|
||||
ws[c + 33] = dc
|
||||
ws[c + 41] = dc
|
||||
ws[c + 49] = dc
|
||||
ws[c + 57] = dc
|
||||
else
|
||||
-- even part
|
||||
local z2 = c2 * readu16(q, qo + 32)
|
||||
local z3 = c6 * readu16(q, qo + 96)
|
||||
local z1 = (z2 + z3) * 4433
|
||||
local tmp2 = z1 - z3 * 15137
|
||||
local tmp3 = z1 + z2 * 6270
|
||||
z2 = readi16(coef, o) * readu16(q, qo)
|
||||
z3 = c4 * readu16(q, qo + 64)
|
||||
local tmp0 = (z2 + z3) * 8192
|
||||
local tmp1 = (z2 - z3) * 8192
|
||||
local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3
|
||||
local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2
|
||||
-- odd part
|
||||
local t0 = c7 * readu16(q, qo + 112)
|
||||
local t1 = c5 * readu16(q, qo + 80)
|
||||
local t2 = c3 * readu16(q, qo + 48)
|
||||
local t3 = c1 * readu16(q, qo + 16)
|
||||
z1 = t0 + t3
|
||||
z2 = t1 + t2
|
||||
z3 = t0 + t2
|
||||
local z4 = t1 + t3
|
||||
local z5 = (z3 + z4) * 9633
|
||||
t0 *= 2446
|
||||
t1 *= 16819
|
||||
t2 *= 25172
|
||||
t3 *= 12299
|
||||
z1 *= -7373
|
||||
z2 *= -20995
|
||||
z3 = z3 * -16069 + z5
|
||||
z4 = z4 * -3196 + z5
|
||||
t0 += z1 + z3
|
||||
t1 += z2 + z4
|
||||
t2 += z2 + z3
|
||||
t3 += z1 + z4
|
||||
ws[c + 1] = (tmp10 + t3 + h1) // s1
|
||||
ws[c + 57] = (tmp10 - t3 + h1) // s1
|
||||
ws[c + 9] = (tmp11 + t2 + h1) // s1
|
||||
ws[c + 49] = (tmp11 - t2 + h1) // s1
|
||||
ws[c + 17] = (tmp12 + t1 + h1) // s1
|
||||
ws[c + 41] = (tmp12 - t1 + h1) // s1
|
||||
ws[c + 25] = (tmp13 + t0 + h1) // s1
|
||||
ws[c + 33] = (tmp13 - t0 + h1) // s1
|
||||
end
|
||||
end
|
||||
local sd = 2 ^ (p1 + 3)
|
||||
local hd = sd / 2 + center * sd
|
||||
for r = 0, 7 do
|
||||
local b = r * 8
|
||||
local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4]
|
||||
local w4, w5, w6, w7 = ws[b + 5], ws[b + 6], ws[b + 7], ws[b + 8]
|
||||
local o = (out + r * stride) * 2
|
||||
if w1 == 0 and w2 == 0 and w3 == 0 and w4 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then
|
||||
local v = clamp((w0 + hd) // sd, 0, maxv)
|
||||
for i = 0, 14, 2 do
|
||||
writeu16(plane, o + i, v)
|
||||
end
|
||||
else
|
||||
local z1 = (w2 + w6) * 4433
|
||||
local tmp2 = z1 - w6 * 15137
|
||||
local tmp3 = z1 + w2 * 6270
|
||||
local tmp0 = (w0 + w4) * 8192
|
||||
local tmp1 = (w0 - w4) * 8192
|
||||
local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3
|
||||
local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2
|
||||
local t0, t1, t2, t3 = w7, w5, w3, w1
|
||||
z1 = t0 + t3
|
||||
local z2 = t1 + t2
|
||||
local z3 = t0 + t2
|
||||
local z4 = t1 + t3
|
||||
local z5 = (z3 + z4) * 9633
|
||||
t0 *= 2446
|
||||
t1 *= 16819
|
||||
t2 *= 25172
|
||||
t3 *= 12299
|
||||
z1 *= -7373
|
||||
z2 *= -20995
|
||||
z3 = z3 * -16069 + z5
|
||||
z4 = z4 * -3196 + z5
|
||||
t0 += z1 + z3
|
||||
t1 += z2 + z4
|
||||
t2 += z2 + z3
|
||||
t3 += z1 + z4
|
||||
writeu16(plane, o, clamp((tmp10 + t3 + h2) // s2, 0, maxv))
|
||||
writeu16(plane, o + 14, clamp((tmp10 - t3 + h2) // s2, 0, maxv))
|
||||
writeu16(plane, o + 2, clamp((tmp11 + t2 + h2) // s2, 0, maxv))
|
||||
writeu16(plane, o + 12, clamp((tmp11 - t2 + h2) // s2, 0, maxv))
|
||||
writeu16(plane, o + 4, clamp((tmp12 + t1 + h2) // s2, 0, maxv))
|
||||
writeu16(plane, o + 10, clamp((tmp12 - t1 + h2) // s2, 0, maxv))
|
||||
writeu16(plane, o + 6, clamp((tmp13 + t0 + h2) // s2, 0, maxv))
|
||||
writeu16(plane, o + 8, clamp((tmp13 - t0 + h2) // s2, 0, maxv))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function idct4(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number)
|
||||
local s1 = 2 ^ (14 - p1)
|
||||
local h1 = s1 / 2
|
||||
local dcm = 2 ^ p1
|
||||
for c = 0, 7 do
|
||||
if c ~= 4 then
|
||||
local o = off + c * 2
|
||||
local qo = c * 2
|
||||
local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48)
|
||||
local c5, c6, c7 = readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112)
|
||||
if c1 == 0 and c2 == 0 and c3 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then
|
||||
local dc = readi16(coef, o) * readu16(q, qo) * dcm
|
||||
ws[c + 1] = dc
|
||||
ws[c + 9] = dc
|
||||
ws[c + 17] = dc
|
||||
ws[c + 25] = dc
|
||||
else
|
||||
local tmp0 = readi16(coef, o) * readu16(q, qo) * 16384
|
||||
local tmp2 = c2 * readu16(q, qo + 32) * 15137 - c6 * readu16(q, qo + 96) * 6270
|
||||
local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2
|
||||
local z1 = c7 * readu16(q, qo + 112)
|
||||
local z2 = c5 * readu16(q, qo + 80)
|
||||
local z3 = c3 * readu16(q, qo + 48)
|
||||
local z4 = c1 * readu16(q, qo + 16)
|
||||
tmp0 = z1 * -1730 + z2 * 11893 + z3 * -17799 + z4 * 8697
|
||||
tmp2 = z1 * -4176 + z2 * -4926 + z3 * 7373 + z4 * 20995
|
||||
ws[c + 1] = (tmp10 + tmp2 + h1) // s1
|
||||
ws[c + 25] = (tmp10 - tmp2 + h1) // s1
|
||||
ws[c + 9] = (tmp12 + tmp0 + h1) // s1
|
||||
ws[c + 17] = (tmp12 - tmp0 + h1) // s1
|
||||
end
|
||||
end
|
||||
end
|
||||
local s2 = 2 ^ (17 + p1)
|
||||
local h2 = s2 / 2 + center * s2
|
||||
local sd = 2 ^ (p1 + 3)
|
||||
local hd = sd / 2 + center * sd
|
||||
for r = 0, 3 do
|
||||
local b = r * 8
|
||||
local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4]
|
||||
local w5, w6, w7 = ws[b + 6], ws[b + 7], ws[b + 8]
|
||||
local o = (out + r * stride) * 2
|
||||
if w1 == 0 and w2 == 0 and w3 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then
|
||||
local v = clamp((w0 + hd) // sd, 0, maxv)
|
||||
writeu16(plane, o, v)
|
||||
writeu16(plane, o + 2, v)
|
||||
writeu16(plane, o + 4, v)
|
||||
writeu16(plane, o + 6, v)
|
||||
else
|
||||
local tmp0 = w0 * 16384
|
||||
local tmp2 = w2 * 15137 - w6 * 6270
|
||||
local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2
|
||||
tmp0 = w7 * -1730 + w5 * 11893 + w3 * -17799 + w1 * 8697
|
||||
tmp2 = w7 * -4176 + w5 * -4926 + w3 * 7373 + w1 * 20995
|
||||
writeu16(plane, o, clamp((tmp10 + tmp2 + h2) // s2, 0, maxv))
|
||||
writeu16(plane, o + 6, clamp((tmp10 - tmp2 + h2) // s2, 0, maxv))
|
||||
writeu16(plane, o + 2, clamp((tmp12 + tmp0 + h2) // s2, 0, maxv))
|
||||
writeu16(plane, o + 4, clamp((tmp12 - tmp0 + h2) // s2, 0, maxv))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function idct2(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number)
|
||||
local s1 = 2 ^ (15 - p1)
|
||||
local h1 = s1 / 2
|
||||
local dcm = 2 ^ p1
|
||||
for c = 0, 7 do
|
||||
if c ~= 2 and c ~= 4 and c ~= 6 then
|
||||
local o = off + c * 2
|
||||
local qo = c * 2
|
||||
local c1, c3 = readi16(coef, o + 16), readi16(coef, o + 48)
|
||||
local c5, c7 = readi16(coef, o + 80), readi16(coef, o + 112)
|
||||
if c1 == 0 and c3 == 0 and c5 == 0 and c7 == 0 then
|
||||
local dc = readi16(coef, o) * readu16(q, qo) * dcm
|
||||
ws[c + 1] = dc
|
||||
ws[c + 9] = dc
|
||||
else
|
||||
local tmp10 = readi16(coef, o) * readu16(q, qo) * 32768
|
||||
local tmp0 = c7 * readu16(q, qo + 112) * -5906
|
||||
+ c5 * readu16(q, qo + 80) * 6967
|
||||
+ c3 * readu16(q, qo + 48) * -10426
|
||||
+ c1 * readu16(q, qo + 16) * 29692
|
||||
ws[c + 1] = (tmp10 + tmp0 + h1) // s1
|
||||
ws[c + 9] = (tmp10 - tmp0 + h1) // s1
|
||||
end
|
||||
end
|
||||
end
|
||||
local s2 = 2 ^ (18 + p1)
|
||||
local h2 = s2 / 2 + center * s2
|
||||
local sd = 2 ^ (p1 + 3)
|
||||
local hd = sd / 2 + center * sd
|
||||
for r = 0, 1 do
|
||||
local b = r * 8
|
||||
local w0, w1, w3, w5, w7 = ws[b + 1], ws[b + 2], ws[b + 4], ws[b + 6], ws[b + 8]
|
||||
local o = (out + r * stride) * 2
|
||||
if w1 == 0 and w3 == 0 and w5 == 0 and w7 == 0 then
|
||||
local v = clamp((w0 + hd) // sd, 0, maxv)
|
||||
writeu16(plane, o, v)
|
||||
writeu16(plane, o + 2, v)
|
||||
else
|
||||
local tmp10 = w0 * 32768
|
||||
local tmp0 = w7 * -5906 + w5 * 6967 + w3 * -10426 + w1 * 29692
|
||||
writeu16(plane, o, clamp((tmp10 + tmp0 + h2) // s2, 0, maxv))
|
||||
writeu16(plane, o + 2, clamp((tmp10 - tmp0 + h2) // s2, 0, maxv))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Inverse-transforms every block of a component: coef (i16, 64 per block, natural order) on a bpl x bpc block
|
||||
-- grid, quantisation table q (64 u16, natural order), into plane (u16 samples, (bpl * size) per row) at size x
|
||||
-- size samples per block. p1 is PASS1_BITS (2 for 8-bit, 1 for 12-bit), center the level shift, maxv the top.
|
||||
function Dct.idctComponent(coef: buffer, q: buffer, bpl: number, bpc: number, size: number, plane: buffer, p1: number, center: number, maxv: number)
|
||||
local stride = bpl * size
|
||||
for by = 0, bpc - 1 do
|
||||
for bx = 0, bpl - 1 do
|
||||
local off = (by * bpl + bx) * 128
|
||||
local out = by * size * stride + bx * size
|
||||
if size == 8 then
|
||||
idct8(coef, off, q, plane, out, stride, p1, center, maxv)
|
||||
elseif size == 4 then
|
||||
idct4(coef, off, q, plane, out, stride, p1, center, maxv)
|
||||
elseif size == 2 then
|
||||
idct2(coef, off, q, plane, out, stride, p1, center, maxv)
|
||||
else
|
||||
local v = (readi16(coef, off) * readu16(q, 0) + 4) // 8 + center
|
||||
writeu16(plane, out * 2, clamp(v, 0, maxv))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- idctBlock(coef, off, q, plane, out, stride, p1, center, maxv): one 8x8 block, coef (i16, natural order) at byte
|
||||
-- offset off, dequantised by q (64 u16), into the u16 plane at sample index out with stride samples per row
|
||||
function Dct.idctBlock(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number)
|
||||
idct8(coef, off, q, plane, out, stride, p1, center, maxv)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ forward
|
||||
local fw = table.create(64, 0)
|
||||
|
||||
local function quant(coef: buffer, off: number, div: buffer, v: number, i: number)
|
||||
local qv = readu16(div, i * 2) * 8
|
||||
local h = qv // 2
|
||||
if v < 0 then
|
||||
writei16(coef, off + i * 2, -((h - v) // qv))
|
||||
else
|
||||
writei16(coef, off + i * 2, (v + h) // qv)
|
||||
end
|
||||
end
|
||||
|
||||
-- fdctQuantize(src, stride, x, y, w, h, div, coef, off): the 8x8 block of u8 samples at (x, y) in src (stride bytes
|
||||
-- per row; samples past w - 1 / h - 1 repeat the edge), level-shifted by 128, forward DCT (jfdctint.c islow), then
|
||||
-- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored, q = div (64 u16, natural order). Writes
|
||||
-- 64 i16 at coef[off] (natural order). The caller keeps x < w, y < h and the src range valid.
|
||||
function Dct.fdctQuantize(src: buffer, stride: number, x: number, y: number, w: number, h: number, div: buffer, coef: buffer, off: number)
|
||||
local lastX, lastY = w - 1, h - 1
|
||||
for r = 0, 7 do
|
||||
local row = math.min(y + r, lastY) * stride
|
||||
local d0: number, d1: number, d2: number, d3: number, d4: number, d5: number, d6: number, d7: number
|
||||
if x + 7 <= lastX then
|
||||
local p = row + x
|
||||
d0, d1, d2, d3 = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3)
|
||||
d4, d5, d6, d7 = readu8(src, p + 4), readu8(src, p + 5), readu8(src, p + 6), readu8(src, p + 7)
|
||||
else
|
||||
d0 = readu8(src, row + math.min(x, lastX))
|
||||
d1 = readu8(src, row + math.min(x + 1, lastX))
|
||||
d2 = readu8(src, row + math.min(x + 2, lastX))
|
||||
d3 = readu8(src, row + math.min(x + 3, lastX))
|
||||
d4 = readu8(src, row + math.min(x + 4, lastX))
|
||||
d5 = readu8(src, row + math.min(x + 5, lastX))
|
||||
d6 = readu8(src, row + math.min(x + 6, lastX))
|
||||
d7 = readu8(src, row + math.min(x + 7, lastX))
|
||||
end
|
||||
d0 -= 128
|
||||
d1 -= 128
|
||||
d2 -= 128
|
||||
d3 -= 128
|
||||
d4 -= 128
|
||||
d5 -= 128
|
||||
d6 -= 128
|
||||
d7 -= 128
|
||||
local tmp0, tmp7 = d0 + d7, d0 - d7
|
||||
local tmp1, tmp6 = d1 + d6, d1 - d6
|
||||
local tmp2, tmp5 = d2 + d5, d2 - d5
|
||||
local tmp3, tmp4 = d3 + d4, d3 - d4
|
||||
local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3
|
||||
local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2
|
||||
local b = r * 8 + 1
|
||||
fw[b] = (tmp10 + tmp11) * 4
|
||||
fw[b + 4] = (tmp10 - tmp11) * 4
|
||||
local z1 = (tmp12 + tmp13) * 4433
|
||||
fw[b + 2] = (z1 + tmp13 * 6270 + 1024) // 2048
|
||||
fw[b + 6] = (z1 - tmp12 * 15137 + 1024) // 2048
|
||||
z1 = tmp4 + tmp7
|
||||
local z2 = tmp5 + tmp6
|
||||
local z3 = tmp4 + tmp6
|
||||
local z4 = tmp5 + tmp7
|
||||
local z5 = (z3 + z4) * 9633
|
||||
tmp4 *= 2446
|
||||
tmp5 *= 16819
|
||||
tmp6 *= 25172
|
||||
tmp7 *= 12299
|
||||
z1 *= -7373
|
||||
z2 *= -20995
|
||||
z3 = z3 * -16069 + z5
|
||||
z4 = z4 * -3196 + z5
|
||||
fw[b + 7] = (tmp4 + z1 + z3 + 1024) // 2048
|
||||
fw[b + 5] = (tmp5 + z2 + z4 + 1024) // 2048
|
||||
fw[b + 3] = (tmp6 + z2 + z3 + 1024) // 2048
|
||||
fw[b + 1] = (tmp7 + z1 + z4 + 1024) // 2048
|
||||
end
|
||||
for c = 1, 8 do
|
||||
local d0, d1, d2, d3 = fw[c], fw[c + 8], fw[c + 16], fw[c + 24]
|
||||
local d4, d5, d6, d7 = fw[c + 32], fw[c + 40], fw[c + 48], fw[c + 56]
|
||||
local tmp0, tmp7 = d0 + d7, d0 - d7
|
||||
local tmp1, tmp6 = d1 + d6, d1 - d6
|
||||
local tmp2, tmp5 = d2 + d5, d2 - d5
|
||||
local tmp3, tmp4 = d3 + d4, d3 - d4
|
||||
local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3
|
||||
local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2
|
||||
local o0 = (tmp10 + tmp11 + 2) // 4
|
||||
local o4 = (tmp10 - tmp11 + 2) // 4
|
||||
local z1 = (tmp12 + tmp13) * 4433
|
||||
local o2 = (z1 + tmp13 * 6270 + 16384) // 32768
|
||||
local o6 = (z1 - tmp12 * 15137 + 16384) // 32768
|
||||
z1 = tmp4 + tmp7
|
||||
local z2 = tmp5 + tmp6
|
||||
local z3 = tmp4 + tmp6
|
||||
local z4 = tmp5 + tmp7
|
||||
local z5 = (z3 + z4) * 9633
|
||||
tmp4 *= 2446
|
||||
tmp5 *= 16819
|
||||
tmp6 *= 25172
|
||||
tmp7 *= 12299
|
||||
z1 *= -7373
|
||||
z2 *= -20995
|
||||
z3 = z3 * -16069 + z5
|
||||
z4 = z4 * -3196 + z5
|
||||
local o7 = (tmp4 + z1 + z3 + 16384) // 32768
|
||||
local o5 = (tmp5 + z2 + z4 + 16384) // 32768
|
||||
local o3 = (tmp6 + z2 + z3 + 16384) // 32768
|
||||
local o1 = (tmp7 + z1 + z4 + 16384) // 32768
|
||||
local cc = c - 1
|
||||
quant(coef, off, div, o0, cc)
|
||||
quant(coef, off, div, o1, cc + 8)
|
||||
quant(coef, off, div, o2, cc + 16)
|
||||
quant(coef, off, div, o3, cc + 24)
|
||||
quant(coef, off, div, o4, cc + 32)
|
||||
quant(coef, off, div, o5, cc + 40)
|
||||
quant(coef, off, div, o6, cc + 48)
|
||||
quant(coef, off, div, o7, cc + 56)
|
||||
end
|
||||
end
|
||||
|
||||
return Dct
|
||||
@@ -0,0 +1,282 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
|
||||
-- image/tiff build on it. New code (no port), written from the GIF89a spec (appendix F) and TIFF 6.0 section 13.
|
||||
-- gif LSB-first codes, a minimum code size 1..11 (2..8 in GIF), clear = 2^min, EOI = clear + 1, the code width
|
||||
-- grows when the next free code reaches 2^width (max 12 bits; a full table stays frozen until a clear).
|
||||
-- tiff MSB-first codes, 8-bit symbols, clear = 256, EOI = 257, "early change": the width grows one code
|
||||
-- earlier (next free code = 2^width - 1). Old-style (pre-6.0, LSB-first, no early change) TIFF LZW is
|
||||
-- detected by its first bytes (0x00 then an odd byte) and decoded too.
|
||||
--
|
||||
-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "gif", minCodeSize) -- bytes written
|
||||
-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "tiff")
|
||||
-- local codes = Lzw.encode(data, off, len, "gif", minCodeSize) -- buffer
|
||||
-- local codes = Lzw.encode(data, off, len, "tiff")
|
||||
--
|
||||
-- decode writes at most maxOut bytes at out[outOff ..] and returns how many it wrote; it stops at EOI, at the end of
|
||||
-- the input or when out is full. err is nil for a clean stream, "truncated" when the input ended without EOI, or
|
||||
-- "corrupt" for an impossible code (everything decoded up to it is kept). Never throws; the caller checks that
|
||||
-- [outOff, outOff + maxOut) lies inside out and [off, off + len) inside src (decode clamps both anyway).
|
||||
local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16
|
||||
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
|
||||
local blen = buffer.len
|
||||
|
||||
local Lzw = {}
|
||||
|
||||
local MAX_CODES = 4096
|
||||
|
||||
-- per-call tables (allocated once: decode / encode are not re-entrant across coroutines, but never yield)
|
||||
local prefix = buffer.create(MAX_CODES * 2) -- u16: the code this entry extends
|
||||
local suffix = buffer.create(MAX_CODES) -- u8: its last byte
|
||||
local first = buffer.create(MAX_CODES) -- u8: its first byte
|
||||
local length = buffer.create(MAX_CODES * 2) -- u16: its length
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- writes the string of code c (length l) ending at out[o + l - 1]; clipped to [o, lim)
|
||||
local function emit(out: buffer, o: number, c: number, l: number, lim: number)
|
||||
local p = o + l - 1
|
||||
if p < lim then
|
||||
while p >= o do
|
||||
writeu8(out, p, readu8(suffix, c))
|
||||
c = readu16(prefix, c * 2)
|
||||
p -= 1
|
||||
end
|
||||
else
|
||||
while p >= o do
|
||||
if p < lim then
|
||||
writeu8(out, p, readu8(suffix, c))
|
||||
end
|
||||
c = readu16(prefix, c * 2)
|
||||
p -= 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: number, maxOut: number, variant: string, minCodeSize: number?): (number, string?)
|
||||
local n = blen(src)
|
||||
if off < 0 or off > n then
|
||||
return 0, "corrupt"
|
||||
end
|
||||
local e = math.min(off + math.max(0, len), n)
|
||||
local lim = math.min(outOff + math.max(0, maxOut), blen(out))
|
||||
if outOff < 0 then
|
||||
return 0, "corrupt"
|
||||
end
|
||||
local msb = variant == "tiff"
|
||||
local early = 0 -- 1 for TIFF's early change
|
||||
local min = minCodeSize or 8
|
||||
if msb then
|
||||
min = 8
|
||||
early = 1
|
||||
-- old-style TIFF LZW: LSB-first, no early change (libtiff LZWPreDecode's check)
|
||||
if e - off >= 2 and readu8(src, off) == 0 and band(readu8(src, off + 1), 1) == 1 then
|
||||
msb = false
|
||||
early = 0
|
||||
end
|
||||
end
|
||||
if min < 1 or min > 11 then
|
||||
return 0, "corrupt"
|
||||
end
|
||||
local clear = lshift(1, min)
|
||||
local eoi = clear + 1
|
||||
for i = 0, clear - 1 do
|
||||
writeu16(prefix, i * 2, 0)
|
||||
writeu8(suffix, i, band(i, 255))
|
||||
writeu8(first, i, band(i, 255))
|
||||
writeu16(length, i * 2, 1)
|
||||
end
|
||||
local size = min + 1
|
||||
local mask = lshift(1, size) - 1
|
||||
local nextc = clear + 2
|
||||
local prev = -1
|
||||
local o = outOff
|
||||
local p = off
|
||||
local acc, nb = 0, 0
|
||||
while true do
|
||||
-- refill (at most 12 + 7 bits held: below 2^20)
|
||||
while nb < size do
|
||||
if p >= e then
|
||||
return o - outOff, "truncated"
|
||||
end
|
||||
if msb then
|
||||
acc = acc * 256 + readu8(src, p)
|
||||
else
|
||||
acc += lshift(readu8(src, p), nb)
|
||||
end
|
||||
p += 1
|
||||
nb += 8
|
||||
end
|
||||
local c
|
||||
if msb then
|
||||
nb -= size
|
||||
c = band(rshift(acc, nb), mask)
|
||||
acc = band(acc, lshift(1, nb) - 1)
|
||||
else
|
||||
c = band(acc, mask)
|
||||
acc = rshift(acc, size)
|
||||
nb -= size
|
||||
end
|
||||
if c == clear then
|
||||
size = min + 1
|
||||
mask = lshift(1, size) - 1
|
||||
nextc = clear + 2
|
||||
prev = -1
|
||||
elseif c == eoi then
|
||||
return o - outOff, nil
|
||||
else
|
||||
if o >= lim then
|
||||
return o - outOff, nil -- full: the rest (normally just EOI) is ignored
|
||||
end
|
||||
if prev < 0 then
|
||||
if c >= clear then
|
||||
return o - outOff, "corrupt"
|
||||
end
|
||||
writeu8(out, o, readu8(suffix, c))
|
||||
o += 1
|
||||
prev = c
|
||||
else
|
||||
local l
|
||||
if c < nextc then
|
||||
l = readu16(length, c * 2)
|
||||
emit(out, o, c, l, lim)
|
||||
if nextc < MAX_CODES then
|
||||
writeu16(prefix, nextc * 2, prev)
|
||||
writeu8(suffix, nextc, readu8(first, c))
|
||||
writeu8(first, nextc, readu8(first, prev))
|
||||
writeu16(length, nextc * 2, readu16(length, prev * 2) + 1)
|
||||
nextc += 1
|
||||
end
|
||||
elseif c == nextc and nextc < MAX_CODES then
|
||||
-- KwKwK: the new entry is prev + first(prev)
|
||||
local f = readu8(first, prev)
|
||||
writeu16(prefix, nextc * 2, prev)
|
||||
writeu8(suffix, nextc, f)
|
||||
writeu8(first, nextc, f)
|
||||
l = readu16(length, prev * 2) + 1
|
||||
writeu16(length, nextc * 2, l)
|
||||
nextc += 1
|
||||
emit(out, o, c, l, lim)
|
||||
else
|
||||
return o - outOff, "corrupt"
|
||||
end
|
||||
o = math.min(o + l, lim)
|
||||
prev = c
|
||||
end
|
||||
if nextc + early >= lshift(1, size) and size < 12 then
|
||||
size += 1
|
||||
mask = lshift(1, size) - 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local HASH = 8192 -- open addressing over (prefix << 8 | byte) keys: a power of two above 4096 entries
|
||||
local hkey = buffer.create(HASH * 4) -- i32 key + 1 (0 = empty)
|
||||
local hval = buffer.create(HASH * 2) -- u16 code
|
||||
|
||||
-- encode(data, off, len, variant, minCodeSize?) -> the code stream (GIF: without the sub-block framing). Symbols in
|
||||
-- data must be below 2^minCodeSize (GIF; larger ones are masked) or bytes (TIFF).
|
||||
function Lzw.encode(data: buffer, off: number, len: number, variant: string, minCodeSize: number?): buffer
|
||||
local msb = variant == "tiff"
|
||||
local min = if msb then 8 else math.clamp(minCodeSize or 8, 1, 11)
|
||||
local early = if msb then 1 else 0
|
||||
local symMask = lshift(1, min) - 1
|
||||
local clear = lshift(1, min)
|
||||
local eoi = clear + 1
|
||||
local n = blen(data)
|
||||
off = math.clamp(off, 0, n)
|
||||
local e = math.clamp(off + len, off, n)
|
||||
local cap = (e - off) * 2 + 64
|
||||
local out = buffer.create(cap)
|
||||
local op = 0
|
||||
local acc, nb = 0, 0
|
||||
local size = min + 1
|
||||
local function put(code: number)
|
||||
if op + 4 > cap then
|
||||
cap *= 2
|
||||
local nbuf = buffer.create(cap)
|
||||
buffer.copy(nbuf, 0, out, 0, op)
|
||||
out = nbuf
|
||||
end
|
||||
if msb then
|
||||
acc = acc * lshift(1, size) + code
|
||||
nb += size
|
||||
while nb >= 8 do
|
||||
nb -= 8
|
||||
writeu8(out, op, rshift(acc, nb))
|
||||
op += 1
|
||||
acc = band(acc, lshift(1, nb) - 1)
|
||||
end
|
||||
else
|
||||
acc += lshift(code, nb)
|
||||
nb += size
|
||||
while nb >= 8 do
|
||||
writeu8(out, op, band(acc, 255))
|
||||
op += 1
|
||||
acc = rshift(acc, 8)
|
||||
nb -= 8
|
||||
end
|
||||
end
|
||||
end
|
||||
buffer.fill(hkey, 0, 0, HASH * 4)
|
||||
local nextc = clear + 2
|
||||
put(clear)
|
||||
if e > off then
|
||||
local cur = band(readu8(data, off), symMask)
|
||||
for i = off + 1, e - 1 do
|
||||
local b = band(readu8(data, i), symMask)
|
||||
local key = cur * 256 + b + 1
|
||||
local h = band(cur * 31 + b * 4099, HASH - 1)
|
||||
local found = -1
|
||||
while true do
|
||||
local k = buffer.readi32(hkey, h * 4)
|
||||
if k == 0 then
|
||||
break
|
||||
elseif k == key then
|
||||
found = readu16(hval, h * 2)
|
||||
break
|
||||
end
|
||||
h = band(h + 1, HASH - 1)
|
||||
end
|
||||
if found >= 0 then
|
||||
cur = found
|
||||
else
|
||||
put(cur)
|
||||
if nextc >= MAX_CODES - 2 then
|
||||
put(clear)
|
||||
size = min + 1
|
||||
nextc = clear + 2
|
||||
buffer.fill(hkey, 0, 0, HASH * 4)
|
||||
else
|
||||
buffer.writei32(hkey, h * 4, key)
|
||||
writeu16(hval, h * 2, nextc)
|
||||
nextc += 1
|
||||
if nextc + early > lshift(1, size) and size < 12 then
|
||||
size += 1
|
||||
end
|
||||
end
|
||||
cur = b
|
||||
end
|
||||
end
|
||||
put(cur)
|
||||
-- the decoder adds an entry for this last code too: its width may grow before EOI
|
||||
if nextc < MAX_CODES then
|
||||
nextc += 1
|
||||
if nextc + early > lshift(1, size) and size < 12 then
|
||||
size += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
put(eoi)
|
||||
if nb > 0 then
|
||||
writeu8(out, op, if msb then band(lshift(acc, 8 - nb), 255) else band(acc, 255))
|
||||
op += 1
|
||||
end
|
||||
local res = buffer.create(op)
|
||||
buffer.copy(res, 0, out, 0, op)
|
||||
return res
|
||||
end
|
||||
|
||||
return Lzw
|
||||
@@ -0,0 +1,483 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
|
||||
-- writer) builds on it. New code: Heckbert's median cut and Gervautz-Purgathofer octree, both over a 5-bit-per-channel
|
||||
-- weighted histogram (palette colours are the exact means of the pixels they cover), nearest-colour mapping with
|
||||
-- optional Floyd-Steinberg error diffusion. Deterministic: the same palette and indexes on every runtime (no table
|
||||
-- iteration order is ever relied on).
|
||||
--
|
||||
-- local pal, exact = Quantize.palette(pixels, w, h, 256, { method = "mediancut" }) -- { {r, g, b, 255} }, boolean
|
||||
-- local idx = Quantize.map(pixels, w, h, pal, { dither = true, transparentIndex = 255 }) -- buffer of w * h u8
|
||||
--
|
||||
-- Pixels with alpha < 128 are "transparent": palette() ignores them, map() gives them opts.transparentIndex (0-based)
|
||||
-- when set (otherwise they map like opaque pixels). When the opaque pixels have at most maxColors distinct colours,
|
||||
-- palette() returns exactly those (in first-seen order) and exact = true, and map() is then lossless. The octree
|
||||
-- folds whole nodes, so it may return fewer than maxColors entries; below 8 colours median cut is used instead.
|
||||
-- Never throws: bad arguments give an empty palette / a zero-filled index buffer.
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64
|
||||
local floor = math.floor
|
||||
local blen = buffer.len
|
||||
|
||||
local Quantize = {}
|
||||
|
||||
export type Color = { number } -- { r, g, b, a } 0..255
|
||||
export type PaletteOptions = {
|
||||
method: ("mediancut" | "octree")?, -- default "mediancut"
|
||||
}
|
||||
export type MapOptions = {
|
||||
dither: boolean?, -- Floyd-Steinberg error diffusion (default false)
|
||||
transparentIndex: number?, -- 0-based index for pixels with alpha < 128 (default: none)
|
||||
}
|
||||
|
||||
local BINS = 32768 -- 5 bits per channel
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ helpers
|
||||
local function count(pixels: buffer, n: number): (buffer, buffer)
|
||||
-- per bin: u32 count; f64 sums of r, g, b
|
||||
local cnt = buffer.create(BINS * 4)
|
||||
local sums = buffer.create(BINS * 24)
|
||||
for i = 0, n - 1 do
|
||||
local o = i * 4
|
||||
if readu8(pixels, o + 3) >= 128 then
|
||||
local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2)
|
||||
local bin = (r // 8) * 1024 + (g // 8) * 32 + b // 8
|
||||
writeu32(cnt, bin * 4, readu32(cnt, bin * 4) + 1)
|
||||
local s = bin * 24
|
||||
writef64(sums, s, readf64(sums, s) + r)
|
||||
writef64(sums, s + 8, readf64(sums, s + 8) + g)
|
||||
writef64(sums, s + 16, readf64(sums, s + 16) + b)
|
||||
end
|
||||
end
|
||||
return cnt, sums
|
||||
end
|
||||
|
||||
local function mean(cnt: buffer, sums: buffer, bins: { number }, lo: number, hi: number): Color
|
||||
local n, r, g, b = 0, 0, 0, 0
|
||||
for i = lo, hi do
|
||||
local bin = bins[i]
|
||||
n += readu32(cnt, bin * 4)
|
||||
r += readf64(sums, bin * 24)
|
||||
g += readf64(sums, bin * 24 + 8)
|
||||
b += readf64(sums, bin * 24 + 16)
|
||||
end
|
||||
if n == 0 then
|
||||
return { 0, 0, 0, 255 }
|
||||
end
|
||||
return { floor(r / n + 0.5), floor(g / n + 0.5), floor(b / n + 0.5), 255 }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ median cut
|
||||
local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color }
|
||||
local bins: { number } = {}
|
||||
for bin = 0, BINS - 1 do
|
||||
if readu32(cnt, bin * 4) > 0 then
|
||||
table.insert(bins, bin)
|
||||
end
|
||||
end
|
||||
if #bins == 0 then
|
||||
return {}
|
||||
end
|
||||
-- boxes: { lo, hi } ranges of the bins array
|
||||
local boxes: { { number } } = {}
|
||||
local function channel(bin: number, c: number): number
|
||||
if c == 0 then
|
||||
return bin // 1024
|
||||
elseif c == 1 then
|
||||
return (bin // 32) % 32
|
||||
end
|
||||
return bin % 32
|
||||
end
|
||||
local function stats(box: { number }): (number, number, number)
|
||||
-- returns the widest channel, its range, the pixel count
|
||||
local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 }
|
||||
local n = 0
|
||||
for i = box[1], box[2] do
|
||||
local bin = bins[i]
|
||||
n += readu32(cnt, bin * 4)
|
||||
for c = 0, 2 do
|
||||
local v = channel(bin, c)
|
||||
if v < mins[c + 1] then
|
||||
mins[c + 1] = v
|
||||
end
|
||||
if v > maxs[c + 1] then
|
||||
maxs[c + 1] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
local best, range = 0, -1
|
||||
for c = 0, 2 do
|
||||
local rg = maxs[c + 1] - mins[c + 1]
|
||||
if rg > range then
|
||||
best, range = c, rg
|
||||
end
|
||||
end
|
||||
return best, range, n
|
||||
end
|
||||
local function scored(lo: number, hi: number): { number }
|
||||
local c, range, n = stats({ lo, hi })
|
||||
return { lo, hi, c, if hi > lo then range * math.sqrt(n) else 0 }
|
||||
end
|
||||
boxes[1] = scored(1, #bins)
|
||||
while #boxes < maxColors do
|
||||
-- split the box with the largest range * sqrt(count) score (ties: the first)
|
||||
local pick, pickScore = 0, 0
|
||||
for i, box in boxes do
|
||||
if box[4] > pickScore then
|
||||
pick, pickScore = i, box[4]
|
||||
end
|
||||
end
|
||||
if pick == 0 then
|
||||
break
|
||||
end
|
||||
local box = boxes[pick]
|
||||
local lo, hi, c = box[1], box[2], box[3]
|
||||
-- sort the range by the channel, ties by bin number: unique numeric keys, no comparator
|
||||
local keys = table.create(hi - lo + 1)
|
||||
for i = lo, hi do
|
||||
keys[i - lo + 1] = channel(bins[i], c) * BINS + bins[i]
|
||||
end
|
||||
table.sort(keys)
|
||||
local total = 0
|
||||
for i = 1, #keys do
|
||||
local bin = keys[i] % BINS
|
||||
bins[lo + i - 1] = bin
|
||||
total += readu32(cnt, bin * 4)
|
||||
end
|
||||
-- the weighted median, keeping both halves non-empty
|
||||
local acc, cut = 0, lo
|
||||
for i = lo, hi - 1 do
|
||||
acc += readu32(cnt, bins[i] * 4)
|
||||
cut = i
|
||||
if acc * 2 >= total then
|
||||
break
|
||||
end
|
||||
end
|
||||
boxes[pick] = scored(lo, cut)
|
||||
table.insert(boxes, scored(cut + 1, hi))
|
||||
end
|
||||
local pal = table.create(#boxes)
|
||||
for i, box in boxes do
|
||||
pal[i] = mean(cnt, sums, bins, box[1], box[2])
|
||||
end
|
||||
return pal
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ octree
|
||||
-- over the histogram bins: 5 levels (one bit of each channel per level). Nodes are array slots.
|
||||
local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color }
|
||||
local child: { number } = {} -- node * 8 + k -> node (0 = none)
|
||||
local n: { number } = {} -- pixel count
|
||||
local sr: { number }, sg: { number }, sb: { number } = {}, {}, {}
|
||||
local leaf: { boolean } = {}
|
||||
local level: { number } = {}
|
||||
local nodes = 1
|
||||
n[1], sr[1], sg[1], sb[1], leaf[1], level[1] = 0, 0, 0, 0, false, 0
|
||||
for k = 1, 8 do
|
||||
child[k] = 0
|
||||
end
|
||||
local byLevel: { { number } } = { {}, {}, {}, {}, {} } -- inner nodes per level 0..4, creation order
|
||||
table.insert(byLevel[1], 1)
|
||||
local leaves = 0
|
||||
for bin = 0, BINS - 1 do
|
||||
local c = readu32(cnt, bin * 4)
|
||||
if c > 0 then
|
||||
local r5, g5, b5 = bin // 1024, (bin // 32) % 32, bin % 32
|
||||
local node = 1
|
||||
for lv = 0, 4 do
|
||||
local sh = 4 - lv
|
||||
local k = ((r5 // 2 ^ sh) % 2) * 4 + ((g5 // 2 ^ sh) % 2) * 2 + (b5 // 2 ^ sh) % 2
|
||||
local slot = (node - 1) * 8 + k + 1
|
||||
local nx = child[slot]
|
||||
if nx == 0 then
|
||||
nodes += 1
|
||||
nx = nodes
|
||||
child[slot] = nx
|
||||
for j = 1, 8 do
|
||||
child[(nx - 1) * 8 + j] = 0
|
||||
end
|
||||
n[nx], sr[nx], sg[nx], sb[nx], level[nx] = 0, 0, 0, 0, lv + 1
|
||||
leaf[nx] = lv == 4
|
||||
if lv == 4 then
|
||||
leaves += 1
|
||||
else
|
||||
table.insert(byLevel[lv + 2], nx)
|
||||
end
|
||||
end
|
||||
node = nx
|
||||
end
|
||||
n[node] += c
|
||||
sr[node] += readf64(sums, bin * 24)
|
||||
sg[node] += readf64(sums, bin * 24 + 8)
|
||||
sb[node] += readf64(sums, bin * 24 + 16)
|
||||
end
|
||||
end
|
||||
-- fold the deepest inner nodes (fewest pixels first, ties by creation order) until few enough leaves remain
|
||||
local function fold(node: number): number
|
||||
-- merges the children (all leaves) into node; returns how many leaves disappeared
|
||||
local merged = 0
|
||||
for k = 1, 8 do
|
||||
local slot = (node - 1) * 8 + k
|
||||
local ch = child[slot]
|
||||
if ch ~= 0 then
|
||||
n[node] += n[ch]
|
||||
sr[node] += sr[ch]
|
||||
sg[node] += sg[ch]
|
||||
sb[node] += sb[ch]
|
||||
child[slot] = 0
|
||||
merged += 1
|
||||
end
|
||||
end
|
||||
leaf[node] = true
|
||||
return merged - 1
|
||||
end
|
||||
local function subtotal(node: number): number
|
||||
local s = 0
|
||||
for k = 1, 8 do
|
||||
local ch = child[(node - 1) * 8 + k]
|
||||
if ch ~= 0 then
|
||||
s += n[ch]
|
||||
end
|
||||
end
|
||||
return s
|
||||
end
|
||||
for lv = 5, 1, -1 do
|
||||
if leaves <= maxColors then
|
||||
break
|
||||
end
|
||||
local list = byLevel[lv]
|
||||
local order = table.create(#list)
|
||||
for i, node in list do
|
||||
order[i] = { node, subtotal(node), i }
|
||||
end
|
||||
table.sort(order, function(a: { number }, b: { number }): boolean
|
||||
if a[2] ~= b[2] then
|
||||
return a[2] < b[2]
|
||||
end
|
||||
return a[3] < b[3]
|
||||
end)
|
||||
for _, e in order do
|
||||
if leaves <= maxColors then
|
||||
break
|
||||
end
|
||||
leaves -= fold(e[1])
|
||||
end
|
||||
end
|
||||
-- collect leaves depth first in child order
|
||||
local pal: { Color } = {}
|
||||
local function walk(node: number)
|
||||
if leaf[node] then
|
||||
local c = n[node]
|
||||
if c > 0 then
|
||||
table.insert(pal, { floor(sr[node] / c + 0.5), floor(sg[node] / c + 0.5), floor(sb[node] / c + 0.5), 255 })
|
||||
end
|
||||
return
|
||||
end
|
||||
for k = 1, 8 do
|
||||
local ch = child[(node - 1) * 8 + k]
|
||||
if ch ~= 0 then
|
||||
walk(ch)
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(1)
|
||||
-- the root itself can end up a leaf with everything (maxColors 1)
|
||||
while #pal > maxColors do
|
||||
table.remove(pal)
|
||||
end
|
||||
return pal
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ palette
|
||||
-- palette(pixels, w, h, maxColors, opts?) -> palette, exact
|
||||
function Quantize.palette(pixels: buffer, w: number, h: number, maxColors: number, opts: PaletteOptions?): ({ Color }, boolean)
|
||||
if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 then
|
||||
return {}, false
|
||||
end
|
||||
local maxc = math.clamp(floor(tonumber(maxColors) or 256), 1, 65536)
|
||||
local npx = w * h
|
||||
-- exact colours, in first-seen order (stops counting past maxColors)
|
||||
local seen: { [number]: boolean } = {}
|
||||
local exact: { Color } = {}
|
||||
local over = false
|
||||
for i = 0, npx - 1 do
|
||||
local o = i * 4
|
||||
if readu8(pixels, o + 3) >= 128 then
|
||||
local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2)
|
||||
local key = r * 65536 + g * 256 + b
|
||||
if not seen[key] then
|
||||
if #exact >= maxc then
|
||||
over = true
|
||||
break
|
||||
end
|
||||
seen[key] = true
|
||||
table.insert(exact, { r, g, b, 255 })
|
||||
end
|
||||
end
|
||||
end
|
||||
if not over then
|
||||
return exact, true
|
||||
end
|
||||
local cnt, sums = count(pixels, npx)
|
||||
local method = opts and opts.method or "mediancut"
|
||||
if method == "octree" and maxc >= 8 then -- below 8 the octree can only fold to a single colour
|
||||
return octree(cnt, sums, maxc), false
|
||||
end
|
||||
return medianCut(cnt, sums, maxc), false
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ map
|
||||
-- map(pixels, w, h, palette, opts?) -> buffer of w * h palette indexes (0-based)
|
||||
function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, opts: MapOptions?): buffer
|
||||
if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 or type(palette) ~= "table" then
|
||||
return buffer.create(0)
|
||||
end
|
||||
local npx = w * h
|
||||
local out = buffer.create(npx)
|
||||
local dither = opts and opts.dither or false
|
||||
local tidx = opts and opts.transparentIndex
|
||||
-- the searchable entries (the transparent slot is excluded)
|
||||
local pr, pg, pb, pi = {}, {}, {}, {}
|
||||
for i, c in palette do
|
||||
if tidx == nil or i - 1 ~= tidx then
|
||||
table.insert(pr, c[1] or 0)
|
||||
table.insert(pg, c[2] or 0)
|
||||
table.insert(pb, c[3] or 0)
|
||||
table.insert(pi, i - 1)
|
||||
end
|
||||
end
|
||||
local np = #pr
|
||||
-- sorted by green (the heaviest weight), so the search can stop once 4 * dg^2 alone is worse than the best
|
||||
do
|
||||
local order = table.create(np)
|
||||
for k = 1, np do
|
||||
order[k] = pg[k] * 65536 + k
|
||||
end
|
||||
table.sort(order)
|
||||
local r2, g2, b2, i2 = table.create(np), table.create(np), table.create(np), table.create(np)
|
||||
for k = 1, np do
|
||||
local j = order[k] % 65536
|
||||
r2[k], g2[k], b2[k], i2[k] = pr[j], pg[j], pb[j], pi[j]
|
||||
end
|
||||
pr, pg, pb, pi = r2, g2, b2, i2
|
||||
end
|
||||
local startAt = table.create(256, np) -- the first entry with green >= g (1-based), np + 1 past the end
|
||||
do
|
||||
local k = 1
|
||||
for g = 0, 255 do
|
||||
while k <= np and pg[k] < g do
|
||||
k += 1
|
||||
end
|
||||
startAt[g + 1] = k
|
||||
end
|
||||
end
|
||||
if np == 0 then
|
||||
if tidx then
|
||||
buffer.fill(out, 0, math.clamp(tidx, 0, 255), npx)
|
||||
end
|
||||
return out
|
||||
end
|
||||
local cache: { [number]: number } = {}
|
||||
local function nearest(r: number, g: number, b: number): number
|
||||
local key = r * 65536 + g * 256 + b
|
||||
local hit = cache[key]
|
||||
if hit then
|
||||
return hit
|
||||
end
|
||||
local best, bd = 1, math.huge
|
||||
local up = startAt[math.clamp(g, 0, 255) + 1]
|
||||
local down = up - 1
|
||||
while up <= np or down >= 1 do
|
||||
if up <= np then
|
||||
local dg = pg[up] - g
|
||||
if dg * dg * 4 >= bd then
|
||||
up = np + 1
|
||||
else
|
||||
local dr, db = r - pr[up], b - pb[up]
|
||||
local d = dr * dr * 2 + dg * dg * 4 + db * db * 3
|
||||
if d < bd then
|
||||
best, bd = up, d
|
||||
end
|
||||
up += 1
|
||||
end
|
||||
end
|
||||
if down >= 1 then
|
||||
local dg = g - pg[down]
|
||||
if dg * dg * 4 >= bd then
|
||||
down = 0
|
||||
else
|
||||
local dr, db = r - pr[down], b - pb[down]
|
||||
local d = dr * dr * 2 + dg * dg * 4 + db * db * 3
|
||||
if d < bd then
|
||||
best, bd = down, d
|
||||
end
|
||||
down -= 1
|
||||
end
|
||||
end
|
||||
end
|
||||
cache[key] = best
|
||||
return best
|
||||
end
|
||||
local tbyte = if tidx then math.clamp(tidx, 0, 255) else 0
|
||||
if not dither then
|
||||
for i = 0, npx - 1 do
|
||||
local o = i * 4
|
||||
if tidx and readu8(pixels, o + 3) < 128 then
|
||||
writeu8(out, i, tbyte)
|
||||
else
|
||||
writeu8(out, i, pi[nearest(readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2))])
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
-- Floyd-Steinberg: error rows (f64 r, g, b per pixel, one extra pixel each side)
|
||||
local rowLen = (w + 2) * 24
|
||||
local cur, nxt = buffer.create(rowLen), buffer.create(rowLen)
|
||||
for y = 0, h - 1 do
|
||||
buffer.fill(nxt, 0, 0, rowLen)
|
||||
for x = 0, w - 1 do
|
||||
local i = y * w + x
|
||||
local o = i * 4
|
||||
if tidx and readu8(pixels, o + 3) < 128 then
|
||||
writeu8(out, i, tbyte)
|
||||
else
|
||||
local e = (x + 1) * 24
|
||||
local r = math.clamp(floor(readu8(pixels, o) + readf64(cur, e) + 0.5), 0, 255)
|
||||
local g = math.clamp(floor(readu8(pixels, o + 1) + readf64(cur, e + 8) + 0.5), 0, 255)
|
||||
local b = math.clamp(floor(readu8(pixels, o + 2) + readf64(cur, e + 16) + 0.5), 0, 255)
|
||||
local k = nearest(r, g, b)
|
||||
writeu8(out, i, pi[k])
|
||||
local er, eg, eb = r - pr[k], g - pg[k], b - pb[k]
|
||||
-- 7/16 right, 3/16 down-left, 5/16 down, 1/16 down-right
|
||||
writef64(cur, e + 24, readf64(cur, e + 24) + er * 0.4375)
|
||||
writef64(cur, e + 32, readf64(cur, e + 32) + eg * 0.4375)
|
||||
writef64(cur, e + 40, readf64(cur, e + 40) + eb * 0.4375)
|
||||
writef64(nxt, e - 24, readf64(nxt, e - 24) + er * 0.1875)
|
||||
writef64(nxt, e - 16, readf64(nxt, e - 16) + eg * 0.1875)
|
||||
writef64(nxt, e - 8, readf64(nxt, e - 8) + eb * 0.1875)
|
||||
writef64(nxt, e, readf64(nxt, e) + er * 0.3125)
|
||||
writef64(nxt, e + 8, readf64(nxt, e + 8) + eg * 0.3125)
|
||||
writef64(nxt, e + 16, readf64(nxt, e + 16) + eb * 0.3125)
|
||||
writef64(nxt, e + 24, readf64(nxt, e + 24) + er * 0.0625)
|
||||
writef64(nxt, e + 32, readf64(nxt, e + 32) + eg * 0.0625)
|
||||
writef64(nxt, e + 40, readf64(nxt, e + 40) + eb * 0.0625)
|
||||
end
|
||||
end
|
||||
cur, nxt = nxt, cur
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- quantize(pixels, w, h, maxColors, opts?) -> indexes, palette, exact: palette() then map() (opts of both)
|
||||
function Quantize.quantize(pixels: buffer, w: number, h: number, maxColors: number, opts: any?): (buffer, { Color }, boolean)
|
||||
local pal, exact = Quantize.palette(pixels, w, h, maxColors, opts)
|
||||
local mo = opts
|
||||
if exact and opts and opts.dither then
|
||||
mo = table.clone(opts)
|
||||
mo.dither = false -- nothing to diffuse
|
||||
end
|
||||
return Quantize.map(pixels, w, h, pal, mo), pal, exact
|
||||
end
|
||||
|
||||
return Quantize
|
||||
@@ -0,0 +1,68 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/gif/Decode: the per-frame pixel work (native; never throws): palette indexes (plain or interlaced rows) to
|
||||
-- rgba8, and drawing a frame onto the canvas (transparent pixels leave the canvas as it is). The caller sizes every
|
||||
-- buffer: indexes fw * fh bytes, the palette 256 u32 entries, the frame fw * fh * 4, the canvas cw * ch * 4.
|
||||
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
|
||||
|
||||
local Decode = {}
|
||||
|
||||
-- the source row of output row y in an interlaced frame (passes: every 8th from 0, every 8th from 4, every 4th from
|
||||
-- 2, every 2nd from 1)
|
||||
local function interlacedRow(fh: number): { number }
|
||||
local map = table.create(fh, 0)
|
||||
local r = 0
|
||||
for _, pass in { { 0, 8 }, { 4, 8 }, { 2, 4 }, { 1, 2 } } do
|
||||
local y = pass[1]
|
||||
while y < fh do
|
||||
map[y + 1] = r
|
||||
r += 1
|
||||
y += pass[2]
|
||||
end
|
||||
end
|
||||
return map
|
||||
end
|
||||
|
||||
-- toRgba(indexes, fw, fh, interlaced, palette, out): out = the frame in rgba8 (palette: 256 u32 entries, the
|
||||
-- transparent one already alpha 0)
|
||||
function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer)
|
||||
local rows = if interlaced then interlacedRow(fh) else nil
|
||||
for y = 0, fh - 1 do
|
||||
local src = (if rows then rows[y + 1] else y) * fw
|
||||
local dst = y * fw * 4
|
||||
for x = 0, fw - 1 do
|
||||
writeu32(out, dst + x * 4, readu32(palette, readu8(indexes, src + x) * 4))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- draw(canvas, cw, ch, frame, fx, fy, fw, fh): frame pixels with alpha > 0 replace the canvas (clipped)
|
||||
function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number)
|
||||
local x0, y0 = math.max(0, fx), math.max(0, fy)
|
||||
local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh)
|
||||
for y = y0, y1 - 1 do
|
||||
local s = ((y - fy) * fw - fx) * 4
|
||||
local d = y * cw * 4
|
||||
for x = x0, x1 - 1 do
|
||||
local v = readu32(frame, s + x * 4)
|
||||
if v >= 0x01000000 then
|
||||
writeu32(canvas, d + x * 4, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- clear(canvas, cw, ch, fx, fy, fw, fh): the frame's rectangle to transparent black (dispose to background)
|
||||
function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number)
|
||||
local x0, y0 = math.max(0, fx), math.max(0, fy)
|
||||
local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh)
|
||||
if x1 <= x0 then
|
||||
return
|
||||
end
|
||||
for y = y0, y1 - 1 do
|
||||
buffer.fill(canvas, (y * cw + x0) * 4, 0, (x1 - x0) * 4)
|
||||
end
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -0,0 +1,534 @@
|
||||
--!strict
|
||||
-- image/gif: GIF87a / GIF89a. New code from the GIF89a spec (W3C / CompuServe 1990). Supports: decode of every image
|
||||
-- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames
|
||||
-- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background /
|
||||
-- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames
|
||||
-- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/Quantize
|
||||
-- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with
|
||||
-- alpha < 128 as the transparent index.
|
||||
-- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input"
|
||||
-- flag, and blend = "source" frames that clear pixels to transparent (GIF can only draw over).
|
||||
--
|
||||
-- Decoded value: img.pixels = the first frame composited on a transparent canvas; for animations img.frames = every
|
||||
-- frame's own rectangle (rgba8; blend "over" when it has a transparent index, else "source") and img.loops, the
|
||||
-- number of plays (0 = forever; 1 when the file has no loop extension). The NETSCAPE2.0 value counts repeats, as
|
||||
-- browsers and ImageMagick read it: a stored n plays n + 1 times (n = 0: forever).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Lzw = require("@formats/codecs/Lzw")
|
||||
local Quantize = require("@formats/codecs/Quantize")
|
||||
local Types = require("@formats/Types")
|
||||
local Decode = require("@formats/image/gif/Decode")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Gif = {
|
||||
name = "gif",
|
||||
category = "image",
|
||||
extensions = { "gif" },
|
||||
mime = { "image/gif" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/Lzw", "codecs/Quantize", "Types" },
|
||||
caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26)
|
||||
maxTotalPixels: number?, -- refuse animations whose frames add up to more (default 2^28)
|
||||
maxFrames: number?, -- stop after this many frames (default: all)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
maxColors: number?, -- 2..256 per palette (default 256; one is taken by transparency when needed)
|
||||
method: ("mediancut" | "octree")?, -- default "mediancut"
|
||||
dither: boolean?, -- Floyd-Steinberg (default false)
|
||||
loops: number?, -- animation plays override (0 = forever, 1..65536; default img.loops)
|
||||
globalPalette: boolean?, -- one palette for every frame (default false: a single image uses the global table,
|
||||
-- each animation frame gets its own local table)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local readu8 = buffer.readu8
|
||||
local DISPOSE = { [0] = "none", [1] = "none", [2] = "background", [3] = "previous" }
|
||||
local DISPOSE_CODE = { none = 1, background = 2, previous = 3 }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Gif.sniff(r: Bytes.Reader): number
|
||||
local s = r:peek(6)
|
||||
return if s == "GIF89a" or s == "GIF87a" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list
|
||||
local function colorTable(b: buffer, p: number, n: number): (buffer, { { number } })
|
||||
local t = buffer.create(1024)
|
||||
local list = table.create(n)
|
||||
for i = 0, 255 do
|
||||
buffer.writeu32(t, i * 4, 0xFF000000)
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
local q = p + i * 3
|
||||
local r, g, bl = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2)
|
||||
buffer.writeu32(t, i * 4, r + g * 256 + bl * 65536 + 0xFF000000)
|
||||
list[i + 1] = { r, g, bl, 255 }
|
||||
end
|
||||
return t, list
|
||||
end
|
||||
|
||||
function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
local maxTotal = opts and opts.maxTotalPixels or 2 ^ 28
|
||||
local maxFrames = opts and opts.maxFrames or math.huge
|
||||
local sig = r:string(6)
|
||||
local cw, ch = r:u16le(), r:u16le()
|
||||
local flags, bg, aspect = r:u8(), r:u8(), r:u8()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if sig ~= "GIF89a" and sig ~= "GIF87a" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad signature", r.base)
|
||||
end
|
||||
if cw == 0 or ch == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "zero canvas size", r.base + 6)
|
||||
end
|
||||
if cw * ch > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", cw, ch, maxPixels))
|
||||
end
|
||||
local b = r.buf
|
||||
local gct: buffer? = nil
|
||||
local gpal: { { number } }? = nil
|
||||
if bit32.band(flags, 0x80) ~= 0 then
|
||||
local n = bit32.lshift(1, bit32.band(flags, 7) + 1)
|
||||
if not r:need(n * 3) then
|
||||
return nil, r.err
|
||||
end
|
||||
gct, gpal = colorTable(b, r.pos, n)
|
||||
r.pos += n * 3
|
||||
end
|
||||
local img = Types.Image.new(cw, ch, "rgba8")
|
||||
local frames: { Types.Frame } = {}
|
||||
local comments: { string } = {}
|
||||
local loops: number? = nil
|
||||
local total = 0
|
||||
-- the pending Graphic Control Extension
|
||||
local delay, dispose, trans = 0, 0, -1
|
||||
local truncated = false
|
||||
local interlacedAny = false
|
||||
local localTables = 0
|
||||
local minCode = 8
|
||||
local limit = r.limit
|
||||
-- the sub-blocks at r.pos: joined into one buffer (nil when they run past the end)
|
||||
local function subBlocks(): (buffer?, number)
|
||||
local p = r.pos
|
||||
local n = 0
|
||||
while true do
|
||||
if p >= limit then
|
||||
return nil, p
|
||||
end
|
||||
local len = readu8(b, p)
|
||||
if len == 0 then
|
||||
break
|
||||
end
|
||||
if p + 1 + len > limit then
|
||||
-- keep what is there: a truncated last block
|
||||
n += limit - p - 1
|
||||
p = limit
|
||||
local out = buffer.create(n)
|
||||
local q, o = r.pos, 0
|
||||
while q < limit do
|
||||
local l = math.min(readu8(b, q), limit - q - 1)
|
||||
buffer.copy(out, o, b, q + 1, l)
|
||||
o += l
|
||||
q += 1 + l
|
||||
end
|
||||
return out, -1
|
||||
end
|
||||
n += len
|
||||
p += 1 + len
|
||||
end
|
||||
local out = buffer.create(n)
|
||||
local q, o = r.pos, 0
|
||||
while q < p do
|
||||
local l = readu8(b, q)
|
||||
buffer.copy(out, o, b, q + 1, l)
|
||||
o += l
|
||||
q += 1 + l
|
||||
end
|
||||
return out, p + 1
|
||||
end
|
||||
local function skipBlocks(): boolean
|
||||
local p = r.pos
|
||||
while p < limit do
|
||||
local len = readu8(b, p)
|
||||
if len == 0 then
|
||||
r.pos = p + 1
|
||||
return true
|
||||
end
|
||||
p += 1 + len
|
||||
end
|
||||
r.pos = limit
|
||||
return false
|
||||
end
|
||||
while true do
|
||||
if r.pos >= limit then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
local intro = r:u8()
|
||||
if intro == 0x3B then
|
||||
break
|
||||
elseif intro == 0x21 then
|
||||
local label = r:u8()
|
||||
if r.err then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
local p = r.pos
|
||||
if label == 0xF9 and p + 6 <= limit and readu8(b, p) >= 4 then
|
||||
local f = readu8(b, p + 1)
|
||||
dispose = bit32.band(bit32.rshift(f, 2), 7)
|
||||
delay = readu8(b, p + 2) + readu8(b, p + 3) * 256
|
||||
trans = if bit32.band(f, 1) ~= 0 then readu8(b, p + 4) else -1
|
||||
elseif label == 0xFF and p + 15 <= limit and readu8(b, p) == 11 then
|
||||
local id = buffer.readstring(b, p + 1, 11)
|
||||
if (id == "NETSCAPE2.0" or id == "ANIMEXTS1.0") and readu8(b, p + 12) >= 3 and readu8(b, p + 13) == 1 then
|
||||
local rep = readu8(b, p + 14) + readu8(b, p + 15) * 256
|
||||
loops = if rep == 0 then 0 else rep + 1 -- the stored value repeats: plays = value + 1
|
||||
end
|
||||
elseif label == 0xFE then
|
||||
local data = subBlocks()
|
||||
if data then
|
||||
table.insert(comments, buffer.tostring(data))
|
||||
end
|
||||
end
|
||||
if not skipBlocks() then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
elseif intro == 0x2C then
|
||||
local fx, fy, fw, fh = r:u16le(), r:u16le(), r:u16le(), r:u16le()
|
||||
local f = r:u8()
|
||||
if r.err then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
if fw * fh > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("a %d x %d frame is over the %d pixel limit", fw, fh, maxPixels), r.pos)
|
||||
end
|
||||
total += fw * fh
|
||||
if total > maxTotal then
|
||||
return nil, Err.new(Err.LIMIT, string.format("the frames add up to over %d pixels", maxTotal), r.pos)
|
||||
end
|
||||
local pal = gct
|
||||
if bit32.band(f, 0x80) ~= 0 then
|
||||
local n = bit32.lshift(1, bit32.band(f, 7) + 1)
|
||||
if not r:need(n * 3) then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
pal = colorTable(b, r.pos, n)
|
||||
r.pos += n * 3
|
||||
localTables += 1
|
||||
end
|
||||
local interlaced = bit32.band(f, 0x40) ~= 0
|
||||
interlacedAny = interlacedAny or interlaced
|
||||
local mc = r:u8()
|
||||
if r.err then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
if mc < 1 or mc > 11 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad LZW minimum code size " .. mc, r.pos - 1)
|
||||
end
|
||||
minCode = mc
|
||||
local data, nextPos = subBlocks()
|
||||
if not data then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
local n = fw * fh
|
||||
local idx = buffer.create(n)
|
||||
local got, lerr = Lzw.decode(data, 0, buffer.len(data), idx, 0, n, "gif", mc)
|
||||
if got < n or nextPos < 0 then
|
||||
truncated = true -- the missing pixels stay index 0, as most decoders show them
|
||||
end
|
||||
local _ = lerr -- a corrupt code ends the frame early (kept: what was decoded is shown)
|
||||
local t = buffer.create(1024)
|
||||
if pal then
|
||||
buffer.copy(t, 0, pal)
|
||||
else
|
||||
-- no colour table at all: a grey ramp (what the spec leaves to the decoder)
|
||||
for i = 0, 255 do
|
||||
buffer.writeu32(t, i * 4, i + i * 256 + i * 65536 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
if trans >= 0 then
|
||||
buffer.writeu32(t, trans * 4, 0)
|
||||
end
|
||||
local fimg = Types.Image.new(fw, fh, "rgba8")
|
||||
Decode.toRgba(idx, fw, fh, interlaced, t, fimg.pixels)
|
||||
if #frames == 0 then
|
||||
Decode.draw(img.pixels, cw, ch, fimg.pixels, fx, fy, fw, fh)
|
||||
end
|
||||
table.insert(frames, {
|
||||
image = fimg,
|
||||
delay = delay / 100,
|
||||
x = fx,
|
||||
y = fy,
|
||||
dispose = DISPOSE[dispose] or "none",
|
||||
blend = if trans >= 0 then "over" else "source",
|
||||
} :: Types.Frame)
|
||||
delay, dispose, trans = 0, 0, -1
|
||||
if nextPos < 0 then
|
||||
break
|
||||
end
|
||||
r.pos = nextPos
|
||||
if #frames >= maxFrames then
|
||||
break
|
||||
end
|
||||
else
|
||||
-- junk between blocks: stop here, keeping what was read
|
||||
if #frames == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("bad block introducer 0x%02x", intro), r.pos - 1)
|
||||
end
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
end
|
||||
if #frames == 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "no image data", r.pos)
|
||||
end
|
||||
if #frames > 1 then
|
||||
img.frames = frames
|
||||
img.loops = loops or 1
|
||||
else
|
||||
img.loops = loops or 0
|
||||
end
|
||||
img.meta.palette = gpal
|
||||
img.meta.background = bg
|
||||
if #comments > 0 then
|
||||
img.meta.text = { comment = table.concat(comments, "\n") }
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.source = {
|
||||
format = "gif",
|
||||
version = string.sub(sig, 4),
|
||||
bitDepth = minCode,
|
||||
colorType = "palette",
|
||||
frames = #frames,
|
||||
interlaced = interlacedAny,
|
||||
localPalettes = localTables,
|
||||
aspect = aspect,
|
||||
loopExtension = loops ~= nil,
|
||||
}
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function validImage(i: any): boolean
|
||||
return type(i) == "table" and i.format == "rgba8" and type(i.pixels) == "buffer" and type(i.width) == "number" and type(i.height) == "number" and i.width >= 1 and i.height >= 1 and i.width <= 65535 and i.height <= 65535 and i.width % 1 == 0 and i.height % 1 == 0 and buffer.len(i.pixels) >= i.width * i.height * 4
|
||||
end
|
||||
|
||||
local function hasTransparency(px: buffer, n: number): boolean
|
||||
for i = 0, n - 1 do
|
||||
if readu8(px, i * 4 + 3) < 128 then
|
||||
return true
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- palette list -> padded table bytes (power of two entries, >= 2) and its size code
|
||||
local function writeTable(w: Bytes.Writer, pal: { { number } }): number
|
||||
local bits = 1
|
||||
while bit32.lshift(1, bits) < #pal do
|
||||
bits += 1
|
||||
end
|
||||
for i = 1, bit32.lshift(1, bits) do
|
||||
local c = pal[i]
|
||||
if c then
|
||||
w:u8(c[1])
|
||||
w:u8(c[2])
|
||||
w:u8(c[3])
|
||||
else
|
||||
w:fill(0, 3)
|
||||
end
|
||||
end
|
||||
return bits
|
||||
end
|
||||
|
||||
local function tableBits(n: number): number
|
||||
local bits = 1
|
||||
while bit32.lshift(1, bits) < n do
|
||||
bits += 1
|
||||
end
|
||||
return bits
|
||||
end
|
||||
|
||||
function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if not validImage(img) then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image of 1..65535 x 1..65535 pixels")
|
||||
end
|
||||
local maxColors = opts and opts.maxColors or 256
|
||||
if type(maxColors) ~= "number" or maxColors < 2 or maxColors > 256 then
|
||||
return nil, Err.new(Err.ARG, "maxColors must be 2..256")
|
||||
end
|
||||
maxColors = math.floor(maxColors)
|
||||
local method = opts and opts.method or "mediancut"
|
||||
if method ~= "mediancut" and method ~= "octree" then
|
||||
return nil, Err.new(Err.ARG, "method must be mediancut or octree")
|
||||
end
|
||||
local dither = opts and opts.dither or false
|
||||
-- the frames to write: { image, x, y, delay, dispose }
|
||||
local list: { Types.Frame } = {}
|
||||
if type(img.frames) == "table" and #(img.frames :: any) > 0 then
|
||||
for i, f in img.frames :: { Types.Frame } do
|
||||
if type(f) ~= "table" or not validImage(f.image) then
|
||||
return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image")
|
||||
end
|
||||
local x, y = f.x or 0, f.y or 0
|
||||
if type(x) ~= "number" or type(y) ~= "number" or x < 0 or y < 0 or x + f.image.width > 65535 or y + f.image.height > 65535 then
|
||||
return nil, Err.new(Err.ARG, "frame " .. i .. ": bad position")
|
||||
end
|
||||
table.insert(list, f)
|
||||
end
|
||||
else
|
||||
list[1] = { image = img, x = 0, y = 0, delay = 0, dispose = "none", blend = "source" }
|
||||
end
|
||||
local animated = #list > 1
|
||||
local loops = opts and opts.loops or img.loops or 0
|
||||
if type(loops) ~= "number" or loops < 0 or loops > 65536 or loops % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "loops must be 0..65536")
|
||||
end
|
||||
-- palettes
|
||||
local shared = (opts and opts.globalPalette) or not animated
|
||||
local qopts = { method = method, dither = dither }
|
||||
local globalPal: { { number } }? = nil
|
||||
local globalTrans = false
|
||||
if shared then
|
||||
-- every frame's pixels together
|
||||
local npx = 0
|
||||
for _, f in list do
|
||||
npx += f.image.width * f.image.height
|
||||
end
|
||||
local all = buffer.create(npx * 4)
|
||||
local o = 0
|
||||
for _, f in list do
|
||||
local n = f.image.width * f.image.height * 4
|
||||
buffer.copy(all, o, f.image.pixels, 0, n)
|
||||
o += n
|
||||
end
|
||||
globalTrans = hasTransparency(all, npx)
|
||||
local pal = Quantize.palette(all, npx, 1, if globalTrans then maxColors - 1 else maxColors, qopts)
|
||||
if #pal == 0 then
|
||||
pal = { { 0, 0, 0, 255 } }
|
||||
end
|
||||
if globalTrans then
|
||||
table.insert(pal, { 0, 0, 0, 0 })
|
||||
end
|
||||
globalPal = pal
|
||||
end
|
||||
local w = Bytes.writer(img.width * img.height + 1024)
|
||||
w:string("GIF89a")
|
||||
w:u16le(img.width)
|
||||
w:u16le(img.height)
|
||||
if globalPal then
|
||||
w:u8(0x80 + 0x70 + (tableBits(#globalPal) - 1))
|
||||
w:u8(0)
|
||||
w:u8(0)
|
||||
writeTable(w, globalPal)
|
||||
else
|
||||
w:u8(0x70)
|
||||
w:u8(0)
|
||||
w:u8(0)
|
||||
end
|
||||
if animated and loops ~= 1 then
|
||||
w:u8(0x21)
|
||||
w:u8(0xFF)
|
||||
w:u8(11)
|
||||
w:string("NETSCAPE2.0")
|
||||
w:u8(3)
|
||||
w:u8(1)
|
||||
w:u16le(if loops == 0 then 0 else loops - 1)
|
||||
w:u8(0)
|
||||
end
|
||||
local text = img.meta and img.meta.text
|
||||
local comment = text and (text.comment or text.Comment)
|
||||
if type(comment) == "string" and #comment > 0 then
|
||||
w:u8(0x21)
|
||||
w:u8(0xFE)
|
||||
for i = 1, #comment, 255 do
|
||||
local part = string.sub(comment, i, i + 254)
|
||||
w:u8(#part)
|
||||
w:string(part)
|
||||
end
|
||||
w:u8(0)
|
||||
end
|
||||
for _, f in list do
|
||||
local fi = f.image
|
||||
local fw, fh = fi.width, fi.height
|
||||
local n = fw * fh
|
||||
local pal: { { number } }
|
||||
local tidx: number? = nil
|
||||
if globalPal then
|
||||
pal = globalPal
|
||||
if globalTrans then
|
||||
tidx = #pal - 1
|
||||
end
|
||||
else
|
||||
local tr = hasTransparency(fi.pixels, n)
|
||||
pal = Quantize.palette(fi.pixels, fw, fh, if tr then maxColors - 1 else maxColors, qopts)
|
||||
if #pal == 0 then
|
||||
pal = { { 0, 0, 0, 255 } }
|
||||
end
|
||||
if tr then
|
||||
table.insert(pal, { 0, 0, 0, 0 })
|
||||
tidx = #pal - 1
|
||||
end
|
||||
end
|
||||
local idx = Quantize.map(fi.pixels, fw, fh, pal, { dither = dither, transparentIndex = tidx })
|
||||
-- the Graphic Control Extension: always for animations, else only for transparency
|
||||
if animated or tidx then
|
||||
local d = DISPOSE_CODE[f.dispose or "none"] or 1
|
||||
w:u8(0x21)
|
||||
w:u8(0xF9)
|
||||
w:u8(4)
|
||||
w:u8(d * 4 + (if tidx then 1 else 0))
|
||||
w:u16le(math.clamp(math.floor((f.delay or 0) * 100 + 0.5), 0, 65535))
|
||||
w:u8(tidx or 0)
|
||||
w:u8(0)
|
||||
end
|
||||
w:u8(0x2C)
|
||||
w:u16le(f.x or 0)
|
||||
w:u16le(f.y or 0)
|
||||
w:u16le(fw)
|
||||
w:u16le(fh)
|
||||
local bits
|
||||
if globalPal then
|
||||
w:u8(0)
|
||||
bits = tableBits(#globalPal)
|
||||
else
|
||||
bits = tableBits(#pal)
|
||||
w:u8(0x80 + bits - 1)
|
||||
writeTable(w, pal)
|
||||
end
|
||||
local mc = math.max(2, bits)
|
||||
w:u8(mc)
|
||||
local codes = Lzw.encode(idx, 0, n, "gif", mc)
|
||||
local cl = buffer.len(codes)
|
||||
local p = 0
|
||||
while p < cl do
|
||||
local l = math.min(255, cl - p)
|
||||
w:u8(l)
|
||||
w:bytes(codes, p, l)
|
||||
p += l
|
||||
end
|
||||
w:u8(0)
|
||||
end
|
||||
w:u8(0x3B)
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
return Gif
|
||||
@@ -0,0 +1,219 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/hdr/Codec: Radiance RGBE scanlines (native; never throws). Written from the Radiance file format notes
|
||||
-- (Greg Ward, "Real Pixels", Graphics Gems II) and Bruce Walter's rgbe.c conventions: flat pixels, old-style RLE
|
||||
-- (1, 1, 1, n repeats the previous pixel, shifted by 8 for consecutive markers) and new-style RLE (2, 2, width, then
|
||||
-- four run-length coded channel planes). RGBE -> float is mantissa * 2^(e - 136), as rgbe.c, stb_image and
|
||||
-- ImageMagick (no +0.5 offset); float -> RGBE as rgbe.c float2rgbe (frexp). Every read is bounds-checked.
|
||||
local readu8, writeu8, writef32, readf32 = buffer.readu8, buffer.writeu8, buffer.writef32, buffer.readf32
|
||||
local frexp = math.frexp
|
||||
|
||||
local Codec = {}
|
||||
|
||||
-- readLine(b, p, limit, w, row) -> new position | nil, message: one scanline into row (w * 4 RGBE bytes)
|
||||
function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buffer): (number?, string?)
|
||||
if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then
|
||||
if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then
|
||||
return nil, "scanline width mismatch"
|
||||
end
|
||||
p += 4
|
||||
for c = 0, 3 do
|
||||
local x = 0
|
||||
while x < w do
|
||||
if p >= limit then
|
||||
return nil, "truncated"
|
||||
end
|
||||
local n = readu8(b, p)
|
||||
p += 1
|
||||
if n > 128 then
|
||||
n -= 128
|
||||
if x + n > w or p >= limit then
|
||||
return nil, if p >= limit then "truncated" else "bad run"
|
||||
end
|
||||
local v = readu8(b, p)
|
||||
p += 1
|
||||
for i = x, x + n - 1 do
|
||||
writeu8(row, i * 4 + c, v)
|
||||
end
|
||||
else
|
||||
if n == 0 or x + n > w then
|
||||
return nil, "bad count"
|
||||
end
|
||||
if p + n > limit then
|
||||
return nil, "truncated"
|
||||
end
|
||||
for i = x, x + n - 1 do
|
||||
writeu8(row, i * 4 + c, readu8(b, p))
|
||||
p += 1
|
||||
end
|
||||
end
|
||||
x += n
|
||||
end
|
||||
end
|
||||
return p, nil
|
||||
end
|
||||
-- flat pixels, with old-style runs
|
||||
local x = 0
|
||||
local shift = 0
|
||||
while x < w do
|
||||
if p + 4 > limit then
|
||||
return nil, "truncated"
|
||||
end
|
||||
local r, g, bl, e = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3)
|
||||
p += 4
|
||||
if r == 1 and g == 1 and bl == 1 then
|
||||
if x == 0 then
|
||||
return nil, "run at the start of a scanline"
|
||||
end
|
||||
local n = e * 2 ^ shift
|
||||
if x + n > w then
|
||||
return nil, "bad run"
|
||||
end
|
||||
local q = (x - 1) * 4
|
||||
local pr, pg, pb, pe = readu8(row, q), readu8(row, q + 1), readu8(row, q + 2), readu8(row, q + 3)
|
||||
for i = x, x + n - 1 do
|
||||
writeu8(row, i * 4, pr)
|
||||
writeu8(row, i * 4 + 1, pg)
|
||||
writeu8(row, i * 4 + 2, pb)
|
||||
writeu8(row, i * 4 + 3, pe)
|
||||
end
|
||||
x += n
|
||||
shift += 8
|
||||
if shift > 24 then
|
||||
return nil, "bad run"
|
||||
end
|
||||
else
|
||||
writeu8(row, x * 4, r)
|
||||
writeu8(row, x * 4 + 1, g)
|
||||
writeu8(row, x * 4 + 2, bl)
|
||||
writeu8(row, x * 4 + 3, e)
|
||||
x += 1
|
||||
shift = 0
|
||||
end
|
||||
end
|
||||
return p, nil
|
||||
end
|
||||
|
||||
-- toFloat(row, n, out, offsets): n RGBE pixels -> rgbaf32 at out byte offsets dest(i) = base + i * step
|
||||
function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: number)
|
||||
for i = 0, n - 1 do
|
||||
local q = i * 4
|
||||
local e = readu8(row, q + 3)
|
||||
local o = base + i * step
|
||||
if e == 0 then
|
||||
writef32(out, o, 0)
|
||||
writef32(out, o + 4, 0)
|
||||
writef32(out, o + 8, 0)
|
||||
else
|
||||
local f = 2 ^ (e - 136)
|
||||
writef32(out, o, readu8(row, q) * f)
|
||||
writef32(out, o + 4, readu8(row, q + 1) * f)
|
||||
writef32(out, o + 8, readu8(row, q + 2) * f)
|
||||
end
|
||||
writef32(out, o + 12, 1)
|
||||
end
|
||||
end
|
||||
|
||||
-- fromFloat(px, y, w, row): row y of an rgbaf32 image -> w RGBE pixels (rgbe.c float2rgbe)
|
||||
function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer)
|
||||
for x = 0, w - 1 do
|
||||
local q = (y * w + x) * 16
|
||||
local r, g, b = readf32(px, q), readf32(px, q + 4), readf32(px, q + 8)
|
||||
if r ~= r or r < 0 then
|
||||
r = 0
|
||||
end
|
||||
if g ~= g or g < 0 then
|
||||
g = 0
|
||||
end
|
||||
if b ~= b or b < 0 then
|
||||
b = 0
|
||||
end
|
||||
local v = math.max(r, g, b)
|
||||
local o = x * 4
|
||||
if v < 1e-32 or v == math.huge then
|
||||
if v == math.huge then
|
||||
-- clamp infinities to the largest RGBE value
|
||||
writeu8(row, o, if r == math.huge then 255 else 0)
|
||||
writeu8(row, o + 1, if g == math.huge then 255 else 0)
|
||||
writeu8(row, o + 2, if b == math.huge then 255 else 0)
|
||||
writeu8(row, o + 3, 255)
|
||||
else
|
||||
writeu8(row, o, 0)
|
||||
writeu8(row, o + 1, 0)
|
||||
writeu8(row, o + 2, 0)
|
||||
writeu8(row, o + 3, 0)
|
||||
end
|
||||
else
|
||||
local m, e = frexp(v)
|
||||
if e > 127 then
|
||||
writeu8(row, o, 255)
|
||||
writeu8(row, o + 1, 255)
|
||||
writeu8(row, o + 2, 255)
|
||||
writeu8(row, o + 3, 255)
|
||||
else
|
||||
local s = m * 256 / v
|
||||
writeu8(row, o, math.min(255, math.floor(r * s)))
|
||||
writeu8(row, o + 1, math.min(255, math.floor(g * s)))
|
||||
writeu8(row, o + 2, math.min(255, math.floor(b * s)))
|
||||
writeu8(row, o + 3, e + 128)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- writeLine(row, w, out, o) -> new offset: new-style RLE (rgbe.c RGBE_WriteBytes_RLE); out needs w * 4 + w + 8
|
||||
function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number
|
||||
writeu8(out, o, 2)
|
||||
writeu8(out, o + 1, 2)
|
||||
writeu8(out, o + 2, w // 256)
|
||||
writeu8(out, o + 3, w % 256)
|
||||
o += 4
|
||||
for c = 0, 3 do
|
||||
local cur = 0
|
||||
while cur < w do
|
||||
-- find the next run of at least 4
|
||||
local begRun = cur
|
||||
local runCount = 0
|
||||
local oldRun = 0
|
||||
while runCount < 4 and begRun < w do
|
||||
begRun += runCount
|
||||
oldRun = runCount
|
||||
runCount = 1
|
||||
if begRun < w then
|
||||
local v = readu8(row, begRun * 4 + c)
|
||||
while begRun + runCount < w and runCount < 127 and readu8(row, (begRun + runCount) * 4 + c) == v do
|
||||
runCount += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
-- a short run just before the long one
|
||||
if oldRun > 1 and oldRun == begRun - cur then
|
||||
writeu8(out, o, 128 + oldRun)
|
||||
writeu8(out, o + 1, readu8(row, cur * 4 + c))
|
||||
o += 2
|
||||
cur = begRun
|
||||
end
|
||||
-- raw bytes up to the run
|
||||
while cur < begRun do
|
||||
local n = math.min(begRun - cur, 128)
|
||||
writeu8(out, o, n)
|
||||
o += 1
|
||||
for i = cur, cur + n - 1 do
|
||||
writeu8(out, o, readu8(row, i * 4 + c))
|
||||
o += 1
|
||||
end
|
||||
cur += n
|
||||
end
|
||||
if runCount >= 4 then
|
||||
writeu8(out, o, 128 + runCount)
|
||||
writeu8(out, o + 1, readu8(row, begRun * 4 + c))
|
||||
o += 2
|
||||
cur += runCount
|
||||
end
|
||||
end
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
return Codec
|
||||
@@ -0,0 +1,234 @@
|
||||
--!strict
|
||||
-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), written from the Radiance file format notes and rgbe.c conventions.
|
||||
-- Decode: "#?RADIANCE" / "#?RGBE" (any "#?" program name) headers, FORMAT=32-bit_rle_rgbe, EXPOSURE (the product of
|
||||
-- every EXPOSURE line, kept in meta.exposure, not applied), other header lines in meta.text, the eight resolution
|
||||
-- orientations (-Y +X standard, +Y, -X and the X-major ones), flat, old-style RLE and new-style RLE scanlines.
|
||||
-- opts.native gives the linear rgbaf32 values (alpha 1); the default rgba8 is a display conversion:
|
||||
-- round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) per channel. Encode: rgbaf32 (or rgba8 through the inverse curve) to a
|
||||
-- -Y +X file with new-style RLE (flat scanlines for widths outside 8..32767).
|
||||
-- Not supported: FORMAT=32-bit_rle_xyze (CIE XYZ files: UNSUPPORTED), PRIMARIES / COLORCORR (ignored).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Codec = require("@formats/image/hdr/Codec")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Hdr = {
|
||||
name = "hdr",
|
||||
category = "image",
|
||||
extensions = { "hdr", "pic", "rgbe" },
|
||||
mime = { "image/vnd.radiance", "image/x-hdr" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
rle: boolean?, -- new-style RLE scanlines (default true)
|
||||
exposure: number?, -- write an EXPOSURE line (default meta.exposure when not 1)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local GAMMA = 1 / 2.2
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Hdr.sniff(r: Bytes.Reader): number
|
||||
local s = r:peek(10)
|
||||
if s == "#?RADIANCE" then
|
||||
return 1
|
||||
end
|
||||
if string.sub(s, 1, 6) == "#?RGBE" then
|
||||
return 1
|
||||
end
|
||||
if string.sub(s, 1, 2) == "#?" and string.match(s, "^#%?%u") then
|
||||
return 0.5
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
local b, limit = r.buf, r.limit
|
||||
local p = r.base
|
||||
-- header lines up to the first empty one
|
||||
local function line(): string?
|
||||
local s = p
|
||||
while p < limit and buffer.readu8(b, p) ~= 10 do
|
||||
p += 1
|
||||
end
|
||||
if p >= limit then
|
||||
return nil
|
||||
end
|
||||
local l = buffer.readstring(b, s, p - s)
|
||||
p += 1
|
||||
return l
|
||||
end
|
||||
local first = line()
|
||||
if not first or string.sub(first, 1, 2) ~= "#?" then
|
||||
return nil, Err.new(Err.CORRUPT, "not a Radiance file (no #? line)", r.base)
|
||||
end
|
||||
local exposure = 1
|
||||
local format = nil
|
||||
local text: { [string]: string } = {}
|
||||
while true do
|
||||
local l = line()
|
||||
if l == nil then
|
||||
return nil, Err.new(Err.TRUNCATED, "header ends early", p)
|
||||
end
|
||||
l = string.gsub(l, "\r$", "")
|
||||
if l == "" then
|
||||
break
|
||||
end
|
||||
local k, v = string.match(l, "^%s*([%w_%-]+)%s*=%s*(.-)%s*$")
|
||||
if k == "FORMAT" then
|
||||
format = v
|
||||
elseif k == "EXPOSURE" then
|
||||
local e = tonumber(v)
|
||||
if e and e > 0 then
|
||||
exposure *= e
|
||||
end
|
||||
elseif k then
|
||||
text[k] = v :: string
|
||||
end
|
||||
end
|
||||
if format and format ~= "32-bit_rle_rgbe" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "FORMAT=" .. format)
|
||||
end
|
||||
local res = line()
|
||||
if not res then
|
||||
return nil, Err.new(Err.TRUNCATED, "no resolution line", p)
|
||||
end
|
||||
local s1, a1, n1, s2, a2, n2 = string.match(res, "^%s*([%+%-])([XY])%s+(%d+)%s+([%+%-])([XY])%s+(%d+)%s*$")
|
||||
if not s1 or a1 == a2 or #n1 > 9 or #n2 > 9 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad resolution line", p)
|
||||
end
|
||||
local outer, inner = tonumber(n1) :: number, tonumber(n2) :: number
|
||||
local w, h = if a1 == "Y" then inner else outer, if a1 == "Y" then outer else inner
|
||||
if w < 1 or h < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "zero size")
|
||||
end
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgbaf32")
|
||||
local px = img.pixels
|
||||
local row = buffer.create(inner * 4)
|
||||
local truncated = false
|
||||
for i = 0, outer - 1 do
|
||||
local np, err = Codec.readLine(b, p, limit, inner, row)
|
||||
if not np then
|
||||
if err == "truncated" then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, tostring(err), p)
|
||||
end
|
||||
p = np
|
||||
-- where scanline i, pixel j lands: Y decreasing ("-Y") = top first, X increasing ("+X") = left first
|
||||
local base, step
|
||||
if a1 == "Y" then
|
||||
local y = if s1 == "-" then i else h - 1 - i
|
||||
if s2 == "+" then
|
||||
base, step = y * w * 16, 16
|
||||
else
|
||||
base, step = (y * w + w - 1) * 16, -16
|
||||
end
|
||||
else
|
||||
local x = if s1 == "+" then i else w - 1 - i
|
||||
if s2 == "-" then
|
||||
base, step = x * 16, w * 16
|
||||
else
|
||||
base, step = ((h - 1) * w + x) * 16, -w * 16
|
||||
end
|
||||
end
|
||||
Codec.toFloat(row, inner, px, base, step)
|
||||
end
|
||||
if not (opts and opts.native) then
|
||||
local o = Types.Image.new(w, h, "rgba8")
|
||||
for i = 0, w * h - 1 do
|
||||
for c = 0, 2 do
|
||||
local v = buffer.readf32(px, i * 16 + c * 4)
|
||||
buffer.writeu8(o.pixels, i * 4 + c, math.floor(math.clamp(v, 0, 1) ^ GAMMA * 255 + 0.5))
|
||||
end
|
||||
buffer.writeu8(o.pixels, i * 4 + 3, 255)
|
||||
end
|
||||
o.meta = img.meta
|
||||
img = o
|
||||
end
|
||||
img.meta.exposure = exposure
|
||||
img.meta.colorSpace = "linear"
|
||||
if next(text) then
|
||||
img.meta.text = text
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.source = { format = "hdr", bitDepth = 32, colorType = "rgbe", program = string.sub(first, 3), orientation = string.format("%s%s %s%s", s1, a1, s2, a2) }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Hdr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then
|
||||
return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
local bpp = if img.format == "rgbaf32" then 16 else 4
|
||||
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
|
||||
return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
|
||||
end
|
||||
local o: any = opts or {}
|
||||
local px = img.pixels
|
||||
if bpp == 4 then
|
||||
-- rgba8 through the inverse of the decoder's display curve
|
||||
local lut = table.create(256, 0)
|
||||
for v = 0, 255 do
|
||||
lut[v + 1] = (v / 255) ^ 2.2
|
||||
end
|
||||
px = buffer.create(w * h * 16)
|
||||
for i = 0, w * h - 1 do
|
||||
for c = 0, 2 do
|
||||
buffer.writef32(px, i * 16 + c * 4, lut[buffer.readu8(img.pixels, i * 4 + c) + 1])
|
||||
end
|
||||
buffer.writef32(px, i * 16 + 12, 1)
|
||||
end
|
||||
end
|
||||
local exposure = o.exposure or (img.meta and img.meta.exposure)
|
||||
local head = "#?RADIANCE\n# written by formats-luau\nFORMAT=32-bit_rle_rgbe\n"
|
||||
if type(exposure) == "number" and exposure > 0 and exposure ~= 1 then
|
||||
head ..= string.format("EXPOSURE=%.9g\n", exposure)
|
||||
end
|
||||
head ..= string.format("\n-Y %d +X %d\n", h, w)
|
||||
local rle = o.rle ~= false and w >= 8 and w <= 32767
|
||||
local out = buffer.create(#head + h * (w * 5 + 8))
|
||||
buffer.writestring(out, 0, head)
|
||||
local op = #head
|
||||
local row = buffer.create(w * 4)
|
||||
for y = 0, h - 1 do
|
||||
Codec.fromFloat(px, y, w, row)
|
||||
if rle then
|
||||
op = Codec.writeLine(row, w, out, op)
|
||||
else
|
||||
buffer.copy(out, op, row, 0, w * 4)
|
||||
for x = 0, w - 1 do
|
||||
-- 1, 1, 1 would read as an old-style run marker
|
||||
if buffer.readu8(out, op + x * 4) == 1 and buffer.readu8(out, op + x * 4 + 1) == 1 and buffer.readu8(out, op + x * 4 + 2) == 1 then
|
||||
buffer.writeu8(out, op + x * 4 + 2, 0)
|
||||
end
|
||||
end
|
||||
op += w * 4
|
||||
end
|
||||
end
|
||||
local res = buffer.create(op)
|
||||
buffer.copy(res, 0, out, 0, op)
|
||||
return res, nil
|
||||
end
|
||||
|
||||
return Hdr
|
||||
@@ -0,0 +1,106 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from
|
||||
-- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit
|
||||
-- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha
|
||||
-- channel unless it is all zero (old icons), in which case the AND mask decides.
|
||||
local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32
|
||||
|
||||
local Dib = {}
|
||||
|
||||
-- decode(b, p, e, w, h, bpp, pal, palN, out) -> ok, message: the XOR + AND bitmaps at b[p, e) into rgba8 out
|
||||
function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?)
|
||||
local stride = ((w * bpp + 31) // 32) * 4
|
||||
local maskStride = ((w + 31) // 32) * 4
|
||||
if p + stride * h > e then
|
||||
return false, "colour bitmap runs past the entry"
|
||||
end
|
||||
local hasMask = p + stride * h + maskStride * h <= e
|
||||
local anyAlpha = false
|
||||
for y = 0, h - 1 do
|
||||
local row = p + (h - 1 - y) * stride
|
||||
for x = 0, w - 1 do
|
||||
local v
|
||||
if bpp == 32 then
|
||||
v = readu8(b, row + x * 4 + 2) + readu8(b, row + x * 4 + 1) * 256 + readu8(b, row + x * 4) * 65536 + readu8(b, row + x * 4 + 3) * 16777216
|
||||
if v >= 16777216 then
|
||||
anyAlpha = true
|
||||
end
|
||||
elseif bpp == 24 then
|
||||
v = readu8(b, row + x * 3 + 2) + readu8(b, row + x * 3 + 1) * 256 + readu8(b, row + x * 3) * 65536 + 0xFF000000
|
||||
elseif bpp == 16 then
|
||||
local s = readu16(b, row + x * 2)
|
||||
local r, g, bl = (s // 1024) % 32, (s // 32) % 32, s % 32
|
||||
v = (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + 0xFF000000
|
||||
else
|
||||
local bit = x * bpp
|
||||
local byte = readu8(b, row + bit // 8)
|
||||
local idx = (byte // 2 ^ (8 - bpp - bit % 8)) % 2 ^ bpp
|
||||
v = if idx < palN then readu32(pal, idx * 4) else 0xFF000000
|
||||
end
|
||||
writeu32(out, (y * w + x) * 4, v)
|
||||
end
|
||||
end
|
||||
if bpp == 32 and anyAlpha then
|
||||
return true, nil
|
||||
end
|
||||
if hasMask then
|
||||
local mp = p + stride * h
|
||||
for y = 0, h - 1 do
|
||||
local row = mp + (h - 1 - y) * maskStride
|
||||
for x = 0, w - 1 do
|
||||
local o = (y * w + x) * 4
|
||||
local px = readu32(out, o) % 16777216
|
||||
if (readu8(b, row + x // 8) // 2 ^ (7 - x % 8)) % 2 == 1 then
|
||||
writeu32(out, o, px) -- transparent
|
||||
else
|
||||
writeu32(out, o, px + 0xFF000000)
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif bpp == 32 then
|
||||
-- no alpha and no mask: opaque
|
||||
for i = 0, w * h - 1 do
|
||||
writeu32(out, i * 4, readu32(out, i * 4) % 16777216 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- encode(px, w, h, out, o) -> new offset: rgba8 as a 32-bit BGRA bitmap (bottom-up) + an AND mask (alpha 0 = 1).
|
||||
-- out needs room for w * h * 4 + maskStride * h bytes.
|
||||
function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number
|
||||
for y = h - 1, 0, -1 do
|
||||
for x = 0, w - 1 do
|
||||
local q = (y * w + x) * 4
|
||||
buffer.writeu8(out, o, readu8(px, q + 2))
|
||||
buffer.writeu8(out, o + 1, readu8(px, q + 1))
|
||||
buffer.writeu8(out, o + 2, readu8(px, q))
|
||||
buffer.writeu8(out, o + 3, readu8(px, q + 3))
|
||||
o += 4
|
||||
end
|
||||
end
|
||||
local maskStride = ((w + 31) // 32) * 4
|
||||
for y = h - 1, 0, -1 do
|
||||
local acc, nb, written = 0, 0, 0
|
||||
for x = 0, w - 1 do
|
||||
acc = acc * 2 + (if readu8(px, (y * w + x) * 4 + 3) == 0 then 1 else 0)
|
||||
nb += 1
|
||||
if nb == 8 then
|
||||
buffer.writeu8(out, o + written, acc)
|
||||
written += 1
|
||||
acc, nb = 0, 0
|
||||
end
|
||||
end
|
||||
if nb > 0 then
|
||||
buffer.writeu8(out, o + written, acc * 2 ^ (8 - nb))
|
||||
written += 1
|
||||
end
|
||||
buffer.fill(out, o + written, 0, maskStride - written)
|
||||
o += maskStride
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
return Dib
|
||||
@@ -0,0 +1,282 @@
|
||||
--!strict
|
||||
-- image/ico: Windows icons and cursors (ICO / CUR), written from Microsoft's ICO format documentation. Decode: every
|
||||
-- directory entry, as a BMP DIB (1 / 4 / 8 / 16 / 24 / 32-bit with a colour table and the AND mask; 32-bit alpha) or
|
||||
-- an embedded PNG, decoded through the api hook opts.decodeImage (F.load supplies it; without it PNG entries are
|
||||
-- skipped, and a file of PNG entries only returns UNSUPPORTED). The image is the largest entry (then the deepest);
|
||||
-- img.frames lists every decoded entry in file order (Types.Frame, each frame image with meta.source.bitDepth / png
|
||||
-- and, for cursors, meta.hotspot = { x, y }). Encode: the image, or every img.frames image (each up to 256 x 256), as
|
||||
-- 32-bit DIB entries with an AND mask; 256-pixel entries (or all with opts.png) as PNG through opts.encodeImage when it
|
||||
-- is there; a cursor (CUR) with opts.cursor or when the image has meta.hotspot.
|
||||
-- Not supported: resizing to a set of icon sizes (do that with ops/ImageOps first), DIB compression (BI_BITFIELDS
|
||||
-- 16 / 32-bit is read as 5-5-5 / BGRA), the obsolete 2-colour planes.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Dib = require("@formats/image/ico/Dib")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ico = {
|
||||
name = "ico",
|
||||
category = "image",
|
||||
extensions = { "ico", "cur" },
|
||||
mime = { "image/vnd.microsoft.icon", "image/x-icon" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one)
|
||||
maxPixels: number?, -- refuse larger entries (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one)
|
||||
png: boolean?, -- every entry as PNG (needs encodeImage; default: only 256-pixel entries, when it exists)
|
||||
cursor: boolean?, -- write a CUR (default: when the image has meta.hotspot)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local PNG_SIG = "\137PNG\r\n\26\n"
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ico.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 22 then
|
||||
return 0
|
||||
end
|
||||
local b, o = r.buf, r.pos
|
||||
local typ = buffer.readu16(b, o + 2)
|
||||
local count = buffer.readu16(b, o + 4)
|
||||
if buffer.readu16(b, o) ~= 0 or (typ ~= 1 and typ ~= 2) or count == 0 then
|
||||
return 0
|
||||
end
|
||||
-- the first entry: reserved byte 0, a size and offset inside the file
|
||||
local size, off = buffer.readu32(b, o + 14), buffer.readu32(b, o + 18)
|
||||
if readu8(b, o + 9) ~= 0 or size == 0 or off < 6 + count * 16 then
|
||||
return 0
|
||||
end
|
||||
return 0.8
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function le16(b: buffer, p: number): number
|
||||
return buffer.readu16(b, p)
|
||||
end
|
||||
local function le32(b: buffer, p: number): number
|
||||
return buffer.readu32(b, p)
|
||||
end
|
||||
|
||||
function Ico.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
local decodeImage = opts and opts.decodeImage
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
if limit - base < 6 then
|
||||
return nil, Err.new(Err.TRUNCATED, "short header", base)
|
||||
end
|
||||
local typ, count = le16(b, base + 2), le16(b, base + 4)
|
||||
if le16(b, base) ~= 0 or (typ ~= 1 and typ ~= 2) then
|
||||
return nil, Err.new(Err.CORRUPT, "not an ICO / CUR file", base)
|
||||
end
|
||||
if count == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no images", base)
|
||||
end
|
||||
if base + 6 + count * 16 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "directory runs past the end", base)
|
||||
end
|
||||
local frames: { Types.Frame } = {}
|
||||
local best: Types.Image? = nil
|
||||
local bestScore = -1
|
||||
local skipped, lastErr = 0, nil :: Err.Err?
|
||||
for i = 0, count - 1 do
|
||||
local d = base + 6 + i * 16
|
||||
local dw, dh = readu8(b, d), readu8(b, d + 1)
|
||||
dw = if dw == 0 then 256 else dw
|
||||
dh = if dh == 0 then 256 else dh
|
||||
local f1, f2 = le16(b, d + 4), le16(b, d + 6)
|
||||
local size, off = le32(b, d + 8), le32(b, d + 12)
|
||||
local p, e = base + off, base + off + size
|
||||
local img: Types.Image? = nil
|
||||
local depth = 0
|
||||
local isPng = false
|
||||
if off < 6 or p >= limit then
|
||||
lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " lies past the end", d)
|
||||
else
|
||||
e = math.min(e, limit)
|
||||
if e - p >= 8 and buffer.readstring(b, p, 8) == PNG_SIG then
|
||||
isPng = true
|
||||
depth = 32
|
||||
if decodeImage then
|
||||
local sub = buffer.create(e - p)
|
||||
buffer.copy(sub, 0, b, p, e - p)
|
||||
local ok, pimg, perr = pcall(decodeImage, sub)
|
||||
if ok and pimg and pimg.format == "rgba8" then
|
||||
img = pimg
|
||||
else
|
||||
lastErr = if ok and perr then perr else Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad PNG")
|
||||
end
|
||||
else
|
||||
lastErr = Err.new(Err.UNSUPPORTED, "PNG entries need opts.decodeImage (F.load passes it)")
|
||||
end
|
||||
elseif e - p >= 40 then
|
||||
local hs = le32(b, p)
|
||||
local bw = buffer.readi32(b, p + 4)
|
||||
local bh = buffer.readi32(b, p + 8)
|
||||
local bpp = le16(b, p + 14)
|
||||
local clrUsed = le32(b, p + 32)
|
||||
local w = if bw > 0 then bw else dw
|
||||
local h = if bh ~= 0 then math.abs(bh) // 2 else dh
|
||||
if hs < 12 or hs > e - p or w < 1 or h < 1 or w > 4096 or h > 4096 then
|
||||
lastErr = Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad bitmap header", p)
|
||||
elseif bpp ~= 1 and bpp ~= 4 and bpp ~= 8 and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then
|
||||
lastErr = Err.new(Err.UNSUPPORTED, "entry " .. (i + 1) .. ": " .. bpp .. "-bit bitmap", p)
|
||||
elseif w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
else
|
||||
depth = bpp
|
||||
local q = p + hs
|
||||
local palN = 0
|
||||
local pal = buffer.create(4)
|
||||
if bpp <= 8 then
|
||||
palN = if clrUsed > 0 and clrUsed < 2 ^ bpp then clrUsed else 2 ^ bpp
|
||||
if q + palN * 4 > e then
|
||||
palN = 0
|
||||
lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": colour table runs past the entry", q)
|
||||
else
|
||||
pal = buffer.create(palN * 4)
|
||||
for k = 0, palN - 1 do
|
||||
local c = q + k * 4
|
||||
buffer.writeu32(pal, k * 4, readu8(b, c + 2) + readu8(b, c + 1) * 256 + readu8(b, c) * 65536 + 0xFF000000)
|
||||
end
|
||||
q += palN * 4
|
||||
end
|
||||
end
|
||||
if bpp > 8 or palN > 0 then
|
||||
if bpp == 16 and le32(b, p + 16) == 3 then
|
||||
q += 12 -- BI_BITFIELDS masks (assumed 5-5-5)
|
||||
end
|
||||
local out = Types.Image.new(w, h, "rgba8")
|
||||
local ok, msg = Dib.decode(b, q, e, w, h, bpp, pal, palN, out.pixels)
|
||||
if ok then
|
||||
img = out
|
||||
else
|
||||
lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": " .. tostring(msg), q)
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " is too short", p)
|
||||
end
|
||||
end
|
||||
if img then
|
||||
local im = img :: Types.Image
|
||||
im.meta.source = { format = "ico", bitDepth = depth, png = isPng, colorCount = readu8(b, d + 2) }
|
||||
if typ == 2 then
|
||||
im.meta.hotspot = { x = f1, y = f2 }
|
||||
end
|
||||
table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" })
|
||||
local score = im.width * im.height * 64 + depth
|
||||
if score > bestScore then
|
||||
best, bestScore = im, score
|
||||
end
|
||||
else
|
||||
skipped += 1
|
||||
end
|
||||
end
|
||||
if not best then
|
||||
return nil, lastErr or Err.new(Err.CORRUPT, "no decodable entry")
|
||||
end
|
||||
local main = best :: Types.Image
|
||||
local img = Types.Image.new(main.width, main.height, "rgba8")
|
||||
buffer.copy(img.pixels, 0, main.pixels)
|
||||
if #frames > 1 then
|
||||
img.frames = frames
|
||||
end
|
||||
img.meta.source = { format = "ico", type = if typ == 2 then "cur" else "ico", bitDepth = main.meta.source and main.meta.source.bitDepth, entries = count, skipped = skipped, png = main.meta.source and main.meta.source.png }
|
||||
img.meta.hotspot = main.meta.hotspot
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Ico.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local o: any = opts or {}
|
||||
local list: { Types.Image } = {}
|
||||
if type(img.frames) == "table" and #img.frames > 0 then
|
||||
for _, f in img.frames do
|
||||
table.insert(list, f.image)
|
||||
end
|
||||
else
|
||||
list[1] = img
|
||||
end
|
||||
local cursor = o.cursor
|
||||
if cursor == nil then
|
||||
cursor = type(img.meta) == "table" and img.meta.hotspot ~= nil
|
||||
end
|
||||
local blobs: { buffer } = {}
|
||||
for i, im in list do
|
||||
if type(im) ~= "table" or im.format ~= "rgba8" or type(im.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "entry " .. i .. ": needs an rgba8 Image")
|
||||
end
|
||||
local w, h = im.width, im.height
|
||||
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 256 or h > 256 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(im.pixels) < w * h * 4 then
|
||||
return nil, Err.new(Err.ARG, "entry " .. i .. ": icons are 1..256 pixels per side")
|
||||
end
|
||||
local png = nil
|
||||
if o.encodeImage and (o.png or w == 256 or h == 256) then
|
||||
local ok, res, err = pcall(o.encodeImage, im, "png")
|
||||
if not ok or not res then
|
||||
return nil, if ok and err then err else Err.new(Err.ARG, "entry " .. i .. ": PNG encode failed")
|
||||
end
|
||||
png = res
|
||||
elseif o.png then
|
||||
return nil, Err.new(Err.ARG, "opts.png needs opts.encodeImage (F.save passes it)")
|
||||
end
|
||||
if png then
|
||||
blobs[i] = png
|
||||
else
|
||||
local maskStride = ((w + 31) // 32) * 4
|
||||
local n = 40 + w * h * 4 + maskStride * h
|
||||
local d = buffer.create(n)
|
||||
buffer.writeu32(d, 0, 40)
|
||||
buffer.writei32(d, 4, w)
|
||||
buffer.writei32(d, 8, h * 2)
|
||||
buffer.writeu16(d, 12, 1)
|
||||
buffer.writeu16(d, 14, 32)
|
||||
buffer.writeu32(d, 20, w * h * 4 + maskStride * h)
|
||||
Dib.encode(im.pixels, w, h, d, 40)
|
||||
blobs[i] = d
|
||||
end
|
||||
end
|
||||
local total = 6 + #list * 16
|
||||
for _, bl in blobs do
|
||||
total += buffer.len(bl)
|
||||
end
|
||||
local out = buffer.create(total)
|
||||
buffer.writeu16(out, 2, if cursor then 2 else 1)
|
||||
buffer.writeu16(out, 4, #list)
|
||||
local off = 6 + #list * 16
|
||||
for i, im in list do
|
||||
local d = 6 + (i - 1) * 16
|
||||
buffer.writeu8(out, d, im.width % 256)
|
||||
buffer.writeu8(out, d + 1, im.height % 256)
|
||||
if cursor then
|
||||
local hs = (type(im.meta) == "table" and im.meta.hotspot) or (img.meta and img.meta.hotspot) or { x = 0, y = 0 }
|
||||
buffer.writeu16(out, d + 4, math.clamp(math.floor(tonumber(hs.x) or 0), 0, 65535))
|
||||
buffer.writeu16(out, d + 6, math.clamp(math.floor(tonumber(hs.y) or 0), 0, 65535))
|
||||
else
|
||||
buffer.writeu16(out, d + 4, 1)
|
||||
buffer.writeu16(out, d + 6, 32)
|
||||
end
|
||||
buffer.writeu32(out, d + 8, buffer.len(blobs[i]))
|
||||
buffer.writeu32(out, d + 12, off)
|
||||
buffer.copy(out, off, blobs[i])
|
||||
off += buffer.len(blobs[i])
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Ico
|
||||
@@ -0,0 +1,414 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised
|
||||
-- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's
|
||||
-- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table.
|
||||
--
|
||||
-- It reads the destuffed scan data that Scan.destuff produces (0xFF 0x00 already removed, RSTn positions recorded);
|
||||
-- past the end of a restart segment it reads zero bytes, the convention libjpeg follows when the decoder runs into a
|
||||
-- marker (libjpeg's encoder also drops trailing zero bytes, so reading past the end is normal and not a sign of
|
||||
-- truncation: the caller flags a scan that runs into the end of the file instead). Statistics bins live in one buffer: DC tables at [t * 64], AC tables at [256 + t * 256], the fixed 0.5
|
||||
-- bin at [1280].
|
||||
local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16
|
||||
local band, bxor = bit32.band, bit32.bxor
|
||||
|
||||
local Arith = {}
|
||||
|
||||
-- jaricom.c: Qe << 16 | Next_Index_MPS << 8 | Switch_MPS << 7 | Next_Index_LPS
|
||||
local TAB = buffer.create(114 * 4)
|
||||
do
|
||||
local raw = {
|
||||
{ 0x5a1d, 1, 1, 1 }, { 0x2586, 14, 2, 0 }, { 0x1114, 16, 3, 0 }, { 0x080b, 18, 4, 0 }, { 0x03d8, 20, 5, 0 },
|
||||
{ 0x01da, 23, 6, 0 }, { 0x00e5, 25, 7, 0 }, { 0x006f, 28, 8, 0 }, { 0x0036, 30, 9, 0 }, { 0x001a, 33, 10, 0 },
|
||||
{ 0x000d, 35, 11, 0 }, { 0x0006, 9, 12, 0 }, { 0x0003, 10, 13, 0 }, { 0x0001, 12, 13, 0 }, { 0x5a7f, 15, 15, 1 },
|
||||
{ 0x3f25, 36, 16, 0 }, { 0x2cf2, 38, 17, 0 }, { 0x207c, 39, 18, 0 }, { 0x17b9, 40, 19, 0 }, { 0x1182, 42, 20, 0 },
|
||||
{ 0x0cef, 43, 21, 0 }, { 0x09a1, 45, 22, 0 }, { 0x072f, 46, 23, 0 }, { 0x055c, 48, 24, 0 }, { 0x0406, 49, 25, 0 },
|
||||
{ 0x0303, 51, 26, 0 }, { 0x0240, 52, 27, 0 }, { 0x01b1, 54, 28, 0 }, { 0x0144, 56, 29, 0 }, { 0x00f5, 57, 30, 0 },
|
||||
{ 0x00b7, 59, 31, 0 }, { 0x008a, 60, 32, 0 }, { 0x0068, 62, 33, 0 }, { 0x004e, 63, 34, 0 }, { 0x003b, 32, 35, 0 },
|
||||
{ 0x002c, 33, 9, 0 }, { 0x5ae1, 37, 37, 1 }, { 0x484c, 64, 38, 0 }, { 0x3a0d, 65, 39, 0 }, { 0x2ef1, 67, 40, 0 },
|
||||
{ 0x261f, 68, 41, 0 }, { 0x1f33, 69, 42, 0 }, { 0x19a8, 70, 43, 0 }, { 0x1518, 72, 44, 0 }, { 0x1177, 73, 45, 0 },
|
||||
{ 0x0e74, 74, 46, 0 }, { 0x0bfb, 75, 47, 0 }, { 0x09f8, 77, 48, 0 }, { 0x0861, 78, 49, 0 }, { 0x0706, 79, 50, 0 },
|
||||
{ 0x05cd, 48, 51, 0 }, { 0x04de, 50, 52, 0 }, { 0x040f, 50, 53, 0 }, { 0x0363, 51, 54, 0 }, { 0x02d4, 52, 55, 0 },
|
||||
{ 0x025c, 53, 56, 0 }, { 0x01f8, 54, 57, 0 }, { 0x01a4, 55, 58, 0 }, { 0x0160, 56, 59, 0 }, { 0x0125, 57, 60, 0 },
|
||||
{ 0x00f6, 58, 61, 0 }, { 0x00cb, 59, 62, 0 }, { 0x00ab, 61, 63, 0 }, { 0x008f, 61, 32, 0 }, { 0x5b12, 65, 65, 1 },
|
||||
{ 0x4d04, 80, 66, 0 }, { 0x412c, 81, 67, 0 }, { 0x37d8, 82, 68, 0 }, { 0x2fe8, 83, 69, 0 }, { 0x293c, 84, 70, 0 },
|
||||
{ 0x2379, 86, 71, 0 }, { 0x1edf, 87, 72, 0 }, { 0x1aa9, 87, 73, 0 }, { 0x174e, 72, 74, 0 }, { 0x1424, 72, 75, 0 },
|
||||
{ 0x119c, 74, 76, 0 }, { 0x0f6b, 74, 77, 0 }, { 0x0d51, 75, 78, 0 }, { 0x0bb6, 77, 79, 0 }, { 0x0a40, 77, 48, 0 },
|
||||
{ 0x5832, 80, 81, 1 }, { 0x4d1c, 88, 82, 0 }, { 0x438e, 89, 83, 0 }, { 0x3bdd, 90, 84, 0 }, { 0x34ee, 91, 85, 0 },
|
||||
{ 0x2eae, 92, 86, 0 }, { 0x299a, 93, 87, 0 }, { 0x2516, 86, 71, 0 }, { 0x5570, 88, 89, 1 }, { 0x4ca9, 95, 90, 0 },
|
||||
{ 0x44d9, 96, 91, 0 }, { 0x3e22, 97, 92, 0 }, { 0x3824, 99, 93, 0 }, { 0x32b4, 99, 94, 0 }, { 0x2e17, 93, 86, 0 },
|
||||
{ 0x56a8, 95, 96, 1 }, { 0x4f46, 101, 97, 0 }, { 0x47e5, 102, 98, 0 }, { 0x41cf, 103, 99, 0 }, { 0x3c3d, 104, 100, 0 },
|
||||
{ 0x375e, 99, 93, 0 }, { 0x5231, 105, 102, 0 }, { 0x4c0f, 106, 103, 0 }, { 0x4639, 107, 104, 0 }, { 0x415e, 103, 99, 0 },
|
||||
{ 0x5627, 105, 106, 1 }, { 0x50e7, 108, 107, 0 }, { 0x4b85, 109, 103, 0 }, { 0x5597, 110, 109, 0 }, { 0x504f, 111, 107, 0 },
|
||||
{ 0x5a10, 110, 111, 1 }, { 0x5522, 112, 109, 0 }, { 0x59eb, 112, 111, 1 }, { 0x5a1d, 113, 113, 0 },
|
||||
}
|
||||
for i, e in raw do
|
||||
buffer.writeu16(TAB, (i - 1) * 4, e[1]) -- Qe
|
||||
writeu8(TAB, (i - 1) * 4 + 2, e[4] * 128 + e[2]) -- Switch_MPS << 7 | Next_Index_LPS
|
||||
writeu8(TAB, (i - 1) * 4 + 3, e[3]) -- Next_Index_MPS
|
||||
end
|
||||
end
|
||||
|
||||
local ZZ: buffer = buffer.create(80) -- set by Arith.init (Scan.ZIGZAG)
|
||||
|
||||
local STATS = 1281
|
||||
local POW2 = buffer.create(8)
|
||||
for i = 0, 7 do
|
||||
writeu8(POW2, i, 2 ^ i)
|
||||
end
|
||||
local FIXED = 1280
|
||||
|
||||
-- decoder state (one scan at a time; never yields)
|
||||
local D: buffer = buffer.create(0)
|
||||
local P = 0 -- next byte
|
||||
local SEGEND = 0 -- reads at or past this return 0
|
||||
local OVER = 0 -- zero bytes supplied past the end
|
||||
local C, A, CT = 0, 0, -16
|
||||
local st: buffer = buffer.create(STATS)
|
||||
|
||||
local function decode(s: number): number
|
||||
while A < 0x8000 do
|
||||
CT -= 1
|
||||
if CT < 0 then
|
||||
local data = 0
|
||||
if P < SEGEND then
|
||||
data = readu8(D, P)
|
||||
P += 1
|
||||
else
|
||||
OVER += 1
|
||||
end
|
||||
C = C * 256 + data
|
||||
CT += 8
|
||||
if CT < 0 then
|
||||
CT += 1
|
||||
if CT == 0 then
|
||||
A = 0x8000
|
||||
end
|
||||
end
|
||||
end
|
||||
A *= 2
|
||||
end
|
||||
local sv = readu8(st, s)
|
||||
local t = band(sv, 0x7F) * 4
|
||||
local qe = buffer.readu16(TAB, t)
|
||||
local nl = readu8(TAB, t + 2)
|
||||
local nm = readu8(TAB, t + 3)
|
||||
local temp = A - qe
|
||||
A = temp
|
||||
temp *= readu8(POW2, CT)
|
||||
if C >= temp then
|
||||
C -= temp
|
||||
if A < qe then
|
||||
A = qe
|
||||
writeu8(st, s, bxor(band(sv, 0x80), nm))
|
||||
else
|
||||
A = qe
|
||||
writeu8(st, s, bxor(band(sv, 0x80), nl))
|
||||
sv = bxor(sv, 0x80)
|
||||
end
|
||||
elseif A < 0x8000 then
|
||||
if A < qe then
|
||||
writeu8(st, s, bxor(band(sv, 0x80), nl))
|
||||
sv = bxor(sv, 0x80)
|
||||
else
|
||||
writeu8(st, s, bxor(band(sv, 0x80), nm))
|
||||
end
|
||||
end
|
||||
return if sv >= 0x80 then 1 else 0
|
||||
end
|
||||
|
||||
local function i16(v: number): number
|
||||
v = band(v, 0xFFFF)
|
||||
return if v >= 0x8000 then v - 0x10000 else v
|
||||
end
|
||||
|
||||
export type ArithComp = {
|
||||
coef: buffer,
|
||||
bpl: number,
|
||||
h: number,
|
||||
v: number,
|
||||
bw: number,
|
||||
bh: number,
|
||||
dcTbl: number, -- 0..3
|
||||
acTbl: number,
|
||||
pred: number,
|
||||
ctx: number,
|
||||
}
|
||||
|
||||
export type ArithParams = {
|
||||
comps: { ArithComp },
|
||||
mcusX: number,
|
||||
mcusY: number,
|
||||
ri: number,
|
||||
mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine
|
||||
ss: number,
|
||||
se: number,
|
||||
al: number,
|
||||
dcL: { number }, -- conditioning per table (DAC), 1-based by table + 1
|
||||
dcU: { number },
|
||||
acK: { number },
|
||||
}
|
||||
|
||||
-- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24); returns the new predictor or nil on a bad code
|
||||
local function dcDiff(c: ArithComp, L: number, U: number): number?
|
||||
local base = c.dcTbl * 64
|
||||
local s = base + c.ctx
|
||||
if decode(s) == 0 then
|
||||
c.ctx = 0
|
||||
return c.pred
|
||||
end
|
||||
local sign = decode(s + 1)
|
||||
s = s + 2 + sign
|
||||
local m = decode(s)
|
||||
if m ~= 0 then
|
||||
s = base + 20
|
||||
while decode(s) ~= 0 do
|
||||
m *= 2
|
||||
if m == 0x8000 then
|
||||
return nil
|
||||
end
|
||||
s += 1
|
||||
end
|
||||
end
|
||||
if m < 2 ^ L // 2 then
|
||||
c.ctx = 0
|
||||
elseif m > 2 ^ U // 2 then
|
||||
c.ctx = 12 + sign * 4
|
||||
else
|
||||
c.ctx = 4 + sign * 4
|
||||
end
|
||||
local v = m
|
||||
s += 14
|
||||
m = m // 2
|
||||
while m > 0 do
|
||||
if decode(s) ~= 0 then
|
||||
v += m
|
||||
end
|
||||
m = m // 2
|
||||
end
|
||||
v += 1
|
||||
if sign ~= 0 then
|
||||
v = -v
|
||||
end
|
||||
return band(c.pred + v, 0xFFFF)
|
||||
end
|
||||
|
||||
-- AC coefficients k = ss..se of one block (figure F.20); false on a bad code
|
||||
local function acFirst(coef: buffer, off: number, tbl: number, ss: number, se: number, K: number, mul: number): boolean
|
||||
local base = 256 + tbl * 256
|
||||
local k = ss
|
||||
while k <= se do
|
||||
local s = base + 3 * (k - 1)
|
||||
if decode(s) ~= 0 then
|
||||
break -- EOB
|
||||
end
|
||||
while decode(s + 1) == 0 do
|
||||
s += 3
|
||||
k += 1
|
||||
if k > se then
|
||||
return false
|
||||
end
|
||||
end
|
||||
local sign = decode(FIXED)
|
||||
s += 2
|
||||
local m = decode(s)
|
||||
if m ~= 0 then
|
||||
if decode(s) ~= 0 then
|
||||
m *= 2
|
||||
s = base + (if k <= K then 189 else 217)
|
||||
while decode(s) ~= 0 do
|
||||
m *= 2
|
||||
if m == 0x8000 then
|
||||
return false
|
||||
end
|
||||
s += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
local v = m
|
||||
s += 14
|
||||
m = m // 2
|
||||
while m > 0 do
|
||||
if decode(s) ~= 0 then
|
||||
v += m
|
||||
end
|
||||
m = m // 2
|
||||
end
|
||||
v += 1
|
||||
if sign ~= 0 then
|
||||
v = -v
|
||||
end
|
||||
writei16(coef, off + readu8(ZZ, k) * 2, i16(v * mul))
|
||||
k += 1
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function acRefine(coef: buffer, off: number, tbl: number, ss: number, se: number, al: number): boolean
|
||||
local base = 256 + tbl * 256
|
||||
local p1 = 2 ^ al
|
||||
local m1 = -p1
|
||||
local kex = se
|
||||
while kex > 0 do
|
||||
if readi16(coef, off + readu8(ZZ, kex) * 2) ~= 0 then
|
||||
break
|
||||
end
|
||||
kex -= 1
|
||||
end
|
||||
local k = ss
|
||||
while k <= se do
|
||||
local s = base + 3 * (k - 1)
|
||||
if k > kex then
|
||||
if decode(s) ~= 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
while true do
|
||||
local o = off + readu8(ZZ, k) * 2
|
||||
local cv = readi16(coef, o)
|
||||
if cv ~= 0 then
|
||||
if decode(s + 2) ~= 0 then
|
||||
writei16(coef, o, i16(if cv < 0 then cv + m1 else cv + p1))
|
||||
end
|
||||
break
|
||||
end
|
||||
if decode(s + 1) ~= 0 then
|
||||
writei16(coef, o, i16(if decode(FIXED) ~= 0 then m1 else p1))
|
||||
break
|
||||
end
|
||||
s += 3
|
||||
k += 1
|
||||
if k > se then
|
||||
return false
|
||||
end
|
||||
end
|
||||
k += 1
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
function Arith.init(zigzag: buffer)
|
||||
ZZ = zigzag
|
||||
end
|
||||
|
||||
-- run(d, cleanLen, rst, nrst, P) -> truncated: decodes one scan (see Scan.run for the data layout)
|
||||
function Arith.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, Pm: ArithParams): boolean
|
||||
local comps = Pm.comps
|
||||
local nc = #comps
|
||||
local mode, ss, se, al, ri = Pm.mode, Pm.ss, Pm.se, Pm.al, Pm.ri
|
||||
local units, ux
|
||||
if nc == 1 then
|
||||
ux = comps[1].bw
|
||||
units = ux * comps[1].bh
|
||||
else
|
||||
ux = Pm.mcusX
|
||||
units = ux * Pm.mcusY
|
||||
end
|
||||
local resetDc = mode == 0 or mode == 1
|
||||
local resetAc = mode == 0 or mode == 3 or mode == 4
|
||||
local function reset()
|
||||
for i = 1, nc do
|
||||
local c = comps[i]
|
||||
if resetDc then
|
||||
buffer.fill(st, c.dcTbl * 64, 0, 64)
|
||||
c.pred = 0
|
||||
c.ctx = 0
|
||||
end
|
||||
if resetAc then
|
||||
buffer.fill(st, 256 + c.acTbl * 256, 0, 256)
|
||||
end
|
||||
end
|
||||
C, A, CT = 0, 0, -16
|
||||
end
|
||||
D = d
|
||||
P = 0
|
||||
SEGEND = if nrst >= 1 then math.min(rst[1], cleanLen) else cleanLen
|
||||
OVER = 0
|
||||
writeu8(st, FIXED, 113)
|
||||
reset()
|
||||
local rstIdx = 0
|
||||
local bad = false
|
||||
local truncated = false
|
||||
local mul = 2 ^ al
|
||||
for u = 0, units - 1 do
|
||||
if ri > 0 and u > 0 and u % ri == 0 then
|
||||
rstIdx += 1
|
||||
if rstIdx <= nrst then
|
||||
P = math.min(rst[rstIdx], cleanLen)
|
||||
SEGEND = if rstIdx + 1 <= nrst then math.min(rst[rstIdx + 1], cleanLen) else cleanLen
|
||||
bad = false
|
||||
else
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
reset()
|
||||
end
|
||||
if not bad then
|
||||
local my, mx = u // ux, u % ux
|
||||
for ci = 1, nc do
|
||||
local c = comps[ci]
|
||||
local bh, bw, by0, bx0
|
||||
if nc == 1 then
|
||||
bh, bw, by0, bx0 = 1, 1, my, mx
|
||||
else
|
||||
bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h
|
||||
end
|
||||
local coef, bpl = c.coef, c.bpl
|
||||
for by = by0, by0 + bh - 1 do
|
||||
for bx = bx0, bx0 + bw - 1 do
|
||||
local off = (by * bpl + bx) * 128
|
||||
if mode == 0 then
|
||||
local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1])
|
||||
if not pred then
|
||||
bad = true
|
||||
else
|
||||
c.pred = pred
|
||||
writei16(coef, off, i16(pred))
|
||||
if not acFirst(coef, off, c.acTbl, 1, 63, Pm.acK[c.acTbl + 1], 1) then
|
||||
bad = true
|
||||
end
|
||||
end
|
||||
elseif mode == 1 then
|
||||
local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1])
|
||||
if not pred then
|
||||
bad = true
|
||||
else
|
||||
c.pred = pred
|
||||
writei16(coef, off, i16(pred * mul))
|
||||
end
|
||||
elseif mode == 2 then
|
||||
if decode(FIXED) ~= 0 then
|
||||
local cv = readi16(coef, off)
|
||||
if band(cv, mul) == 0 then
|
||||
writei16(coef, off, i16(cv + mul))
|
||||
end
|
||||
end
|
||||
elseif mode == 3 then
|
||||
if not acFirst(coef, off, c.acTbl, ss, se, Pm.acK[c.acTbl + 1], mul) then
|
||||
bad = true
|
||||
end
|
||||
else
|
||||
if not acRefine(coef, off, c.acTbl, ss, se, al) then
|
||||
bad = true
|
||||
end
|
||||
end
|
||||
if bad then
|
||||
break
|
||||
end
|
||||
end
|
||||
if bad then
|
||||
break
|
||||
end
|
||||
end
|
||||
if bad then
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
D = buffer.create(0)
|
||||
return truncated
|
||||
end
|
||||
|
||||
return Arith
|
||||
@@ -0,0 +1,229 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never
|
||||
-- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's
|
||||
-- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md).
|
||||
--
|
||||
-- Upsampling follows libjpeg-turbo's jdsample.c, so the output matches djpeg's defaults:
|
||||
-- FULL the component is at output resolution
|
||||
-- H2V1 "fancy" triangle filter, 3/4 nearer + 1/4 further sample, alternating rounding (1, 2) / 4
|
||||
-- H2V2 fancy in both directions: vertical 3:1 column sums, then horizontal 3:1, rounding (8, 7) / 16
|
||||
-- H1V2 fancy vertical only, rounding 1 (upper row) / 2 (lower row)
|
||||
-- REPLICATE any other ratio (or no fancy upsampling): nearest sample, as int_upsample
|
||||
-- Edges replicate the last real sample (downW x downH), as libjpeg does with its context rows.
|
||||
-- Colour conversion is jdcolor.c's table-driven YCbCr -> RGB (16-bit fixed point), plus grey, RGB, CMYK and
|
||||
-- YCCK (Adobe inverted CMYK: R = C * K / 255).
|
||||
local readu16, readi32, readu8, writeu16, writeu32 = buffer.readu16, buffer.readi32, buffer.readu8, buffer.writeu16, buffer.writeu32
|
||||
local clamp, min, max = math.clamp, math.min, math.max
|
||||
|
||||
local Color = {}
|
||||
|
||||
Color.FULL = 0
|
||||
Color.REPLICATE = 1
|
||||
Color.H2V1 = 2
|
||||
Color.H2V2 = 3
|
||||
Color.H1V2 = 4
|
||||
|
||||
Color.GRAY = 0
|
||||
Color.YCC = 1
|
||||
Color.RGB = 2
|
||||
Color.CMYK = 3
|
||||
Color.YCCK = 4
|
||||
Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted
|
||||
|
||||
export type Comp = {
|
||||
plane: buffer, -- u16 samples, stride per row
|
||||
stride: number,
|
||||
rows: number, -- plane height
|
||||
downW: number, -- real samples across / down (the rest is block padding)
|
||||
downH: number,
|
||||
method: number,
|
||||
hIn: number,
|
||||
hOut: number,
|
||||
vIn: number,
|
||||
vOut: number,
|
||||
row: buffer, -- scratch row (u16, at least max(outW, 2 * downW) + 8 samples)
|
||||
}
|
||||
|
||||
export type Params = {
|
||||
comps: { Comp },
|
||||
space: number,
|
||||
outW: number,
|
||||
outH: number,
|
||||
maxv: number,
|
||||
pixels: buffer,
|
||||
-- YCbCr tables (maxv + 1 i32 entries)
|
||||
crr: buffer,
|
||||
cbb: buffer,
|
||||
crg: buffer,
|
||||
cbg: buffer,
|
||||
toByte: buffer?, -- maxv + 1 u8 entries (12-bit), nil for 8-bit
|
||||
}
|
||||
|
||||
-- jdcolor.c build_ycc_rgb_table
|
||||
function Color.tables(maxv: number): (buffer, buffer, buffer, buffer)
|
||||
local n = maxv + 1
|
||||
local center = n // 2
|
||||
local crr, cbb, crg, cbg = buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4)
|
||||
local function fix(x: number): number
|
||||
return math.floor(x * 65536 + 0.5)
|
||||
end
|
||||
for i = 0, maxv do
|
||||
local x = i - center
|
||||
buffer.writei32(crr, i * 4, (fix(1.40200) * x + 32768) // 65536)
|
||||
buffer.writei32(cbb, i * 4, (fix(1.77200) * x + 32768) // 65536)
|
||||
buffer.writei32(crg, i * 4, -fix(0.71414) * x)
|
||||
buffer.writei32(cbg, i * 4, -fix(0.34414) * x + 32768)
|
||||
end
|
||||
return crr, cbb, crg, cbg
|
||||
end
|
||||
|
||||
-- fills c.row with output row y; returns the buffer and byte offset of the row's samples
|
||||
local function fetch(c: Comp, y: number, outW: number): (buffer, number)
|
||||
local method = c.method
|
||||
local plane, stride, row = c.plane, c.stride, c.row
|
||||
if method == 0 then
|
||||
return plane, min(y, c.rows - 1) * stride * 2
|
||||
elseif method == 2 then
|
||||
local w = c.downW
|
||||
local b = min(y, c.rows - 1) * stride * 2
|
||||
local cur = readu16(plane, b)
|
||||
writeu16(row, 0, cur)
|
||||
local nxt = readu16(plane, b + 2)
|
||||
writeu16(row, 2, (cur * 3 + nxt + 2) // 4)
|
||||
local prev = cur
|
||||
cur = nxt
|
||||
for i = 1, w - 2 do
|
||||
nxt = readu16(plane, b + (i + 1) * 2)
|
||||
local v3 = cur * 3
|
||||
writeu16(row, i * 4, (v3 + prev + 1) // 4)
|
||||
writeu16(row, i * 4 + 2, (v3 + nxt + 2) // 4)
|
||||
prev = cur
|
||||
cur = nxt
|
||||
end
|
||||
writeu16(row, (w - 1) * 4, (cur * 3 + prev + 1) // 4)
|
||||
writeu16(row, (w - 1) * 4 + 2, cur)
|
||||
return row, 0
|
||||
elseif method == 3 then
|
||||
local w = c.downW
|
||||
local iy = min(y // 2, c.downH - 1)
|
||||
local oy = if y % 2 == 0 then max(iy - 1, 0) else min(iy + 1, c.downH - 1)
|
||||
local b0, b1 = iy * stride * 2, oy * stride * 2
|
||||
local this = readu16(plane, b0) * 3 + readu16(plane, b1)
|
||||
local nxt = readu16(plane, b0 + 2) * 3 + readu16(plane, b1 + 2)
|
||||
writeu16(row, 0, (this * 4 + 8) // 16)
|
||||
writeu16(row, 2, (this * 3 + nxt + 7) // 16)
|
||||
local last = this
|
||||
this = nxt
|
||||
for i = 1, w - 2 do
|
||||
nxt = readu16(plane, b0 + (i + 1) * 2) * 3 + readu16(plane, b1 + (i + 1) * 2)
|
||||
local t3 = this * 3
|
||||
writeu16(row, i * 4, (t3 + last + 8) // 16)
|
||||
writeu16(row, i * 4 + 2, (t3 + nxt + 7) // 16)
|
||||
last = this
|
||||
this = nxt
|
||||
end
|
||||
writeu16(row, (w - 1) * 4, (this * 3 + last + 8) // 16)
|
||||
writeu16(row, (w - 1) * 4 + 2, (this * 4 + 7) // 16)
|
||||
return row, 0
|
||||
elseif method == 4 then
|
||||
local iy = min(y // 2, c.downH - 1)
|
||||
local oy, bias
|
||||
if y % 2 == 0 then
|
||||
oy, bias = max(iy - 1, 0), 1
|
||||
else
|
||||
oy, bias = min(iy + 1, c.downH - 1), 2
|
||||
end
|
||||
local b0, b1 = iy * stride * 2, oy * stride * 2
|
||||
for x = 0, outW - 1 do
|
||||
writeu16(row, x * 2, (readu16(plane, b0 + x * 2) * 3 + readu16(plane, b1 + x * 2) + bias) // 4)
|
||||
end
|
||||
return row, 0
|
||||
else
|
||||
local hIn, hOut = c.hIn, c.hOut
|
||||
local iy = min((y * c.vIn) // c.vOut, c.rows - 1)
|
||||
local b = iy * stride * 2
|
||||
local last = stride - 1
|
||||
for x = 0, outW - 1 do
|
||||
writeu16(row, x * 2, readu16(plane, b + min((x * hIn) // hOut, last) * 2))
|
||||
end
|
||||
return row, 0
|
||||
end
|
||||
end
|
||||
|
||||
function Color.run(P: Params)
|
||||
local comps = P.comps
|
||||
local nc = #comps
|
||||
local space, outW, outH, maxv, out = P.space, P.outW, P.outH, P.maxv, P.pixels
|
||||
local crr, cbb, crg, cbg = P.crr, P.cbb, P.crg, P.cbg
|
||||
local toByte = P.toByte
|
||||
local o = 0
|
||||
for y = 0, outH - 1 do
|
||||
local s0, b0 = fetch(comps[1], y, outW)
|
||||
if space == 0 or nc < 3 then
|
||||
for x = 0, outW - 1 do
|
||||
local v = readu16(s0, b0 + x * 2)
|
||||
if toByte then
|
||||
v = readu8(toByte, v)
|
||||
end
|
||||
writeu32(out, o, 0xFF000000 + v * 0x10101)
|
||||
o += 4
|
||||
end
|
||||
else
|
||||
local s1, b1 = fetch(comps[2], y, outW)
|
||||
local s2, b2 = fetch(comps[3], y, outW)
|
||||
local s3, b3 = s0, b0
|
||||
if nc >= 4 then
|
||||
s3, b3 = fetch(comps[4], y, outW)
|
||||
end
|
||||
if space == 1 and not toByte then
|
||||
-- the common case: 8-bit YCbCr
|
||||
for x = 0, outW - 1 do
|
||||
local i = x * 2
|
||||
local yv, cb, cr = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i)
|
||||
local r = clamp(yv + readi32(crr, cr * 4), 0, 255)
|
||||
local g = clamp(yv + (readi32(cbg, cb * 4) + readi32(crg, cr * 4)) // 65536, 0, 255)
|
||||
local b = clamp(yv + readi32(cbb, cb * 4), 0, 255)
|
||||
writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536)
|
||||
o += 4
|
||||
end
|
||||
continue
|
||||
end
|
||||
for x = 0, outW - 1 do
|
||||
local i = x * 2
|
||||
local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i)
|
||||
local r, g, b
|
||||
if space == 2 then
|
||||
r, g, b = c0, c1, c2
|
||||
elseif space == 3 or space == 5 then
|
||||
local k = readu16(s3, b3 + i)
|
||||
if space == 5 then
|
||||
c0, c1, c2, k = maxv - c0, maxv - c1, maxv - c2, maxv - k
|
||||
end
|
||||
r = (c0 * k + maxv // 2) // maxv
|
||||
g = (c1 * k + maxv // 2) // maxv
|
||||
b = (c2 * k + maxv // 2) // maxv
|
||||
else
|
||||
r = clamp(c0 + readi32(crr, c2 * 4), 0, maxv)
|
||||
g = clamp(c0 + (readi32(cbg, c1 * 4) + readi32(crg, c2 * 4)) // 65536, 0, maxv)
|
||||
b = clamp(c0 + readi32(cbb, c1 * 4), 0, maxv)
|
||||
if space == 4 then
|
||||
-- YCCK: the YCC part decodes to inverted C, M, Y (libjpeg ycck_cmyk_convert), K as stored
|
||||
local k = readu16(s3, b3 + i)
|
||||
r = ((maxv - r) * k + maxv // 2) // maxv
|
||||
g = ((maxv - g) * k + maxv // 2) // maxv
|
||||
b = ((maxv - b) * k + maxv // 2) // maxv
|
||||
end
|
||||
end
|
||||
if toByte then
|
||||
r, g, b = readu8(toByte, r), readu8(toByte, g), readu8(toByte, b)
|
||||
end
|
||||
writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536)
|
||||
o += 4
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Color
|
||||
@@ -0,0 +1,666 @@
|
||||
--!strict
|
||||
-- image/jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan /
|
||||
-- Arith / Dct / Color loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended:
|
||||
-- arithmetic-coded frames (SOF9 / SOF10, DAC), a reader range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM
|
||||
-- / JFIF density collected for meta. The IDCT size choice for scaled decodes follows libjpeg-turbo's jdmaster.c.
|
||||
local Scan = require("@formats/image/jpeg/Scan")
|
||||
local Arith = require("@formats/image/jpeg/Arith")
|
||||
local Color = require("@formats/image/jpeg/Color")
|
||||
local Tables = require("@formats/image/jpeg/Tables")
|
||||
local Dct = require("@formats/codecs/Dct")
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
local band, rshift = bit32.band, bit32.rshift
|
||||
|
||||
local Decode = {}
|
||||
|
||||
Arith.init(Scan.ZIGZAG)
|
||||
|
||||
local function be16(b: buffer, p: number): number
|
||||
return readu8(b, p) * 256 + readu8(b, p + 1)
|
||||
end
|
||||
|
||||
local stdBuilt: { [string]: buffer } = {}
|
||||
local function stdTable(class: string, slot: number): buffer?
|
||||
local key = class .. slot
|
||||
if not stdBuilt[key] then
|
||||
local def = (if class == "dc" then Tables.DC else Tables.AC)[slot + 1]
|
||||
if not def then
|
||||
return nil
|
||||
end
|
||||
stdBuilt[key] = Scan.buildTable(def.counts, def.symbols)
|
||||
end
|
||||
return stdBuilt[key]
|
||||
end
|
||||
|
||||
-- the EXIF TIFF block (after "Exif\0\0") and its orientation tag, from an APP1 segment at [p, e)
|
||||
local function exif(b: buffer, p: number, e: number): (number?, number?)
|
||||
if e - p < 14 or buffer.readstring(b, p, 6) ~= "Exif\0\0" then
|
||||
return nil, nil
|
||||
end
|
||||
local t = p + 6
|
||||
local le
|
||||
local bo = buffer.readstring(b, t, 2)
|
||||
if bo == "II" then
|
||||
le = true
|
||||
elseif bo == "MM" then
|
||||
le = false
|
||||
else
|
||||
return nil, nil
|
||||
end
|
||||
local function r16(at: number): number
|
||||
if le then
|
||||
return readu8(b, at) + readu8(b, at + 1) * 256
|
||||
end
|
||||
return readu8(b, at) * 256 + readu8(b, at + 1)
|
||||
end
|
||||
local function r32(at: number): number
|
||||
if le then
|
||||
return r16(at) + r16(at + 2) * 65536
|
||||
end
|
||||
return r16(at) * 65536 + r16(at + 2)
|
||||
end
|
||||
local ifd = t + r32(t + 4)
|
||||
if ifd + 2 > e then
|
||||
return t, nil
|
||||
end
|
||||
local count = r16(ifd)
|
||||
for i = 0, count - 1 do
|
||||
local en = ifd + 2 + i * 12
|
||||
if en + 12 > e then
|
||||
return t, nil
|
||||
end
|
||||
if r16(en) == 0x0112 then
|
||||
local v = r16(en + 8)
|
||||
return t, if v >= 1 and v <= 8 then v else nil
|
||||
end
|
||||
end
|
||||
return t, nil
|
||||
end
|
||||
|
||||
type Comp = {
|
||||
id: number,
|
||||
h: number,
|
||||
v: number,
|
||||
tq: number,
|
||||
bpl: number,
|
||||
bpc: number,
|
||||
bw: number,
|
||||
bh: number,
|
||||
coef: buffer?,
|
||||
quant: buffer?, -- latched at the component's first scan
|
||||
dct: buffer?,
|
||||
act: buffer?,
|
||||
dcTbl: number,
|
||||
acTbl: number,
|
||||
pred: number,
|
||||
ctx: number,
|
||||
}
|
||||
|
||||
type Frame = {
|
||||
width: number,
|
||||
height: number,
|
||||
precision: number,
|
||||
progressive: boolean,
|
||||
arithmetic: boolean,
|
||||
comps: { Comp },
|
||||
hmax: number,
|
||||
vmax: number,
|
||||
mcusX: number,
|
||||
mcusY: number,
|
||||
}
|
||||
|
||||
local SOF_REFUSED = {
|
||||
[0xC3] = "lossless",
|
||||
[0xC5] = "hierarchical",
|
||||
[0xC6] = "hierarchical",
|
||||
[0xC7] = "hierarchical",
|
||||
[0xCB] = "lossless arithmetic-coded",
|
||||
[0xCD] = "hierarchical arithmetic-coded",
|
||||
[0xCE] = "hierarchical arithmetic-coded",
|
||||
[0xCF] = "hierarchical arithmetic-coded",
|
||||
}
|
||||
|
||||
-- failures carry a code: "corrupt" | "unsupported" | "limit" | "truncated"
|
||||
local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, string?, string?)
|
||||
if e - p < 6 then
|
||||
return nil, "corrupt", "short SOF"
|
||||
end
|
||||
local prec = readu8(b, p)
|
||||
local height, width, nf = be16(b, p + 1), be16(b, p + 3), readu8(b, p + 5)
|
||||
if prec ~= 8 and prec ~= 12 then
|
||||
return nil, "unsupported", "sample precision " .. prec
|
||||
end
|
||||
if width == 0 or height == 0 then
|
||||
if height == 0 and width > 0 then
|
||||
return nil, "unsupported", "DNL (height 0 in the frame header)"
|
||||
end
|
||||
return nil, "corrupt", "bad size " .. width .. "x" .. height
|
||||
end
|
||||
if nf ~= 1 and nf ~= 3 and nf ~= 4 then
|
||||
return nil, "unsupported", "component count " .. nf
|
||||
end
|
||||
if e - p < 6 + nf * 3 then
|
||||
return nil, "corrupt", "short SOF"
|
||||
end
|
||||
local comps = {}
|
||||
local hmax, vmax = 1, 1
|
||||
for i = 0, nf - 1 do
|
||||
local q = p + 6 + i * 3
|
||||
local hv = readu8(b, q + 1)
|
||||
local h, v, tq = rshift(hv, 4), band(hv, 15), readu8(b, q + 2)
|
||||
if h < 1 or h > 4 or v < 1 or v > 4 then
|
||||
return nil, "corrupt", "bad sampling factors " .. h .. "x" .. v
|
||||
end
|
||||
if tq > 3 then
|
||||
return nil, "corrupt", "bad quantisation table selector " .. tq
|
||||
end
|
||||
local id = readu8(b, q)
|
||||
for _, c in comps do
|
||||
if c.id == id then
|
||||
return nil, "corrupt", "duplicate component id " .. id
|
||||
end
|
||||
end
|
||||
hmax, vmax = math.max(hmax, h), math.max(vmax, v)
|
||||
table.insert(comps, { id = id, h = h, v = v, tq = tq, bpl = 0, bpc = 0, bw = 0, bh = 0, dcTbl = 0, acTbl = 0, pred = 0, ctx = 0 } :: Comp)
|
||||
end
|
||||
local mcusX = math.ceil(width / (8 * hmax))
|
||||
local mcusY = math.ceil(height / (8 * vmax))
|
||||
for _, c in comps do
|
||||
c.bpl = mcusX * c.h
|
||||
c.bpc = mcusY * c.v
|
||||
c.bw = math.ceil(math.ceil(width * c.h / hmax) / 8)
|
||||
c.bh = math.ceil(math.ceil(height * c.v / vmax) / 8)
|
||||
end
|
||||
return {
|
||||
width = width,
|
||||
height = height,
|
||||
precision = prec,
|
||||
progressive = m == 0xC2 or m == 0xCA,
|
||||
arithmetic = m == 0xC9 or m == 0xCA,
|
||||
comps = comps,
|
||||
hmax = hmax,
|
||||
vmax = vmax,
|
||||
mcusX = mcusX,
|
||||
mcusY = mcusY,
|
||||
}
|
||||
end
|
||||
|
||||
local function colorSpaceOf(frame: Frame, adobe: number?, jfif: boolean): string
|
||||
local n = #frame.comps
|
||||
if n == 1 then
|
||||
return "gray"
|
||||
elseif n == 3 then
|
||||
if adobe ~= nil then
|
||||
return if adobe == 0 then "rgb" else "ycbcr"
|
||||
end
|
||||
local c = frame.comps
|
||||
if not jfif and c[1].id == 82 and c[2].id == 71 and c[3].id == 66 then
|
||||
return "rgb"
|
||||
end
|
||||
return "ycbcr"
|
||||
end
|
||||
return if adobe == 2 then "ycck" else "cmyk"
|
||||
end
|
||||
Decode.colorSpaceOf = colorSpaceOf
|
||||
|
||||
-- The IDCT size (8, 4, 2 or 1) for a component at a scale. libjpeg-turbo scales chroma up through a bigger IDCT
|
||||
-- instead of upsampling it, when the sampling ratios allow (jdmaster.c jpeg_calc_output_dimensions).
|
||||
local function idctSize(f: Frame, c: Comp, scale: number): number
|
||||
local minSize = 8 // scale
|
||||
local ssize = minSize
|
||||
while ssize < 8 and (f.hmax * minSize) % (c.h * ssize * 2) == 0 and (f.vmax * minSize) % (c.v * ssize * 2) == 0 do
|
||||
ssize *= 2
|
||||
end
|
||||
return ssize
|
||||
end
|
||||
|
||||
export type State = {
|
||||
frame: any,
|
||||
adobe: number?,
|
||||
jfif: boolean,
|
||||
density: { unit: number, x: number, y: number }?,
|
||||
orientation: number,
|
||||
exif: buffer?,
|
||||
icc: buffer?,
|
||||
comments: { string },
|
||||
truncated: boolean,
|
||||
scale: number,
|
||||
}
|
||||
|
||||
-- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with
|
||||
-- headerOnly it stops at the frame header, otherwise it decodes every scan into the components' coefficients.
|
||||
function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: boolean): (State?, string?, string?)
|
||||
if n - base < 4 or readu8(b, base) ~= 0xFF or readu8(b, base + 1) ~= 0xD8 then
|
||||
return nil, "corrupt", "not a JPEG file (no SOI marker)"
|
||||
end
|
||||
local scale = (opts and opts.scale) or 1
|
||||
if scale ~= 1 and scale ~= 2 and scale ~= 4 and scale ~= 8 then
|
||||
return nil, "arg", "scale must be 1, 2, 4 or 8"
|
||||
end
|
||||
local maxPixels = (opts and opts.maxPixels) or 2 ^ 26
|
||||
local quant: { [number]: buffer } = {}
|
||||
local dcT: { [number]: buffer } = {}
|
||||
local acT: { [number]: buffer } = {}
|
||||
local dcL, dcU, acK = { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 5, 5, 5, 5 }
|
||||
local frame: Frame? = nil
|
||||
local st: State = {
|
||||
frame = nil,
|
||||
adobe = nil,
|
||||
jfif = false,
|
||||
density = nil,
|
||||
orientation = 1,
|
||||
exif = nil,
|
||||
icc = nil,
|
||||
comments = {},
|
||||
truncated = false,
|
||||
scale = scale,
|
||||
}
|
||||
local iccChunks: { buffer } = {}
|
||||
local ri = 0
|
||||
local scans = 0
|
||||
local clean: buffer? = nil
|
||||
local rst = {}
|
||||
local pos = base + 2
|
||||
while pos < n do
|
||||
-- find the next marker (tolerate garbage and fill bytes)
|
||||
if readu8(b, pos) ~= 0xFF then
|
||||
pos += 1
|
||||
continue
|
||||
end
|
||||
while pos < n and readu8(b, pos) == 0xFF do
|
||||
pos += 1
|
||||
end
|
||||
if pos >= n then
|
||||
break
|
||||
end
|
||||
local m = readu8(b, pos)
|
||||
pos += 1
|
||||
if m == 0xD9 then
|
||||
break -- EOI
|
||||
elseif m == 0 or m == 0x01 or m == 0xD8 or (m >= 0xD0 and m <= 0xD7) then
|
||||
continue -- standalone markers (or stray stuffing)
|
||||
end
|
||||
if pos + 2 > n then
|
||||
st.truncated = true
|
||||
break
|
||||
end
|
||||
local len = be16(b, pos)
|
||||
if len < 2 then
|
||||
return nil, "corrupt", string.format("bad segment length for marker %02X", m)
|
||||
end
|
||||
local p, e = pos + 2, pos + len
|
||||
if e > n then
|
||||
if m == 0xDA and frame and not headerOnly then
|
||||
e = n -- a truncated SOS header still fails below
|
||||
else
|
||||
st.truncated = true
|
||||
break
|
||||
end
|
||||
end
|
||||
pos = e
|
||||
if m == 0xE0 then
|
||||
if e - p >= 12 and buffer.readstring(b, p, 5) == "JFIF\0" then
|
||||
st.jfif = true
|
||||
st.density = { unit = readu8(b, p + 7), x = be16(b, p + 8), y = be16(b, p + 10) }
|
||||
end
|
||||
elseif m == 0xE1 then
|
||||
local t, o = exif(b, p, e)
|
||||
if t and not st.exif then
|
||||
local x = buffer.create(e - t)
|
||||
buffer.copy(x, 0, b, t, e - t)
|
||||
st.exif = x
|
||||
end
|
||||
if o then
|
||||
st.orientation = o
|
||||
end
|
||||
elseif m == 0xE2 then
|
||||
-- ICC_PROFILE\0, sequence number, count, data
|
||||
if e - p >= 14 and buffer.readstring(b, p, 12) == "ICC_PROFILE\0" then
|
||||
local seq = readu8(b, p + 12)
|
||||
local x = buffer.create(e - p - 14)
|
||||
buffer.copy(x, 0, b, p + 14, e - p - 14)
|
||||
if seq >= 1 then
|
||||
iccChunks[seq] = x
|
||||
end
|
||||
end
|
||||
elseif m == 0xEE then
|
||||
if e - p >= 12 and buffer.readstring(b, p, 5) == "Adobe" then
|
||||
st.adobe = readu8(b, p + 11)
|
||||
end
|
||||
elseif m == 0xFE then
|
||||
table.insert(st.comments, buffer.readstring(b, p, e - p))
|
||||
elseif m == 0xDB then
|
||||
-- DQT
|
||||
while p < e do
|
||||
local pt = readu8(b, p)
|
||||
local pq, tq = rshift(pt, 4), band(pt, 15)
|
||||
local size = if pq == 0 then 64 else 128
|
||||
if tq > 3 or pq > 1 or p + 1 + size > e then
|
||||
return nil, "corrupt", "bad DQT segment"
|
||||
end
|
||||
local q = buffer.create(128)
|
||||
for k = 0, 63 do
|
||||
local v = if pq == 0 then readu8(b, p + 1 + k) else be16(b, p + 1 + k * 2)
|
||||
buffer.writeu16(q, readu8(Scan.ZIGZAG, k) * 2, v)
|
||||
end
|
||||
quant[tq] = q
|
||||
p += 1 + size
|
||||
end
|
||||
elseif m == 0xC4 then
|
||||
-- DHT
|
||||
while p < e do
|
||||
if p + 17 > e then
|
||||
return nil, "corrupt", "bad DHT segment"
|
||||
end
|
||||
local tc = readu8(b, p)
|
||||
local class, slot = rshift(tc, 4), band(tc, 15)
|
||||
if class > 1 or slot > 3 then
|
||||
return nil, "corrupt", "bad DHT table class / slot"
|
||||
end
|
||||
local counts, total = {}, 0
|
||||
for l = 1, 16 do
|
||||
counts[l] = readu8(b, p + l)
|
||||
total += counts[l]
|
||||
end
|
||||
if total > 256 or p + 17 + total > e then
|
||||
return nil, "corrupt", "bad DHT segment"
|
||||
end
|
||||
local syms = {}
|
||||
for i = 1, total do
|
||||
syms[i] = readu8(b, p + 16 + i)
|
||||
end
|
||||
local t = Scan.buildTable(counts, syms)
|
||||
if class == 0 then
|
||||
dcT[slot] = t
|
||||
else
|
||||
acT[slot] = t
|
||||
end
|
||||
p += 17 + total
|
||||
end
|
||||
elseif m == 0xCC then
|
||||
-- DAC: arithmetic conditioning
|
||||
while p + 2 <= e do
|
||||
local tc, v = readu8(b, p), readu8(b, p + 1)
|
||||
local class, slot = rshift(tc, 4), band(tc, 15)
|
||||
if class > 1 or slot > 3 then
|
||||
return nil, "corrupt", "bad DAC segment"
|
||||
end
|
||||
if class == 0 then
|
||||
local L, U = band(v, 15), rshift(v, 4)
|
||||
if L > U then
|
||||
return nil, "corrupt", "bad DAC value"
|
||||
end
|
||||
dcL[slot + 1], dcU[slot + 1] = L, U
|
||||
else
|
||||
if v < 1 or v > 63 then
|
||||
return nil, "corrupt", "bad DAC value"
|
||||
end
|
||||
acK[slot + 1] = v
|
||||
end
|
||||
p += 2
|
||||
end
|
||||
elseif m == 0xDD then
|
||||
if e - p < 2 then
|
||||
return nil, "corrupt", "bad DRI segment"
|
||||
end
|
||||
ri = be16(b, p)
|
||||
elseif m == 0xC0 or m == 0xC1 or m == 0xC2 or m == 0xC9 or m == 0xCA then
|
||||
if frame then
|
||||
return nil, "corrupt", "more than one frame header"
|
||||
end
|
||||
local f, code, err = parseSof(b, p, e, m)
|
||||
if not f then
|
||||
return nil, code, err
|
||||
end
|
||||
if f.width * f.height > maxPixels then
|
||||
return nil, "limit", string.format("%d x %d is over the %d pixel limit", f.width, f.height, maxPixels)
|
||||
end
|
||||
frame = f
|
||||
st.frame = f
|
||||
if headerOnly then
|
||||
return st
|
||||
end
|
||||
elseif SOF_REFUSED[m] then
|
||||
return nil, "unsupported", SOF_REFUSED[m] .. " JPEG"
|
||||
elseif m == 0xDA then
|
||||
if headerOnly then
|
||||
break
|
||||
end
|
||||
if not frame then
|
||||
return nil, "corrupt", "scan before the frame header"
|
||||
end
|
||||
local f = frame :: Frame
|
||||
local ns = if p < e then readu8(b, p) else 0
|
||||
if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then
|
||||
return nil, "corrupt", "bad SOS segment"
|
||||
end
|
||||
local sc = {}
|
||||
local blocks = 0
|
||||
for i = 0, ns - 1 do
|
||||
local id, t = readu8(b, p + 1 + i * 2), readu8(b, p + 2 + i * 2)
|
||||
local comp = nil
|
||||
for _, c in f.comps do
|
||||
if c.id == id then
|
||||
comp = c
|
||||
end
|
||||
end
|
||||
if not comp or table.find(sc, comp) then
|
||||
return nil, "corrupt", "scan names an unknown component " .. id
|
||||
end
|
||||
local td, ta = rshift(t, 4), band(t, 15)
|
||||
if td > 3 or ta > 3 then
|
||||
return nil, "corrupt", "bad entropy table selector"
|
||||
end
|
||||
comp.dcTbl, comp.acTbl = td, ta
|
||||
if not f.arithmetic then
|
||||
comp.dct = dcT[td] or stdTable("dc", td)
|
||||
comp.act = acT[ta] or stdTable("ac", ta)
|
||||
end
|
||||
blocks += comp.h * comp.v
|
||||
table.insert(sc, comp)
|
||||
end
|
||||
local q = p + 1 + ns * 2
|
||||
local ss, se, a = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2)
|
||||
local ah, al = rshift(a, 4), band(a, 15)
|
||||
if ns > 1 and blocks > 10 then
|
||||
return nil, "corrupt", "more than 10 blocks per MCU"
|
||||
end
|
||||
local mode
|
||||
if not f.progressive then
|
||||
mode = 0
|
||||
ss, se, ah, al = 0, 63, 0, 0
|
||||
else
|
||||
if se > 63 or ss > se or ah > 13 or al > 13 or (ss == 0 and se ~= 0) or (ss > 0 and ns ~= 1) then
|
||||
return nil, "corrupt", "bad progressive scan parameters"
|
||||
end
|
||||
if ss == 0 then
|
||||
mode = if ah == 0 then 1 else 2
|
||||
else
|
||||
mode = if ah == 0 then 3 else 4
|
||||
end
|
||||
end
|
||||
for _, c in sc do
|
||||
if not f.arithmetic then
|
||||
if (mode == 0 or mode == 1) and not c.dct then
|
||||
return nil, "corrupt", "missing DC Huffman table"
|
||||
end
|
||||
if (mode == 0 or mode == 3 or mode == 4) and not c.act then
|
||||
return nil, "corrupt", "missing AC Huffman table"
|
||||
end
|
||||
end
|
||||
if not c.coef then
|
||||
c.coef = buffer.create(c.bpl * c.bpc * 128)
|
||||
end
|
||||
if not c.quant then
|
||||
c.quant = quant[c.tq]
|
||||
end
|
||||
end
|
||||
if not clean then
|
||||
clean = buffer.create(n - base + Scan.PAD)
|
||||
end
|
||||
local cb = clean :: buffer
|
||||
local nextPos, cleanLen, nrst = Scan.destuff(b, pos, n, cb, rst)
|
||||
if nextPos >= n then
|
||||
st.truncated = true -- no EOI
|
||||
end
|
||||
-- a component decoded through the 1x1 IDCT only needs its DC coefficient: skip its AC scans
|
||||
if not (mode >= 3 and idctSize(f, sc[1], scale) == 1) then
|
||||
local params = {
|
||||
comps = sc :: any,
|
||||
mcusX = f.mcusX,
|
||||
mcusY = f.mcusY,
|
||||
ri = ri,
|
||||
mode = mode,
|
||||
ss = ss,
|
||||
se = se,
|
||||
al = al,
|
||||
dcL = dcL,
|
||||
dcU = dcU,
|
||||
acK = acK,
|
||||
}
|
||||
local short
|
||||
if f.arithmetic then
|
||||
short = Arith.run(cb, cleanLen, rst, nrst, params)
|
||||
else
|
||||
local _
|
||||
_, short = Scan.run(cb, cleanLen, rst, nrst, params)
|
||||
end
|
||||
st.truncated = st.truncated or short
|
||||
end
|
||||
scans += 1
|
||||
pos = nextPos
|
||||
end
|
||||
end
|
||||
if not frame then
|
||||
return nil, if st.truncated then "truncated" else "corrupt", "no frame header"
|
||||
end
|
||||
if #iccChunks > 0 then
|
||||
local total = 0
|
||||
for _, c in iccChunks do
|
||||
total += buffer.len(c)
|
||||
end
|
||||
local icc = buffer.create(total)
|
||||
local o = 0
|
||||
for _, c in iccChunks do
|
||||
buffer.copy(icc, o, c)
|
||||
o += buffer.len(c)
|
||||
end
|
||||
st.icc = icc
|
||||
end
|
||||
if headerOnly then
|
||||
return st
|
||||
end
|
||||
if scans == 0 then
|
||||
return nil, "truncated", "no image data"
|
||||
end
|
||||
return st
|
||||
end
|
||||
|
||||
local SPACE_IDS = { gray = Color.GRAY, ycbcr = Color.YCC, rgb = Color.RGB, cmyk = Color.CMYK, ycck = Color.YCCK }
|
||||
|
||||
local tableCache: { [number]: { buffer } } = {}
|
||||
local function yccTables(maxv: number): { buffer }
|
||||
local t = tableCache[maxv]
|
||||
if not t then
|
||||
local a, b, c, d = Color.tables(maxv)
|
||||
t = { a, b, c, d }
|
||||
tableCache[maxv] = t
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
local toByte12: buffer? = nil
|
||||
|
||||
-- output(st) -> width, height, rgba8 pixels, colour space | nil, code, message
|
||||
function Decode.output(st: State): (number?, any, any, string?)
|
||||
local f: Frame = st.frame
|
||||
local scale = st.scale
|
||||
local minSize = 8 // scale
|
||||
local maxv = if f.precision == 12 then 4095 else 255
|
||||
local center = (maxv + 1) // 2
|
||||
local p1 = if f.precision == 12 then 1 else 2
|
||||
local outW = math.ceil(f.width * minSize / 8)
|
||||
local outH = math.ceil(f.height * minSize / 8)
|
||||
local fancy = minSize > 1
|
||||
local ccomps = {}
|
||||
local zeroQ = buffer.create(128)
|
||||
for _, c in f.comps do
|
||||
local ssize = idctSize(f, c, scale)
|
||||
local stride, rows = c.bpl * ssize, c.bpc * ssize
|
||||
local plane = buffer.create(stride * rows * 2)
|
||||
local coef = c.coef or buffer.create(c.bpl * c.bpc * 128)
|
||||
local q = c.quant
|
||||
if not q then
|
||||
if c.coef then
|
||||
return nil, "corrupt", "missing quantisation table " .. c.tq
|
||||
end
|
||||
q = zeroQ -- the component never appeared in a scan: mid grey
|
||||
end
|
||||
Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, ssize, plane, p1, center, maxv)
|
||||
local hIn, hOut = c.h * ssize // minSize, f.hmax
|
||||
local vIn, vOut = c.v * ssize // minSize, f.vmax
|
||||
local downW = math.ceil(f.width * c.h * ssize / (f.hmax * 8))
|
||||
local downH = math.ceil(f.height * c.v * ssize / (f.vmax * 8))
|
||||
local method
|
||||
if hIn == hOut and vIn == vOut then
|
||||
method = Color.FULL
|
||||
elseif hIn * 2 == hOut and vIn * 2 == vOut and fancy and downW > 2 then
|
||||
method = Color.H2V2
|
||||
elseif hIn * 2 == hOut and vIn == vOut and fancy and downW > 2 then
|
||||
method = Color.H2V1
|
||||
elseif hIn == hOut and vIn * 2 == vOut and fancy then
|
||||
method = Color.H1V2
|
||||
else
|
||||
method = Color.REPLICATE
|
||||
end
|
||||
table.insert(ccomps, {
|
||||
plane = plane,
|
||||
stride = stride,
|
||||
rows = rows,
|
||||
downW = downW,
|
||||
downH = downH,
|
||||
method = method,
|
||||
hIn = hIn,
|
||||
hOut = hOut,
|
||||
vIn = vIn,
|
||||
vOut = vOut,
|
||||
row = buffer.create((math.max(outW, 2 * stride) + 8) * 2),
|
||||
})
|
||||
c.coef = nil -- free the coefficients early
|
||||
end
|
||||
local space = colorSpaceOf(f, st.adobe, st.jfif)
|
||||
local spaceId = SPACE_IDS[space]
|
||||
if space == "cmyk" and st.adobe == nil then
|
||||
spaceId = Color.CMYK_PLAIN
|
||||
end
|
||||
local t = yccTables(maxv)
|
||||
local tb = nil
|
||||
if maxv == 4095 then
|
||||
if not toByte12 then
|
||||
local tbuf = buffer.create(4096)
|
||||
for v = 0, 4095 do
|
||||
buffer.writeu8(tbuf, v, (v * 255 + 2047) // 4095)
|
||||
end
|
||||
toByte12 = tbuf
|
||||
end
|
||||
tb = toByte12
|
||||
end
|
||||
local pixels = buffer.create(outW * outH * 4)
|
||||
Color.run({
|
||||
comps = ccomps,
|
||||
space = spaceId,
|
||||
outW = outW,
|
||||
outH = outH,
|
||||
maxv = maxv,
|
||||
pixels = pixels,
|
||||
crr = t[1],
|
||||
cbb = t[2],
|
||||
crg = t[3],
|
||||
cbg = t[4],
|
||||
toByte = tb,
|
||||
})
|
||||
return outW, outH, pixels, space
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -0,0 +1,883 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman
|
||||
-- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr
|
||||
-- 4:4:4 / 4:2:2 / 4:2:0; restart intervals. It follows libjpeg-turbo's encoder step for step so that its output is
|
||||
-- byte-identical to cjpeg's for the same settings: jccolor.c (fixed-point RGB -> YCbCr), jcsample.c (box downsampling
|
||||
-- with alternating rounding bias, right-edge replication), jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c
|
||||
-- (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs,
|
||||
-- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md.
|
||||
local Dct = require("@formats/codecs/Dct")
|
||||
local Tables = require("@formats/image/jpeg/Tables")
|
||||
|
||||
local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16
|
||||
local band, countlz = bit32.band, bit32.countlz
|
||||
|
||||
local Encode = {}
|
||||
|
||||
-- natural order index of zigzag position k
|
||||
local ZZ = buffer.create(64)
|
||||
do
|
||||
local i = 0
|
||||
for s = 0, 14 do
|
||||
local lo, hi = math.max(0, s - 7), math.min(s, 7)
|
||||
if s % 2 == 0 then
|
||||
for r = hi, lo, -1 do
|
||||
writeu8(ZZ, i, r * 8 + (s - r))
|
||||
i += 1
|
||||
end
|
||||
else
|
||||
for r = lo, hi do
|
||||
writeu8(ZZ, i, r * 8 + (s - r))
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Encode.ZIGZAG = ZZ
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ output
|
||||
local OUT = buffer.create(0)
|
||||
local OP = 0
|
||||
local CAP = 0
|
||||
local ACC, NB = 0, 0
|
||||
local GATHER = false
|
||||
|
||||
local function grow(n: number)
|
||||
if OP + n > CAP then
|
||||
local c = math.max(CAP * 2, OP + n + 1024)
|
||||
local nb = buffer.create(c)
|
||||
buffer.copy(nb, 0, OUT, 0, OP)
|
||||
OUT = nb
|
||||
CAP = c
|
||||
end
|
||||
end
|
||||
|
||||
local function byte(v: number)
|
||||
grow(1)
|
||||
writeu8(OUT, OP, v)
|
||||
OP += 1
|
||||
end
|
||||
|
||||
local function u16be(v: number)
|
||||
byte(v // 256)
|
||||
byte(v % 256)
|
||||
end
|
||||
|
||||
-- n bits of v (n <= 16), MSB first, with 0xFF stuffing
|
||||
local function bits(v: number, n: number)
|
||||
if GATHER or n == 0 then
|
||||
return
|
||||
end
|
||||
local p = 2 ^ n
|
||||
ACC = ACC * p + band(v, p - 1)
|
||||
NB += n
|
||||
while NB >= 8 do
|
||||
NB -= 8
|
||||
local d = 2 ^ NB
|
||||
local b = ACC // d
|
||||
ACC -= b * d
|
||||
grow(2)
|
||||
writeu8(OUT, OP, b)
|
||||
OP += 1
|
||||
if b == 0xFF then
|
||||
writeu8(OUT, OP, 0)
|
||||
OP += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function flushBits()
|
||||
if NB > 0 then
|
||||
bits(0x7F, 8 - NB) -- pad with ones
|
||||
end
|
||||
ACC, NB = 0, 0
|
||||
end
|
||||
|
||||
local function nbits(v: number): number
|
||||
return if v == 0 then 0 else 32 - countlz(v)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Huffman tables
|
||||
-- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl)
|
||||
export type Derived = { code: buffer, size: buffer }
|
||||
|
||||
local function derive(counts: { number }, symbols: { number }): Derived
|
||||
local code, size = buffer.create(512), buffer.create(256)
|
||||
local c, k = 0, 1
|
||||
for l = 1, 16 do
|
||||
for _ = 1, counts[l] or 0 do
|
||||
local s = symbols[k]
|
||||
if s then
|
||||
writeu16(code, s * 2, c)
|
||||
writeu8(size, s, l)
|
||||
end
|
||||
k += 1
|
||||
c += 1
|
||||
end
|
||||
c *= 2
|
||||
end
|
||||
return { code = code, size = size }
|
||||
end
|
||||
|
||||
-- jchuff.c jpeg_gen_optimal_table: freq (0..256, 1-based +1) -> counts, symbols
|
||||
local function optimal(freqIn: { number }): ({ number }, { number })
|
||||
local freq = table.create(257, 0)
|
||||
local bitsT = table.create(34, 0)
|
||||
local codesize = table.create(257, 0)
|
||||
local others = table.create(257, -1)
|
||||
local nz = table.create(257, 0)
|
||||
local n = 0
|
||||
for i = 0, 256 do
|
||||
local f = if i == 256 then 1 else freqIn[i + 1]
|
||||
if f > 0 then
|
||||
n += 1
|
||||
nz[n] = i
|
||||
freq[n] = f
|
||||
end
|
||||
end
|
||||
while true do
|
||||
local c1, c2 = -1, -1
|
||||
local v, v2 = 1e9, 1e9
|
||||
for i = 1, n do
|
||||
local f = freq[i]
|
||||
if f <= v2 then
|
||||
if f <= v then
|
||||
c2 = c1
|
||||
v2 = v
|
||||
v = f
|
||||
c1 = i
|
||||
else
|
||||
v2 = f
|
||||
c2 = i
|
||||
end
|
||||
end
|
||||
end
|
||||
if c2 < 0 then
|
||||
break
|
||||
end
|
||||
freq[c1] += freq[c2]
|
||||
freq[c2] = 1000000001
|
||||
codesize[c1] += 1
|
||||
while others[c1] >= 0 do
|
||||
c1 = others[c1]
|
||||
codesize[c1] += 1
|
||||
end
|
||||
others[c1] = c2
|
||||
codesize[c2] += 1
|
||||
while others[c2] >= 0 do
|
||||
c2 = others[c2]
|
||||
codesize[c2] += 1
|
||||
end
|
||||
end
|
||||
for i = 1, n do
|
||||
local cs = math.min(codesize[i], 32)
|
||||
bitsT[cs + 1] += 1
|
||||
end
|
||||
local bitPos = table.create(34, 0)
|
||||
local p = 0
|
||||
for i = 1, 32 do
|
||||
bitPos[i + 1] = p
|
||||
p += bitsT[i + 1]
|
||||
end
|
||||
local i = 32
|
||||
while i > 16 do
|
||||
while bitsT[i + 1] > 0 do
|
||||
local j = i - 2
|
||||
while bitsT[j + 1] == 0 do
|
||||
j -= 1
|
||||
end
|
||||
bitsT[i + 1] -= 2
|
||||
bitsT[i] += 1
|
||||
bitsT[j + 2] += 2
|
||||
bitsT[j + 1] -= 1
|
||||
end
|
||||
i -= 1
|
||||
end
|
||||
while bitsT[i + 1] == 0 do
|
||||
i -= 1
|
||||
end
|
||||
bitsT[i + 1] -= 1
|
||||
local counts = table.create(16, 0)
|
||||
for l = 1, 16 do
|
||||
counts[l] = bitsT[l + 1]
|
||||
end
|
||||
local symbols = table.create(n, 0)
|
||||
for k = 1, n - 1 do
|
||||
local cs = math.min(codesize[k], 32)
|
||||
symbols[bitPos[cs + 1] + 1] = nz[k]
|
||||
bitPos[cs + 1] += 1
|
||||
end
|
||||
local total = 0
|
||||
for l = 1, 16 do
|
||||
total += counts[l]
|
||||
end
|
||||
local out = table.create(total, 0)
|
||||
for k = 1, total do
|
||||
out[k] = symbols[k]
|
||||
end
|
||||
return counts, out
|
||||
end
|
||||
Encode.optimal = optimal
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ entropy coding state
|
||||
local dcTab: { Derived } = {}
|
||||
local acTab: { Derived } = {}
|
||||
local dcFreq: { { number } } = {}
|
||||
local acFreq: { { number } } = {}
|
||||
|
||||
local function symbol(t: Derived, freq: { number }, s: number)
|
||||
if GATHER then
|
||||
freq[s + 1] += 1
|
||||
else
|
||||
bits(readu16(t.code, s * 2), readu8(t.size, s))
|
||||
end
|
||||
end
|
||||
|
||||
export type Comp = {
|
||||
id: number,
|
||||
h: number,
|
||||
v: number,
|
||||
tq: number,
|
||||
td: number, -- DC table slot
|
||||
ta: number, -- AC table slot
|
||||
bw: number, -- real blocks across / down
|
||||
bh: number,
|
||||
bpl: number, -- MCU-padded block grid
|
||||
bpc: number,
|
||||
coef: buffer, -- i16, 64 per block, natural order
|
||||
last: number, -- DC predictor
|
||||
}
|
||||
|
||||
local function dcDiff(c: Comp, diff: number)
|
||||
local t = diff
|
||||
local t2 = diff
|
||||
if t < 0 then
|
||||
t = -t
|
||||
t2 -= 1
|
||||
end
|
||||
local n = nbits(t)
|
||||
symbol(dcTab[c.td + 1], dcFreq[c.td + 1], n)
|
||||
if n > 0 then
|
||||
bits(t2, n)
|
||||
end
|
||||
end
|
||||
|
||||
-- jchuff.c encode_one_block
|
||||
local function blockSeq(c: Comp, off: number)
|
||||
local coef = c.coef
|
||||
local dc = readi16(coef, off)
|
||||
dcDiff(c, dc - c.last)
|
||||
c.last = dc
|
||||
local at, af = acTab[c.ta + 1], acFreq[c.ta + 1]
|
||||
local r = 0
|
||||
for k = 1, 63 do
|
||||
local v = readi16(coef, off + readu8(ZZ, k) * 2)
|
||||
if v == 0 then
|
||||
r += 1
|
||||
else
|
||||
while r > 15 do
|
||||
symbol(at, af, 0xF0)
|
||||
r -= 16
|
||||
end
|
||||
local t, t2 = v, v
|
||||
if t < 0 then
|
||||
t = -t
|
||||
t2 -= 1
|
||||
end
|
||||
local n = nbits(t)
|
||||
symbol(at, af, r * 16 + n)
|
||||
bits(t2, n)
|
||||
r = 0
|
||||
end
|
||||
end
|
||||
if r > 0 then
|
||||
symbol(at, af, 0)
|
||||
end
|
||||
end
|
||||
|
||||
-- progressive state (jcphuff.c)
|
||||
local EOBRUN = 0
|
||||
local BE = 0
|
||||
local CORR: { number } = table.create(1000, 0)
|
||||
local curAc: Derived = { code = buffer.create(512), size = buffer.create(256) }
|
||||
local curAcFreq: { number } = {}
|
||||
|
||||
local function emitEobrun()
|
||||
if EOBRUN > 0 then
|
||||
local n = nbits(EOBRUN) - 1
|
||||
symbol(curAc, curAcFreq, n * 16)
|
||||
if n > 0 then
|
||||
bits(EOBRUN, n)
|
||||
end
|
||||
EOBRUN = 0
|
||||
if not GATHER then
|
||||
for i = 1, BE do
|
||||
bits(CORR[i], 1)
|
||||
end
|
||||
end
|
||||
BE = 0
|
||||
end
|
||||
end
|
||||
|
||||
local function blockDcFirst(c: Comp, off: number, al: number)
|
||||
local t2 = readi16(c.coef, off) // 2 ^ al
|
||||
dcDiff(c, t2 - c.last)
|
||||
c.last = t2
|
||||
end
|
||||
|
||||
local function blockAcFirst(c: Comp, off: number, ss: number, se: number, al: number)
|
||||
local coef = c.coef
|
||||
local d = 2 ^ al
|
||||
local r = 0
|
||||
for k = ss, se do
|
||||
local v = readi16(coef, off + readu8(ZZ, k) * 2)
|
||||
local t, t2
|
||||
if v < 0 then
|
||||
t = (-v) // d
|
||||
t2 = -t - 1 -- ~t
|
||||
else
|
||||
t = v // d
|
||||
t2 = t
|
||||
end
|
||||
if t == 0 then
|
||||
r += 1
|
||||
else
|
||||
emitEobrun()
|
||||
while r > 15 do
|
||||
symbol(curAc, curAcFreq, 0xF0)
|
||||
r -= 16
|
||||
end
|
||||
local n = nbits(t)
|
||||
symbol(curAc, curAcFreq, r * 16 + n)
|
||||
bits(t2, n)
|
||||
r = 0
|
||||
end
|
||||
end
|
||||
if r > 0 then
|
||||
EOBRUN += 1
|
||||
if EOBRUN == 0x7FFF then
|
||||
emitEobrun()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local absv = table.create(64, 0)
|
||||
|
||||
local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: number)
|
||||
local coef = c.coef
|
||||
local d = 2 ^ al
|
||||
local eob = 0
|
||||
for k = ss, se do
|
||||
local v = readi16(coef, off + readu8(ZZ, k) * 2)
|
||||
local t = (if v < 0 then -v else v) // d
|
||||
absv[k + 1] = t
|
||||
if t == 1 then
|
||||
eob = k
|
||||
end
|
||||
end
|
||||
local r = 0
|
||||
local br = 0 -- correction bits added in this block, at CORR[brStart + 1 ..]
|
||||
local brStart = BE
|
||||
for k = ss, se do
|
||||
local t = absv[k + 1]
|
||||
if t == 0 then
|
||||
r += 1
|
||||
continue
|
||||
end
|
||||
while r > 15 and k <= eob do
|
||||
emitEobrun()
|
||||
symbol(curAc, curAcFreq, 0xF0)
|
||||
r -= 16
|
||||
if not GATHER then
|
||||
for i = 1, br do
|
||||
bits(CORR[brStart + i], 1)
|
||||
end
|
||||
end
|
||||
brStart = 0
|
||||
br = 0
|
||||
end
|
||||
if t > 1 then
|
||||
br += 1
|
||||
CORR[brStart + br] = t % 2
|
||||
continue
|
||||
end
|
||||
emitEobrun()
|
||||
symbol(curAc, curAcFreq, r * 16 + 1)
|
||||
bits(if readi16(coef, off + readu8(ZZ, k) * 2) < 0 then 0 else 1, 1)
|
||||
if not GATHER then
|
||||
for i = 1, br do
|
||||
bits(CORR[brStart + i], 1)
|
||||
end
|
||||
end
|
||||
brStart = 0
|
||||
br = 0
|
||||
r = 0
|
||||
end
|
||||
if r > 0 or br > 0 then
|
||||
EOBRUN += 1
|
||||
BE += br
|
||||
if EOBRUN == 0x7FFF or BE > 1000 - 64 + 1 then
|
||||
emitEobrun()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ scans
|
||||
export type ScanSpec = { comps: { number }, ss: number, se: number, ah: number, al: number }
|
||||
|
||||
-- iterate the scan's MCUs (or blocks, for one component), calling fn(c, off) per block; restart markers when ri > 0
|
||||
local function walk(comps: { Comp }, mcusX: number, mcusY: number, ri: number, onRestart: (number) -> (), fn: (Comp, number) -> ())
|
||||
local nc = #comps
|
||||
local units, ux
|
||||
if nc == 1 then
|
||||
ux = comps[1].bw
|
||||
units = ux * comps[1].bh
|
||||
else
|
||||
ux = mcusX
|
||||
units = ux * mcusY
|
||||
end
|
||||
local rn = 0
|
||||
for u = 0, units - 1 do
|
||||
if ri > 0 and u > 0 and u % ri == 0 then
|
||||
onRestart(rn)
|
||||
rn = (rn + 1) % 8
|
||||
end
|
||||
local my, mx = u // ux, u % ux
|
||||
for ci = 1, nc do
|
||||
local c = comps[ci]
|
||||
if nc == 1 then
|
||||
fn(c, (my * c.bpl + mx) * 128)
|
||||
else
|
||||
for by = my * c.v, my * c.v + c.v - 1 do
|
||||
for bx = mx * c.h, mx * c.h + c.h - 1 do
|
||||
fn(c, (by * c.bpl + bx) * 128)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function dht(class: number, slot: number, counts: { number }, symbols: { number })
|
||||
byte(0xFF)
|
||||
byte(0xC4)
|
||||
u16be(2 + 17 + #symbols)
|
||||
byte(class * 16 + slot)
|
||||
for l = 1, 16 do
|
||||
byte(counts[l])
|
||||
end
|
||||
for _, s in symbols do
|
||||
byte(s)
|
||||
end
|
||||
end
|
||||
|
||||
local function sos(comps: { Comp }, ss: number, se: number, ah: number, al: number, dcOnly: boolean, acOnly: boolean)
|
||||
byte(0xFF)
|
||||
byte(0xDA)
|
||||
u16be(6 + 2 * #comps)
|
||||
byte(#comps)
|
||||
for _, c in comps do
|
||||
byte(c.id)
|
||||
local td = if acOnly then 0 else c.td
|
||||
local ta = if dcOnly then 0 else c.ta
|
||||
byte(td * 16 + ta)
|
||||
end
|
||||
byte(ss)
|
||||
byte(se)
|
||||
byte(ah * 16 + al)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ planes
|
||||
-- jccolor.c rgb_ycc_start tables (16-bit fixed point)
|
||||
local function fix(x: number): number
|
||||
return math.floor(x * 65536 + 0.5)
|
||||
end
|
||||
local YR, YG, YB = fix(0.29900), fix(0.58700), fix(0.11400)
|
||||
local CBR, CBG, HALF = fix(0.16874), fix(0.33126), fix(0.5)
|
||||
local CRG, CRB = fix(0.41869), fix(0.08131)
|
||||
local OFF = 128 * 65536 + 32768 - 1
|
||||
|
||||
-- pixels (rgba8 / rgb8 / gray8) -> Y, Cb, Cr planes (w * h bytes each; Cb / Cr nil for grey output)
|
||||
local function planes(px: buffer, w: number, h: number, bpp: number, gray: boolean): (buffer, buffer?, buffer?)
|
||||
local n = w * h
|
||||
local Y = buffer.create(n)
|
||||
if bpp == 1 then
|
||||
buffer.copy(Y, 0, px, 0, n)
|
||||
if gray then
|
||||
return Y, nil, nil
|
||||
end
|
||||
local Cb = buffer.create(n)
|
||||
buffer.fill(Cb, 0, 128, n)
|
||||
local Cr = buffer.create(n)
|
||||
buffer.fill(Cr, 0, 128, n)
|
||||
return Y, Cb, Cr
|
||||
end
|
||||
if gray then
|
||||
for i = 0, n - 1 do
|
||||
local o = i * bpp
|
||||
local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2)
|
||||
writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536)
|
||||
end
|
||||
return Y, nil, nil
|
||||
end
|
||||
local Cb, Cr = buffer.create(n), buffer.create(n)
|
||||
for i = 0, n - 1 do
|
||||
local o = i * bpp
|
||||
local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2)
|
||||
writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536)
|
||||
writeu8(Cb, i, (-CBR * r - CBG * g + HALF * b + OFF) // 65536)
|
||||
writeu8(Cr, i, (HALF * r - CRG * g - CRB * b + OFF) // 65536)
|
||||
end
|
||||
return Y, Cb, Cr
|
||||
end
|
||||
|
||||
-- jcsample.c: a full-resolution plane (w x h) -> the component's samples, (bw * 8) x ch, for factors hf x vf
|
||||
-- (1 or 2 each); full-resolution columns past w - 1 repeat the last one, rows past h - 1 the last row
|
||||
local function downsample(src: buffer, w: number, h: number, hf: number, vf: number, outW: number, outH: number): buffer
|
||||
local out = buffer.create(outW * outH)
|
||||
for oy = 0, outH - 1 do
|
||||
local r0 = math.min(oy * vf, h - 1) * w
|
||||
local r1 = math.min(oy * vf + vf - 1, h - 1) * w
|
||||
local bias = if hf == 2 and vf == 2 then 1 elseif hf == 2 then 0 else (if vf == 2 then 1 else 0)
|
||||
for ox = 0, outW - 1 do
|
||||
local x0 = math.min(ox * hf, w - 1)
|
||||
local x1 = math.min(ox * hf + hf - 1, w - 1)
|
||||
local v
|
||||
if hf == 2 and vf == 2 then
|
||||
v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + readu8(src, r1 + x0) + readu8(src, r1 + x1) + bias) // 4
|
||||
bias = 3 - bias
|
||||
elseif hf == 2 then
|
||||
v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + bias) // 2
|
||||
bias = 1 - bias
|
||||
else
|
||||
v = (readu8(src, r0 + x0) + readu8(src, r1 + x0) + bias) // 2
|
||||
bias = 1 - bias
|
||||
end
|
||||
writeu8(out, oy * outW + ox, v)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
export type Options = {
|
||||
quality: number, -- 1..100
|
||||
sampling: string, -- "444" | "422" | "420"
|
||||
progressive: boolean,
|
||||
optimize: boolean, -- baseline: optimised Huffman tables (progressive always optimises)
|
||||
gray: boolean,
|
||||
restart: number, -- MCUs per restart interval (0 = none)
|
||||
segments: { { marker: number, data: buffer } }, -- APPn / COM segments after the JFIF header
|
||||
jfif: boolean,
|
||||
density: { unit: number, x: number, y: number }?,
|
||||
}
|
||||
|
||||
-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8); the caller
|
||||
-- validated sizes (1..65535) and options.
|
||||
function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer
|
||||
OUT = buffer.create(math.max(1024, w * h // 2))
|
||||
CAP = buffer.len(OUT)
|
||||
OP = 0
|
||||
ACC, NB = 0, 0
|
||||
GATHER = false
|
||||
EOBRUN, BE = 0, 0
|
||||
|
||||
local Y, Cb, Cr = planes(px, w, h, bpp, o.gray)
|
||||
local hs, vs = 1, 1
|
||||
if not o.gray then
|
||||
if o.sampling == "420" then
|
||||
hs, vs = 2, 2
|
||||
elseif o.sampling == "422" then
|
||||
hs, vs = 2, 1
|
||||
end
|
||||
end
|
||||
local mcusX = math.ceil(w / (8 * hs))
|
||||
local mcusY = math.ceil(h / (8 * vs))
|
||||
local qt = { Tables.quant(Tables.LUMA, o.quality), Tables.quant(Tables.CHROMA, o.quality) }
|
||||
local qdiv = {}
|
||||
for t = 1, 2 do
|
||||
local b = buffer.create(128)
|
||||
for i = 1, 64 do
|
||||
writeu16(b, (i - 1) * 2, qt[t][i])
|
||||
end
|
||||
qdiv[t] = b
|
||||
end
|
||||
|
||||
-- components and their quantised coefficients
|
||||
local comps: { Comp } = {}
|
||||
local srcs = if o.gray then { Y } else { Y, Cb :: buffer, Cr :: buffer }
|
||||
for i, src in srcs do
|
||||
local ch, cv = if i == 1 then hs else 1, if i == 1 then vs else 1
|
||||
local cw = math.ceil(w * ch / hs)
|
||||
local chh = math.ceil(h * cv / vs)
|
||||
local bw, bh = math.ceil(cw / 8), math.ceil(chh / 8)
|
||||
local bpl, bpc = mcusX * ch, mcusY * cv
|
||||
local plane, pw, ph = src, w, h
|
||||
if ch < hs or cv < vs then
|
||||
pw, ph = bw * 8, chh
|
||||
plane = downsample(src, w, h, hs // ch, vs // cv, pw, ph)
|
||||
end
|
||||
local coef = buffer.create(bpl * bpc * 128)
|
||||
local c: Comp = {
|
||||
id = i,
|
||||
h = ch,
|
||||
v = cv,
|
||||
tq = if i == 1 then 0 else 1,
|
||||
td = if i == 1 then 0 else 1,
|
||||
ta = if i == 1 then 0 else 1,
|
||||
bw = bw,
|
||||
bh = bh,
|
||||
bpl = bpl,
|
||||
bpc = bpc,
|
||||
coef = coef,
|
||||
last = 0,
|
||||
}
|
||||
local div = qdiv[c.tq + 1]
|
||||
for by = 0, bpc - 1 do
|
||||
for bx = 0, bpl - 1 do
|
||||
local off = (by * bpl + bx) * 128
|
||||
if by < bh and bx < bw then
|
||||
Dct.fdctQuantize(plane, pw, bx * 8, by * 8, pw, ph, div, coef, off)
|
||||
elseif by < bh then
|
||||
writei16(coef, off, readi16(coef, off - 128)) -- right edge: the previous block's DC
|
||||
else
|
||||
-- bottom: the DC of the MCU's last block in the row above
|
||||
local lb = (bx // ch) * ch + ch - 1
|
||||
writei16(coef, off, readi16(coef, ((by - 1) * bpl + lb) * 128))
|
||||
end
|
||||
end
|
||||
end
|
||||
comps[i] = c
|
||||
end
|
||||
|
||||
-- headers
|
||||
byte(0xFF)
|
||||
byte(0xD8)
|
||||
if o.jfif then
|
||||
local d = o.density or { unit = 0, x = 1, y = 1 }
|
||||
byte(0xFF)
|
||||
byte(0xE0)
|
||||
u16be(16)
|
||||
for _, ch in { 0x4A, 0x46, 0x49, 0x46, 0 } do
|
||||
byte(ch)
|
||||
end
|
||||
byte(1)
|
||||
byte(1)
|
||||
byte(d.unit)
|
||||
u16be(d.x)
|
||||
u16be(d.y)
|
||||
byte(0)
|
||||
byte(0)
|
||||
end
|
||||
for _, s in o.segments do
|
||||
local n = buffer.len(s.data)
|
||||
byte(0xFF)
|
||||
byte(s.marker)
|
||||
u16be(n + 2)
|
||||
grow(n)
|
||||
buffer.copy(OUT, OP, s.data, 0, n)
|
||||
OP += n
|
||||
end
|
||||
for t = 1, (if o.gray then 1 else 2) do
|
||||
byte(0xFF)
|
||||
byte(0xDB)
|
||||
u16be(67)
|
||||
byte(t - 1)
|
||||
for k = 0, 63 do
|
||||
byte(qt[t][readu8(ZZ, k) + 1])
|
||||
end
|
||||
end
|
||||
byte(0xFF)
|
||||
byte(if o.progressive then 0xC2 else 0xC0)
|
||||
u16be(8 + 3 * #comps)
|
||||
byte(8)
|
||||
u16be(h)
|
||||
u16be(w)
|
||||
byte(#comps)
|
||||
for _, c in comps do
|
||||
byte(c.id)
|
||||
byte(c.h * 16 + c.v)
|
||||
byte(c.tq)
|
||||
end
|
||||
local ntab = if o.gray then 1 else 2
|
||||
|
||||
local function restartMarker(n: number)
|
||||
flushBits()
|
||||
byte(0xFF)
|
||||
byte(0xD0 + n)
|
||||
end
|
||||
|
||||
if not o.progressive then
|
||||
if o.optimize then
|
||||
GATHER = true
|
||||
for t = 1, ntab do
|
||||
dcFreq[t] = table.create(257, 0)
|
||||
acFreq[t] = table.create(257, 0)
|
||||
end
|
||||
for _, c in comps do
|
||||
c.last = 0
|
||||
end
|
||||
walk(comps, mcusX, mcusY, o.restart, function()
|
||||
for _, c in comps do
|
||||
c.last = 0
|
||||
end
|
||||
end, blockSeq)
|
||||
GATHER = false
|
||||
end
|
||||
for t = 1, ntab do
|
||||
local dcC, dcS, acC, acS
|
||||
if o.optimize then
|
||||
dcC, dcS = optimal(dcFreq[t])
|
||||
acC, acS = optimal(acFreq[t])
|
||||
else
|
||||
local d, a = Tables.DC[t], Tables.AC[t]
|
||||
dcC, dcS, acC, acS = d.counts, d.symbols, a.counts, a.symbols
|
||||
end
|
||||
dcTab[t] = derive(dcC, dcS)
|
||||
acTab[t] = derive(acC, acS)
|
||||
dcFreq[t] = table.create(257, 0)
|
||||
acFreq[t] = table.create(257, 0)
|
||||
-- libjpeg emits each table before the scan in component order: DC0, AC0, DC1, AC1
|
||||
dht(0, t - 1, dcC, dcS)
|
||||
dht(1, t - 1, acC, acS)
|
||||
end
|
||||
if o.restart > 0 then
|
||||
byte(0xFF)
|
||||
byte(0xDD)
|
||||
u16be(4)
|
||||
u16be(o.restart)
|
||||
end
|
||||
sos(comps, 0, 63, 0, 0, false, false)
|
||||
for _, c in comps do
|
||||
c.last = 0
|
||||
end
|
||||
walk(comps, mcusX, mcusY, o.restart, function(n: number)
|
||||
restartMarker(n)
|
||||
for _, c in comps do
|
||||
c.last = 0
|
||||
end
|
||||
end, blockSeq)
|
||||
flushBits()
|
||||
else
|
||||
local script: { ScanSpec }
|
||||
if o.gray then
|
||||
script = {
|
||||
{ comps = { 1 }, ss = 0, se = 0, ah = 0, al = 1 },
|
||||
{ comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 },
|
||||
{ comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 },
|
||||
{ comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 },
|
||||
{ comps = { 1 }, ss = 0, se = 0, ah = 1, al = 0 },
|
||||
{ comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 },
|
||||
}
|
||||
else
|
||||
script = {
|
||||
{ comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 0, al = 1 },
|
||||
{ comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 },
|
||||
{ comps = { 3 }, ss = 1, se = 63, ah = 0, al = 1 },
|
||||
{ comps = { 2 }, ss = 1, se = 63, ah = 0, al = 1 },
|
||||
{ comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 },
|
||||
{ comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 },
|
||||
{ comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 1, al = 0 },
|
||||
{ comps = { 3 }, ss = 1, se = 63, ah = 1, al = 0 },
|
||||
{ comps = { 2 }, ss = 1, se = 63, ah = 1, al = 0 },
|
||||
{ comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 },
|
||||
}
|
||||
end
|
||||
local driSent = false
|
||||
for _, sc in script do
|
||||
local sComps = {}
|
||||
for _, ci in sc.comps do
|
||||
table.insert(sComps, comps[ci])
|
||||
end
|
||||
local ss, se, ah, al = sc.ss, sc.se, sc.ah, sc.al
|
||||
local isDc = ss == 0
|
||||
local blockFn: (Comp, number) -> ()
|
||||
if isDc and ah == 0 then
|
||||
blockFn = function(c: Comp, off: number)
|
||||
blockDcFirst(c, off, al)
|
||||
end
|
||||
elseif isDc then
|
||||
blockFn = function(c: Comp, off: number)
|
||||
bits(band(readi16(c.coef, off) // 2 ^ al, 1), 1)
|
||||
end
|
||||
elseif ah == 0 then
|
||||
blockFn = function(c: Comp, off: number)
|
||||
blockAcFirst(c, off, ss, se, al)
|
||||
end
|
||||
else
|
||||
blockFn = function(c: Comp, off: number)
|
||||
blockAcRefine(c, off, ss, se, al)
|
||||
end
|
||||
end
|
||||
local function onRestart(n: number)
|
||||
emitEobrun()
|
||||
if not GATHER then
|
||||
restartMarker(n)
|
||||
end
|
||||
for _, c in sComps do
|
||||
c.last = 0
|
||||
end
|
||||
EOBRUN, BE = 0, 0
|
||||
end
|
||||
local function pass()
|
||||
for _, c in sComps do
|
||||
c.last = 0
|
||||
end
|
||||
EOBRUN, BE = 0, 0
|
||||
walk(sComps, mcusX, mcusY, o.restart, onRestart, blockFn)
|
||||
emitEobrun()
|
||||
end
|
||||
-- gather statistics, then emit the optimal tables this scan uses
|
||||
if not (isDc and ah > 0) then
|
||||
GATHER = true
|
||||
for t = 1, ntab do
|
||||
dcFreq[t] = table.create(257, 0)
|
||||
acFreq[t] = table.create(257, 0)
|
||||
end
|
||||
if not isDc then
|
||||
curAcFreq = acFreq[sComps[1].ta + 1]
|
||||
end
|
||||
pass()
|
||||
GATHER = false
|
||||
local sent = {}
|
||||
for _, c in sComps do
|
||||
local slot = if isDc then c.td else c.ta
|
||||
if not sent[slot] then
|
||||
sent[slot] = true
|
||||
local counts, syms = optimal(if isDc then dcFreq[slot + 1] else acFreq[slot + 1])
|
||||
dht(if isDc then 0 else 1, slot, counts, syms)
|
||||
if isDc then
|
||||
dcTab[slot + 1] = derive(counts, syms)
|
||||
else
|
||||
acTab[slot + 1] = derive(counts, syms)
|
||||
end
|
||||
end
|
||||
end
|
||||
if not isDc then
|
||||
curAc = acTab[sComps[1].ta + 1]
|
||||
end
|
||||
end
|
||||
if o.restart > 0 and not driSent then
|
||||
driSent = true
|
||||
byte(0xFF)
|
||||
byte(0xDD)
|
||||
u16be(4)
|
||||
u16be(o.restart)
|
||||
end
|
||||
sos(sComps, ss, se, ah, al, isDc, not isDc or ah > 0) -- DC refinement uses no table: td = 0 (as libjpeg)
|
||||
pass()
|
||||
flushBits()
|
||||
end
|
||||
end
|
||||
byte(0xFF)
|
||||
byte(0xD9)
|
||||
local res = buffer.create(OP)
|
||||
buffer.copy(res, 0, OUT, 0, OP)
|
||||
OUT = buffer.create(0)
|
||||
CAP = 0
|
||||
return res
|
||||
end
|
||||
|
||||
return Encode
|
||||
@@ -0,0 +1,456 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from
|
||||
-- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header.
|
||||
--
|
||||
-- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF,
|
||||
-- records where each RSTn marker fell, and stops at any other marker. The clean buffer is followed by at least
|
||||
-- PAD zero bytes, so the bit reader can read 32 bits at any position up to PAD bytes past the end without a
|
||||
-- bounds check. `run` checks the position once per MCU, and no MCU (at most 10 blocks, enforced by the parser)
|
||||
-- can consume PAD bytes. So every buffer index stays in range, even on garbage data.
|
||||
--
|
||||
-- The bit reader keeps no state but a bit position: `peek` reads the big-endian 32-bit word that holds it.
|
||||
-- Huffman tables (built by `buildTable`) are buffers:
|
||||
-- [0, 1024) fast lookup by the next 9 bits: u16 (length << 8) | symbol, 0 = longer code
|
||||
-- [1024, 1096) maxcode[l], l = 0..17: u32, one past the last code of length l, left-aligned to 16 bits
|
||||
-- [1096, 1168) delta[l]: i32, symbol index = code + delta[l]
|
||||
-- [1168, 1424) symbols
|
||||
-- [1424, 1426) symbol count
|
||||
-- [1428, 3476) fast AC lookup by the next 9 bits: i32 value * 256 + run * 16 + total length, when the code
|
||||
-- and its extra bits fit in 9 bits (0 otherwise)
|
||||
local readu8, readu16, readu32, readi32, readi16 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readi16
|
||||
local writeu8, writeu16, writeu32, writei32, writei16 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei32, buffer.writei16
|
||||
local band, bor, lshift, rshift, byteswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.byteswap
|
||||
|
||||
local Scan = {}
|
||||
|
||||
Scan.PAD = 4096
|
||||
Scan.TABLE_SIZE = 3476
|
||||
|
||||
local T_MAX = 1024
|
||||
local T_DELTA = 1096
|
||||
local T_VAL = 1168
|
||||
local T_COUNT = 1424
|
||||
local T_FASTAC = 1428
|
||||
|
||||
-- zigzag index -> natural (row-major) index, padded with 63s so a run past the end stays in range
|
||||
local ZZ = buffer.create(80)
|
||||
do
|
||||
local i = 0
|
||||
for s = 0, 14 do
|
||||
local lo, hi = math.max(0, s - 7), math.min(s, 7)
|
||||
if s % 2 == 0 then
|
||||
for r = hi, lo, -1 do
|
||||
writeu8(ZZ, i, r * 8 + (s - r))
|
||||
i += 1
|
||||
end
|
||||
else
|
||||
for r = lo, hi do
|
||||
writeu8(ZZ, i, r * 8 + (s - r))
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
for j = 64, 79 do
|
||||
writeu8(ZZ, j, 63)
|
||||
end
|
||||
end
|
||||
Scan.ZIGZAG = ZZ
|
||||
|
||||
-- Builds a Huffman table from the 16 code-length counts and the symbols (Luau arrays, 1-based). An
|
||||
-- over-subscribed table keeps the codes that fit; the rest decode as invalid.
|
||||
function Scan.buildTable(counts: { number }, symbols: { number }): buffer
|
||||
local t = buffer.create(Scan.TABLE_SIZE)
|
||||
local code, k = 0, 0
|
||||
local nsym = #symbols
|
||||
local codes, sizes = {}, {}
|
||||
local broken = false
|
||||
for l = 1, 16 do
|
||||
writei32(t, T_DELTA + l * 4, k - code)
|
||||
local n = counts[l] or 0
|
||||
for _ = 1, n do
|
||||
if broken or code >= lshift(1, l) or k >= nsym or k >= 256 then
|
||||
broken = true
|
||||
break
|
||||
end
|
||||
k += 1
|
||||
codes[k] = code
|
||||
sizes[k] = l
|
||||
code += 1
|
||||
end
|
||||
writeu32(t, T_MAX + l * 4, if broken then 0 else lshift(code, 16 - l))
|
||||
code *= 2
|
||||
end
|
||||
writeu32(t, T_MAX + 17 * 4, 0xFFFFFFFF)
|
||||
for i = 1, k do
|
||||
writeu8(t, T_VAL + i - 1, symbols[i])
|
||||
end
|
||||
writeu16(t, T_COUNT, k)
|
||||
-- fast lookups
|
||||
for i = 1, k do
|
||||
local l = sizes[i]
|
||||
if l <= 9 then
|
||||
local sym = symbols[i]
|
||||
local base = lshift(codes[i], 9 - l)
|
||||
for j = 0, lshift(1, 9 - l) - 1 do
|
||||
local idx = base + j
|
||||
writeu16(t, idx * 2, l * 256 + sym)
|
||||
local r, s = rshift(sym, 4), band(sym, 15)
|
||||
if s ~= 0 and l + s <= 9 then
|
||||
local v = band(rshift(idx, 9 - l - s), lshift(1, s) - 1)
|
||||
if v < lshift(1, s - 1) then
|
||||
v = v - lshift(1, s) + 1
|
||||
end
|
||||
writei32(t, T_FASTAC + idx * 4, v * 256 + r * 16 + l + s)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
-- Copies the entropy-coded data at src[pos..n) into dst (at least n - pos + PAD bytes): byte stuffing removed,
|
||||
-- RSTn offsets (in dst) stored in rst[1..]. Returns the source position of the marker that ended the scan (or n),
|
||||
-- the clean length, and the RST count. The PAD bytes after the clean data are zeroed.
|
||||
function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }): (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)
|
||||
o += 1
|
||||
pos = q + 1
|
||||
elseif m >= 0xD0 and m <= 0xD7 then
|
||||
nr += 1
|
||||
rst[nr] = o
|
||||
pos = q + 1
|
||||
else
|
||||
pos = q - 1
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
buffer.fill(dst, o, 0, Scan.PAD)
|
||||
return pos, o, nr
|
||||
end
|
||||
|
||||
local function huff(d: buffer, pos: number, t: buffer): (number, number)
|
||||
local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
|
||||
local f = readu16(t, rshift(w, 23) * 2)
|
||||
if f ~= 0 then
|
||||
return band(f, 255), pos + rshift(f, 8)
|
||||
end
|
||||
local c = rshift(w, 16)
|
||||
local l = 10
|
||||
while c >= readu32(t, T_MAX + l * 4) do
|
||||
l += 1
|
||||
end
|
||||
if l > 16 then
|
||||
return 0, pos + 16 -- invalid code
|
||||
end
|
||||
local idx = rshift(c, 16 - l) + readi32(t, T_DELTA + l * 4)
|
||||
if idx < 0 or idx >= readu16(t, T_COUNT) then
|
||||
return 0, pos + l
|
||||
end
|
||||
return readu8(t, T_VAL + idx), pos + l
|
||||
end
|
||||
|
||||
-- the next s bits (1 <= s <= 16) as an unsigned number
|
||||
local function bits(d: buffer, pos: number, s: number): number
|
||||
return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s)
|
||||
end
|
||||
|
||||
local function extend(v: number, s: number): number
|
||||
if v < lshift(1, s - 1) then
|
||||
return v - lshift(1, s) + 1
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- sequential (baseline / extended) block: returns pos, DC predictor
|
||||
local function blockSeq(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, act: buffer, pred: number): (number, number)
|
||||
local s
|
||||
s, pos = huff(d, pos, dct)
|
||||
if s ~= 0 then
|
||||
if s > 16 then
|
||||
s = 16
|
||||
end
|
||||
pred += extend(bits(d, pos, s), s)
|
||||
pos += s
|
||||
end
|
||||
writei16(coef, off, pred)
|
||||
local k = 1
|
||||
while k < 64 do
|
||||
local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
|
||||
local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4)
|
||||
if fa ~= 0 then
|
||||
local low = fa % 256
|
||||
k += low // 16
|
||||
pos += low % 16
|
||||
if k > 63 then
|
||||
break
|
||||
end
|
||||
writei16(coef, off + readu8(ZZ, k) * 2, fa // 256)
|
||||
k += 1
|
||||
else
|
||||
local rs
|
||||
rs, pos = huff(d, pos, act)
|
||||
local r, sz = rshift(rs, 4), band(rs, 15)
|
||||
if sz == 0 then
|
||||
if r ~= 15 then
|
||||
break
|
||||
end
|
||||
k += 16
|
||||
else
|
||||
k += r
|
||||
if k > 63 then
|
||||
break
|
||||
end
|
||||
writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, sz), sz))
|
||||
pos += sz
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return pos, pred
|
||||
end
|
||||
|
||||
local function blockDcFirst(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, pred: number, al: number): (number, number)
|
||||
local s
|
||||
s, pos = huff(d, pos, dct)
|
||||
if s ~= 0 then
|
||||
if s > 16 then
|
||||
s = 16
|
||||
end
|
||||
pred += extend(bits(d, pos, s), s)
|
||||
pos += s
|
||||
end
|
||||
writei16(coef, off, pred * lshift(1, al))
|
||||
return pos, pred
|
||||
end
|
||||
|
||||
local function blockAcFirst(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number)
|
||||
if eobrun > 0 then
|
||||
return pos, eobrun - 1
|
||||
end
|
||||
local mul = lshift(1, al)
|
||||
local k = ss
|
||||
while k <= se do
|
||||
local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
|
||||
local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4)
|
||||
if fa ~= 0 then
|
||||
local low = fa % 256
|
||||
k += low // 16
|
||||
pos += low % 16
|
||||
if k > se then
|
||||
break
|
||||
end
|
||||
writei16(coef, off + readu8(ZZ, k) * 2, (fa // 256) * mul)
|
||||
k += 1
|
||||
else
|
||||
local rs
|
||||
rs, pos = huff(d, pos, act)
|
||||
local r, s = rshift(rs, 4), band(rs, 15)
|
||||
if s == 0 then
|
||||
if r < 15 then
|
||||
eobrun = lshift(1, r) - 1
|
||||
if r > 0 then
|
||||
eobrun += bits(d, pos, r)
|
||||
pos += r
|
||||
end
|
||||
break
|
||||
end
|
||||
k += 16
|
||||
else
|
||||
k += r
|
||||
if k > se then
|
||||
break
|
||||
end
|
||||
writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, s), s) * mul)
|
||||
pos += s
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return pos, eobrun
|
||||
end
|
||||
|
||||
-- successive-approximation refinement of AC coefficients ss..se (as stb_image / libjpeg decode_mcu_AC_refine)
|
||||
local function blockAcRefine(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number)
|
||||
local bit = lshift(1, al)
|
||||
if eobrun > 0 then
|
||||
for k = ss, se do
|
||||
local o = off + readu8(ZZ, k) * 2
|
||||
local p = readi16(coef, o)
|
||||
if p ~= 0 then
|
||||
local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
|
||||
pos += 1
|
||||
if b ~= 0 and band(p, bit) == 0 then
|
||||
writei16(coef, o, if p > 0 then p + bit else p - bit)
|
||||
end
|
||||
end
|
||||
end
|
||||
return pos, eobrun - 1
|
||||
end
|
||||
local k = ss
|
||||
while k <= se do
|
||||
local rs
|
||||
rs, pos = huff(d, pos, act)
|
||||
local s, r = band(rs, 15), rshift(rs, 4)
|
||||
local val = 0
|
||||
if s == 0 then
|
||||
if r < 15 then
|
||||
eobrun = lshift(1, r) - 1
|
||||
if r > 0 then
|
||||
eobrun += bits(d, pos, r)
|
||||
pos += r
|
||||
end
|
||||
r = 64 -- the rest of the block only refines
|
||||
end
|
||||
else
|
||||
-- s must be 1; anything else is corrupt and treated as 1
|
||||
local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
|
||||
pos += 1
|
||||
val = if b ~= 0 then bit else -bit
|
||||
end
|
||||
while k <= se do
|
||||
local o = off + readu8(ZZ, k) * 2
|
||||
k += 1
|
||||
local p = readi16(coef, o)
|
||||
if p ~= 0 then
|
||||
local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
|
||||
pos += 1
|
||||
if b ~= 0 and band(p, bit) == 0 then
|
||||
writei16(coef, o, if p > 0 then p + bit else p - bit)
|
||||
end
|
||||
else
|
||||
if r == 0 then
|
||||
if val ~= 0 then
|
||||
writei16(coef, o, val)
|
||||
end
|
||||
break
|
||||
end
|
||||
r -= 1
|
||||
end
|
||||
end
|
||||
end
|
||||
-- an EOB run that started in this block counts it already (eobrun = run length - 1)
|
||||
return pos, eobrun
|
||||
end
|
||||
|
||||
export type ScanComp = {
|
||||
coef: buffer, -- i16 coefficients, 64 per block in natural order, blocks row-major on a bpl-wide grid
|
||||
bpl: number,
|
||||
h: number,
|
||||
v: number,
|
||||
bw: number, -- blocks across / down the component itself (non-interleaved scans)
|
||||
bh: number,
|
||||
dct: buffer?,
|
||||
act: buffer?,
|
||||
pred: number,
|
||||
}
|
||||
|
||||
export type ScanParams = {
|
||||
comps: { ScanComp },
|
||||
mcusX: number,
|
||||
mcusY: number,
|
||||
ri: number, -- restart interval in MCUs (0 = none)
|
||||
mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine
|
||||
ss: number,
|
||||
se: number,
|
||||
al: number,
|
||||
}
|
||||
|
||||
-- Decodes one scan from the clean data d (cleanLen bytes, then PAD zeros). Returns the final bit position and
|
||||
-- whether the data ran out (or overran) before the last MCU.
|
||||
function Scan.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, P: ScanParams): (number, boolean)
|
||||
local comps = P.comps
|
||||
local nc = #comps
|
||||
local mode, ss, se, al, ri = P.mode, P.ss, P.se, P.al, P.ri
|
||||
local endBits = cleanLen * 8
|
||||
local units, ux
|
||||
if nc == 1 then
|
||||
ux = comps[1].bw
|
||||
units = ux * comps[1].bh
|
||||
else
|
||||
ux = P.mcusX
|
||||
units = ux * P.mcusY
|
||||
end
|
||||
for i = 1, nc do
|
||||
comps[i].pred = 0
|
||||
end
|
||||
local pos, eobrun, rstIdx = 0, 0, 0
|
||||
local truncated, skipping = false, false
|
||||
local bit = lshift(1, al)
|
||||
for u = 0, units - 1 do
|
||||
if ri > 0 and u > 0 and u % ri == 0 then
|
||||
rstIdx += 1
|
||||
if rstIdx <= nrst then
|
||||
pos = rst[rstIdx] * 8
|
||||
skipping = false
|
||||
end
|
||||
for i = 1, nc do
|
||||
comps[i].pred = 0
|
||||
end
|
||||
eobrun = 0
|
||||
end
|
||||
if pos > endBits then
|
||||
truncated = true
|
||||
if ri == 0 or rstIdx >= nrst then
|
||||
break
|
||||
end
|
||||
skipping = true
|
||||
end
|
||||
if not skipping then
|
||||
local my, mx = u // ux, u % ux
|
||||
for ci = 1, nc do
|
||||
local c = comps[ci]
|
||||
local bh, bw, by0, bx0
|
||||
if nc == 1 then
|
||||
bh, bw, by0, bx0 = 1, 1, my, mx
|
||||
else
|
||||
bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h
|
||||
end
|
||||
local coef, bpl = c.coef, c.bpl
|
||||
for by = by0, by0 + bh - 1 do
|
||||
for bx = bx0, bx0 + bw - 1 do
|
||||
local off = (by * bpl + bx) * 128
|
||||
if mode == 0 then
|
||||
pos, c.pred = blockSeq(d, pos, coef, off, c.dct :: buffer, c.act :: buffer, c.pred)
|
||||
elseif mode == 1 then
|
||||
pos, c.pred = blockDcFirst(d, pos, coef, off, c.dct :: buffer, c.pred, al)
|
||||
elseif mode == 2 then
|
||||
local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
|
||||
pos += 1
|
||||
if b ~= 0 then
|
||||
writei16(coef, off, bor(readi16(coef, off), bit))
|
||||
end
|
||||
elseif mode == 3 then
|
||||
pos, eobrun = blockAcFirst(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun)
|
||||
else
|
||||
pos, eobrun = blockAcRefine(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return pos, truncated
|
||||
end
|
||||
|
||||
return Scan
|
||||
@@ -0,0 +1,77 @@
|
||||
--!strict
|
||||
-- image/jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline
|
||||
-- encoder without optimisation writes and Motion-JPEG frames leave out) and the luminance / chrominance quantisation
|
||||
-- tables (K.1) with libjpeg's quality scaling (jcparam.c jpeg_quality_scaling / jpeg_add_quant_table).
|
||||
local Tables = {}
|
||||
|
||||
local function range(t: { number }, a: number, b: number)
|
||||
for v = a, b do
|
||||
table.insert(t, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- { counts (16 code-length counts), symbols } per table: dc[1] luma, dc[2] chroma, ac[1], ac[2]
|
||||
local dcl = { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }
|
||||
local dcc = { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }
|
||||
local dcv = {}
|
||||
range(dcv, 0, 11)
|
||||
local acl = { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d }
|
||||
local aclv = {
|
||||
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
|
||||
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
|
||||
0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
|
||||
0x29, 0x2a,
|
||||
}
|
||||
range(aclv, 0x34, 0x3a)
|
||||
for hi = 4, 8 do
|
||||
range(aclv, hi * 16 + 3, hi * 16 + 10)
|
||||
end
|
||||
for hi = 9, 13 do
|
||||
range(aclv, hi * 16 + 2, hi * 16 + 10)
|
||||
end
|
||||
range(aclv, 0xe1, 0xea)
|
||||
range(aclv, 0xf1, 0xfa)
|
||||
local acc = { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 }
|
||||
local accv = {
|
||||
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
|
||||
0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
|
||||
0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
|
||||
0x27, 0x28, 0x29, 0x2a,
|
||||
}
|
||||
range(accv, 0x35, 0x3a)
|
||||
for hi = 4, 7 do
|
||||
range(accv, hi * 16 + 3, hi * 16 + 10)
|
||||
end
|
||||
for hi = 8, 14 do
|
||||
range(accv, hi * 16 + 2, hi * 16 + 10)
|
||||
end
|
||||
range(accv, 0xf2, 0xfa)
|
||||
|
||||
export type Spec = { counts: { number }, symbols: { number } }
|
||||
Tables.DC = { { counts = dcl, symbols = dcv }, { counts = dcc, symbols = dcv } } :: { Spec }
|
||||
Tables.AC = { { counts = acl, symbols = aclv }, { counts = acc, symbols = accv } } :: { Spec }
|
||||
|
||||
-- K.1, natural (row-major) order
|
||||
Tables.LUMA = {
|
||||
16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29,
|
||||
51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121,
|
||||
120, 101, 72, 92, 95, 98, 112, 100, 103, 99,
|
||||
}
|
||||
Tables.CHROMA = {
|
||||
17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99,
|
||||
99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
|
||||
99, 99, 99, 99, 99, 99, 99, 99,
|
||||
}
|
||||
|
||||
-- quant(base, quality) -> 64 values (natural order) for quality 1..100, clamped to 1..255 (baseline)
|
||||
function Tables.quant(base: { number }, quality: number): { number }
|
||||
local q = math.clamp(math.floor(quality), 1, 100)
|
||||
local scale = if q < 50 then 5000 // q else 200 - q * 2
|
||||
local out = table.create(64, 1)
|
||||
for i = 1, 64 do
|
||||
out[i] = math.clamp((base[i] * scale + 50) // 100, 1, 255)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return Tables
|
||||
@@ -0,0 +1,285 @@
|
||||
--!strict
|
||||
-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81). Absorbed from jpeg-luau 1.0 (same author: the Huffman decoder, IDCTs,
|
||||
-- upsampling and colour conversion, bit-exact with libjpeg-turbo's djpeg) and extended with arithmetic coding, meta
|
||||
-- (EXIF, ICC, comments, density) and an encoder. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md.
|
||||
-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit
|
||||
-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt
|
||||
-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's
|
||||
-- reduced IDCTs), EXIF orientation reported in meta.orientation and applied with opts.orient. Truncated or corrupt
|
||||
-- scans decode as far as they go (meta.truncated = true).
|
||||
-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or
|
||||
-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, EXIF / ICC / comment segments from meta;
|
||||
-- byte-identical to cjpeg for the same settings.
|
||||
-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, ICC colour management, 12-bit
|
||||
-- or CMYK encoding.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Decode = require("@formats/image/jpeg/Decode")
|
||||
local Encode = require("@formats/image/jpeg/Encode")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Jpeg = {
|
||||
name = "jpeg",
|
||||
category = "image",
|
||||
extensions = { "jpg", "jpeg", "jpe", "jfif" },
|
||||
mime = { "image/jpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" },
|
||||
caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only)
|
||||
orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only)
|
||||
native: boolean?, -- grey files decode to gray8 (default false: rgba8)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables
|
||||
subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420")
|
||||
progressive: boolean?, -- default false
|
||||
optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises)
|
||||
gray: boolean?, -- a one-component file (default: true for gray8 images)
|
||||
restart: number?, -- restart interval in MCUs (default 0 = none)
|
||||
jfif: boolean?, -- write the JFIF APP0 header (default true)
|
||||
meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true)
|
||||
}
|
||||
|
||||
export type Info = {
|
||||
width: number,
|
||||
height: number,
|
||||
components: number,
|
||||
progressive: boolean,
|
||||
arithmetic: boolean,
|
||||
precision: number,
|
||||
colorSpace: string,
|
||||
sampling: { { number } }, -- { h, v } per component
|
||||
orientation: number,
|
||||
adobe: number?,
|
||||
jfif: boolean,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Jpeg.sniff(r: Bytes.Reader): number
|
||||
local s = r:peek(3)
|
||||
return if s == "\255\216\255" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function parse(r: Bytes.Reader, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?)
|
||||
local ok, st, code, msg = pcall(Decode.parse, r.buf, r.base, r.limit, opts, headerOnly)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st))
|
||||
end
|
||||
if not st then
|
||||
return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed")
|
||||
end
|
||||
return st, nil
|
||||
end
|
||||
|
||||
-- info(r) -> Info | nil, Err (reads the headers up to the frame header)
|
||||
function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
local st, err = parse(r, nil, true)
|
||||
if not st then
|
||||
return nil, err
|
||||
end
|
||||
local f = st.frame
|
||||
local sampling = {}
|
||||
for _, c in f.comps do
|
||||
table.insert(sampling, { c.h, c.v })
|
||||
end
|
||||
return {
|
||||
width = f.width,
|
||||
height = f.height,
|
||||
components = #f.comps,
|
||||
progressive = f.progressive,
|
||||
arithmetic = f.arithmetic,
|
||||
precision = f.precision,
|
||||
colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif),
|
||||
sampling = sampling,
|
||||
orientation = st.orientation,
|
||||
adobe = st.adobe,
|
||||
jfif = st.jfif,
|
||||
},
|
||||
nil
|
||||
end
|
||||
|
||||
-- the EXIF orientation applied to rgba8 pixels: buffer, width, height
|
||||
local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number)
|
||||
if o <= 1 or o > 8 then
|
||||
return px, w, h
|
||||
end
|
||||
local swap = o >= 5
|
||||
local ow, oh = if swap then h else w, if swap then w else h
|
||||
local out = buffer.create(ow * oh * 4)
|
||||
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
||||
for y = 0, oh - 1 do
|
||||
for x = 0, ow - 1 do
|
||||
local col, row
|
||||
if o == 2 then
|
||||
col, row = w - 1 - x, y
|
||||
elseif o == 3 then
|
||||
col, row = w - 1 - x, h - 1 - y
|
||||
elseif o == 4 then
|
||||
col, row = x, h - 1 - y
|
||||
elseif o == 5 then
|
||||
col, row = y, x
|
||||
elseif o == 6 then
|
||||
col, row = y, h - 1 - x
|
||||
elseif o == 7 then
|
||||
col, row = w - 1 - y, h - 1 - x
|
||||
else
|
||||
col, row = w - 1 - y, x
|
||||
end
|
||||
writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4))
|
||||
end
|
||||
end
|
||||
return out, ow, oh
|
||||
end
|
||||
|
||||
function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local st, err = parse(r, opts, false)
|
||||
if not st then
|
||||
return nil, err
|
||||
end
|
||||
local ok, w, h, px, space = pcall(Decode.output, st :: Decode.State)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
|
||||
end
|
||||
if not w then
|
||||
return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px))
|
||||
end
|
||||
local orientation = st.orientation
|
||||
if opts and opts.orient then
|
||||
px, w, h = orient(px, w, h, orientation)
|
||||
end
|
||||
local img = Types.Image.new(1, 1)
|
||||
img.width, img.height, img.pixels = w, h, px
|
||||
if opts and opts.native and space == "gray" then
|
||||
local g = buffer.create(w * h)
|
||||
for i = 0, w * h - 1 do
|
||||
buffer.writeu8(g, i, buffer.readu8(px, i * 4))
|
||||
end
|
||||
img.pixels, img.format = g, "gray8"
|
||||
end
|
||||
local f = st.frame
|
||||
local sampling = {}
|
||||
for _, c in f.comps do
|
||||
table.insert(sampling, { c.h, c.v })
|
||||
end
|
||||
img.meta.orientation = orientation
|
||||
img.meta.oriented = (opts and opts.orient) or false
|
||||
img.meta.exif = st.exif
|
||||
img.meta.icc = st.icc
|
||||
if #st.comments > 0 then
|
||||
img.meta.text = { comment = table.concat(st.comments, "\n") }
|
||||
end
|
||||
if st.density and st.density.unit > 0 and st.density.x > 0 and st.density.y > 0 then
|
||||
local k = if st.density.unit == 2 then 2.54 else 1
|
||||
img.meta.dpi = { x = st.density.x * k, y = st.density.y * k }
|
||||
end
|
||||
img.meta.truncated = st.truncated
|
||||
img.meta.source = {
|
||||
format = "jpeg",
|
||||
bitDepth = f.precision,
|
||||
colorType = space,
|
||||
components = #f.comps,
|
||||
progressive = f.progressive,
|
||||
arithmetic = f.arithmetic,
|
||||
sampling = sampling,
|
||||
scale = st.scale,
|
||||
adobe = st.adobe,
|
||||
jfif = st.jfif,
|
||||
}
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1 }
|
||||
|
||||
function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local bpp = BPP[img.format]
|
||||
if not bpp then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image (got " .. tostring(img.format) .. ")")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
|
||||
return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
|
||||
end
|
||||
local o: any = opts or {}
|
||||
local quality = o.quality or 90
|
||||
if type(quality) ~= "number" or quality < 1 or quality > 100 then
|
||||
return nil, Err.new(Err.ARG, "quality must be 1..100")
|
||||
end
|
||||
local sub = o.subsampling or "420"
|
||||
if sub ~= "420" and sub ~= "422" and sub ~= "444" then
|
||||
return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"")
|
||||
end
|
||||
local restart = o.restart or 0
|
||||
if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs")
|
||||
end
|
||||
local gray = o.gray
|
||||
if gray == nil then
|
||||
gray = img.format == "gray8"
|
||||
end
|
||||
local segments = {}
|
||||
local meta = img.meta or {}
|
||||
if o.meta ~= false then
|
||||
if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then
|
||||
local d = buffer.create(buffer.len(meta.exif) + 6)
|
||||
buffer.writestring(d, 0, "Exif\0\0")
|
||||
buffer.copy(d, 6, meta.exif)
|
||||
table.insert(segments, { marker = 0xE1, data = d })
|
||||
end
|
||||
if type(meta.icc) == "buffer" then
|
||||
local icc = meta.icc :: buffer
|
||||
local n = buffer.len(icc)
|
||||
local chunk = 65519
|
||||
local count = math.max(1, math.ceil(n / chunk))
|
||||
if count <= 255 then
|
||||
for i = 1, count do
|
||||
local a = (i - 1) * chunk
|
||||
local l = math.min(chunk, n - a)
|
||||
local d = buffer.create(l + 14)
|
||||
buffer.writestring(d, 0, "ICC_PROFILE\0")
|
||||
buffer.writeu8(d, 12, i)
|
||||
buffer.writeu8(d, 13, count)
|
||||
buffer.copy(d, 14, icc, a, l)
|
||||
table.insert(segments, { marker = 0xE2, data = d })
|
||||
end
|
||||
end
|
||||
end
|
||||
local text = meta.text
|
||||
if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then
|
||||
table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) })
|
||||
end
|
||||
end
|
||||
local density = nil
|
||||
if type(meta.dpi) == "table" and type(meta.dpi.x) == "number" and type(meta.dpi.y) == "number" then
|
||||
density = { unit = 1, x = math.clamp(math.floor(meta.dpi.x + 0.5), 1, 65535), y = math.clamp(math.floor(meta.dpi.y + 0.5), 1, 65535) }
|
||||
end
|
||||
local out = Encode.run(img.pixels, w, h, bpp, {
|
||||
quality = quality,
|
||||
sampling = sub,
|
||||
progressive = o.progressive == true,
|
||||
optimize = o.optimize == true,
|
||||
gray = gray,
|
||||
restart = restart,
|
||||
segments = segments,
|
||||
jfif = o.jfif ~= false,
|
||||
density = density,
|
||||
})
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Jpeg
|
||||
@@ -0,0 +1,289 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/pnm/Codec: the Netpbm sample loops (native; never throws). Written from the Netpbm format pages (pbm, pgm,
|
||||
-- ppm, pam, pfm). Reading: binary 8 / 16-bit samples, ASCII samples (P1 digits may run together), P4 bit rows, PFM
|
||||
-- floats (either byte order, bottom-to-top rows); packing samples into a Types pixel format with maxval scaling.
|
||||
-- Writing: samples of any pixel format extracted at 1..4 channels and 8 or 16 bits. Every read is bounds-checked.
|
||||
local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16
|
||||
local readf32, writef32, readu32, writeu32 = buffer.readf32, buffer.writef32, buffer.readu32, buffer.writeu32
|
||||
local byteswap = bit32.byteswap
|
||||
|
||||
local Codec = {}
|
||||
|
||||
-- readSamples(b, p, limit, count, mode, out) -> true | false, message: count raw values into out (u16 each).
|
||||
-- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits)
|
||||
function Codec.readSamples(b: buffer, p: number, limit: number, count: number, mode: number, out: buffer): (boolean, string?)
|
||||
if mode == 1 then
|
||||
if p + count > limit then
|
||||
return false, "truncated"
|
||||
end
|
||||
for i = 0, count - 1 do
|
||||
writeu16(out, i * 2, readu8(b, p + i))
|
||||
end
|
||||
return true, nil
|
||||
elseif mode == 2 then
|
||||
if p + count * 2 > limit then
|
||||
return false, "truncated"
|
||||
end
|
||||
for i = 0, count - 1 do
|
||||
writeu16(out, i * 2, readu8(b, p + i * 2) * 256 + readu8(b, p + i * 2 + 1))
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
local i = 0
|
||||
while i < count do
|
||||
-- skip whitespace and comments
|
||||
while p < limit do
|
||||
local c = readu8(b, p)
|
||||
if c == 35 then -- '#'
|
||||
while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do
|
||||
p += 1
|
||||
end
|
||||
elseif c == 32 or (c >= 9 and c <= 13) then
|
||||
p += 1
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
if p >= limit then
|
||||
return false, "truncated"
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
if c < 48 or c > 57 then
|
||||
return false, "bad ASCII sample"
|
||||
end
|
||||
if mode == 4 then
|
||||
writeu16(out, i * 2, c - 48)
|
||||
p += 1
|
||||
else
|
||||
local v = 0
|
||||
while p < limit do
|
||||
local d = readu8(b, p)
|
||||
if d < 48 or d > 57 then
|
||||
break
|
||||
end
|
||||
v = math.min(v * 10 + d - 48, 65535)
|
||||
p += 1
|
||||
end
|
||||
writeu16(out, i * 2, v)
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- readBits(b, p, limit, w, h, out) -> ok, message: P4 rows (MSB first, rows padded to bytes) as u16 0 / 1 values
|
||||
function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: number, out: buffer): (boolean, string?)
|
||||
local rowBytes = (w + 7) // 8
|
||||
if p + rowBytes * h > limit then
|
||||
return false, "truncated"
|
||||
end
|
||||
for y = 0, h - 1 do
|
||||
local r = p + y * rowBytes
|
||||
for x = 0, w - 1 do
|
||||
local byte = readu8(b, r + x // 8)
|
||||
writeu16(out, (y * w + x) * 2, (byte // 2 ^ (7 - x % 8)) % 2)
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- format codes for pack / extract
|
||||
Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6
|
||||
|
||||
-- pack(samples, n, ch, maxval, invert, fmt, dst): n pixels of ch raw samples (u16, 0..maxval; invert: 1 - v for
|
||||
-- PBM bits) into dst in pixel format fmt, scaled to the format's range (8-bit: round(v * 255 / maxval))
|
||||
function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: boolean, fmt: number, dst: buffer)
|
||||
local wide = fmt == 4 or fmt == 5
|
||||
local top = if wide then 65535 else 255
|
||||
local half = maxval // 2
|
||||
local function get(i: number): number
|
||||
local v = math.min(readu16(s, i * 2), maxval)
|
||||
if invert then
|
||||
v = maxval - v
|
||||
end
|
||||
if maxval == top then
|
||||
return v
|
||||
end
|
||||
return (v * top + half) // maxval
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
local q = i * ch
|
||||
local r, g, b, a
|
||||
if ch == 1 then
|
||||
r = get(q)
|
||||
g, b, a = r, r, top
|
||||
elseif ch == 2 then
|
||||
r = get(q)
|
||||
g, b, a = r, r, get(q + 1)
|
||||
elseif ch == 3 then
|
||||
r, g, b, a = get(q), get(q + 1), get(q + 2), top
|
||||
else
|
||||
r, g, b, a = get(q), get(q + 1), get(q + 2), get(q + 3)
|
||||
end
|
||||
if fmt == 0 then
|
||||
writeu32(dst, i * 4, r + g * 256 + b * 65536 + a * 16777216)
|
||||
elseif fmt == 1 then
|
||||
writeu8(dst, i * 3, r)
|
||||
writeu8(dst, i * 3 + 1, g)
|
||||
writeu8(dst, i * 3 + 2, b)
|
||||
elseif fmt == 2 then
|
||||
writeu8(dst, i, r)
|
||||
elseif fmt == 3 then
|
||||
writeu8(dst, i * 2, r)
|
||||
writeu8(dst, i * 2 + 1, a)
|
||||
elseif fmt == 4 then
|
||||
writeu16(dst, i * 8, r)
|
||||
writeu16(dst, i * 8 + 2, g)
|
||||
writeu16(dst, i * 8 + 4, b)
|
||||
writeu16(dst, i * 8 + 6, a)
|
||||
elseif fmt == 5 then
|
||||
writeu16(dst, i * 2, r)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- readFloats(b, p, limit, w, h, ch, le, dst) -> ok, message: PFM rows (bottom-to-top) into rgbaf32 dst
|
||||
function Codec.readFloats(b: buffer, p: number, limit: number, w: number, h: number, ch: number, le: boolean, dst: buffer): (boolean, string?)
|
||||
if p + w * h * ch * 4 > limit then
|
||||
return false, "truncated"
|
||||
end
|
||||
local tmp = buffer.create(4)
|
||||
for y = 0, h - 1 do
|
||||
local row = p + (h - 1 - y) * w * ch * 4
|
||||
for x = 0, w - 1 do
|
||||
local o = (y * w + x) * 16
|
||||
for c = 0, ch - 1 do
|
||||
local v
|
||||
if le then
|
||||
v = readf32(b, row + (x * ch + c) * 4)
|
||||
else
|
||||
writeu32(tmp, 0, byteswap(readu32(b, row + (x * ch + c) * 4)))
|
||||
v = readf32(tmp, 0)
|
||||
end
|
||||
writef32(dst, o + c * 4, v)
|
||||
end
|
||||
if ch == 1 then
|
||||
local v = readf32(dst, o)
|
||||
writef32(dst, o + 4, v)
|
||||
writef32(dst, o + 8, v)
|
||||
end
|
||||
writef32(dst, o + 12, 1)
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
local function f(v: number): number
|
||||
if v ~= v then
|
||||
return 0
|
||||
end
|
||||
return math.floor(math.clamp(v, 0, 1) * 65535 + 0.5)
|
||||
end
|
||||
|
||||
-- extract(px, fmt, n, ch, wide) -> u16 samples: n pixels of format fmt as ch channels (1 grey (Rec. 601 luma for
|
||||
-- colour sources, Pillow's L = (299 R + 587 G + 114 B) / 1000), 2 grey + alpha, 3 RGB, 4 RGBA), 16-bit if wide
|
||||
function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boolean): buffer
|
||||
local out = buffer.create(n * ch * 2)
|
||||
local srcWide = fmt == 4 or fmt == 5
|
||||
local isGray = fmt == 2 or fmt == 3 or fmt == 5
|
||||
for i = 0, n - 1 do
|
||||
local r, g, b, a
|
||||
if fmt == 0 then
|
||||
r, g, b, a = readu8(px, i * 4), readu8(px, i * 4 + 1), readu8(px, i * 4 + 2), readu8(px, i * 4 + 3)
|
||||
elseif fmt == 1 then
|
||||
r, g, b, a = readu8(px, i * 3), readu8(px, i * 3 + 1), readu8(px, i * 3 + 2), 255
|
||||
elseif fmt == 2 then
|
||||
r = readu8(px, i)
|
||||
g, b, a = r, r, 255
|
||||
elseif fmt == 3 then
|
||||
r, a = readu8(px, i * 2), readu8(px, i * 2 + 1)
|
||||
g, b = r, r
|
||||
elseif fmt == 4 then
|
||||
r, g, b, a = readu16(px, i * 8), readu16(px, i * 8 + 2), readu16(px, i * 8 + 4), readu16(px, i * 8 + 6)
|
||||
elseif fmt == 5 then
|
||||
r = readu16(px, i * 2)
|
||||
g, b, a = r, r, 65535
|
||||
else
|
||||
r, g, b, a = f(readf32(px, i * 16)), f(readf32(px, i * 16 + 4)), f(readf32(px, i * 16 + 8)), f(readf32(px, i * 16 + 12))
|
||||
end
|
||||
local w16 = srcWide or fmt == 6
|
||||
local gray = r
|
||||
if ch <= 2 and not isGray then
|
||||
gray = (r * 299 + g * 587 + b * 114) // 1000
|
||||
end
|
||||
local vals = if ch == 1 then 1 elseif ch == 2 then 2 else ch
|
||||
for c = 0, vals - 1 do
|
||||
local v
|
||||
if ch <= 2 then
|
||||
v = if c == 0 then gray else a
|
||||
else
|
||||
v = if c == 0 then r elseif c == 1 then g elseif c == 2 then b else a
|
||||
end
|
||||
if wide and not w16 then
|
||||
v *= 257
|
||||
elseif w16 and not wide then
|
||||
v = (v * 255 + 32767) // 65535
|
||||
end
|
||||
writeu16(out, (i * ch + c) * 2, v)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- writeSamples(s, count, wide, out, o) -> new offset: binary samples (8-bit or 16-bit big-endian)
|
||||
function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer, o: number): number
|
||||
if wide then
|
||||
for i = 0, count - 1 do
|
||||
local v = readu16(s, i * 2)
|
||||
writeu8(out, o, v // 256)
|
||||
writeu8(out, o + 1, v % 256)
|
||||
o += 2
|
||||
end
|
||||
else
|
||||
for i = 0, count - 1 do
|
||||
writeu8(out, o, readu16(s, i * 2))
|
||||
o += 1
|
||||
end
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
-- writeBits(s, w, h, threshold, out, o) -> new offset: P4 rows from grey samples (below threshold = black = 1)
|
||||
function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out: buffer, o: number): number
|
||||
for y = 0, h - 1 do
|
||||
local acc, nb = 0, 0
|
||||
for x = 0, w - 1 do
|
||||
acc = acc * 2 + (if readu16(s, (y * w + x) * 2) < threshold then 1 else 0)
|
||||
nb += 1
|
||||
if nb == 8 then
|
||||
writeu8(out, o, acc)
|
||||
o += 1
|
||||
acc, nb = 0, 0
|
||||
end
|
||||
end
|
||||
if nb > 0 then
|
||||
writeu8(out, o, acc * 2 ^ (8 - nb))
|
||||
o += 1
|
||||
end
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
-- writeFloats(px, w, h, ch, out, o) -> new offset: rgbaf32 (ch 3) or its first channel (ch 1) as little-endian PFM
|
||||
-- rows, bottom-to-top
|
||||
function Codec.writeFloats(px: buffer, w: number, h: number, ch: number, out: buffer, o: number): number
|
||||
for y = h - 1, 0, -1 do
|
||||
for x = 0, w - 1 do
|
||||
local q = (y * w + x) * 16
|
||||
for c = 0, ch - 1 do
|
||||
writef32(out, o, readf32(px, q + c * 4))
|
||||
o += 4
|
||||
end
|
||||
end
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
return Codec
|
||||
@@ -0,0 +1,383 @@
|
||||
--!strict
|
||||
-- image/pnm: the Netpbm family, written from the Netpbm format pages: PBM (P1 ASCII / P4 binary), PGM (P2 / P5),
|
||||
-- PPM (P3 / P6), PAM (P7: BLACKANDWHITE, GRAYSCALE, GRAYSCALE_ALPHA, RGB, RGB_ALPHA and their _ALPHA forms, any
|
||||
-- tuple type of depth 1..4) and PFM (PF colour / Pf grey 32-bit float, either byte order, bottom-to-top rows).
|
||||
-- maxval 1..65535 (scaled to 8 bits by round(v * 255 / maxval)). Decode: rgba8, or with opts.native the source layout
|
||||
-- (gray8, gray16, graya8, rgb8, rgba8, rgba16 for 16-bit colour or grey + alpha, rgbaf32 for PFM). PFM to rgba8 is
|
||||
-- clamp(v, 0, 1) * 255 rounded (linear, no gamma). Encode: any of the seven types, binary or ASCII, from every pixel
|
||||
-- format; the subtype comes from opts.format / the file extension (pbm, pgm, ppm, pam, pfm) or the image.
|
||||
-- Not supported: multi-image streams (the first image is read), PAM depths above 4.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Codec = require("@formats/image/pnm/Codec")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Pnm = {
|
||||
name = "pnm",
|
||||
category = "image",
|
||||
extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" },
|
||||
mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
native: boolean?, -- keep the source layout (default false: rgba8)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
format: string?, -- "pbm" | "pgm" | "ppm" | "pam" | "pfm" (default: from the image: grey -> pgm, opaque colour
|
||||
-- -> ppm, alpha -> pam, rgbaf32 -> pfm); "pnm" means the default
|
||||
ascii: boolean?, -- P1 / P2 / P3 instead of P4 / P5 / P6 (default false)
|
||||
maxval: number?, -- 1..65535 (default 255, or 65535 for 16-bit / float sources); pbm ignores it
|
||||
threshold: number?, -- pbm: grey below this (0..255) is black (default 128)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local FMT_CODE = { rgba8 = 0, rgb8 = 1, gray8 = 2, graya8 = 3, rgba16 = 4, gray16 = 5, rgbaf32 = 6 }
|
||||
local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, graya8 = 2, rgba16 = 8, gray16 = 2, rgbaf32 = 16 }
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Pnm.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 3 then
|
||||
return 0
|
||||
end
|
||||
local a, b, c = r:peekU8(0), r:peekU8(1), r:peekU8(2)
|
||||
if a ~= 80 then -- 'P'
|
||||
return 0
|
||||
end
|
||||
local ws = c == 32 or (c >= 9 and c <= 13)
|
||||
if b >= 49 and b <= 55 and ws then -- P1..P7
|
||||
return 0.9
|
||||
end
|
||||
if (b == 70 or b == 102) and ws then -- PF / Pf
|
||||
return 0.9
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function isSpace(c: number): boolean
|
||||
return c == 32 or (c >= 9 and c <= 13)
|
||||
end
|
||||
|
||||
-- the next header token from p: token, position after it (nil at the end)
|
||||
local function token(b: buffer, p: number, limit: number): (string?, number)
|
||||
while p < limit do
|
||||
local c = readu8(b, p)
|
||||
if c == 35 then
|
||||
while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do
|
||||
p += 1
|
||||
end
|
||||
elseif isSpace(c) then
|
||||
p += 1
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
local s = p
|
||||
while p < limit and not isSpace(readu8(b, p)) and readu8(b, p) ~= 35 do
|
||||
p += 1
|
||||
end
|
||||
if p == s then
|
||||
return nil, p
|
||||
end
|
||||
return buffer.readstring(b, s, p - s), p
|
||||
end
|
||||
|
||||
local function int(s: string?): number?
|
||||
if s == nil or not string.match(s, "^%d+$") or #s > 9 then
|
||||
return nil
|
||||
end
|
||||
return tonumber(s)
|
||||
end
|
||||
|
||||
function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
local native = opts and opts.native or false
|
||||
local b, limit = r.buf, r.limit
|
||||
if r.limit - r.base < 3 or readu8(b, r.base) ~= 80 then
|
||||
return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base)
|
||||
end
|
||||
local kind = string.char(readu8(b, r.base + 1))
|
||||
local p = r.base + 2
|
||||
local w, h, maxval, ch, mode
|
||||
local bits = false -- PBM: 1 = black
|
||||
local bw = false -- PAM BLACKANDWHITE: 1 = white
|
||||
local tupl: string? = nil
|
||||
local scale: number? = nil
|
||||
if kind == "1" or kind == "2" or kind == "3" or kind == "4" or kind == "5" or kind == "6" or kind == "F" or kind == "f" then
|
||||
local t1, t2, t3
|
||||
t1, p = token(b, p, limit)
|
||||
t2, p = token(b, p, limit)
|
||||
w, h = int(t1), int(t2)
|
||||
if kind == "1" or kind == "4" then
|
||||
maxval = 1
|
||||
elseif kind == "F" or kind == "f" then
|
||||
t3, p = token(b, p, limit)
|
||||
scale = if t3 then tonumber(t3) else nil
|
||||
if scale == nil or scale == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad PFM scale", p)
|
||||
end
|
||||
maxval = 1
|
||||
else
|
||||
t3, p = token(b, p, limit)
|
||||
maxval = int(t3)
|
||||
end
|
||||
if w == nil or h == nil or maxval == nil then
|
||||
return nil, if p >= limit then Err.new(Err.TRUNCATED, "header ends early", p) else Err.new(Err.CORRUPT, "bad header", p)
|
||||
end
|
||||
if kind ~= "1" and kind ~= "2" and kind ~= "3" then
|
||||
p += 1 -- exactly one whitespace byte before binary data
|
||||
end
|
||||
ch = if kind == "3" or kind == "6" or kind == "F" then 3 else 1
|
||||
bits = kind == "1" or kind == "4"
|
||||
mode = if kind == "1" then 4 elseif kind == "2" or kind == "3" then 3 elseif kind == "4" then 0 elseif maxval > 255 then 2 else 1
|
||||
elseif kind == "7" then
|
||||
local depth
|
||||
while true do
|
||||
local key
|
||||
key, p = token(b, p, limit)
|
||||
if key == nil then
|
||||
return nil, Err.new(Err.TRUNCATED, "PAM header ends early", p)
|
||||
end
|
||||
if key == "ENDHDR" then
|
||||
break
|
||||
end
|
||||
local v
|
||||
v, p = token(b, p, limit)
|
||||
if key == "WIDTH" then
|
||||
w = int(v)
|
||||
elseif key == "HEIGHT" then
|
||||
h = int(v)
|
||||
elseif key == "DEPTH" then
|
||||
depth = int(v)
|
||||
elseif key == "MAXVAL" then
|
||||
maxval = int(v)
|
||||
elseif key == "TUPLTYPE" then
|
||||
tupl = v
|
||||
-- the rest of the line belongs to the value
|
||||
while p < limit and readu8(b, p) ~= 10 do
|
||||
p += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
-- ENDHDR ends with a newline
|
||||
while p < limit and readu8(b, p) ~= 10 do
|
||||
p += 1
|
||||
end
|
||||
p += 1
|
||||
if w == nil or h == nil or depth == nil or maxval == nil then
|
||||
return nil, Err.new(Err.CORRUPT, "PAM header misses WIDTH / HEIGHT / DEPTH / MAXVAL", p)
|
||||
end
|
||||
if depth < 1 or depth > 4 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "PAM depth " .. depth)
|
||||
end
|
||||
ch = depth
|
||||
bw = tupl ~= nil and string.sub(tupl, 1, 13) == "BLACKANDWHITE"
|
||||
mode = if maxval > 255 then 2 else 1
|
||||
else
|
||||
return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base)
|
||||
end
|
||||
if w < 1 or h < 1 or maxval < 1 or maxval > 65535 then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d or maxval %d", w, h, maxval))
|
||||
end
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local n = w * h
|
||||
local img: Types.Image
|
||||
local colorType = if ch == 1 then "gray" elseif ch == 2 then "graya" elseif ch == 3 then "rgb" else "rgba"
|
||||
if scale then
|
||||
local f = Types.Image.new(w, h, "rgbaf32")
|
||||
local ok, e = Codec.readFloats(b, p, limit, w, h, ch, (scale :: number) < 0, f.pixels)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.TRUNCATED, tostring(e))
|
||||
end
|
||||
img = f
|
||||
if not native then
|
||||
local o = Types.Image.new(w, h, "rgba8")
|
||||
for i = 0, n * 4 - 1 do
|
||||
local v = buffer.readf32(f.pixels, i * 4)
|
||||
buffer.writeu8(o.pixels, i, if v ~= v then 0 else math.floor(math.clamp(v, 0, 1) * 255 + 0.5))
|
||||
end
|
||||
img = o
|
||||
end
|
||||
img.meta.source = { format = "pnm", type = if ch == 3 then "pfm" else "pfm-gray", bitDepth = 32, colorType = colorType, scale = math.abs(scale :: number), byteOrder = if (scale :: number) < 0 then "little" else "big" }
|
||||
return img, nil
|
||||
end
|
||||
local samples = buffer.create(n * ch * 2)
|
||||
local ok, e
|
||||
if mode == 0 then
|
||||
ok, e = Codec.readBits(b, p, limit, w, h, samples)
|
||||
else
|
||||
ok, e = Codec.readSamples(b, p, limit, n * ch, mode, samples)
|
||||
end
|
||||
if not ok then
|
||||
return nil, Err.new(if e == "truncated" then Err.TRUNCATED else Err.CORRUPT, tostring(e))
|
||||
end
|
||||
local fmt = "rgba8"
|
||||
if native then
|
||||
local wide = maxval > 255
|
||||
if bits or bw or ch == 1 then
|
||||
fmt = if wide then "gray16" else "gray8"
|
||||
elseif ch == 2 then
|
||||
fmt = if wide then "rgba16" else "graya8"
|
||||
elseif ch == 3 then
|
||||
fmt = if wide then "rgba16" else "rgb8"
|
||||
else
|
||||
fmt = if wide then "rgba16" else "rgba8"
|
||||
end
|
||||
end
|
||||
img = Types.Image.new(w, h, fmt :: Types.PixelFormat)
|
||||
Codec.pack(samples, n, ch, maxval, bits, FMT_CODE[fmt], img.pixels)
|
||||
local typ = if kind == "7" then "pam" elseif bits then "pbm" elseif ch == 1 then "pgm" else "ppm"
|
||||
img.meta.source = {
|
||||
format = "pnm",
|
||||
type = typ,
|
||||
ascii = mode == 3 or mode == 4,
|
||||
bitDepth = if bits or bw then 1 elseif maxval > 255 then 16 else 8,
|
||||
maxval = maxval,
|
||||
colorType = if bits or bw then "bilevel" else colorType,
|
||||
tupltype = tupl,
|
||||
}
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local SUBTYPES = { pbm = true, pgm = true, ppm = true, pam = true, pfm = true }
|
||||
|
||||
function Pnm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local fc = FMT_CODE[img.format]
|
||||
if fc == nil then
|
||||
return nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format))
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * BPP[img.format] then
|
||||
return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
|
||||
end
|
||||
local o: any = opts or {}
|
||||
local n = w * h
|
||||
local isGray = img.format == "gray8" or img.format == "gray16" or img.format == "graya8"
|
||||
local hasAlpha = img.format == "graya8" or img.format == "rgba16" or img.format == "rgba8" or img.format == "rgbaf32"
|
||||
if hasAlpha and img.format ~= "graya8" then
|
||||
-- an alpha channel that is fully opaque does not count
|
||||
local opaque = true
|
||||
for i = 0, n - 1 do
|
||||
local a
|
||||
if img.format == "rgba8" then
|
||||
a = buffer.readu8(img.pixels, i * 4 + 3) == 255
|
||||
elseif img.format == "rgba16" then
|
||||
a = buffer.readu16(img.pixels, i * 8 + 6) == 65535
|
||||
else
|
||||
a = buffer.readf32(img.pixels, i * 16 + 12) == 1
|
||||
end
|
||||
if not a then
|
||||
opaque = false
|
||||
break
|
||||
end
|
||||
end
|
||||
hasAlpha = not opaque
|
||||
end
|
||||
local sub = if type(o.format) == "string" then string.lower(o.format) else nil
|
||||
if not (sub and SUBTYPES[sub]) then
|
||||
if img.format == "rgbaf32" and not hasAlpha then
|
||||
sub = "pfm"
|
||||
elseif hasAlpha then
|
||||
sub = "pam"
|
||||
elseif isGray then
|
||||
sub = "pgm"
|
||||
else
|
||||
sub = "ppm"
|
||||
end
|
||||
end
|
||||
local ascii = o.ascii == true
|
||||
local wideSrc = img.format == "gray16" or img.format == "rgba16" or img.format == "rgbaf32"
|
||||
local maxval = o.maxval or (if wideSrc then 65535 else 255)
|
||||
if type(maxval) ~= "number" or maxval < 1 or maxval > 65535 or maxval % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "maxval must be 1..65535")
|
||||
end
|
||||
local out: buffer
|
||||
local op = 0
|
||||
local function header(s: string, extra: number)
|
||||
out = buffer.create(#s + extra)
|
||||
buffer.writestring(out, 0, s)
|
||||
op = #s
|
||||
end
|
||||
if sub == "pfm" then
|
||||
local ch = if isGray then 1 else 3
|
||||
local src = img
|
||||
if img.format ~= "rgbaf32" then
|
||||
local s = Codec.extract(img.pixels, fc, n, 4, true)
|
||||
src = Types.Image.new(w, h, "rgbaf32")
|
||||
for i = 0, n * 4 - 1 do
|
||||
buffer.writef32(src.pixels, i * 4, buffer.readu16(s, i * 2) / 65535)
|
||||
end
|
||||
end
|
||||
header(string.format("%s\n%d %d\n-1.0\n", if ch == 3 then "PF" else "Pf", w, h), n * ch * 4)
|
||||
op = Codec.writeFloats(src.pixels, w, h, ch, out, op)
|
||||
return out, nil
|
||||
end
|
||||
local ch = if sub == "pbm" or sub == "pgm" then 1 elseif sub == "ppm" then 3 elseif isGray then (if hasAlpha then 2 else 1) else (if hasAlpha then 4 else 3)
|
||||
if sub == "pbm" then
|
||||
local thr = o.threshold or 128
|
||||
local s = Codec.extract(img.pixels, fc, n, 1, false)
|
||||
if ascii then
|
||||
local parts = table.create(h + 1)
|
||||
parts[1] = string.format("P1\n%d %d\n", w, h)
|
||||
for y = 0, h - 1 do
|
||||
local row = table.create(w)
|
||||
for x = 0, w - 1 do
|
||||
row[x + 1] = if buffer.readu16(s, (y * w + x) * 2) < thr then "1" else "0"
|
||||
end
|
||||
parts[y + 2] = table.concat(row, " ") .. "\n"
|
||||
end
|
||||
return buffer.fromstring(table.concat(parts)), nil
|
||||
end
|
||||
header(string.format("P4\n%d %d\n", w, h), ((w + 7) // 8) * h)
|
||||
op = Codec.writeBits(s, w, h, thr, out, op)
|
||||
return out, nil
|
||||
end
|
||||
local wide = maxval > 255
|
||||
local s = Codec.extract(img.pixels, fc, n, ch, wide)
|
||||
if maxval ~= 255 and maxval ~= 65535 then
|
||||
local top = if wide then 65535 else 255
|
||||
for i = 0, n * ch - 1 do
|
||||
buffer.writeu16(s, i * 2, (buffer.readu16(s, i * 2) * maxval + top // 2) // top)
|
||||
end
|
||||
end
|
||||
local magic
|
||||
if sub == "pam" then
|
||||
local tt = if ch == 1 then "GRAYSCALE" elseif ch == 2 then "GRAYSCALE_ALPHA" elseif ch == 3 then "RGB" else "RGB_ALPHA"
|
||||
header(string.format("P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", w, h, ch, maxval, tt), n * ch * (if wide then 2 else 1))
|
||||
op = Codec.writeSamples(s, n * ch, wide, out, op)
|
||||
return out, nil
|
||||
end
|
||||
magic = if sub == "pgm" then (if ascii then "P2" else "P5") else (if ascii then "P3" else "P6")
|
||||
if ascii then
|
||||
local parts = table.create(h + 1)
|
||||
parts[1] = string.format("%s\n%d %d\n%d\n", magic, w, h, maxval)
|
||||
local rowLen = w * ch
|
||||
for y = 0, h - 1 do
|
||||
local row = table.create(rowLen)
|
||||
for i = 0, rowLen - 1 do
|
||||
row[i + 1] = tostring(buffer.readu16(s, (y * rowLen + i) * 2))
|
||||
end
|
||||
parts[y + 2] = table.concat(row, " ") .. "\n"
|
||||
end
|
||||
return buffer.fromstring(table.concat(parts)), nil
|
||||
end
|
||||
header(string.format("%s\n%d %d\n%d\n", magic, w, h, maxval), n * ch * (if wide then 2 else 1))
|
||||
op = Codec.writeSamples(s, n * ch, wide, out, op)
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Pnm
|
||||
@@ -0,0 +1,144 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/qoi/Codec: the QOI op loops (native; never throws). Written from the QOI specification 1.0 (qoiformat.org).
|
||||
-- decode reads ops from b[p, limit) into an rgba8 buffer; encode writes ops for rgba8 / rgb8 pixels. Every input read
|
||||
-- is checked against limit; the output buffer has exactly w * h * 4 bytes and the loop stops when it is full.
|
||||
local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
|
||||
|
||||
local Codec = {}
|
||||
|
||||
local index = buffer.create(256)
|
||||
|
||||
-- decode(b, p, limit, out, n) -> true | false, "truncated" (n pixels into out)
|
||||
function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?)
|
||||
buffer.fill(index, 0, 0, 256)
|
||||
local r, g, bl, a = 0, 0, 0, 255
|
||||
local o = 0
|
||||
local stop = n * 4
|
||||
while o < stop do
|
||||
if p >= limit then
|
||||
return false, "truncated"
|
||||
end
|
||||
local op = readu8(b, p)
|
||||
p += 1
|
||||
if op == 0xFE then
|
||||
if p + 3 > limit then
|
||||
return false, "truncated"
|
||||
end
|
||||
r, g, bl = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2)
|
||||
p += 3
|
||||
elseif op == 0xFF then
|
||||
if p + 4 > limit then
|
||||
return false, "truncated"
|
||||
end
|
||||
r, g, bl, a = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3)
|
||||
p += 4
|
||||
else
|
||||
local tag = op // 64
|
||||
if tag == 0 then
|
||||
local q = op * 4
|
||||
r, g, bl, a = readu8(index, q), readu8(index, q + 1), readu8(index, q + 2), readu8(index, q + 3)
|
||||
elseif tag == 1 then
|
||||
r = (r + (op // 16) % 4 - 2) % 256
|
||||
g = (g + (op // 4) % 4 - 2) % 256
|
||||
bl = (bl + op % 4 - 2) % 256
|
||||
elseif tag == 2 then
|
||||
if p >= limit then
|
||||
return false, "truncated"
|
||||
end
|
||||
local d2 = readu8(b, p)
|
||||
p += 1
|
||||
local dg = op % 64 - 32
|
||||
g = (g + dg) % 256
|
||||
r = (r + dg + d2 // 16 - 8) % 256
|
||||
bl = (bl + dg + d2 % 16 - 8) % 256
|
||||
else
|
||||
local run = op % 64 -- 1..62 more copies of the previous pixel (63 / 64 are RGB / RGBA)
|
||||
local v = r + g * 256 + bl * 65536 + a * 16777216
|
||||
local e = math.min(o + run * 4, stop - 4)
|
||||
while o < e do
|
||||
writeu32(out, o, v)
|
||||
o += 4
|
||||
end
|
||||
end
|
||||
end
|
||||
writeu32(out, o, r + g * 256 + bl * 65536 + a * 16777216)
|
||||
o += 4
|
||||
local h = ((r * 3 + g * 5 + bl * 7 + a * 11) % 64) * 4
|
||||
writeu8(index, h, r)
|
||||
writeu8(index, h + 1, g)
|
||||
writeu8(index, h + 2, bl)
|
||||
writeu8(index, h + 3, a)
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- encode(px, n, bpp, out, o) -> new offset: n pixels of bpp (3 or 4) bytes; out has room for n * (bpp + 1) bytes
|
||||
function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number
|
||||
buffer.fill(index, 0, 0, 256)
|
||||
local pr, pg, pb, pa = 0, 0, 0, 255
|
||||
local run = 0
|
||||
local hasA = bpp == 4
|
||||
for i = 0, n - 1 do
|
||||
local q = i * bpp
|
||||
local r, g, b = readu8(px, q), readu8(px, q + 1), readu8(px, q + 2)
|
||||
local a = if hasA then readu8(px, q + 3) else 255
|
||||
if r == pr and g == pg and b == pb and a == pa then
|
||||
run += 1
|
||||
if run == 62 or i == n - 1 then
|
||||
writeu8(out, o, 0xC0 + run - 1)
|
||||
o += 1
|
||||
run = 0
|
||||
end
|
||||
else
|
||||
if run > 0 then
|
||||
writeu8(out, o, 0xC0 + run - 1)
|
||||
o += 1
|
||||
run = 0
|
||||
end
|
||||
local h = (r * 3 + g * 5 + b * 7 + a * 11) % 64
|
||||
local hq = h * 4
|
||||
if readu8(index, hq) == r and readu8(index, hq + 1) == g and readu8(index, hq + 2) == b and readu8(index, hq + 3) == a then
|
||||
writeu8(out, o, h)
|
||||
o += 1
|
||||
else
|
||||
writeu8(index, hq, r)
|
||||
writeu8(index, hq + 1, g)
|
||||
writeu8(index, hq + 2, b)
|
||||
writeu8(index, hq + 3, a)
|
||||
if a == pa then
|
||||
local dr = (r - pr + 128) % 256 - 128
|
||||
local dg = (g - pg + 128) % 256 - 128
|
||||
local db = (b - pb + 128) % 256 - 128
|
||||
local dgr, dgb = dr - dg, db - dg
|
||||
if dr >= -2 and dr <= 1 and dg >= -2 and dg <= 1 and db >= -2 and db <= 1 then
|
||||
writeu8(out, o, 0x40 + (dr + 2) * 16 + (dg + 2) * 4 + db + 2)
|
||||
o += 1
|
||||
elseif dg >= -32 and dg <= 31 and dgr >= -8 and dgr <= 7 and dgb >= -8 and dgb <= 7 then
|
||||
writeu8(out, o, 0x80 + dg + 32)
|
||||
writeu8(out, o + 1, (dgr + 8) * 16 + dgb + 8)
|
||||
o += 2
|
||||
else
|
||||
writeu8(out, o, 0xFE)
|
||||
writeu8(out, o + 1, r)
|
||||
writeu8(out, o + 2, g)
|
||||
writeu8(out, o + 3, b)
|
||||
o += 4
|
||||
end
|
||||
else
|
||||
writeu8(out, o, 0xFF)
|
||||
writeu8(out, o + 1, r)
|
||||
writeu8(out, o + 2, g)
|
||||
writeu8(out, o + 3, b)
|
||||
writeu8(out, o + 4, a)
|
||||
o += 5
|
||||
end
|
||||
end
|
||||
pr, pg, pb, pa = r, g, b, a
|
||||
end
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
return Codec
|
||||
@@ -0,0 +1,122 @@
|
||||
--!strict
|
||||
-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). New code written from the spec.
|
||||
-- Supports: decode of RGB and RGBA files (either colour space tag) to rgba8 (opts.native: rgb8 for 3-channel files);
|
||||
-- encode of rgba8 (4 channels) and rgb8 (3 channels), lossless; meta.source.colorSpace keeps the sRGB / linear tag.
|
||||
-- Not supported: nothing in the spec is left out.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Codec = require("@formats/image/qoi/Codec")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Qoi = {
|
||||
name = "qoi",
|
||||
category = "image",
|
||||
extensions = { "qoi" },
|
||||
mime = { "image/qoi", "image/x-qoi" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, depths = { 8 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
native: boolean?, -- rgb8 for 3-channel files (default false: always rgba8)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
channels: number?, -- 3 or 4 (default: 3 for rgb8 images or opaque rgba8, else 4)
|
||||
linear: boolean?, -- tag the file as linear instead of sRGB (default: meta.source.colorSpace == "linear")
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Qoi.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(4) == "qoif" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Qoi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
local magic = r:string(4)
|
||||
local w, h = r:u32be(), r:u32be()
|
||||
local channels, cs = r:u8(), r:u8()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if magic ~= "qoif" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", r.base)
|
||||
end
|
||||
if w == 0 or h == 0 or (channels ~= 3 and channels ~= 4) or cs > 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header", r.base + 4)
|
||||
end
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local ok, e = Codec.decode(r.buf, r.pos, r.limit, img.pixels, w * h)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.TRUNCATED, tostring(e))
|
||||
end
|
||||
if opts and opts.native and channels == 3 then
|
||||
local rgb = Types.Image.new(w, h, "rgb8")
|
||||
local src, dst = img.pixels, rgb.pixels
|
||||
for i = 0, w * h - 1 do
|
||||
buffer.writeu16(dst, i * 3, buffer.readu16(src, i * 4))
|
||||
buffer.writeu8(dst, i * 3 + 2, buffer.readu8(src, i * 4 + 2))
|
||||
end
|
||||
img = rgb
|
||||
end
|
||||
img.meta.source = { format = "qoi", bitDepth = 8, colorType = if channels == 4 then "rgba" else "rgb", channels = channels, colorSpace = if cs == 1 then "linear" else "srgb" }
|
||||
if cs == 1 then
|
||||
img.meta.colorSpace = "linear"
|
||||
end
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgba8" and img.format ~= "rgb8") then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 or rgb8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
local bpp = if img.format == "rgba8" then 4 else 3
|
||||
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
|
||||
return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
|
||||
end
|
||||
local channels = opts and opts.channels
|
||||
if channels == nil then
|
||||
channels = 3
|
||||
if bpp == 4 then
|
||||
local px = img.pixels
|
||||
for i = 0, w * h - 1 do
|
||||
if buffer.readu8(px, i * 4 + 3) ~= 255 then
|
||||
channels = 4
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif channels ~= 3 and channels ~= 4 then
|
||||
return nil, Err.new(Err.ARG, "channels must be 3 or 4")
|
||||
end
|
||||
local linear = opts and opts.linear
|
||||
if linear == nil then
|
||||
local src = img.meta and img.meta.source
|
||||
linear = (type(src) == "table" and src.colorSpace == "linear") or (img.meta and img.meta.colorSpace == "linear") or false
|
||||
end
|
||||
local n = w * h
|
||||
local out = buffer.create(14 + n * (bpp + 1) + 8)
|
||||
buffer.writestring(out, 0, "qoif")
|
||||
buffer.writeu32(out, 4, bit32.byteswap(w))
|
||||
buffer.writeu32(out, 8, bit32.byteswap(h))
|
||||
buffer.writeu8(out, 12, channels)
|
||||
buffer.writeu8(out, 13, if linear then 1 else 0)
|
||||
local o = Codec.encode(img.pixels, n, bpp, out, 14)
|
||||
buffer.writestring(out, o, "\0\0\0\0\0\0\0\1")
|
||||
o += 8
|
||||
local res = buffer.create(o)
|
||||
buffer.copy(res, 0, out, 0, o)
|
||||
return res, nil
|
||||
end
|
||||
|
||||
return Qoi
|
||||
@@ -0,0 +1,157 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/tga/Codec: the Truevision TGA pixel loops (native; never throws). Written from the Truevision TGA 2.0
|
||||
-- specification. decode reads raw or RLE pixel data (packets may cross scanlines) into rgba8 at the oriented
|
||||
-- position; encode writes raw or RLE rows. Every read is bounds-checked; the output has exactly w * h * 4 bytes.
|
||||
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
|
||||
|
||||
local Codec = {}
|
||||
|
||||
-- one source pixel at b[p] -> rgba as a u32; kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555,
|
||||
-- 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 (pal: u32 entries, palN of them)
|
||||
local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number
|
||||
if kind == 0 then
|
||||
return readu8(b, p) * 0x10101 + 0xFF000000
|
||||
elseif kind == 1 then
|
||||
return readu8(b, p) * 0x10101 + readu8(b, p + 1) * 0x1000000
|
||||
elseif kind == 2 then
|
||||
local v = readu16(b, p)
|
||||
local r, g, bl = (v // 1024) % 32, (v // 32) % 32, v % 32
|
||||
local a = if alpha1 and v < 32768 then 0 else 255
|
||||
return (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + a * 16777216 -- round(v * 255 / 31), as ImageMagick
|
||||
elseif kind == 3 then
|
||||
return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + 0xFF000000
|
||||
elseif kind == 4 then
|
||||
return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + readu8(b, p + 3) * 16777216
|
||||
end
|
||||
local i = if kind == 5 then readu8(b, p) else readu16(b, p)
|
||||
if i >= palN then
|
||||
return 0xFF000000
|
||||
end
|
||||
return readu32(pal, i * 4)
|
||||
end
|
||||
Codec.pixel = pixel
|
||||
|
||||
-- decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) -> pixels written, truncated?
|
||||
function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean)
|
||||
local n = w * h
|
||||
local i = 0
|
||||
local function put(v: number)
|
||||
local row, col = i // w, i % w
|
||||
if bottomUp then
|
||||
row = h - 1 - row
|
||||
end
|
||||
if rtl then
|
||||
col = w - 1 - col
|
||||
end
|
||||
writeu32(out, (row * w + col) * 4, v)
|
||||
i += 1
|
||||
end
|
||||
if not rle then
|
||||
local avail = math.min(n, (limit - p) // bpp)
|
||||
for _ = 1, avail do
|
||||
put(pixel(b, p, kind, alpha1, pal, palN))
|
||||
p += bpp
|
||||
end
|
||||
return i, avail < n
|
||||
end
|
||||
while i < n do
|
||||
if p >= limit then
|
||||
return i, true
|
||||
end
|
||||
local hd = readu8(b, p)
|
||||
p += 1
|
||||
local count = hd % 128 + 1
|
||||
if hd >= 128 then
|
||||
if p + bpp > limit then
|
||||
return i, true
|
||||
end
|
||||
local v = pixel(b, p, kind, alpha1, pal, palN)
|
||||
p += bpp
|
||||
for _ = 1, math.min(count, n - i) do
|
||||
put(v)
|
||||
end
|
||||
else
|
||||
for _ = 1, math.min(count, n - i) do
|
||||
if p + bpp > limit then
|
||||
return i, true
|
||||
end
|
||||
put(pixel(b, p, kind, alpha1, pal, palN))
|
||||
p += bpp
|
||||
end
|
||||
end
|
||||
end
|
||||
return i, false
|
||||
end
|
||||
|
||||
-- encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) -> new offset. px: rgba8 / rgb8 / gray8 (srcBpp 4 / 3 / 1);
|
||||
-- written as BGRA / BGR / grey (outBpp 4 / 3 / 1), rows top-down or bottom-up; RLE packets stay inside a row.
|
||||
-- out needs room for w * h * (outBpp + 1) bytes.
|
||||
function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number
|
||||
local function get(q: number): number
|
||||
if srcBpp == 1 then
|
||||
return readu8(px, q)
|
||||
elseif srcBpp == 3 then
|
||||
return readu8(px, q) + readu8(px, q + 1) * 256 + readu8(px, q + 2) * 65536 + 0xFF000000
|
||||
end
|
||||
return readu32(px, q)
|
||||
end
|
||||
local function emit(v: number)
|
||||
if outBpp == 1 then
|
||||
writeu8(out, o, v % 256)
|
||||
else
|
||||
writeu8(out, o, (v // 65536) % 256)
|
||||
writeu8(out, o + 1, (v // 256) % 256)
|
||||
writeu8(out, o + 2, v % 256)
|
||||
if outBpp == 4 then
|
||||
writeu8(out, o + 3, v // 16777216)
|
||||
end
|
||||
end
|
||||
o += outBpp
|
||||
end
|
||||
for y = 0, h - 1 do
|
||||
local row = if topDown then y else h - 1 - y
|
||||
local base = row * w * srcBpp
|
||||
if not rle then
|
||||
for x = 0, w - 1 do
|
||||
emit(get(base + x * srcBpp))
|
||||
end
|
||||
else
|
||||
local x = 0
|
||||
while x < w do
|
||||
local v = get(base + x * srcBpp)
|
||||
local run = 1
|
||||
while x + run < w and run < 128 and get(base + (x + run) * srcBpp) == v do
|
||||
run += 1
|
||||
end
|
||||
if run >= 2 then
|
||||
writeu8(out, o, 127 + run)
|
||||
o += 1
|
||||
emit(v)
|
||||
x += run
|
||||
else
|
||||
-- a raw packet up to the next run of 2 or more
|
||||
local s = x
|
||||
local cnt = 0
|
||||
while x < w and cnt < 128 do
|
||||
local c = get(base + x * srcBpp)
|
||||
if x + 1 < w and get(base + (x + 1) * srcBpp) == c then
|
||||
break
|
||||
end
|
||||
cnt += 1
|
||||
x += 1
|
||||
end
|
||||
writeu8(out, o, cnt - 1)
|
||||
o += 1
|
||||
for k = s, s + cnt - 1 do
|
||||
emit(get(base + k * srcBpp))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
return Codec
|
||||
@@ -0,0 +1,276 @@
|
||||
--!strict
|
||||
-- image/tga: Truevision TGA (TGA 2.0 specification; new code). Decode: colour-mapped (1), true-colour (2) and grey (3)
|
||||
-- images, raw or RLE (9, 10, 11; packets may cross scanlines), 8 / 15 / 16 / 24 / 32-bit pixels, 15 / 16 / 24 /
|
||||
-- 32-bit colour maps with a first index, 8 / 16-bit indexes, grey + alpha (16-bit type 3), every origin (bottom-left,
|
||||
-- top-left, right-to-left), the alpha bits of the descriptor (16-bit: alpha only when it declares 1 alpha bit; 32-bit:
|
||||
-- alpha always), the image ID (meta.text.id) and the TGA 2.0 footer (tolerated, not needed). Truncated pixel data
|
||||
-- leaves the rest transparent black (meta.truncated). opts.native: gray8 for grey files, rgb8 for 24-bit.
|
||||
-- Encode: rgba8 (32-bit BGRA when there is alpha, else 24-bit), rgb8 (24-bit), gray8 (type 3), raw or RLE, bottom-left
|
||||
-- (default) or top-left origin, with the TGA 2.0 footer. Not supported: the extension area's fields (gamma, postage
|
||||
-- stamp, ...), which are ignored.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Codec = require("@formats/image/tga/Codec")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Tga = {
|
||||
name = "tga",
|
||||
category = "image",
|
||||
extensions = { "tga", "icb", "vda", "vst", "tpic" },
|
||||
mime = { "image/x-tga", "image/x-targa" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
native: boolean?, -- gray8 for grey files, rgb8 for 24-bit ones (default false: rgba8)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
rle: boolean?, -- run-length encode (default false)
|
||||
origin: ("bottom-left" | "top-left")?, -- default "bottom-left" (the classic layout every reader understands)
|
||||
alpha: boolean?, -- force 32-bit (true) or 24-bit (false) for rgba8 (default: 32-bit when any alpha < 255)
|
||||
id: string?, -- the image ID field (up to 255 bytes; default meta.text.id)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local TYPES = { [1] = true, [2] = true, [3] = true, [9] = true, [10] = true, [11] = true }
|
||||
local FOOTER = "TRUEVISION-XFILE.\0"
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
type Header = {
|
||||
idLen: number,
|
||||
cmapType: number,
|
||||
imageType: number,
|
||||
cmapFirst: number,
|
||||
cmapLen: number,
|
||||
cmapBits: number,
|
||||
width: number,
|
||||
height: number,
|
||||
depth: number,
|
||||
desc: number,
|
||||
}
|
||||
|
||||
local function header(r: Bytes.Reader): Header?
|
||||
if r.limit - r.base < 18 then
|
||||
return nil
|
||||
end
|
||||
local b, o = r.buf, r.base
|
||||
local function u16(q: number): number
|
||||
return readu8(b, o + q) + readu8(b, o + q + 1) * 256
|
||||
end
|
||||
local h: Header = {
|
||||
idLen = readu8(b, o),
|
||||
cmapType = readu8(b, o + 1),
|
||||
imageType = readu8(b, o + 2),
|
||||
cmapFirst = u16(3),
|
||||
cmapLen = u16(5),
|
||||
cmapBits = readu8(b, o + 7),
|
||||
width = u16(12),
|
||||
height = u16(14),
|
||||
depth = readu8(b, o + 16),
|
||||
desc = readu8(b, o + 17),
|
||||
}
|
||||
return h
|
||||
end
|
||||
|
||||
-- plausible(h) -> nil | why not
|
||||
local function implausible(h: Header): string?
|
||||
local t = h.imageType
|
||||
if not TYPES[t] then
|
||||
return "image type " .. t
|
||||
end
|
||||
if h.cmapType > 1 then
|
||||
return "colour map type " .. h.cmapType
|
||||
end
|
||||
local mapped = t == 1 or t == 9
|
||||
if mapped and (h.cmapType ~= 1 or (h.depth ~= 8 and h.depth ~= 16)) then
|
||||
return "colour-mapped image without a colour map"
|
||||
end
|
||||
if h.cmapType == 1 and h.cmapLen > 0 and h.cmapBits ~= 15 and h.cmapBits ~= 16 and h.cmapBits ~= 24 and h.cmapBits ~= 32 then
|
||||
return "colour map entry size " .. h.cmapBits
|
||||
end
|
||||
if (t == 2 or t == 10) and h.depth ~= 15 and h.depth ~= 16 and h.depth ~= 24 and h.depth ~= 32 then
|
||||
return "pixel depth " .. h.depth
|
||||
end
|
||||
if (t == 3 or t == 11) and h.depth ~= 8 and h.depth ~= 16 then
|
||||
return "grey pixel depth " .. h.depth
|
||||
end
|
||||
if h.width == 0 or h.height == 0 then
|
||||
return "zero size"
|
||||
end
|
||||
if h.desc >= 64 then
|
||||
return "interleaving / reserved descriptor bits"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function Tga.sniff(r: Bytes.Reader): number
|
||||
local h = header(r)
|
||||
if not h or implausible(h) then
|
||||
return 0
|
||||
end
|
||||
local n = r.limit - r.base
|
||||
if n >= 44 and buffer.readstring(r.buf, r.limit - 18, 18) == FOOTER then
|
||||
return 0.9
|
||||
end
|
||||
return 0.2
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Tga.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
local h = header(r)
|
||||
if not h then
|
||||
return nil, Err.new(Err.TRUNCATED, "short header", r.base)
|
||||
end
|
||||
local why = implausible(h)
|
||||
if why then
|
||||
return nil, Err.new(if h.imageType == 0 then Err.UNSUPPORTED else Err.CORRUPT, why, r.base)
|
||||
end
|
||||
local w, ht = h.width, h.height
|
||||
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 b = r.buf
|
||||
local p = r.base + 18
|
||||
local id = if h.idLen > 0 and p + h.idLen <= r.limit then buffer.readstring(b, p, h.idLen) else nil
|
||||
p += h.idLen
|
||||
-- colour map
|
||||
local pal = buffer.create(4)
|
||||
local palN = 0
|
||||
if h.cmapType == 1 and h.cmapLen > 0 then
|
||||
local eb = (h.cmapBits + 7) // 8
|
||||
if p + h.cmapLen * eb > r.limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p)
|
||||
end
|
||||
local first = h.cmapFirst
|
||||
palN = first + h.cmapLen
|
||||
pal = buffer.create(palN * 4)
|
||||
buffer.fill(pal, 0, 0, palN * 4)
|
||||
local kind = if h.cmapBits == 24 then 3 elseif h.cmapBits == 32 then 4 else 2
|
||||
for i = 0, h.cmapLen - 1 do
|
||||
buffer.writeu32(pal, (first + i) * 4, Codec.pixel(b, p + i * eb, kind, false, pal, 0))
|
||||
end
|
||||
for i = 0, first - 1 do
|
||||
buffer.writeu32(pal, i * 4, 0xFF000000)
|
||||
end
|
||||
p += h.cmapLen * eb
|
||||
end
|
||||
local t = h.imageType
|
||||
local alphaBits = h.desc % 16
|
||||
local kind
|
||||
if t == 1 or t == 9 then
|
||||
kind = if h.depth == 8 then 5 else 6
|
||||
elseif t == 3 or t == 11 then
|
||||
kind = if h.depth == 8 then 0 else 1
|
||||
else
|
||||
kind = if h.depth == 24 then 3 elseif h.depth == 32 then 4 else 2
|
||||
end
|
||||
local bpp = (h.depth + 7) // 8
|
||||
local bottomUp = (h.desc // 32) % 2 == 0
|
||||
local rtl = (h.desc // 16) % 2 == 1
|
||||
local img = Types.Image.new(w, ht, "rgba8")
|
||||
local _, truncated = Codec.decode(b, p, r.limit, w, ht, bpp, kind, h.depth == 16 and alphaBits >= 1, t >= 9, bottomUp, rtl, pal, palN, img.pixels)
|
||||
local native = opts and opts.native
|
||||
if native and kind == 0 then
|
||||
local g = Types.Image.new(w, ht, "gray8")
|
||||
for i = 0, w * ht - 1 do
|
||||
buffer.writeu8(g.pixels, i, readu8(img.pixels, i * 4))
|
||||
end
|
||||
img = g
|
||||
elseif native and kind == 3 then
|
||||
local c = Types.Image.new(w, ht, "rgb8")
|
||||
for i = 0, w * ht - 1 do
|
||||
buffer.writeu16(c.pixels, i * 3, buffer.readu16(img.pixels, i * 4))
|
||||
buffer.writeu8(c.pixels, i * 3 + 2, readu8(img.pixels, i * 4 + 2))
|
||||
end
|
||||
img = c
|
||||
end
|
||||
if palN > 0 then
|
||||
local palette = {}
|
||||
for i = 0, palN - 1 do
|
||||
palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) }
|
||||
end
|
||||
img.meta.palette = palette
|
||||
end
|
||||
if id then
|
||||
img.meta.text = { id = id }
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.source = {
|
||||
format = "tga",
|
||||
bitDepth = h.depth,
|
||||
colorType = if kind >= 5 then "palette" elseif kind <= 1 then (if kind == 1 then "graya" else "gray") else (if kind == 3 then "rgb" else "rgba"),
|
||||
rle = t >= 9,
|
||||
origin = (if bottomUp then "bottom" else "top") .. "-" .. (if rtl then "right" else "left"),
|
||||
alphaBits = alphaBits,
|
||||
}
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Tga.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local srcBpp = if img.format == "rgba8" then 4 elseif img.format == "rgb8" then 3 elseif img.format == "gray8" then 1 else nil
|
||||
if not srcBpp then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * srcBpp then
|
||||
return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
|
||||
end
|
||||
local o: any = opts or {}
|
||||
local origin = o.origin or "bottom-left"
|
||||
if origin ~= "bottom-left" and origin ~= "top-left" then
|
||||
return nil, Err.new(Err.ARG, "origin must be \"bottom-left\" or \"top-left\"")
|
||||
end
|
||||
local outBpp = srcBpp
|
||||
if srcBpp == 4 then
|
||||
local alpha = o.alpha
|
||||
if alpha == nil then
|
||||
alpha = false
|
||||
for i = 0, w * h - 1 do
|
||||
if readu8(img.pixels, i * 4 + 3) ~= 255 then
|
||||
alpha = true
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
outBpp = if alpha then 4 else 3
|
||||
end
|
||||
local id = o.id or (img.meta and img.meta.text and img.meta.text.id) or ""
|
||||
if type(id) ~= "string" then
|
||||
id = ""
|
||||
end
|
||||
id = string.sub(id, 1, 255)
|
||||
local rle = o.rle == true
|
||||
local out = buffer.create(18 + #id + w * h * (outBpp + 1) + 26)
|
||||
buffer.writeu8(out, 0, #id)
|
||||
buffer.writeu8(out, 2, (if outBpp == 1 then 3 else 2) + (if rle then 8 else 0))
|
||||
buffer.writeu16(out, 12, w)
|
||||
buffer.writeu16(out, 14, h)
|
||||
buffer.writeu8(out, 16, outBpp * 8)
|
||||
buffer.writeu8(out, 17, (if outBpp == 4 then 8 else 0) + (if origin == "top-left" then 32 else 0))
|
||||
buffer.writestring(out, 18, id)
|
||||
local op = Codec.encode(img.pixels, w, h, srcBpp, outBpp, rle, origin == "top-left", out, 18 + #id)
|
||||
-- TGA 2.0 footer: no extension / developer areas
|
||||
buffer.writeu32(out, op, 0)
|
||||
buffer.writeu32(out, op + 4, 0)
|
||||
buffer.writestring(out, op + 8, FOOTER)
|
||||
op += 26
|
||||
local res = buffer.create(op)
|
||||
buffer.copy(res, 0, out, 0, op)
|
||||
return res, nil
|
||||
end
|
||||
|
||||
return Tga
|
||||
@@ -0,0 +1,469 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): PackBits, the horizontal (2) and
|
||||
-- floating-point (3) predictors both ways (TIFF 6.0 section 14, Adobe TIFF technote 3; predictor 3 as libtiff's
|
||||
-- fpAcc / fpDiff), fill-order bit reversal, and the sample converter from decoded planes to a Types.Image layout.
|
||||
-- Callers (image/tiff/init) size every buffer before calling: planes hold h rows of rb bytes plus 8 bytes of slack.
|
||||
local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32
|
||||
local readf32, writef32, readf64 = buffer.readf32, buffer.writef32, buffer.readf64
|
||||
local band, bor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.byteswap
|
||||
local floor = math.floor
|
||||
|
||||
local Pixels = {}
|
||||
|
||||
local scratch = buffer.create(8)
|
||||
|
||||
-- floats read through their bits: NaN / infinity never load from memory (LuaJIT's FFI would hand back a NaN with an
|
||||
-- arbitrary payload, which its NaN-tagged values misread as a table / userdata)
|
||||
local function f32(bits: number): number
|
||||
if band(bits, 0x7F800000) == 0x7F800000 then
|
||||
if band(bits, 0x7FFFFF) ~= 0 then
|
||||
return 0 / 0
|
||||
end
|
||||
return if bits >= 0x80000000 then -math.huge else math.huge
|
||||
end
|
||||
writeu32(scratch, 0, bits)
|
||||
return readf32(scratch, 0)
|
||||
end
|
||||
local function f64(lo: number, hi: number): number
|
||||
if band(hi, 0x7FF00000) == 0x7FF00000 then
|
||||
if band(hi, 0xFFFFF) ~= 0 or lo ~= 0 then
|
||||
return 0 / 0
|
||||
end
|
||||
return if hi >= 0x80000000 then -math.huge else math.huge
|
||||
end
|
||||
writeu32(scratch, 0, lo)
|
||||
writeu32(scratch, 4, hi)
|
||||
return readf64(scratch, 0)
|
||||
end
|
||||
Pixels.f32 = f32
|
||||
Pixels.f64 = f64
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ PackBits
|
||||
-- packbits(src, off, len, out, outOff, max) -> bytes written (stops when out or src is exhausted)
|
||||
function Pixels.packbits(src: buffer, off: number, len: number, out: buffer, outOff: number, max: number): number
|
||||
local p, e = off, off + len
|
||||
local o, lim = outOff, outOff + max
|
||||
while p < e and o < lim do
|
||||
local n = readu8(src, p)
|
||||
p += 1
|
||||
if n < 128 then
|
||||
local cnt = math.min(n + 1, e - p, lim - o)
|
||||
if cnt <= 0 then
|
||||
break
|
||||
end
|
||||
buffer.copy(out, o, src, p, cnt)
|
||||
p += n + 1
|
||||
o += cnt
|
||||
elseif n > 128 then
|
||||
if p >= e then
|
||||
break
|
||||
end
|
||||
local cnt = math.min(257 - n, lim - o)
|
||||
buffer.fill(out, o, readu8(src, p), cnt)
|
||||
p += 1
|
||||
o += cnt
|
||||
end
|
||||
end
|
||||
return o - outOff
|
||||
end
|
||||
|
||||
-- packbitsEncode(src, off, len) -> buffer (one row at a time is the caller's business)
|
||||
function Pixels.packbitsEncode(src: buffer, off: number, len: number): buffer
|
||||
local out = buffer.create(len + (len + 127) // 128 + 8)
|
||||
local o = 0
|
||||
local p, e = off, off + len
|
||||
while p < e do
|
||||
local run = 1
|
||||
local v = readu8(src, p)
|
||||
while p + run < e and run < 128 and readu8(src, p + run) == v do
|
||||
run += 1
|
||||
end
|
||||
if run >= 3 then
|
||||
writeu8(out, o, 257 - run)
|
||||
writeu8(out, o + 1, v)
|
||||
o += 2
|
||||
p += run
|
||||
else
|
||||
local s = p
|
||||
local n = 0
|
||||
while p < e and n < 128 do
|
||||
if p + 2 < e and readu8(src, p) == readu8(src, p + 1) and readu8(src, p) == readu8(src, p + 2) then
|
||||
break
|
||||
end
|
||||
p += 1
|
||||
n += 1
|
||||
end
|
||||
writeu8(out, o, n - 1)
|
||||
buffer.copy(out, o + 1, src, s, n)
|
||||
o += n + 1
|
||||
end
|
||||
end
|
||||
local r = buffer.create(o)
|
||||
buffer.copy(r, 0, out, 0, o)
|
||||
return r
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fill order
|
||||
local REV = buffer.create(256)
|
||||
for i = 0, 255 do
|
||||
local r = 0
|
||||
for k = 0, 7 do
|
||||
if band(i, lshift(1, k)) ~= 0 then
|
||||
r = bor(r, lshift(1, 7 - k))
|
||||
end
|
||||
end
|
||||
writeu8(REV, i, r)
|
||||
end
|
||||
function Pixels.reverseBits(b: buffer, off: number, len: number)
|
||||
for i = off, off + len - 1 do
|
||||
writeu8(b, i, readu8(REV, readu8(b, i)))
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ predictors
|
||||
-- unpredict2(b, off, rows, rb, stride, bps, le): undo horizontal differencing (bps 8, 16 or 32; others untouched)
|
||||
function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number, le: boolean)
|
||||
for r = 0, rows - 1 do
|
||||
local base = off + r * rb
|
||||
if bps == 8 then
|
||||
for i = base + stride, base + rb - 1 do
|
||||
writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255))
|
||||
end
|
||||
elseif bps == 16 then
|
||||
local n = rb // 2
|
||||
for k = stride, n - 1 do
|
||||
local i = base + k * 2
|
||||
local j = i - stride * 2
|
||||
if le then
|
||||
writeu16(b, i, band(readu16(b, i) + readu16(b, j), 0xFFFF))
|
||||
else
|
||||
local v = readu8(b, i) * 256 + readu8(b, i + 1) + readu8(b, j) * 256 + readu8(b, j + 1)
|
||||
writeu8(b, i, band(rshift(v, 8), 255))
|
||||
writeu8(b, i + 1, band(v, 255))
|
||||
end
|
||||
end
|
||||
elseif bps == 32 then
|
||||
local n = rb // 4
|
||||
for k = stride, n - 1 do
|
||||
local i = base + k * 4
|
||||
local j = i - stride * 4
|
||||
if le then
|
||||
writeu32(b, i, (readu32(b, i) + readu32(b, j)) % 4294967296)
|
||||
else
|
||||
writeu32(b, i, byteswap((byteswap(readu32(b, i)) + byteswap(readu32(b, j))) % 4294967296))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- predict2(b, off, rows, rb, stride, bps): apply horizontal differencing to little-endian samples (8 / 16 bit)
|
||||
function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number)
|
||||
for r = 0, rows - 1 do
|
||||
local base = off + r * rb
|
||||
if bps == 8 then
|
||||
for i = base + rb - 1, base + stride, -1 do
|
||||
writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255))
|
||||
end
|
||||
elseif bps == 16 then
|
||||
for k = rb // 2 - 1, stride, -1 do
|
||||
local i = base + k * 2
|
||||
writeu16(b, i, band(readu16(b, i) - readu16(b, i - stride * 2), 0xFFFF))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- unpredict3(b, off, rows, rb, bytes, stride, tmp): undo the floating-point predictor; the samples come out little
|
||||
-- endian whatever the file's byte order (libtiff fpAcc). tmp holds at least rb bytes.
|
||||
function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer)
|
||||
local wc = rb // bytes
|
||||
for r = 0, rows - 1 do
|
||||
local base = off + r * rb
|
||||
for i = base + stride, base + rb - 1 do
|
||||
writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255))
|
||||
end
|
||||
buffer.copy(tmp, 0, b, base, rb)
|
||||
for c = 0, wc - 1 do
|
||||
for k = 0, bytes - 1 do
|
||||
writeu8(b, base + c * bytes + k, readu8(tmp, (bytes - k - 1) * wc + c))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- predict3(b, off, rows, rb, bytes, stride, tmp): the floating-point predictor on little-endian samples (fpDiff)
|
||||
function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer)
|
||||
local wc = rb // bytes
|
||||
for r = 0, rows - 1 do
|
||||
local base = off + r * rb
|
||||
for c = 0, wc - 1 do
|
||||
for k = 0, bytes - 1 do
|
||||
writeu8(tmp, (bytes - k - 1) * wc + c, readu8(b, base + c * bytes + k))
|
||||
end
|
||||
end
|
||||
buffer.copy(b, base, tmp, 0, rb)
|
||||
for i = base + rb - 1, base + stride, -1 do
|
||||
writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ samples
|
||||
local function half(h: number): number
|
||||
local s = if h >= 0x8000 then -1 else 1
|
||||
local e = band(rshift(h, 10), 31)
|
||||
local m = band(h, 1023)
|
||||
if e == 0 then
|
||||
return s * m * 2 ^ -24
|
||||
elseif e == 31 then
|
||||
return if m == 0 then s * math.huge else 0 / 0
|
||||
end
|
||||
return s * (1 + m / 1024) * 2 ^ (e - 15)
|
||||
end
|
||||
|
||||
export type Params = {
|
||||
planes: { buffer },
|
||||
rb: number, -- bytes per row in each plane
|
||||
chunky: boolean,
|
||||
w: number,
|
||||
h: number,
|
||||
spp: number,
|
||||
bps: number,
|
||||
sfmt: number, -- 1 uint, 2 int, 3 float
|
||||
le: boolean,
|
||||
photo: number, -- 0 min-is-white, 1 min-is-black, 2 RGB, 3 palette, 5 CMYK
|
||||
alpha: number, -- sample index of the alpha channel, -1 = none
|
||||
assoc: boolean, -- premultiplied alpha (undone)
|
||||
cmap: buffer?, -- palette: 3 * 2^bps u16 (red block, green block, blue block)
|
||||
kind: string, -- the output pixel format
|
||||
out: buffer,
|
||||
}
|
||||
|
||||
-- the common 8-bit chunky cases without per-sample dispatch; false when P is not one of them
|
||||
local function fast(P: Params): boolean
|
||||
if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then
|
||||
return false
|
||||
end
|
||||
local b, rb, w, h, spp, alpha, kind, out = P.planes[1], P.rb, P.w, P.h, P.spp, P.alpha, P.kind, P.out
|
||||
local o = 0
|
||||
if P.photo == 2 and spp >= 3 and (kind == "rgba8" or kind == "rgb8") then
|
||||
local four = kind == "rgba8"
|
||||
for y = 0, h - 1 do
|
||||
local p = y * rb
|
||||
for _ = 0, w - 1 do
|
||||
writeu8(out, o, readu8(b, p))
|
||||
writeu8(out, o + 1, readu8(b, p + 1))
|
||||
writeu8(out, o + 2, readu8(b, p + 2))
|
||||
if four then
|
||||
writeu8(out, o + 3, if alpha >= 0 then readu8(b, p + alpha) else 255)
|
||||
o += 4
|
||||
else
|
||||
o += 3
|
||||
end
|
||||
p += spp
|
||||
end
|
||||
end
|
||||
return true
|
||||
elseif (P.photo == 1 or P.photo == 0) and (kind == "rgba8" or kind == "gray8" or kind == "graya8") then
|
||||
local inv = if P.photo == 0 then 255 else 0
|
||||
for y = 0, h - 1 do
|
||||
local p = y * rb
|
||||
for _ = 0, w - 1 do
|
||||
local v = math.abs(inv - readu8(b, p))
|
||||
if kind == "gray8" then
|
||||
writeu8(out, o, v)
|
||||
o += 1
|
||||
elseif kind == "graya8" then
|
||||
writeu8(out, o, v)
|
||||
writeu8(out, o + 1, if alpha >= 0 then readu8(b, p + alpha) else 255)
|
||||
o += 2
|
||||
else
|
||||
writeu32(out, o, v * 0x10101 + (if alpha >= 0 then readu8(b, p + alpha) else 255) * 0x1000000)
|
||||
o += 4
|
||||
end
|
||||
p += spp
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- convert(P): every pixel into P.out in P.kind's layout
|
||||
function Pixels.convert(P: Params)
|
||||
if fast(P) then
|
||||
return
|
||||
end
|
||||
local planes, rb, chunky, w, h, spp, bps, sfmt, le = P.planes, P.rb, P.chunky, P.w, P.h, P.spp, P.bps, P.sfmt, P.le
|
||||
local photo, alpha, assoc, cmap, kind, out = P.photo, P.alpha, P.assoc, P.cmap, P.kind, P.out
|
||||
local maxv = 2 ^ math.min(bps, 32) - 1
|
||||
local float = sfmt == 3
|
||||
local signed = sfmt == 2
|
||||
local cmapN = 2 ^ math.min(bps, 16)
|
||||
-- raw sample s of pixel x in the row starting at byte ro of its plane
|
||||
local function raw(s: number, x: number, row: number): number
|
||||
local b, i
|
||||
if chunky then
|
||||
b, i = planes[1], x * spp + s
|
||||
else
|
||||
b, i = planes[s + 1], x
|
||||
end
|
||||
local ro = row * rb
|
||||
if bps == 8 then
|
||||
local v = readu8(b, ro + i)
|
||||
return if signed then (v + 128) % 256 else v
|
||||
elseif bps == 16 then
|
||||
local p = ro + i * 2
|
||||
local v = if le then readu16(b, p) else readu8(b, p) * 256 + readu8(b, p + 1)
|
||||
if float then
|
||||
return half(v)
|
||||
end
|
||||
return if signed then (v + 32768) % 65536 else v
|
||||
elseif bps == 32 then
|
||||
local p = ro + i * 4
|
||||
if float then
|
||||
return f32(if le then readu32(b, p) else byteswap(readu32(b, p)))
|
||||
end
|
||||
local v = if le then readu32(b, p) else byteswap(readu32(b, p))
|
||||
return if signed then (v + 2147483648) % 4294967296 else v
|
||||
elseif bps == 64 then
|
||||
local p = ro + i * 8
|
||||
if le then
|
||||
return f64(readu32(b, p), readu32(b, p + 4))
|
||||
end
|
||||
return f64(byteswap(readu32(b, p + 4)), byteswap(readu32(b, p)))
|
||||
else
|
||||
-- any other depth (1..31): MSB-first bit fields
|
||||
local bit = i * bps
|
||||
local v = 0
|
||||
local need = bps
|
||||
local p = ro + rshift(bit, 3)
|
||||
local sh = band(bit, 7)
|
||||
local cur = band(readu8(b, p), rshift(255, sh))
|
||||
local avail = 8 - sh
|
||||
while need > 0 do
|
||||
if need >= avail then
|
||||
v = v * 2 ^ avail + cur
|
||||
need -= avail
|
||||
p += 1
|
||||
cur = if need > 0 then readu8(b, p) else 0
|
||||
avail = 8
|
||||
else
|
||||
v = v * 2 ^ need + rshift(cur, avail - need)
|
||||
need = 0
|
||||
end
|
||||
end
|
||||
return v
|
||||
end
|
||||
end
|
||||
-- normalised 0..1 (floats as stored)
|
||||
local function norm(s: number, x: number, row: number): number
|
||||
local v = raw(s, x, row)
|
||||
if float then
|
||||
return v
|
||||
end
|
||||
return v / maxv
|
||||
end
|
||||
local o = 0
|
||||
local is8 = kind == "rgba8" or kind == "rgb8" or kind == "gray8" or kind == "graya8"
|
||||
local is16 = kind == "rgba16" or kind == "gray16"
|
||||
local nch = if kind == "rgba8" or kind == "rgba16" or kind == "rgbaf32" then 4 elseif kind == "rgb8" then 3 elseif kind == "graya8" then 2 else 1
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local r, g, bl, a
|
||||
if photo == 3 then
|
||||
local idx = raw(0, x, y)
|
||||
if cmap and idx < cmapN then
|
||||
r = readu16(cmap, idx * 2) / 65535
|
||||
g = readu16(cmap, (cmapN + idx) * 2) / 65535
|
||||
bl = readu16(cmap, (2 * cmapN + idx) * 2) / 65535
|
||||
else
|
||||
r, g, bl = 0, 0, 0
|
||||
end
|
||||
elseif photo == 2 then
|
||||
r, g, bl = norm(0, x, y), norm(1, x, y), norm(2, x, y)
|
||||
elseif photo == 5 then
|
||||
local c, m, ye, k = norm(0, x, y), norm(1, x, y), norm(2, x, y), norm(3, x, y)
|
||||
r, g, bl = (1 - c) * (1 - k), (1 - m) * (1 - k), (1 - ye) * (1 - k)
|
||||
else
|
||||
local v = norm(0, x, y)
|
||||
if photo == 0 then
|
||||
v = 1 - v
|
||||
end
|
||||
r, g, bl = v, v, v
|
||||
end
|
||||
if alpha >= 0 then
|
||||
a = norm(alpha, x, y)
|
||||
if assoc then
|
||||
if a > 0 then
|
||||
r, g, bl = math.min(r / a, 1), math.min(g / a, 1), math.min(bl / a, 1)
|
||||
else
|
||||
r, g, bl = 0, 0, 0
|
||||
end
|
||||
end
|
||||
else
|
||||
a = 1
|
||||
end
|
||||
if is8 then
|
||||
if r ~= r then
|
||||
r = 0
|
||||
end
|
||||
if g ~= g then
|
||||
g = 0
|
||||
end
|
||||
if bl ~= bl then
|
||||
bl = 0
|
||||
end
|
||||
if a ~= a then
|
||||
a = 0
|
||||
end
|
||||
local R = floor(math.clamp(r, 0, 1) * 255 + 0.5)
|
||||
if nch == 1 then
|
||||
writeu8(out, o, R)
|
||||
elseif nch == 2 then
|
||||
writeu8(out, o, R)
|
||||
writeu8(out, o + 1, floor(math.clamp(a, 0, 1) * 255 + 0.5))
|
||||
else
|
||||
writeu8(out, o, R)
|
||||
writeu8(out, o + 1, floor(math.clamp(g, 0, 1) * 255 + 0.5))
|
||||
writeu8(out, o + 2, floor(math.clamp(bl, 0, 1) * 255 + 0.5))
|
||||
if nch == 4 then
|
||||
writeu8(out, o + 3, floor(math.clamp(a, 0, 1) * 255 + 0.5))
|
||||
end
|
||||
end
|
||||
o += nch
|
||||
elseif is16 then
|
||||
if r ~= r then
|
||||
r = 0
|
||||
end
|
||||
if g ~= g then
|
||||
g = 0
|
||||
end
|
||||
if bl ~= bl then
|
||||
bl = 0
|
||||
end
|
||||
if a ~= a then
|
||||
a = 0
|
||||
end
|
||||
writeu16(out, o, floor(math.clamp(r, 0, 1) * 65535 + 0.5))
|
||||
if nch == 4 then
|
||||
writeu16(out, o + 2, floor(math.clamp(g, 0, 1) * 65535 + 0.5))
|
||||
writeu16(out, o + 4, floor(math.clamp(bl, 0, 1) * 65535 + 0.5))
|
||||
writeu16(out, o + 6, floor(math.clamp(a, 0, 1) * 65535 + 0.5))
|
||||
end
|
||||
o += nch * 2
|
||||
else
|
||||
writef32(out, o, r)
|
||||
writef32(out, o + 4, g)
|
||||
writef32(out, o + 8, bl)
|
||||
writef32(out, o + 12, a)
|
||||
o += 16
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Pixels
|
||||
@@ -0,0 +1,841 @@
|
||||
--!strict
|
||||
-- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification.
|
||||
-- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none /
|
||||
-- LZW (codecs/Lzw, also old-style) / Deflate (8 and 32946, codecs/Deflate) / PackBits, JPEG (7) through the api's
|
||||
-- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float),
|
||||
-- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette,
|
||||
-- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as
|
||||
-- img.frames, resolution (meta.dpi), ICC (meta.icc). Decodes to rgba8, or with opts.native to the nearest standard
|
||||
-- layout (gray8, gray16, graya8, rgb8, rgba8, rgba16, rgbaf32).
|
||||
-- Encode: rgba8 / rgb8 / gray8 / graya8 / gray16 / rgba16 / rgbaf32 as the matching TIFF layout, compression none /
|
||||
-- deflate / lzw / packbits with predictor 2 (integers) or 3 (floats), strips, multi-page from img.frames.
|
||||
-- Not supported: old-style JPEG (6), CCITT fax (2, 3, 4), uncompressed YCbCr with subsampling, CIELab, JBIG.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Deflate = require("@formats/codecs/Deflate")
|
||||
local Lzw = require("@formats/codecs/Lzw")
|
||||
local Pixels = require("@formats/image/tiff/Pixels")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Tiff = {
|
||||
name = "tiff",
|
||||
category = "image",
|
||||
extensions = { "tif", "tiff" },
|
||||
mime = { "image/tiff" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "codecs/Lzw" },
|
||||
caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
native: boolean?, -- keep the source layout (gray8 / gray16 / graya8 / rgb8 / rgba8 / rgba16 / rgbaf32); default rgba8
|
||||
maxPixels: number?, -- per page (default 2^26)
|
||||
maxPages: number?, -- pages decoded into img.frames (default 1024)
|
||||
page: number?, -- decode only this page (1-based)
|
||||
decodeImage: ((buffer) -> (any, any))?, -- the api's hook, for JPEG-compressed pages
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
compression: ("none" | "deflate" | "lzw" | "packbits")?, -- default "deflate"
|
||||
predictor: boolean?, -- horizontal / float predictor with deflate and lzw (default true)
|
||||
level: number?, -- deflate level 0..9 (default 6)
|
||||
rowsPerStrip: number?, -- default: about 64 KB per strip
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local TYPE_SIZE = { [1] = 1, [2] = 1, [3] = 2, [4] = 4, [5] = 8, [6] = 1, [7] = 1, [8] = 2, [9] = 4, [10] = 8, [11] = 4, [12] = 8, [13] = 4, [16] = 8, [17] = 8, [18] = 8 }
|
||||
local COMPRESSION = { [1] = "none", [5] = "lzw", [8] = "deflate", [32946] = "deflate", [32773] = "packbits", [7] = "jpeg" }
|
||||
local PHOTOMETRIC = { [0] = "miniswhite", [1] = "minisblack", [2] = "rgb", [3] = "palette", [5] = "cmyk", [6] = "ycbcr" }
|
||||
local TWO32 = 4294967296
|
||||
|
||||
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Tiff.sniff(r: Bytes.Reader): number
|
||||
local s = r:peek(4)
|
||||
if s == "II*\0" or s == "MM\0*" or s == "II+\0" or s == "MM\0+" then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
type Entry = { tag: number, typ: number, count: number, at: number }
|
||||
type Ctx = { b: buffer, base: number, limit: number, le: boolean, big: boolean }
|
||||
|
||||
local function u16(c: Ctx, at: number): number
|
||||
if at < c.base or at + 2 > c.limit then
|
||||
return 0
|
||||
end
|
||||
return if c.le then readu16(c.b, at) else readu8(c.b, at) * 256 + readu8(c.b, at + 1)
|
||||
end
|
||||
local function u32(c: Ctx, at: number): number
|
||||
if at < c.base or at + 4 > c.limit then
|
||||
return 0
|
||||
end
|
||||
local v = readu32(c.b, at)
|
||||
return if c.le then v else bit32.byteswap(v)
|
||||
end
|
||||
local function u64(c: Ctx, at: number): number
|
||||
local lo, hi = u32(c, at), u32(c, at + 4)
|
||||
if not c.le then
|
||||
lo, hi = hi, lo
|
||||
end
|
||||
return hi * TWO32 + lo
|
||||
end
|
||||
local function off(c: Ctx, at: number): number
|
||||
return if c.big then u64(c, at) else u32(c, at)
|
||||
end
|
||||
|
||||
-- values(c, e, max) -> the entry's numbers (rationals divided) | nil when out of range / too many
|
||||
local function values(c: Ctx, e: Entry?, max: number?): { number }?
|
||||
if not e then
|
||||
return nil
|
||||
end
|
||||
local size = TYPE_SIZE[e.typ]
|
||||
if not size or e.count > (max or 1e7) or e.at < c.base or e.at + e.count * size > c.limit then
|
||||
return nil
|
||||
end
|
||||
local out = table.create(e.count, 0)
|
||||
local b = c.b
|
||||
for i = 0, e.count - 1 do
|
||||
local p = e.at + i * size
|
||||
local t = e.typ
|
||||
local v
|
||||
if t == 1 or t == 2 or t == 7 then
|
||||
v = readu8(b, p)
|
||||
elseif t == 6 then
|
||||
v = buffer.readi8(b, p)
|
||||
elseif t == 3 then
|
||||
v = u16(c, p)
|
||||
elseif t == 8 then
|
||||
v = u16(c, p)
|
||||
if v >= 32768 then
|
||||
v -= 65536
|
||||
end
|
||||
elseif t == 4 or t == 13 then
|
||||
v = u32(c, p)
|
||||
elseif t == 9 then
|
||||
v = u32(c, p)
|
||||
if v >= 2147483648 then
|
||||
v -= TWO32
|
||||
end
|
||||
elseif t == 5 or t == 10 then
|
||||
local n, d = u32(c, p), u32(c, p + 4)
|
||||
if t == 10 then
|
||||
if n >= 2147483648 then
|
||||
n -= TWO32
|
||||
end
|
||||
if d >= 2147483648 then
|
||||
d -= TWO32
|
||||
end
|
||||
end
|
||||
v = if d ~= 0 then n / d else 0
|
||||
elseif t == 11 then
|
||||
v = Pixels.f32(u32(c, p))
|
||||
elseif t == 12 then
|
||||
local lo, hi = u32(c, p), u32(c, p + 4)
|
||||
if not c.le then
|
||||
lo, hi = hi, lo
|
||||
end
|
||||
v = Pixels.f64(lo, hi)
|
||||
else
|
||||
v = u64(c, p)
|
||||
end
|
||||
out[i + 1] = v
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function one(c: Ctx, e: Entry?, default: number): number
|
||||
local v = values(c, e, 64)
|
||||
return if v and v[1] then v[1] else default
|
||||
end
|
||||
|
||||
-- the IFD at absolute offset p: { [tag] = Entry }, next IFD offset (absolute, 0 = none) | nil, Err
|
||||
local function readIfd(c: Ctx, p: number): ({ [number]: Entry }?, number, Err.Err?)
|
||||
local esize = if c.big then 20 else 12
|
||||
local hsize = if c.big then 8 else 2
|
||||
if p < c.base or p + hsize > c.limit then
|
||||
return nil, 0, Err.new(Err.TRUNCATED, "IFD past the end", p)
|
||||
end
|
||||
local n = if c.big then u64(c, p) else u16(c, p)
|
||||
if n == 0 or p + hsize + n * esize > c.limit then
|
||||
return nil, 0, Err.new(if n == 0 then Err.CORRUPT else Err.TRUNCATED, "bad IFD entry count " .. n, p)
|
||||
end
|
||||
local entries: { [number]: Entry } = {}
|
||||
for i = 0, n - 1 do
|
||||
local q = p + hsize + i * esize
|
||||
local tag, typ = u16(c, q), u16(c, q + 2)
|
||||
local count = if c.big then u64(c, q + 4) else u32(c, q + 4)
|
||||
local vat = q + (if c.big then 12 else 8)
|
||||
local size = TYPE_SIZE[typ]
|
||||
if size then
|
||||
local at = vat
|
||||
if count * size > (if c.big then 8 else 4) then
|
||||
at = c.base + off(c, vat)
|
||||
end
|
||||
entries[tag] = { tag = tag, typ = typ, count = count, at = at }
|
||||
end
|
||||
end
|
||||
local nq = p + hsize + n * esize
|
||||
local nextOff = 0
|
||||
if nq + (if c.big then 8 else 4) <= c.limit then
|
||||
nextOff = off(c, nq)
|
||||
end
|
||||
return entries, if nextOff > 0 then c.base + nextOff else 0, nil
|
||||
end
|
||||
|
||||
local function bytesOf(c: Ctx, e: Entry?, max: number): buffer?
|
||||
if not e or e.at < c.base then
|
||||
return nil
|
||||
end
|
||||
local size = TYPE_SIZE[e.typ] or 1
|
||||
local n = e.count * size
|
||||
if n > max or e.at + n > c.limit then
|
||||
return nil
|
||||
end
|
||||
local x = buffer.create(n)
|
||||
buffer.copy(x, 0, c.b, e.at, n)
|
||||
return x
|
||||
end
|
||||
|
||||
-- decompress one chunk at [p, p + len) into out[o, o + size): bytes produced | nil, Err
|
||||
local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: buffer, o: number, size: number, rev: boolean): (number?, Err.Err?)
|
||||
if p < c.base or len < 0 or p + len > c.limit then
|
||||
-- a chunk past the end: keep what exists (truncated files)
|
||||
len = math.max(0, math.min(len, c.limit - p))
|
||||
if p < c.base or p >= c.limit then
|
||||
return 0
|
||||
end
|
||||
end
|
||||
local src, sp = c.b, p
|
||||
if rev then
|
||||
src = buffer.create(len)
|
||||
buffer.copy(src, 0, c.b, p, len)
|
||||
Pixels.reverseBits(src, 0, len)
|
||||
sp = 0
|
||||
end
|
||||
if comp == 1 then
|
||||
local n = math.min(len, size)
|
||||
buffer.copy(out, o, src, sp, n)
|
||||
return n
|
||||
elseif comp == 5 then
|
||||
local n = Lzw.decode(src, sp, len, out, o, size, "tiff")
|
||||
return n
|
||||
elseif comp == 8 or comp == 32946 then
|
||||
local raw = Deflate.zlib(src, sp, len, size)
|
||||
if not raw then
|
||||
raw = Deflate.zlib(src, sp, len) or Deflate.inflate(src, sp, len)
|
||||
end
|
||||
if not raw then
|
||||
return nil, Err.new(Err.CORRUPT, "bad deflate data", p)
|
||||
end
|
||||
local n = math.min(buffer.len(raw :: buffer), size)
|
||||
buffer.copy(out, o, raw :: buffer, 0, n)
|
||||
return n
|
||||
elseif comp == 32773 then
|
||||
return Pixels.packbits(src, sp, len, out, o, size)
|
||||
end
|
||||
return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp)
|
||||
end
|
||||
|
||||
type Page = { image: Types.Image, info: { [string]: any } }
|
||||
|
||||
local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local w, h = one(c, t[256], 0), one(c, t[257], 0)
|
||||
if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad image size")
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local spp = one(c, t[277], 1)
|
||||
local bpsList = values(c, t[258], 64) or { 1 }
|
||||
local bps = bpsList[1] or 1
|
||||
for i = 2, math.min(#bpsList, spp) do
|
||||
if bpsList[i] ~= bps then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "different bit depths per sample")
|
||||
end
|
||||
end
|
||||
local comp = one(c, t[259], 1)
|
||||
local photo = one(c, t[262], if spp >= 3 then 2 else 1)
|
||||
local planar = one(c, t[284], 1)
|
||||
local predictor = one(c, t[317], 1)
|
||||
local sfmt = one(c, t[339], 1)
|
||||
local fill = one(c, t[266], 1)
|
||||
if spp < 1 or spp > 16 or bps < 1 or bps > 64 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("%d samples of %d bits", spp, bps))
|
||||
end
|
||||
if sfmt == 3 and bps ~= 16 and bps ~= 32 and bps ~= 64 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit floats")
|
||||
end
|
||||
if sfmt ~= 3 and bps > 32 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit integers")
|
||||
end
|
||||
if not COMPRESSION[comp] then
|
||||
local names = { [2] = "CCITT RLE", [3] = "CCITT fax 3", [4] = "CCITT fax 4", [6] = "old-style JPEG", [34712] = "JPEG 2000", [34925] = "LZMA", [50000] = "Zstandard", [50001] = "WebP" }
|
||||
return nil, Err.new(Err.UNSUPPORTED, (names[comp] or "compression") .. " (" .. comp .. ")")
|
||||
end
|
||||
if not PHOTOMETRIC[photo] then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "photometric interpretation " .. photo)
|
||||
end
|
||||
local cc = if photo == 2 or photo == 6 then 3 elseif photo == 5 then 4 else 1
|
||||
if spp < cc then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("%d samples for photometric %d", spp, photo))
|
||||
end
|
||||
if photo == 5 and one(c, t[332], 1) ~= 1 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "separated image that is not CMYK")
|
||||
end
|
||||
local extra = values(c, t[338], 16) or {}
|
||||
local alpha, assoc = -1, false
|
||||
if spp > cc then
|
||||
local kind = extra[1] or 0
|
||||
alpha = cc
|
||||
assoc = kind == 1
|
||||
end
|
||||
local chunky = planar ~= 2 or spp == 1
|
||||
local tiled = t[322] ~= nil
|
||||
local cw = if tiled then one(c, t[322], 0) else w
|
||||
local ch = if tiled then one(c, t[323], 0) else math.min(one(c, t[278], h), h)
|
||||
if cw < 1 or ch < 1 or cw > 65536 or (tiled and ch > 65536) then
|
||||
return nil, Err.new(Err.CORRUPT, "bad tile / strip size")
|
||||
end
|
||||
if ch > h and not tiled then
|
||||
ch = h
|
||||
end
|
||||
local pspp = if chunky then spp else 1 -- samples per pixel in one plane
|
||||
local nplanes = if chunky then 1 else spp
|
||||
local rb = math.ceil(w * pspp * bps / 8) -- bytes per image row in a plane
|
||||
local crb = math.ceil(cw * pspp * bps / 8) -- bytes per chunk row
|
||||
if rb * h * nplanes > 2 ^ 30 or crb * ch > 2 ^ 30 then
|
||||
return nil, Err.new(Err.LIMIT, "decoded data over 1 GB")
|
||||
end
|
||||
local across = if tiled then math.ceil(w / cw) else 1
|
||||
local down = math.ceil(h / ch)
|
||||
local perPlane = across * down
|
||||
local offs = values(c, if tiled then t[324] else t[273], 2 ^ 24)
|
||||
local lens = values(c, if tiled then t[325] else t[279], 2 ^ 24)
|
||||
if not offs or #offs < perPlane * nplanes then
|
||||
return nil, Err.new(Err.CORRUPT, "missing or short strip / tile offsets")
|
||||
end
|
||||
local planes = table.create(nplanes)
|
||||
for i = 1, nplanes do
|
||||
planes[i] = buffer.create(rb * h + 8)
|
||||
end
|
||||
local tmp = buffer.create(crb * ch + 8)
|
||||
local ftmp = buffer.create(math.max(rb, crb) + 8)
|
||||
local le = c.le
|
||||
local bytesPer = bps // 8
|
||||
local hook = opts and opts.decodeImage
|
||||
local jpegTables = if comp == 7 then bytesOf(c, t[347], 1 * 2 ^ 20) else nil
|
||||
local jpegPixels: buffer? = nil
|
||||
if comp == 7 then
|
||||
if type(hook) ~= "function" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "JPEG-compressed TIFF needs opts.decodeImage (F.load supplies it)")
|
||||
end
|
||||
jpegPixels = buffer.create(w * h * 4)
|
||||
end
|
||||
for pl = 0, nplanes - 1 do
|
||||
for ty = 0, down - 1 do
|
||||
for tx = 0, across - 1 do
|
||||
local idx = pl * perPlane + ty * across + tx
|
||||
local p = c.base + offs[idx + 1]
|
||||
local len = if lens and lens[idx + 1] then lens[idx + 1] else c.limit - p
|
||||
local rows = if tiled then ch else math.min(ch, h - ty * ch)
|
||||
local size = rows * crb
|
||||
if comp == 7 then
|
||||
-- JPEGTables (SOI .. EOI) + the chunk (SOI .. EOI): one stream without the inner EOI / SOI
|
||||
if p < c.base or p + len > c.limit or len < 4 then
|
||||
return nil, Err.new(Err.TRUNCATED, "JPEG chunk past the end", p)
|
||||
end
|
||||
local tl = if jpegTables and buffer.len(jpegTables) >= 4 then buffer.len(jpegTables) - 2 else 0
|
||||
local s = buffer.create(tl + len - (if tl > 0 then 2 else 0))
|
||||
if tl > 0 then
|
||||
buffer.copy(s, 0, jpegTables :: buffer, 0, tl)
|
||||
buffer.copy(s, tl, c.b, p + 2, len - 2)
|
||||
else
|
||||
buffer.copy(s, 0, c.b, p, len)
|
||||
end
|
||||
local ok, img, herr = pcall(hook :: any, s)
|
||||
if not ok or type(img) ~= "table" or img.format ~= "rgba8" then
|
||||
return nil, if ok and herr then herr else Err.new(Err.CORRUPT, "embedded JPEG: " .. tostring(if ok then herr else img))
|
||||
end
|
||||
local x0, y0 = tx * cw, ty * ch
|
||||
local cwid = math.min(cw, w - x0, img.width)
|
||||
for yy = 0, math.min(rows, h - y0, img.height) - 1 do
|
||||
buffer.copy(jpegPixels :: buffer, ((y0 + yy) * w + x0) * 4, img.pixels, yy * img.width * 4, cwid * 4)
|
||||
end
|
||||
continue
|
||||
end
|
||||
buffer.fill(tmp, 0, 0, size)
|
||||
local _, derr = inflateChunk(c, comp, p, len, tmp, 0, size, fill == 2)
|
||||
if derr then
|
||||
return nil, derr
|
||||
end
|
||||
if predictor == 2 then
|
||||
Pixels.unpredict2(tmp, 0, rows, crb, pspp, bps, le)
|
||||
elseif predictor == 3 and bytesPer >= 2 and crb % bytesPer == 0 then
|
||||
Pixels.unpredict3(tmp, 0, rows, crb, bytesPer, pspp, ftmp)
|
||||
end
|
||||
-- into the plane
|
||||
local plane = planes[pl + 1]
|
||||
local x0b = math.floor(tx * cw * pspp * bps / 8)
|
||||
local cols = math.min(cw, w - tx * cw)
|
||||
local nb = math.min(math.ceil(cols * pspp * bps / 8), rb - x0b)
|
||||
for yy = 0, rows - 1 do
|
||||
local y = ty * ch + yy
|
||||
if y >= h then
|
||||
break
|
||||
end
|
||||
buffer.copy(plane, y * rb + x0b, tmp, yy * crb, nb)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local floatOut = sfmt == 3
|
||||
if predictor == 3 and floatOut then
|
||||
le = true -- fpAcc leaves the samples little endian
|
||||
end
|
||||
local colorType = PHOTOMETRIC[photo]
|
||||
-- the output layout
|
||||
local kind = "rgba8"
|
||||
if opts and opts.native and comp ~= 7 then
|
||||
if photo == 3 or photo == 5 then
|
||||
kind = "rgba8"
|
||||
elseif floatOut then
|
||||
kind = "rgbaf32"
|
||||
elseif cc == 1 then
|
||||
if alpha >= 0 then
|
||||
kind = if bps <= 8 then "graya8" else "rgba16"
|
||||
else
|
||||
kind = if bps <= 8 then "gray8" else "gray16"
|
||||
end
|
||||
else
|
||||
if alpha >= 0 then
|
||||
kind = if bps <= 8 then "rgba8" else "rgba16"
|
||||
else
|
||||
kind = if bps <= 8 then "rgb8" else "rgba16"
|
||||
end
|
||||
end
|
||||
end
|
||||
local img = Types.Image.new(w, h, kind :: any)
|
||||
if comp == 7 then
|
||||
img.pixels = jpegPixels :: buffer
|
||||
else
|
||||
if photo == 6 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "uncompressed YCbCr")
|
||||
end
|
||||
local cmap = nil
|
||||
if photo == 3 then
|
||||
local n = 3 * 2 ^ math.min(bps, 16)
|
||||
local cv = values(c, t[320], n)
|
||||
if not cv or #cv < n then
|
||||
return nil, Err.new(Err.CORRUPT, "palette image without a full ColorMap")
|
||||
end
|
||||
cmap = buffer.create(n * 2)
|
||||
for i = 1, n do
|
||||
buffer.writeu16(cmap, (i - 1) * 2, math.clamp(cv[i], 0, 65535))
|
||||
end
|
||||
end
|
||||
Pixels.convert({
|
||||
planes = planes,
|
||||
rb = rb,
|
||||
chunky = chunky,
|
||||
w = w,
|
||||
h = h,
|
||||
spp = spp,
|
||||
bps = bps,
|
||||
sfmt = sfmt,
|
||||
le = le,
|
||||
photo = photo,
|
||||
alpha = alpha,
|
||||
assoc = assoc,
|
||||
cmap = cmap,
|
||||
kind = kind,
|
||||
out = img.pixels,
|
||||
})
|
||||
end
|
||||
local xr, yr = one(c, t[282], 0), one(c, t[283], 0)
|
||||
if xr > 0 and yr > 0 then
|
||||
local unit = one(c, t[296], 2)
|
||||
local k = if unit == 3 then 2.54 else 1
|
||||
if unit ~= 1 then
|
||||
img.meta.dpi = { x = xr * k, y = yr * k }
|
||||
end
|
||||
end
|
||||
img.meta.icc = bytesOf(c, t[34675], 2 ^ 26)
|
||||
local function ascii(tag: number): string?
|
||||
local v = bytesOf(c, t[tag], 65536)
|
||||
if not v then
|
||||
return nil
|
||||
end
|
||||
local s = buffer.tostring(v)
|
||||
local z = string.find(s, "\0", 1, true)
|
||||
return if z then string.sub(s, 1, z - 1) else s
|
||||
end
|
||||
local text = {}
|
||||
for tag, key in { [270] = "description", [305] = "software", [306] = "datetime", [315] = "artist", [33432] = "copyright" } do
|
||||
local s = ascii(tag)
|
||||
if s and s ~= "" then
|
||||
text[key] = s
|
||||
end
|
||||
end
|
||||
if next(text) then
|
||||
img.meta.text = text
|
||||
end
|
||||
img.meta.source = {
|
||||
format = "tiff",
|
||||
bitDepth = bps,
|
||||
colorType = colorType,
|
||||
photometric = photo,
|
||||
samples = spp,
|
||||
sampleFormat = if sfmt == 3 then "float" elseif sfmt == 2 then "int" else "uint",
|
||||
compression = COMPRESSION[comp],
|
||||
predictor = predictor,
|
||||
planar = planar,
|
||||
tiled = tiled,
|
||||
alpha = if alpha >= 0 then (if assoc then "associated" else "unassociated") else nil,
|
||||
bigtiff = c.big,
|
||||
byteOrder = if c.le then "II" else "MM",
|
||||
}
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- pages(r) -> the IFD tables of every page (and the context) | nil, Err
|
||||
local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry } }?, Ctx?, Err.Err?)
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
if limit - base < 8 then
|
||||
return nil, nil, Err.new(Err.TRUNCATED, "short header")
|
||||
end
|
||||
local bo = buffer.readstring(b, base, 2)
|
||||
if bo ~= "II" and bo ~= "MM" then
|
||||
return nil, nil, Err.new(Err.CORRUPT, "bad byte order mark")
|
||||
end
|
||||
local c: Ctx = { b = b, base = base, limit = limit, le = bo == "II", big = false }
|
||||
local magic = u16(c, base + 2)
|
||||
local first
|
||||
if magic == 42 then
|
||||
first = u32(c, base + 4)
|
||||
elseif magic == 43 then
|
||||
if limit - base < 16 or u16(c, base + 4) ~= 8 then
|
||||
return nil, nil, Err.new(Err.CORRUPT, "bad BigTIFF header")
|
||||
end
|
||||
c.big = true
|
||||
first = u64(c, base + 8)
|
||||
else
|
||||
return nil, nil, Err.new(Err.CORRUPT, "bad magic " .. magic)
|
||||
end
|
||||
local list = {}
|
||||
local seen = {}
|
||||
local p = base + first
|
||||
while p > 0 and #list < maxPages do
|
||||
if seen[p] then
|
||||
break -- an IFD loop
|
||||
end
|
||||
seen[p] = true
|
||||
local t, nextP, err = readIfd(c, p)
|
||||
if not t then
|
||||
if #list == 0 then
|
||||
return nil, nil, err
|
||||
end
|
||||
break
|
||||
end
|
||||
table.insert(list, t)
|
||||
p = nextP
|
||||
end
|
||||
return list, c, nil
|
||||
end
|
||||
|
||||
-- info(r) -> { pages, width, height, bitDepth, samples, compression } of page 1 | nil, Err
|
||||
function Tiff.info(r: Bytes.Reader): ({ [string]: any }?, Err.Err?)
|
||||
local list, c, err = pages(r, 1024)
|
||||
if not list or not c then
|
||||
return nil, err
|
||||
end
|
||||
local t = list[1]
|
||||
return {
|
||||
pages = #list,
|
||||
width = one(c, t[256], 0),
|
||||
height = one(c, t[257], 0),
|
||||
bitDepth = one(c, t[258], 1),
|
||||
samples = one(c, t[277], 1),
|
||||
compression = COMPRESSION[one(c, t[259], 1)] or tostring(one(c, t[259], 1)),
|
||||
photometric = PHOTOMETRIC[one(c, t[262], 1)],
|
||||
bigtiff = c.big,
|
||||
},
|
||||
nil
|
||||
end
|
||||
|
||||
function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local maxPages = opts and opts.maxPages or 1024
|
||||
local list, c, err = pages(r, if opts and opts.page then math.max(1, opts.page) else maxPages)
|
||||
if not list or not c then
|
||||
return nil, err
|
||||
end
|
||||
if opts and opts.page then
|
||||
local t = list[opts.page]
|
||||
if not t then
|
||||
return nil, Err.new(Err.ARG, "no page " .. tostring(opts.page))
|
||||
end
|
||||
local img, perr = decodePage(c, t, opts)
|
||||
if img then
|
||||
img.meta.source.pages = #list
|
||||
end
|
||||
return img, perr
|
||||
end
|
||||
local first: Types.Image? = nil
|
||||
local frames = {}
|
||||
for i, t in list do
|
||||
-- reduced-resolution subfiles (thumbnails) after page 1 are skipped
|
||||
local sub = one(c, t[254], 0)
|
||||
if i > 1 and bit32.band(sub, 1) ~= 0 then
|
||||
continue
|
||||
end
|
||||
local img, perr = decodePage(c, t, opts)
|
||||
if not img then
|
||||
if i == 1 then
|
||||
return nil, perr
|
||||
end
|
||||
continue
|
||||
end
|
||||
if not first then
|
||||
first = img
|
||||
end
|
||||
table.insert(frames, { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" })
|
||||
end
|
||||
local img = first :: Types.Image
|
||||
img.meta.source.pages = #frames
|
||||
if #frames > 1 then
|
||||
img.frames = frames :: any
|
||||
end
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- layout per pixel format: samples, bits, sample format, photometric, extra samples
|
||||
local LAYOUT = {
|
||||
gray8 = { 1, 8, 1, 1 },
|
||||
graya8 = { 2, 8, 1, 1 },
|
||||
gray16 = { 1, 16, 1, 1 },
|
||||
rgb8 = { 3, 8, 1, 2 },
|
||||
rgba8 = { 4, 8, 1, 2 },
|
||||
rgba16 = { 4, 16, 1, 2 },
|
||||
rgbaf32 = { 4, 32, 3, 2 },
|
||||
}
|
||||
local COMP_CODES = { none = 1, deflate = 8, lzw = 5, packbits = 32773 }
|
||||
|
||||
type Tag = { tag: number, typ: number, vals: { number }?, data: buffer? }
|
||||
|
||||
local function encodePage(img: Types.Image, o: EncodeOptions, comp: number): ({ Tag }?, { buffer }?, Err.Err?)
|
||||
local L = LAYOUT[img.format]
|
||||
if not L then
|
||||
return nil, nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format))
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
local spp, bps, sfmt, photo = L[1], L[2], L[3], L[4]
|
||||
local rb = w * spp * bps // 8
|
||||
if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w > 2 ^ 31 or buffer.len(img.pixels) < rb * h then
|
||||
return nil, nil, Err.new(Err.ARG, "bad image size or pixel buffer")
|
||||
end
|
||||
local rps = o.rowsPerStrip or math.max(1, 65536 // rb)
|
||||
if type(rps) ~= "number" or rps < 1 then
|
||||
return nil, nil, Err.new(Err.ARG, "rowsPerStrip must be >= 1")
|
||||
end
|
||||
rps = math.min(math.floor(rps), h)
|
||||
local predictor = 1
|
||||
if (comp == 8 or comp == 5) and o.predictor ~= false then
|
||||
predictor = if sfmt == 3 then 3 else 2
|
||||
end
|
||||
local strips = {}
|
||||
local tmp = buffer.create(rb + 8)
|
||||
for y0 = 0, h - 1, rps do
|
||||
local rows = math.min(rps, h - y0)
|
||||
local raw = buffer.create(rows * rb)
|
||||
buffer.copy(raw, 0, img.pixels, y0 * rb, rows * rb)
|
||||
if predictor == 2 then
|
||||
Pixels.predict2(raw, 0, rows, rb, spp, bps)
|
||||
elseif predictor == 3 then
|
||||
Pixels.predict3(raw, 0, rows, rb, 4, spp, tmp)
|
||||
end
|
||||
local out
|
||||
if comp == 1 then
|
||||
out = raw
|
||||
elseif comp == 8 then
|
||||
out = Deflate.zlibCompress(raw, { level = o.level or 6 }) :: buffer
|
||||
elseif comp == 5 then
|
||||
out = Lzw.encode(raw, 0, rows * rb, "tiff")
|
||||
else
|
||||
local parts, total = {}, 0
|
||||
for r = 0, rows - 1 do
|
||||
local p = Pixels.packbitsEncode(raw, r * rb, rb)
|
||||
table.insert(parts, p)
|
||||
total += buffer.len(p)
|
||||
end
|
||||
out = buffer.create(total)
|
||||
local q = 0
|
||||
for _, p in parts do
|
||||
buffer.copy(out, q, p)
|
||||
q += buffer.len(p)
|
||||
end
|
||||
end
|
||||
table.insert(strips, out)
|
||||
end
|
||||
local bpsv = table.create(spp, bps)
|
||||
local tags: { Tag } = {
|
||||
{ tag = 254, typ = 4, vals = { 0 } },
|
||||
{ tag = 256, typ = 4, vals = { w } },
|
||||
{ tag = 257, typ = 4, vals = { h } },
|
||||
{ tag = 258, typ = 3, vals = bpsv },
|
||||
{ tag = 259, typ = 3, vals = { comp } },
|
||||
{ tag = 262, typ = 3, vals = { photo } },
|
||||
{ tag = 273, typ = 4, vals = table.create(#strips, 0) }, -- patched
|
||||
{ tag = 277, typ = 3, vals = { spp } },
|
||||
{ tag = 278, typ = 4, vals = { rps } },
|
||||
{ tag = 279, typ = 4, vals = table.create(#strips, 0) },
|
||||
{ tag = 284, typ = 3, vals = { 1 } },
|
||||
}
|
||||
for i, s in strips do
|
||||
(tags[10].vals :: { number })[i] = buffer.len(s)
|
||||
end
|
||||
local dpi = img.meta and img.meta.dpi
|
||||
if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then
|
||||
table.insert(tags, { tag = 282, typ = 5, vals = { dpi.x } })
|
||||
table.insert(tags, { tag = 283, typ = 5, vals = { dpi.y } })
|
||||
table.insert(tags, { tag = 296, typ = 3, vals = { 2 } })
|
||||
end
|
||||
if predictor > 1 then
|
||||
table.insert(tags, { tag = 317, typ = 3, vals = { predictor } })
|
||||
end
|
||||
if spp == 2 or spp == 4 then
|
||||
table.insert(tags, { tag = 338, typ = 3, vals = { 2 } })
|
||||
end
|
||||
if sfmt ~= 1 then
|
||||
table.insert(tags, { tag = 339, typ = 3, vals = table.create(spp, sfmt) })
|
||||
end
|
||||
local icc = img.meta and img.meta.icc
|
||||
if type(icc) == "buffer" then
|
||||
table.insert(tags, { tag = 34675, typ = 7, data = icc })
|
||||
end
|
||||
local text = img.meta and img.meta.text
|
||||
if type(text) == "table" then
|
||||
for key, tag in { description = 270, software = 305, datetime = 306, artist = 315, copyright = 33432 } do
|
||||
if type(text[key]) == "string" then
|
||||
table.insert(tags, { tag = tag, typ = 2, data = buffer.fromstring(text[key] .. "\0") })
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(tags, function(a: Tag, b: Tag): boolean
|
||||
return a.tag < b.tag
|
||||
end)
|
||||
return tags, strips, nil
|
||||
end
|
||||
|
||||
function Tiff.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local o: EncodeOptions = opts or {}
|
||||
local comp = COMP_CODES[o.compression or "deflate"]
|
||||
if not comp then
|
||||
return nil, Err.new(Err.ARG, "compression must be none, deflate, lzw or packbits")
|
||||
end
|
||||
local list = { img }
|
||||
if type(img.frames) == "table" and #img.frames > 1 then
|
||||
list = {}
|
||||
for _, f in img.frames :: any do
|
||||
if type(f) ~= "table" or type(f.image) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "bad frame")
|
||||
end
|
||||
table.insert(list, f.image)
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer(1024)
|
||||
w:string("II")
|
||||
w:u16le(42)
|
||||
w:u32le(0) -- first IFD, patched
|
||||
local prevNext = 4
|
||||
for _, page in list do
|
||||
local tags, strips, err = encodePage(page, o, comp)
|
||||
if not tags or not strips then
|
||||
return nil, err
|
||||
end
|
||||
-- strip data first
|
||||
local soffs = {}
|
||||
for i, s in strips do
|
||||
if w:tell() % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
soffs[i] = w:tell()
|
||||
w:bytes(s)
|
||||
end
|
||||
for _, tg in tags do
|
||||
if tg.tag == 273 then
|
||||
tg.vals = soffs
|
||||
end
|
||||
end
|
||||
-- out-of-line values
|
||||
local valOff: { [number]: number } = {}
|
||||
for i, tg in tags do
|
||||
local size = TYPE_SIZE[tg.typ]
|
||||
local n = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number }) * size
|
||||
if n > 4 then
|
||||
if w:tell() % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
valOff[i] = w:tell()
|
||||
if tg.data then
|
||||
w:bytes(tg.data :: buffer)
|
||||
else
|
||||
for _, v in tg.vals :: { number } do
|
||||
if tg.typ == 3 then
|
||||
w:u16le(v)
|
||||
elseif tg.typ == 4 then
|
||||
w:u32le(v)
|
||||
elseif tg.typ == 5 then
|
||||
w:u32le(math.floor(v * 10000 + 0.5))
|
||||
w:u32le(10000)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if w:tell() % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
local ifd = w:tell()
|
||||
w:setU32le(prevNext, ifd)
|
||||
w:u16le(#tags)
|
||||
for i, tg in tags do
|
||||
local count = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number })
|
||||
w:u16le(tg.tag)
|
||||
w:u16le(tg.typ)
|
||||
w:u32le(count)
|
||||
if valOff[i] then
|
||||
w:u32le(valOff[i])
|
||||
else
|
||||
local start = w:tell()
|
||||
if tg.data then
|
||||
w:bytes(tg.data :: buffer)
|
||||
else
|
||||
for _, v in tg.vals :: { number } do
|
||||
if tg.typ == 3 then
|
||||
w:u16le(v)
|
||||
else
|
||||
w:u32le(v)
|
||||
end
|
||||
end
|
||||
end
|
||||
w:fill(0, 4 - (w:tell() - start))
|
||||
end
|
||||
end
|
||||
prevNext = w:tell()
|
||||
w:u32le(0)
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
return Tiff
|
||||
+24
-2
@@ -231,6 +231,28 @@ local function unwrap(value: any, formatName: string, o: Options): any
|
||||
return v
|
||||
end
|
||||
|
||||
-- Embedded images (PNG inside ICO, JPEG inside TIFF, thumbnails, textures): a format never requires another format,
|
||||
-- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) ->
|
||||
-- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for
|
||||
-- the embedded parts) when called directly.
|
||||
local function withHooks(o: Options): Options
|
||||
if o.decodeImage ~= nil and o.encodeImage ~= nil then
|
||||
return o
|
||||
end
|
||||
local c = table.clone(o)
|
||||
if c.decodeImage == nil then
|
||||
c.decodeImage = function(b: buffer): (any, Err.Err?)
|
||||
return F.load(b, { category = "image" })
|
||||
end
|
||||
end
|
||||
if c.encodeImage == nil then
|
||||
c.encodeImage = function(img: any, format: string): (any, Err.Err?)
|
||||
return F.save(img, nil, { format = format, category = "image" })
|
||||
end
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
-- load(src, opts?) -> value | nil, Err
|
||||
function F.load(src: any, opts: Options?): (any, Err.Err?)
|
||||
local o = opts or {}
|
||||
@@ -252,7 +274,7 @@ function F.load(src: any, opts: Options?): (any, Err.Err?)
|
||||
end
|
||||
local value, err
|
||||
if m.decode then
|
||||
local ok, v, e = pcall(m.decode, Bytes.reader(buf), o)
|
||||
local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o))
|
||||
if not ok then
|
||||
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name)
|
||||
end
|
||||
@@ -347,7 +369,7 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
|
||||
if not entry then
|
||||
return nil, err
|
||||
end
|
||||
local ok, buf, e = pcall(m.encode, value, o)
|
||||
local ok, buf, e = pcall(m.encode, value, withHooks(o))
|
||||
if not ok then
|
||||
return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name)
|
||||
end
|
||||
|
||||
@@ -0,0 +1,520 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps (native; never throws). Every function trusts its caller
|
||||
-- (ops/ImageOps validates sizes, formats and buffer lengths first), so all buffer indexes are in range by
|
||||
-- construction. Samples are addressed by kind: 1 = u8, 2 = u16, 4 = f32 (little endian, as Types.Image buffers).
|
||||
-- The resampling follows Pillow's Resample.c (separable convolution, horizontal pass first, filter support scaled by
|
||||
-- the downscale ratio, 22-bit fixed-point coefficients for 8-bit samples) and Geometry.c (affine transforms through
|
||||
-- pixel centres, bilinear with clamped neighbours); the alpha compositing is Pillow's AlphaComposite.c.
|
||||
local readu8, writeu8, readu16, writeu16, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readf32, buffer.writef32
|
||||
local floor, clamp = math.floor, math.clamp
|
||||
|
||||
local K = {}
|
||||
|
||||
-- format ids: rgba8 1, rgba16 2, rgbaf32 3, rgb8 4, gray8 5, gray16 6, graya8 7, alpha8 8
|
||||
K.ID = { rgba8 = 1, rgba16 = 2, rgbaf32 = 3, rgb8 = 4, gray8 = 5, gray16 = 6, graya8 = 7, alpha8 = 8 }
|
||||
K.KIND = { rgba8 = 1, rgba16 = 2, rgbaf32 = 4, rgb8 = 1, gray8 = 1, gray16 = 2, graya8 = 1, alpha8 = 1 }
|
||||
K.CHANNELS = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, rgb8 = 3, gray8 = 1, gray16 = 1, graya8 = 2, alpha8 = 1 }
|
||||
|
||||
local function rd(b: buffer, o: number, kind: number): number
|
||||
if kind == 1 then
|
||||
return readu8(b, o)
|
||||
elseif kind == 2 then
|
||||
return readu16(b, o)
|
||||
end
|
||||
return readf32(b, o)
|
||||
end
|
||||
|
||||
local function wr(b: buffer, o: number, kind: number, v: number)
|
||||
if kind == 1 then
|
||||
writeu8(b, o, clamp(floor(v + 0.5), 0, 255))
|
||||
elseif kind == 2 then
|
||||
writeu16(b, o, clamp(floor(v + 0.5), 0, 65535))
|
||||
else
|
||||
writef32(b, o, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ convert
|
||||
-- depth: 8 -> 0..255, 16 -> 0..65535, 0 -> float 0..1
|
||||
local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 }
|
||||
|
||||
local function depthConv(v: number, from: number, to: number): number
|
||||
if from == to then
|
||||
return v
|
||||
end
|
||||
if from == 8 then
|
||||
if to == 16 then
|
||||
return v * 257
|
||||
end
|
||||
return v / 255
|
||||
elseif from == 16 then
|
||||
if to == 8 then
|
||||
return (v * 255 + 32767) // 65535
|
||||
end
|
||||
return v / 65535
|
||||
end
|
||||
-- float
|
||||
if v ~= v then
|
||||
v = 0
|
||||
end
|
||||
if to == 8 then
|
||||
return clamp(floor(v * 255 + 0.5), 0, 255)
|
||||
end
|
||||
return clamp(floor(v * 65535 + 0.5), 0, 65535)
|
||||
end
|
||||
|
||||
-- Pillow's L24 luma (19595 R + 38470 G + 7471 B + 0x8000) >> 16, in the source depth
|
||||
local function luma(r: number, g: number, b: number, depth: number): number
|
||||
if depth == 0 then
|
||||
return (r * 19595 + g * 38470 + b * 7471) / 65536
|
||||
end
|
||||
return (r * 19595 + g * 38470 + b * 7471 + 32768) // 65536
|
||||
end
|
||||
|
||||
function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number)
|
||||
local sd, dd = DEPTH[sf], DEPTH[df]
|
||||
local smax = if sd == 8 then 255 elseif sd == 16 then 65535 else 1
|
||||
local toGray = df == 5 or df == 6 or df == 7
|
||||
for i = 0, n - 1 do
|
||||
local r, g, b, a
|
||||
if sf == 1 then
|
||||
local o = i * 4
|
||||
r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), readu8(src, o + 3)
|
||||
elseif sf == 2 then
|
||||
local o = i * 8
|
||||
r, g, b, a = readu16(src, o), readu16(src, o + 2), readu16(src, o + 4), readu16(src, o + 6)
|
||||
elseif sf == 3 then
|
||||
local o = i * 16
|
||||
r, g, b, a = readf32(src, o), readf32(src, o + 4), readf32(src, o + 8), readf32(src, o + 12)
|
||||
elseif sf == 4 then
|
||||
local o = i * 3
|
||||
r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), 255
|
||||
elseif sf == 5 then
|
||||
local v = readu8(src, i)
|
||||
r, g, b, a = v, v, v, 255
|
||||
elseif sf == 6 then
|
||||
local v = readu16(src, i * 2)
|
||||
r, g, b, a = v, v, v, 65535
|
||||
elseif sf == 7 then
|
||||
local v = readu8(src, i * 2)
|
||||
r, g, b, a = v, v, v, readu8(src, i * 2 + 1)
|
||||
else
|
||||
r, g, b, a = 255, 255, 255, readu8(src, i)
|
||||
end
|
||||
if toGray then
|
||||
local isGray = sf == 5 or sf == 6 or sf == 7
|
||||
local l = if isGray then r else luma(r, g, b, sd)
|
||||
l = depthConv(l, sd, dd)
|
||||
if df == 5 then
|
||||
writeu8(dst, i, l)
|
||||
elseif df == 6 then
|
||||
writeu16(dst, i * 2, l)
|
||||
else
|
||||
writeu8(dst, i * 2, l)
|
||||
writeu8(dst, i * 2 + 1, depthConv(a, sd, dd))
|
||||
end
|
||||
elseif df == 8 then
|
||||
writeu8(dst, i, depthConv(a, sd, 8))
|
||||
else
|
||||
r, g, b = depthConv(r, sd, dd), depthConv(g, sd, dd), depthConv(b, sd, dd)
|
||||
if df == 1 then
|
||||
local o = i * 4
|
||||
writeu8(dst, o, r)
|
||||
writeu8(dst, o + 1, g)
|
||||
writeu8(dst, o + 2, b)
|
||||
writeu8(dst, o + 3, depthConv(a, sd, dd))
|
||||
elseif df == 2 then
|
||||
local o = i * 8
|
||||
writeu16(dst, o, r)
|
||||
writeu16(dst, o + 2, g)
|
||||
writeu16(dst, o + 4, b)
|
||||
writeu16(dst, o + 6, depthConv(a, sd, dd))
|
||||
elseif df == 3 then
|
||||
local o = i * 16
|
||||
writef32(dst, o, r)
|
||||
writef32(dst, o + 4, g)
|
||||
writef32(dst, o + 8, b)
|
||||
writef32(dst, o + 12, if a == smax and sd ~= 0 then 1 else depthConv(a, sd, dd))
|
||||
else -- rgb8
|
||||
local o = i * 3
|
||||
writeu8(dst, o, r)
|
||||
writeu8(dst, o + 1, g)
|
||||
writeu8(dst, o + 2, b)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- JPEG-style BT.601 full range
|
||||
function K.rgbaToYuv(src: buffer, w: number, h: number, dst: buffer)
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local uo, vo = w * h, w * h + cw * ch
|
||||
for i = 0, w * h - 1 do
|
||||
local o = i * 4
|
||||
local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2)
|
||||
writeu8(dst, i, clamp(floor(0.299 * r + 0.587 * g + 0.114 * b + 0.5), 0, 255))
|
||||
end
|
||||
for cy = 0, ch - 1 do
|
||||
for cx = 0, cw - 1 do
|
||||
local sr, sg, sb, n = 0, 0, 0, 0
|
||||
for dy = 0, 1 do
|
||||
local y = cy * 2 + dy
|
||||
if y < h then
|
||||
for dx = 0, 1 do
|
||||
local x = cx * 2 + dx
|
||||
if x < w then
|
||||
local o = (y * w + x) * 4
|
||||
sr += readu8(src, o)
|
||||
sg += readu8(src, o + 1)
|
||||
sb += readu8(src, o + 2)
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
sr, sg, sb = sr / n, sg / n, sb / n
|
||||
local i = cy * cw + cx
|
||||
writeu8(dst, uo + i, clamp(floor(128 - 0.168736 * sr - 0.331264 * sg + 0.5 * sb + 0.5), 0, 255))
|
||||
writeu8(dst, vo + i, clamp(floor(128 + 0.5 * sr - 0.418688 * sg - 0.081312 * sb + 0.5), 0, 255))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function K.yuvToRgba(src: buffer, w: number, h: number, dst: buffer)
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local uo, vo = w * h, w * h + cw * ch
|
||||
for y = 0, h - 1 do
|
||||
local crow = (y // 2) * cw
|
||||
for x = 0, w - 1 do
|
||||
local yy = readu8(src, y * w + x)
|
||||
local ci = crow + x // 2
|
||||
local u, v = readu8(src, uo + ci) - 128, readu8(src, vo + ci) - 128
|
||||
local o = (y * w + x) * 4
|
||||
writeu8(dst, o, clamp(floor(yy + 1.402 * v + 0.5), 0, 255))
|
||||
writeu8(dst, o + 1, clamp(floor(yy - 0.344136 * u - 0.714136 * v + 0.5), 0, 255))
|
||||
writeu8(dst, o + 2, clamp(floor(yy + 1.772 * u + 0.5), 0, 255))
|
||||
writeu8(dst, o + 3, 255)
|
||||
end
|
||||
end
|
||||
local _ = ch
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ geometry
|
||||
-- flip(src, dst, w, h, bpp, horizontal)
|
||||
function K.flip(src: buffer, dst: buffer, w: number, h: number, bpp: number, horizontal: boolean)
|
||||
local stride = w * bpp
|
||||
if not horizontal then
|
||||
for y = 0, h - 1 do
|
||||
buffer.copy(dst, (h - 1 - y) * stride, src, y * stride, stride)
|
||||
end
|
||||
return
|
||||
end
|
||||
for y = 0, h - 1 do
|
||||
local row = y * stride
|
||||
for x = 0, w - 1 do
|
||||
buffer.copy(dst, row + (w - 1 - x) * bpp, src, row + x * bpp, bpp)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- rotate90(src, dst, w, h, bpp, turns): counter-clockwise quarter turns 1..3
|
||||
function K.rotate90(src: buffer, dst: buffer, w: number, h: number, bpp: number, turns: number)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local ox, oy, ow
|
||||
if turns == 1 then
|
||||
ox, oy, ow = y, w - 1 - x, h
|
||||
elseif turns == 2 then
|
||||
ox, oy, ow = w - 1 - x, h - 1 - y, w
|
||||
else
|
||||
ox, oy, ow = h - 1 - y, x, h
|
||||
end
|
||||
local so, d = (y * w + x) * bpp, (oy * ow + ox) * bpp
|
||||
if bpp == 4 then
|
||||
buffer.writeu32(dst, d, buffer.readu32(src, so))
|
||||
else
|
||||
buffer.copy(dst, d, src, so, bpp)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ resample
|
||||
local function bilinearF(x: number): number
|
||||
if x < 0 then
|
||||
x = -x
|
||||
end
|
||||
if x < 1 then
|
||||
return 1 - x
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
local function sinc(x: number): number
|
||||
if x == 0 then
|
||||
return 1
|
||||
end
|
||||
x *= math.pi
|
||||
return math.sin(x) / x
|
||||
end
|
||||
|
||||
local function lanczosF(x: number): number
|
||||
if x > -3 and x < 3 then
|
||||
return sinc(x) * sinc(x / 3)
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
local function trunc(x: number): number
|
||||
return if x < 0 then math.ceil(x) else floor(x)
|
||||
end
|
||||
|
||||
-- Pillow precompute_coeffs: per output index its first input index, tap count and weights (normalised)
|
||||
export type Coeffs = { start: { number }, count: { number }, weights: { { number } } }
|
||||
|
||||
function K.coeffs(inSize: number, outSize: number, filter: string): Coeffs
|
||||
local support0 = if filter == "lanczos" then 3 else 1
|
||||
local f = if filter == "lanczos" then lanczosF else bilinearF
|
||||
local scale = inSize / outSize
|
||||
local filterscale = math.max(scale, 1)
|
||||
local support = support0 * filterscale
|
||||
local ss = 1 / filterscale
|
||||
local start, count, weights = table.create(outSize, 0), table.create(outSize, 0), table.create(outSize)
|
||||
for xx = 0, outSize - 1 do
|
||||
local center = (xx + 0.5) * scale
|
||||
local xmin = math.max(0, trunc(center - support + 0.5))
|
||||
local xmax = math.min(inSize, trunc(center + support + 0.5)) - xmin
|
||||
local w = table.create(math.max(xmax, 0), 0)
|
||||
local ww = 0
|
||||
for x = 0, xmax - 1 do
|
||||
local v = f((x + xmin - center + 0.5) * ss)
|
||||
w[x + 1] = v
|
||||
ww += v
|
||||
end
|
||||
if ww ~= 0 then
|
||||
for x = 1, xmax do
|
||||
w[x] /= ww
|
||||
end
|
||||
end
|
||||
start[xx + 1], count[xx + 1], weights[xx + 1] = xmin, math.max(xmax, 0), w
|
||||
end
|
||||
return { start = start, count = count, weights = weights }
|
||||
end
|
||||
|
||||
-- one separable pass. horizontal: src w x h -> dst outN x h; vertical: src w x h -> dst w x outN. ch channels of kind.
|
||||
function K.resamplePass(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, outN: number, c: Coeffs, horizontal: boolean)
|
||||
local start, count, weights = c.start, c.count, c.weights
|
||||
local size = kind
|
||||
local fixed = kind == 1
|
||||
-- 8-bit: Pillow's 22-bit fixed-point coefficients
|
||||
local iw: { { number } } = weights
|
||||
if fixed then
|
||||
iw = table.create(outN)
|
||||
for i = 1, outN do
|
||||
local src0 = weights[i]
|
||||
local t = table.create(#src0, 0)
|
||||
for k = 1, #src0 do
|
||||
local v = src0[k] * 4194304
|
||||
t[k] = if v < 0 then math.ceil(v - 0.5) else floor(v + 0.5)
|
||||
end
|
||||
iw[i] = t
|
||||
end
|
||||
end
|
||||
if horizontal then
|
||||
for y = 0, h - 1 do
|
||||
local row = y * w
|
||||
for xx = 0, outN - 1 do
|
||||
local s0, n, wt = start[xx + 1], count[xx + 1], iw[xx + 1]
|
||||
local o = ((y * outN) + xx) * ch * size
|
||||
for cc = 0, ch - 1 do
|
||||
if fixed then
|
||||
local acc = 2097152
|
||||
for k = 0, n - 1 do
|
||||
acc += readu8(src, (row + s0 + k) * ch + cc) * wt[k + 1]
|
||||
end
|
||||
writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255))
|
||||
else
|
||||
local acc = 0
|
||||
for k = 0, n - 1 do
|
||||
acc += rd(src, ((row + s0 + k) * ch + cc) * size, kind) * wt[k + 1]
|
||||
end
|
||||
wr(dst, o + cc * size, kind, acc)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
for yy = 0, outN - 1 do
|
||||
local s0, n, wt = start[yy + 1], count[yy + 1], iw[yy + 1]
|
||||
for x = 0, w - 1 do
|
||||
local o = (yy * w + x) * ch * size
|
||||
for cc = 0, ch - 1 do
|
||||
if fixed then
|
||||
local acc = 2097152
|
||||
for k = 0, n - 1 do
|
||||
acc += readu8(src, ((s0 + k) * w + x) * ch + cc) * wt[k + 1]
|
||||
end
|
||||
writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255))
|
||||
else
|
||||
local acc = 0
|
||||
for k = 0, n - 1 do
|
||||
acc += rd(src, (((s0 + k) * w + x) * ch + cc) * size, kind) * wt[k + 1]
|
||||
end
|
||||
wr(dst, o + cc * size, kind, acc)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local _ = h
|
||||
end
|
||||
|
||||
-- nearest: dst pixel (x, y) = src pixel (floor((x + 0.5) * w / ow), ...)
|
||||
function K.nearest(src: buffer, w: number, h: number, bpp: number, dst: buffer, ow: number, oh: number)
|
||||
local sx, sy = w / ow, h / oh
|
||||
for y = 0, oh - 1 do
|
||||
local iy = math.min(floor((y + 0.5) * sy), h - 1)
|
||||
for x = 0, ow - 1 do
|
||||
local ix = math.min(floor((x + 0.5) * sx), w - 1)
|
||||
buffer.copy(dst, (y * ow + x) * bpp, src, (iy * w + ix) * bpp, bpp)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- affine(src, w, h, ch, kind, dst, ow, oh, m): dst pixel centres mapped through m = { a, b, c, d, e, f } to src
|
||||
-- coordinates (xin = a x + b y + c), bilinear with clamped neighbours; centres outside the source -> zeros (Pillow)
|
||||
function K.affine(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, ow: number, oh: number, m: { number })
|
||||
local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6]
|
||||
local size = kind
|
||||
for y = 0, oh - 1 do
|
||||
local py = y + 0.5
|
||||
for x = 0, ow - 1 do
|
||||
local px = x + 0.5
|
||||
local xin = a * px + b * py + c - 0.5
|
||||
local yin = d * px + e * py + f - 0.5
|
||||
local o = (y * ow + x) * ch * size
|
||||
local x0 = floor(xin)
|
||||
local y0 = floor(yin)
|
||||
if xin < -0.5 or xin >= w - 0.5 or yin < -0.5 or yin >= h - 0.5 then
|
||||
continue -- dst starts zeroed
|
||||
end
|
||||
local dx, dy = xin - x0, yin - y0
|
||||
local xa, xb = clamp(x0, 0, w - 1), clamp(x0 + 1, 0, w - 1)
|
||||
local ya, yb = clamp(y0, 0, h - 1), clamp(y0 + 1, 0, h - 1)
|
||||
for cc = 0, ch - 1 do
|
||||
local p00 = rd(src, ((ya * w + xa) * ch + cc) * size, kind)
|
||||
local p01 = rd(src, ((ya * w + xb) * ch + cc) * size, kind)
|
||||
local p10 = rd(src, ((yb * w + xa) * ch + cc) * size, kind)
|
||||
local p11 = rd(src, ((yb * w + xb) * ch + cc) * size, kind)
|
||||
local top = p00 + (p01 - p00) * dx
|
||||
local bot = p10 + (p11 - p10) * dx
|
||||
local v = top + (bot - top) * dy
|
||||
if kind == 1 then
|
||||
writeu8(dst, o + cc, clamp(floor(v), 0, 255)) -- Pillow truncates
|
||||
else
|
||||
wr(dst, o + cc * size, kind, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ compositing
|
||||
-- overRgba8(dst, dw, src, sw, sx, sy, dx, dy, w, h, opacity255): Pillow's alpha_composite of src onto dst, in place
|
||||
function K.overRgba8(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local so = ((sy + y) * sw + sx + x) * 4
|
||||
local doff = ((dy + y) * dw + dx + x) * 4
|
||||
local sa = readu8(src, so + 3)
|
||||
if opacity < 255 then
|
||||
sa = (sa * opacity + 127) // 255
|
||||
end
|
||||
if sa == 0 then
|
||||
continue
|
||||
end
|
||||
local da = readu8(dst, doff + 3)
|
||||
local blend = da * (255 - sa)
|
||||
local outa255 = sa * 255 + blend
|
||||
local coef1 = (sa * 255 * 255 * 128) // outa255
|
||||
local coef2 = 255 * 128 - coef1
|
||||
for cc = 0, 2 do
|
||||
local t = readu8(src, so + cc) * coef1 + readu8(dst, doff + cc) * coef2 + 0x80 * 128
|
||||
t = ((t // 256) + t) // 256
|
||||
writeu8(dst, doff + cc, t // 128)
|
||||
end
|
||||
local t = outa255 + 0x80
|
||||
writeu8(dst, doff + 3, ((t // 256) + t) // 256)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- overFloat: straight-alpha "over" for rgba16 (kind 2) / rgbaf32 (kind 4); max = 65535 or 1
|
||||
function K.overFloat(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number, kind: number)
|
||||
local max = if kind == 2 then 65535 else 1
|
||||
local px = 4 * kind
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local so = ((sy + y) * sw + sx + x) * px
|
||||
local doff = ((dy + y) * dw + dx + x) * px
|
||||
local sa = rd(src, so + 3 * kind, kind) / max * opacity
|
||||
if sa <= 0 then
|
||||
continue
|
||||
end
|
||||
local da = rd(dst, doff + 3 * kind, kind) / max
|
||||
local oa = sa + da * (1 - sa)
|
||||
for cc = 0, 2 do
|
||||
local s = rd(src, so + cc * kind, kind)
|
||||
local d = rd(dst, doff + cc * kind, kind)
|
||||
wr(dst, doff + cc * kind, kind, if oa > 0 then (s * sa + d * da * (1 - sa)) / oa else 0)
|
||||
end
|
||||
wr(dst, doff + 3 * kind, kind, oa * max)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- copyRect: rows of a rectangle (bpp bytes per pixel)
|
||||
function K.copyRect(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, bpp: number)
|
||||
for y = 0, h - 1 do
|
||||
buffer.copy(dst, ((dy + y) * dw + dx) * bpp, src, ((sy + y) * sw + sx) * bpp, w * bpp)
|
||||
end
|
||||
end
|
||||
|
||||
-- premultiply / unpremultiply in place: ch channels, alpha last, kind
|
||||
function K.premultiply(b: buffer, n: number, ch: number, kind: number, un: boolean)
|
||||
local max = if kind == 1 then 255 elseif kind == 2 then 65535 else 1
|
||||
local px = ch * kind
|
||||
for i = 0, n - 1 do
|
||||
local o = i * px
|
||||
local a = rd(b, o + (ch - 1) * kind, kind)
|
||||
for cc = 0, ch - 2 do
|
||||
local v = rd(b, o + cc * kind, kind)
|
||||
local r
|
||||
if un then
|
||||
if a <= 0 then
|
||||
r = 0
|
||||
elseif kind == 4 then
|
||||
r = v / a
|
||||
elseif kind == 1 then
|
||||
r = math.min(255, (v * 255) // a) -- Pillow's rgbA2rgba
|
||||
else
|
||||
r = math.min(max, (v * max + a // 2) // a)
|
||||
end
|
||||
else
|
||||
if kind == 4 then
|
||||
r = v * a
|
||||
elseif kind == 1 then
|
||||
local t = v * a + 128 -- Pillow's MULDIV255
|
||||
r = ((t // 256) + t) // 256
|
||||
else
|
||||
r = (v * a + max // 2) // max
|
||||
end
|
||||
end
|
||||
wr(b, o + cc * kind, kind, r)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return K
|
||||
@@ -0,0 +1,689 @@
|
||||
--!strict
|
||||
-- ops/ImageOps: editing on the standard Image (layer 5.5: core, Types and codecs only). Pixel format conversion,
|
||||
-- crop, resize (nearest / bilinear / Lanczos-3, as Pillow), flips, quarter turns and arbitrary rotation (bilinear, as
|
||||
-- Pillow's rotate), alpha compositing (Pillow's alpha_composite for rgba8), premultiplication, pixel access, and
|
||||
-- helpers for animations (Image.frames). New code; the resampling and compositing follow Pillow's C sources.
|
||||
--
|
||||
-- local Ops = require("@formats/ops/ImageOps")
|
||||
-- local small = Ops.resize(img, 320, 240, "lanczos") -- every call returns a new Image | nil, Err (never throws)
|
||||
-- local grey = Ops.convert(img, "gray8")
|
||||
-- Ops.blit(canvas, sprite, 10, 20) -- in place on canvas, straight-alpha "over"
|
||||
-- for i, frame in Ops.coalesce(gif) do ... end -- full-canvas frames of an animation
|
||||
--
|
||||
-- Conventions: angles are degrees counter-clockwise and rotate90 turns are counter-clockwise quarter turns (as
|
||||
-- Pillow). Resizing and rotating filter premultiplied alpha (as Pillow does for RGBA / LA). Grey is Pillow's
|
||||
-- L = (19595 R + 38470 G + 7471 B + 32768) >> 16. 8 <-> 16 bit is * 257 and
|
||||
-- (v * 255 + 32767) // 65535; float <-> integer clamps to 0..1 and rounds (no gamma). alpha8 converts to white with
|
||||
-- that alpha. yuv420p is JPEG-style BT.601 full range (2x2 box chroma); geometric ops on yuv420p go through rgba8.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local K = require("@formats/ops/ImageOps/Kernels")
|
||||
|
||||
local ImageOps = {}
|
||||
|
||||
local MAX_PIXELS = 2 ^ 26
|
||||
|
||||
type Image = Types.Image
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ validation
|
||||
local function arg(msg: string): (nil, Err.Err)
|
||||
return nil, Err.new(Err.ARG, msg)
|
||||
end
|
||||
|
||||
local function isInt(v: any): boolean
|
||||
return type(v) == "number" and v == v and v % 1 == 0 and v > -2 ^ 31 and v < 2 ^ 31
|
||||
end
|
||||
|
||||
local function bytesOf(fmt: string, w: number, h: number): number?
|
||||
if fmt == "yuv420p" then
|
||||
return w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
|
||||
end
|
||||
local bpp = Types.BPP[fmt]
|
||||
return if bpp then w * h * bpp else nil
|
||||
end
|
||||
|
||||
-- check(img) -> true | nil, Err: a well-formed Image (known format, sizes, buffer long enough)
|
||||
local function check(img: any): (boolean?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
|
||||
return arg("expected an Image")
|
||||
end
|
||||
if not isInt(img.width) or not isInt(img.height) or img.width < 1 or img.height < 1 then
|
||||
return arg("bad image size")
|
||||
end
|
||||
local need = bytesOf(img.format, img.width, img.height)
|
||||
if not need then
|
||||
return arg("unknown pixel format " .. tostring(img.format))
|
||||
end
|
||||
if buffer.len(img.pixels) < need then
|
||||
return arg("pixel buffer too small for " .. img.width .. " x " .. img.height .. " " .. img.format)
|
||||
end
|
||||
return true
|
||||
end
|
||||
ImageOps.check = check
|
||||
|
||||
local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?)
|
||||
local max = (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS
|
||||
if w * h > max then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, max))
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- a new Image of the same kind with a copy of meta's plain fields (source, palette...) but no frames
|
||||
local function like(img: Image, w: number, h: number, fmt: string?): Image
|
||||
local out = Types.Image.new(w, h, (fmt or img.format) :: any)
|
||||
for k, v in img.meta do
|
||||
out.meta[k] = v
|
||||
end
|
||||
out.loops = img.loops
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ basics
|
||||
-- new(w, h, format?) -> a zero-filled Image | nil, Err
|
||||
function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?)
|
||||
local fmt = format or "rgba8"
|
||||
if not isInt(w) or not isInt(h) or w < 1 or h < 1 then
|
||||
return arg("bad image size")
|
||||
end
|
||||
if not bytesOf(fmt, 1, 1) then
|
||||
return arg("unknown pixel format " .. tostring(fmt))
|
||||
end
|
||||
local ok, e = limit(w, h, nil)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
return Types.Image.new(w, h, fmt :: any)
|
||||
end
|
||||
|
||||
-- copy(img) -> a deep copy of the pixels (frames are shared)
|
||||
function ImageOps.copy(img: Image): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
local out = like(img, img.width, img.height)
|
||||
buffer.copy(out.pixels, 0, img.pixels, 0, buffer.len(out.pixels))
|
||||
out.frames = img.frames
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ convert
|
||||
-- convert(img, format) -> a new Image in format (a copy when it is already)
|
||||
function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if not bytesOf(format, 1, 1) then
|
||||
return arg("unknown pixel format " .. tostring(format))
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if img.format == format then
|
||||
return ImageOps.copy(img)
|
||||
end
|
||||
local src = img
|
||||
if img.format == "yuv420p" then
|
||||
local rgba = like(img, w, h, "rgba8")
|
||||
K.yuvToRgba(img.pixels, w, h, rgba.pixels)
|
||||
if format == "rgba8" then
|
||||
return rgba
|
||||
end
|
||||
src = rgba
|
||||
end
|
||||
local out = like(img, w, h, format)
|
||||
if format == "yuv420p" then
|
||||
local rgba = src
|
||||
if src.format ~= "rgba8" then
|
||||
rgba = like(img, w, h, "rgba8")
|
||||
K.convert(src.pixels, K.ID[src.format], rgba.pixels, K.ID.rgba8, w * h)
|
||||
end
|
||||
K.rgbaToYuv(rgba.pixels, w, h, out.pixels)
|
||||
return out
|
||||
end
|
||||
K.convert(src.pixels, K.ID[src.format], out.pixels, K.ID[format], w * h)
|
||||
return out
|
||||
end
|
||||
|
||||
-- ops on yuv420p run on rgba8 and convert back
|
||||
local function viaRgba(img: Image, f: (Image) -> (Image?, Err.Err?)): (Image?, Err.Err?)
|
||||
if img.format ~= "yuv420p" then
|
||||
return f(img)
|
||||
end
|
||||
local rgba = ImageOps.convert(img, "rgba8") :: Image
|
||||
local res, e = f(rgba)
|
||||
if not res then
|
||||
return nil, e
|
||||
end
|
||||
return ImageOps.convert(res, "yuv420p")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ geometry
|
||||
local ALPHA_CH = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 }
|
||||
|
||||
-- crop(img, x, y, w, h) -> the rectangle clipped to the image | nil, Err (empty)
|
||||
function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if not (isInt(x) and isInt(y) and isInt(w) and isInt(h)) then
|
||||
return arg("crop: integer x, y, w, h")
|
||||
end
|
||||
local x0, y0 = math.max(0, x), math.max(0, y)
|
||||
local x1, y1 = math.min(img.width, x + w), math.min(img.height, y + h)
|
||||
if x1 <= x0 or y1 <= y0 then
|
||||
return arg("crop: the rectangle is outside the image or empty")
|
||||
end
|
||||
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
|
||||
local bpp = Types.BPP[im.format] :: number
|
||||
local out = like(im, x1 - x0, y1 - y0)
|
||||
K.copyRect(out.pixels, out.width, im.pixels, im.width, x0, y0, 0, 0, out.width, out.height, bpp)
|
||||
return out
|
||||
end)
|
||||
end
|
||||
|
||||
-- flip(img, "h" | "v") -> mirrored horizontally (left-right) or vertically (top-bottom)
|
||||
function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if axis ~= "h" and axis ~= "v" then
|
||||
return arg("flip: axis must be \"h\" or \"v\"")
|
||||
end
|
||||
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
|
||||
local out = like(im, im.width, im.height)
|
||||
K.flip(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, axis == "h")
|
||||
return out
|
||||
end)
|
||||
end
|
||||
|
||||
-- rotate90(img, turns) -> turned by turns counter-clockwise quarter turns (any integer; negative = clockwise)
|
||||
function ImageOps.rotate90(img: Image, turns: number): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if not isInt(turns) then
|
||||
return arg("rotate90: integer turns")
|
||||
end
|
||||
local t = turns % 4
|
||||
if t == 0 then
|
||||
return ImageOps.copy(img)
|
||||
end
|
||||
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
|
||||
local swap = t ~= 2
|
||||
local out = like(im, if swap then im.height else im.width, if swap then im.width else im.height)
|
||||
K.rotate90(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, t)
|
||||
return out
|
||||
end)
|
||||
end
|
||||
|
||||
export type ResizeFilter = "nearest" | "bilinear" | "lanczos"
|
||||
|
||||
-- resize(img, w, h, filter?, opts?) -> w x h (filter default "bilinear"; opts.maxPixels)
|
||||
function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts: any?): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if not isInt(w) or not isInt(h) or w < 1 or h < 1 then
|
||||
return arg("resize: bad target size")
|
||||
end
|
||||
local f = filter or "bilinear"
|
||||
if f ~= "nearest" and f ~= "bilinear" and f ~= "lanczos" then
|
||||
return arg("resize: filter must be nearest, bilinear or lanczos")
|
||||
end
|
||||
local lok, le = limit(w, h, opts)
|
||||
if not lok then
|
||||
return nil, le
|
||||
end
|
||||
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
|
||||
local fmt = im.format
|
||||
local bpp = Types.BPP[fmt] :: number
|
||||
local out = like(im, w, h)
|
||||
if f == "nearest" then
|
||||
K.nearest(im.pixels, im.width, im.height, bpp, out.pixels, w, h)
|
||||
return out
|
||||
end
|
||||
local kind, ch = K.KIND[fmt], K.CHANNELS[fmt]
|
||||
local src, sw, sh = im.pixels, im.width, im.height
|
||||
local alpha = ALPHA_CH[fmt]
|
||||
if alpha then
|
||||
src = buffer.create(buffer.len(im.pixels))
|
||||
buffer.copy(src, 0, im.pixels)
|
||||
K.premultiply(src, sw * sh, alpha, kind, false)
|
||||
end
|
||||
if w ~= sw then
|
||||
local tmp = buffer.create(w * sh * bpp)
|
||||
K.resamplePass(src, sw, sh, ch, kind, tmp, w, K.coeffs(sw, w, f), true)
|
||||
src, sw = tmp, w
|
||||
end
|
||||
if h ~= sh then
|
||||
K.resamplePass(src, sw, sh, ch, kind, out.pixels, h, K.coeffs(sh, h, f), false)
|
||||
elseif src == im.pixels or (w == im.width and alpha) then
|
||||
buffer.copy(out.pixels, 0, im.pixels, 0, w * h * bpp)
|
||||
return out
|
||||
else
|
||||
out.pixels = src
|
||||
end
|
||||
if alpha then
|
||||
K.premultiply(out.pixels, w * h, alpha, kind, true)
|
||||
end
|
||||
return out
|
||||
end)
|
||||
end
|
||||
|
||||
-- rotate(img, degrees, opts?) -> rotated counter-clockwise about the centre with bilinear sampling (as Pillow's
|
||||
-- rotate(angle, BILINEAR, expand)): opts.expand (default true) grows the canvas to hold the whole image; uncovered
|
||||
-- pixels are zero (transparent). opts.maxPixels.
|
||||
function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?, maxPixels: number? }?): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if type(degrees) ~= "number" or degrees ~= degrees or degrees == math.huge or degrees == -math.huge then
|
||||
return arg("rotate: degrees must be a finite number")
|
||||
end
|
||||
local expand = not (opts and opts.expand == false)
|
||||
if degrees % 90 == 0 and (expand or degrees % 180 == 0 or img.width == img.height) then
|
||||
return ImageOps.rotate90(img, (degrees // 90) % 4)
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
local ang = -math.rad(degrees)
|
||||
local function r15(v: number): number
|
||||
return math.floor(v * 1e15 + 0.5) / 1e15
|
||||
end
|
||||
local m = { r15(math.cos(ang)), r15(math.sin(ang)), 0, r15(-math.sin(ang)), r15(math.cos(ang)), 0 }
|
||||
local function tr(x: number, y: number): (number, number)
|
||||
return m[1] * x + m[2] * y + m[3], m[4] * x + m[5] * y + m[6]
|
||||
end
|
||||
local cx, cy = w / 2, h / 2
|
||||
m[3], m[6] = tr(-cx, -cy)
|
||||
m[3] += cx
|
||||
m[6] += cy
|
||||
local nw, nh = w, h
|
||||
if expand then
|
||||
local xs, ys = {}, {}
|
||||
for _, p in { { 0, 0 }, { w, 0 }, { w, h }, { 0, h } } do
|
||||
local x, y = tr(p[1], p[2])
|
||||
table.insert(xs, x)
|
||||
table.insert(ys, y)
|
||||
end
|
||||
nw = math.ceil(math.max(xs[1], xs[2], xs[3], xs[4])) - math.floor(math.min(xs[1], xs[2], xs[3], xs[4]))
|
||||
nh = math.ceil(math.max(ys[1], ys[2], ys[3], ys[4])) - math.floor(math.min(ys[1], ys[2], ys[3], ys[4]))
|
||||
m[3], m[6] = tr(-(nw - w) / 2, -(nh - h) / 2)
|
||||
end
|
||||
local lok, le = limit(nw, nh, opts)
|
||||
if not lok then
|
||||
return nil, le
|
||||
end
|
||||
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
|
||||
local out = like(im, nw, nh)
|
||||
local kind = K.KIND[im.format]
|
||||
local alpha = ALPHA_CH[im.format]
|
||||
local src = im.pixels
|
||||
if alpha then
|
||||
src = buffer.create(buffer.len(im.pixels))
|
||||
buffer.copy(src, 0, im.pixels)
|
||||
K.premultiply(src, w * h, alpha, kind, false)
|
||||
end
|
||||
K.affine(src, w, h, K.CHANNELS[im.format], kind, out.pixels, nw, nh, m)
|
||||
if alpha then
|
||||
K.premultiply(out.pixels, nw * nh, alpha, kind, true)
|
||||
end
|
||||
return out
|
||||
end)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ compositing
|
||||
local RGBA = { rgba8 = true, rgba16 = true, rgbaf32 = true }
|
||||
|
||||
export type BlitOptions = { blend: ("over" | "source")?, opacity: number? }
|
||||
|
||||
-- blit(dst, src, x, y, opts?) -> dst (modified in place) | nil, Err. src is clipped to dst; it is converted to dst's
|
||||
-- format first when they differ. blend "over" (default: Porter-Duff over, straight alpha; Pillow's alpha_composite
|
||||
-- for rgba8) or "source" (copy); opts.opacity 0..1 scales src alpha ("over" only).
|
||||
function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitOptions?): (Image?, Err.Err?)
|
||||
local ok, e = check(dst)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
local ok2, e2 = check(src)
|
||||
if not ok2 then
|
||||
return nil, e2
|
||||
end
|
||||
if not isInt(x) or not isInt(y) then
|
||||
return arg("blit: integer x, y")
|
||||
end
|
||||
local blend = (opts and opts.blend) or "over"
|
||||
if blend ~= "over" and blend ~= "source" then
|
||||
return arg("blit: blend must be \"over\" or \"source\"")
|
||||
end
|
||||
local opacity = (opts and opts.opacity) or 1
|
||||
if type(opacity) ~= "number" or not (opacity >= 0 and opacity <= 1) then
|
||||
return arg("blit: opacity must be 0..1")
|
||||
end
|
||||
-- clip
|
||||
local sx, sy = math.max(0, -x), math.max(0, -y)
|
||||
local dx, dy = math.max(0, x), math.max(0, y)
|
||||
local w = math.min(src.width - sx, dst.width - dx)
|
||||
local h = math.min(src.height - sy, dst.height - dy)
|
||||
if w <= 0 or h <= 0 then
|
||||
return dst
|
||||
end
|
||||
if dst.format == "yuv420p" or (blend == "over" and not RGBA[dst.format]) then
|
||||
-- work on an rgba copy of the region, then write it back in dst's format
|
||||
local region = ImageOps.crop(dst, dx, dy, w, h) :: Image
|
||||
local work = if region.format == "rgba8" then region else ImageOps.convert(region, "rgba8") :: Image
|
||||
ImageOps.blit(work, src, x - dx, y - dy, opts)
|
||||
if dst.format == "yuv420p" then
|
||||
local full = ImageOps.convert(dst, "rgba8") :: Image
|
||||
ImageOps.blit(full, work, dx, dy, { blend = "source" })
|
||||
local back = ImageOps.convert(full, "yuv420p") :: Image
|
||||
buffer.copy(dst.pixels, 0, back.pixels, 0, buffer.len(back.pixels))
|
||||
else
|
||||
local back = ImageOps.convert(work, dst.format) :: Image
|
||||
K.copyRect(dst.pixels, dst.width, back.pixels, back.width, 0, 0, dx, dy, w, h, Types.BPP[dst.format] :: number)
|
||||
end
|
||||
return dst
|
||||
end
|
||||
local s = src
|
||||
if src.format ~= dst.format then
|
||||
s = ImageOps.convert(src, dst.format) :: Image
|
||||
end
|
||||
if blend == "source" then
|
||||
K.copyRect(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, Types.BPP[dst.format] :: number)
|
||||
elseif dst.format == "rgba8" then
|
||||
K.overRgba8(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, math.floor(opacity * 255 + 0.5))
|
||||
else
|
||||
K.overFloat(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, opacity, K.KIND[dst.format])
|
||||
end
|
||||
return dst
|
||||
end
|
||||
|
||||
-- composite(dst, src, x?, y?, opts?) -> a new Image: a copy of dst with src blitted onto it
|
||||
function ImageOps.composite(dst: Image, src: Image, x: number?, y: number?, opts: BlitOptions?): (Image?, Err.Err?)
|
||||
local out, e = ImageOps.copy(dst)
|
||||
if not out then
|
||||
return nil, e
|
||||
end
|
||||
out.frames = nil
|
||||
return ImageOps.blit(out, src, x or 0, y or 0, opts)
|
||||
end
|
||||
|
||||
local function premul(img: Image, un: boolean): (Image?, Err.Err?)
|
||||
local out, e = ImageOps.copy(img)
|
||||
if not out then
|
||||
return nil, e
|
||||
end
|
||||
out.frames = nil
|
||||
local ch = ALPHA_CH[img.format]
|
||||
if ch then
|
||||
K.premultiply(out.pixels, img.width * img.height, ch, K.KIND[img.format], un)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- premultiply(img) / unpremultiply(img) -> a new Image (formats without alpha are copied unchanged)
|
||||
function ImageOps.premultiply(img: Image): (Image?, Err.Err?)
|
||||
return premul(img, false)
|
||||
end
|
||||
function ImageOps.unpremultiply(img: Image): (Image?, Err.Err?)
|
||||
return premul(img, true)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ pixels
|
||||
local MAXV = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 }
|
||||
|
||||
-- getPixel(img, x, y) -> r, g, b, a in the format's scale (0..255, 0..65535 or float); grey gives r = g = b;
|
||||
-- alpha8 gives white; yuv420p converts to RGB. nil, Err out of range.
|
||||
function ImageOps.getPixel(img: Image, x: number, y: number): (any, any, number?, number?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then
|
||||
return arg("getPixel: coordinates out of range")
|
||||
end
|
||||
local b, f, i = img.pixels, img.format, y * img.width + x
|
||||
local ru8, ru16, rf = buffer.readu8, buffer.readu16, buffer.readf32
|
||||
if f == "rgba8" then
|
||||
return ru8(b, i * 4), ru8(b, i * 4 + 1), ru8(b, i * 4 + 2), ru8(b, i * 4 + 3)
|
||||
elseif f == "rgba16" then
|
||||
return ru16(b, i * 8), ru16(b, i * 8 + 2), ru16(b, i * 8 + 4), ru16(b, i * 8 + 6)
|
||||
elseif f == "rgbaf32" then
|
||||
return rf(b, i * 16), rf(b, i * 16 + 4), rf(b, i * 16 + 8), rf(b, i * 16 + 12)
|
||||
elseif f == "rgb8" then
|
||||
return ru8(b, i * 3), ru8(b, i * 3 + 1), ru8(b, i * 3 + 2), 255
|
||||
elseif f == "gray8" then
|
||||
local v = ru8(b, i)
|
||||
return v, v, v, 255
|
||||
elseif f == "gray16" then
|
||||
local v = ru16(b, i * 2)
|
||||
return v, v, v, 65535
|
||||
elseif f == "graya8" then
|
||||
local v = ru8(b, i * 2)
|
||||
return v, v, v, ru8(b, i * 2 + 1)
|
||||
elseif f == "alpha8" then
|
||||
return 255, 255, 255, ru8(b, i)
|
||||
end
|
||||
local one = ImageOps.crop(img, x - x % 2, y - y % 2, 2, 2) :: Image
|
||||
local rgba = ImageOps.convert(one, "rgba8") :: Image
|
||||
local j = ((y % 2) * rgba.width + (x % 2)) * 4
|
||||
if j + 4 > buffer.len(rgba.pixels) then
|
||||
j = 0
|
||||
end
|
||||
return ru8(rgba.pixels, j), ru8(rgba.pixels, j + 1), ru8(rgba.pixels, j + 2), 255
|
||||
end
|
||||
|
||||
-- setPixel(img, x, y, r, g, b, a?) -> true (in place) | nil, Err. Values in the format's scale (clamped and
|
||||
-- rounded for integer formats); grey formats take Pillow's luma of r, g, b; a defaults to opaque. Not for yuv420p.
|
||||
function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: number, b: number, a: number?): (boolean?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then
|
||||
return arg("setPixel: coordinates out of range")
|
||||
end
|
||||
if type(r) ~= "number" or type(g) ~= "number" or type(b) ~= "number" or (a ~= nil and type(a) ~= "number") then
|
||||
return arg("setPixel: numeric channels")
|
||||
end
|
||||
local f = img.format
|
||||
if f == "yuv420p" then
|
||||
return arg("setPixel: not supported on yuv420p (convert to rgba8 first)")
|
||||
end
|
||||
local max = MAXV[f]
|
||||
local al = if a == nil then max else a
|
||||
local function q(v: number): number
|
||||
if max == 1 then
|
||||
return v
|
||||
end
|
||||
if v ~= v then
|
||||
return 0
|
||||
end
|
||||
return math.clamp(math.floor(v + 0.5), 0, max)
|
||||
end
|
||||
local px, i = img.pixels, y * img.width + x
|
||||
local wu8, wu16, wf = buffer.writeu8, buffer.writeu16, buffer.writef32
|
||||
local function grey(): number
|
||||
if max == 1 then
|
||||
return (r * 19595 + g * 38470 + b * 7471) / 65536
|
||||
end
|
||||
return (q(r) * 19595 + q(g) * 38470 + q(b) * 7471 + 32768) // 65536
|
||||
end
|
||||
if f == "rgba8" then
|
||||
wu8(px, i * 4, q(r))
|
||||
wu8(px, i * 4 + 1, q(g))
|
||||
wu8(px, i * 4 + 2, q(b))
|
||||
wu8(px, i * 4 + 3, q(al))
|
||||
elseif f == "rgba16" then
|
||||
wu16(px, i * 8, q(r))
|
||||
wu16(px, i * 8 + 2, q(g))
|
||||
wu16(px, i * 8 + 4, q(b))
|
||||
wu16(px, i * 8 + 6, q(al))
|
||||
elseif f == "rgbaf32" then
|
||||
wf(px, i * 16, r)
|
||||
wf(px, i * 16 + 4, g)
|
||||
wf(px, i * 16 + 8, b)
|
||||
wf(px, i * 16 + 12, al)
|
||||
elseif f == "rgb8" then
|
||||
wu8(px, i * 3, q(r))
|
||||
wu8(px, i * 3 + 1, q(g))
|
||||
wu8(px, i * 3 + 2, q(b))
|
||||
elseif f == "gray8" then
|
||||
wu8(px, i, grey())
|
||||
elseif f == "gray16" then
|
||||
wu16(px, i * 2, grey())
|
||||
elseif f == "graya8" then
|
||||
wu8(px, i * 2, grey())
|
||||
wu8(px, i * 2 + 1, q(al))
|
||||
else
|
||||
wu8(px, i, q(al))
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- fill(img, r, g, b, a?) -> img (in place) with every pixel set (values as setPixel)
|
||||
function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if img.format == "yuv420p" then
|
||||
return arg("fill: not supported on yuv420p")
|
||||
end
|
||||
local sok, se = ImageOps.setPixel(img, 0, 0, r, g, b, a)
|
||||
if not sok then
|
||||
return nil, se
|
||||
end
|
||||
local bpp = Types.BPP[img.format] :: number
|
||||
local n = img.width * img.height * bpp
|
||||
local filled = bpp
|
||||
while filled < n do
|
||||
local c = math.min(filled, n - filled)
|
||||
buffer.copy(img.pixels, filled, img.pixels, 0, c)
|
||||
filled += c
|
||||
end
|
||||
return img
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ animation
|
||||
-- frameCount(img) -> the number of frames (1 for a still image)
|
||||
function ImageOps.frameCount(img: Image): number
|
||||
if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then
|
||||
return #img.frames
|
||||
end
|
||||
return 1
|
||||
end
|
||||
|
||||
-- durations(img) -> { seconds } per frame ({ 0 } for a still image)
|
||||
function ImageOps.durations(img: Image): { number }
|
||||
local out = {}
|
||||
if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then
|
||||
for i, f in img.frames do
|
||||
out[i] = if type(f.delay) == "number" then f.delay else 0
|
||||
end
|
||||
return out
|
||||
end
|
||||
return { 0 }
|
||||
end
|
||||
|
||||
-- coalesce(img) -> { Image } | nil, Err: every frame composited onto a width x height canvas (rgba8, or rgba16 /
|
||||
-- rgbaf32 when the image is), honouring each frame's x, y, blend ("over" / "source") and the previous frame's
|
||||
-- dispose ("none" keeps the canvas, "background" clears the frame's rectangle to transparent, "previous" restores
|
||||
-- the canvas from before the frame). A still image gives { img }.
|
||||
function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
local frames = img.frames
|
||||
if type(frames) ~= "table" or #frames == 0 then
|
||||
return { img }
|
||||
end
|
||||
local fmt = if RGBA[img.format] then img.format else "rgba8"
|
||||
local canvas = Types.Image.new(img.width, img.height, fmt :: any)
|
||||
local bpp = Types.BPP[fmt] :: number
|
||||
local out = {}
|
||||
for i, f in frames do
|
||||
if type(f) ~= "table" then
|
||||
return arg("coalesce: frame " .. i .. " is not a Frame")
|
||||
end
|
||||
local fi = f.image
|
||||
local fok, fe = check(fi)
|
||||
if not fok then
|
||||
return nil, Err.new(Err.ARG, "coalesce: frame " .. i .. ": " .. (fe :: Err.Err).message)
|
||||
end
|
||||
local fx, fy = if isInt(f.x) then f.x else 0, if isInt(f.y) then f.y else 0
|
||||
local saved: buffer? = nil
|
||||
if f.dispose == "previous" then
|
||||
local sb = buffer.create(buffer.len(canvas.pixels))
|
||||
buffer.copy(sb, 0, canvas.pixels)
|
||||
saved = sb
|
||||
end
|
||||
local bok, be = ImageOps.blit(canvas, fi, fx, fy, { blend = if f.blend == "source" then "source" else "over" })
|
||||
if not bok then
|
||||
return nil, be
|
||||
end
|
||||
local snap = Types.Image.new(img.width, img.height, fmt :: any)
|
||||
buffer.copy(snap.pixels, 0, canvas.pixels)
|
||||
for k, v in img.meta do
|
||||
snap.meta[k] = v
|
||||
end
|
||||
snap.meta.delay = f.delay
|
||||
out[i] = snap
|
||||
if f.dispose == "background" then
|
||||
local x0, y0 = math.max(0, fx), math.max(0, fy)
|
||||
local x1, y1 = math.min(img.width, fx + fi.width), math.min(img.height, fy + fi.height)
|
||||
for y = y0, y1 - 1 do
|
||||
if x1 > x0 then
|
||||
buffer.fill(canvas.pixels, (y * img.width + x0) * bpp, 0, (x1 - x0) * bpp)
|
||||
end
|
||||
end
|
||||
elseif saved then
|
||||
canvas.pixels = saved
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- fromFrames(images, delays?) -> an animated Image: img.frames = the images as full-canvas frames (x = y = 0,
|
||||
-- dispose "none", blend "source"), img.pixels = a copy of frame 1. delays: a number (every frame) or { seconds }
|
||||
-- (default 0.1). All images need the same size and format.
|
||||
function ImageOps.fromFrames(images: { Image }, delays: (number | { number })?): (Image?, Err.Err?)
|
||||
if type(images) ~= "table" or #images == 0 then
|
||||
return arg("fromFrames: a non-empty list of Images")
|
||||
end
|
||||
local first = images[1]
|
||||
local ok, e = check(first)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
local frames = {}
|
||||
for i, im in images do
|
||||
local iok, ie = check(im)
|
||||
if not iok then
|
||||
return nil, ie
|
||||
end
|
||||
if im.width ~= first.width or im.height ~= first.height or im.format ~= first.format then
|
||||
return arg("fromFrames: frame " .. i .. " differs in size or format from frame 1")
|
||||
end
|
||||
local d = 0.1
|
||||
if type(delays) == "number" then
|
||||
d = delays
|
||||
elseif type(delays) == "table" and type(delays[i]) == "number" then
|
||||
d = delays[i]
|
||||
end
|
||||
frames[i] = { image = im, delay = d, x = 0, y = 0, dispose = "none", blend = "source" }
|
||||
end
|
||||
local out = like(first, first.width, first.height)
|
||||
buffer.copy(out.pixels, 0, first.pixels, 0, buffer.len(out.pixels))
|
||||
out.frames = frames :: any
|
||||
out.loops = 0
|
||||
return out
|
||||
end
|
||||
|
||||
return ImageOps
|
||||
Reference in new issue
Block a user