ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4

C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.
This commit is contained in:
4DBug committed 2026-10-31 12:25:03 -05:00
1 parent 763f4a7c04
commit 51b08575c4
283 files changed
+1877 -1660

No files matched your search

+371
View File
@@ -0,0 +1,371 @@
--!strict
--!native
-- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
-- blend modes of the W3C Compositing and Blending Level 1 spec (the Photoshop / Aseprite set), opacity, a grey layer
-- mask, clipping (source-atop: the backdrop keeps its alpha) and dissolve. Shared by ops/LayerOps (flatten) and the
-- layered formats that must write a composite (layered/psd). Never throws: rectangles are clipped to both buffers.
--
-- Blend.composite(dst, dw, dh, src, sw, sh, x, y, opacity, "multiply", { clip = false, mask = m })
-- Blend.MODES.multiply -> true
--
-- Mode names: normal dissolve darken multiply colorBurn linearBurn darkerColor lighten screen colorDodge linearDodge
-- (= add) lighterColor overlay softLight hardLight vividLight linearLight pinLight hardMix difference exclusion
-- subtract divide hue saturation color luminosity. Unknown names composite as normal.
local Blend = {}
local readu8, writeu8, readu32, writeu32, blen = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32, buffer.len
local min, max, floor, sqrt, abs = math.min, math.max, math.floor, math.sqrt, math.abs
local IDS: { [string]: number } = {
normal = 0,
dissolve = 1,
darken = 2,
multiply = 3,
colorBurn = 4,
linearBurn = 5,
darkerColor = 6,
lighten = 7,
screen = 8,
colorDodge = 9,
linearDodge = 10,
add = 10,
lighterColor = 11,
overlay = 12,
softLight = 13,
hardLight = 14,
vividLight = 15,
linearLight = 16,
pinLight = 17,
hardMix = 18,
difference = 19,
exclusion = 20,
subtract = 21,
divide = 22,
hue = 23,
saturation = 24,
color = 25,
luminosity = 26,
}
local MODES: { [string]: boolean } = {}
for k in IDS do
MODES[k] = true
end
Blend.MODES = table.freeze(MODES)
local function burn(cb: number, cs: number): number
if cb >= 1 then
return 1
elseif cs <= 0 then
return 0
end
return 1 - min(1, (1 - cb) / cs)
end
local function dodge(cb: number, cs: number): number
if cb <= 0 then
return 0
elseif cs >= 1 then
return 1
end
return min(1, cb / (1 - cs))
end
-- B(cb, cs) of a separable mode
local function sep(m: number, cb: number, cs: number): number
if m == 3 then
return cb * cs
elseif m == 8 then
return cb + cs - cb * cs
elseif m == 2 then
return min(cb, cs)
elseif m == 7 then
return max(cb, cs)
elseif m == 12 then -- overlay = hardLight(cs, cb)
if cb <= 0.5 then
return 2 * cb * cs
end
local c = 2 * cb - 1
return cs + c - cs * c
elseif m == 14 then
if cs <= 0.5 then
return 2 * cb * cs
end
local c = 2 * cs - 1
return cb + c - cb * c
elseif m == 13 then
if cs <= 0.5 then
return cb - (1 - 2 * cs) * cb * (1 - cb)
end
local d = if cb <= 0.25 then ((16 * cb - 12) * cb + 4) * cb else sqrt(cb)
return cb + (2 * cs - 1) * (d - cb)
elseif m == 9 then
return dodge(cb, cs)
elseif m == 4 then
return burn(cb, cs)
elseif m == 5 then
return max(0, cb + cs - 1)
elseif m == 10 then
return min(1, cb + cs)
elseif m == 15 then
if cs <= 0.5 then
return burn(cb, 2 * cs)
end
return dodge(cb, 2 * cs - 1)
elseif m == 16 then
return max(0, min(1, cb + 2 * cs - 1))
elseif m == 17 then
if cs <= 0.5 then
return min(cb, 2 * cs)
end
return max(cb, 2 * cs - 1)
elseif m == 18 then
return if cb + cs >= 1 then 1 else 0
elseif m == 19 then
return abs(cb - cs)
elseif m == 20 then
return cb + cs - 2 * cb * cs
elseif m == 21 then
return max(0, cb - cs)
elseif m == 22 then
if cs <= 0 then
return if cb <= 0 then 0 else 1
end
return min(1, cb / cs)
end
return cs
end
-- non-separable helpers (W3C): lum, clip, setLum, sat, setSat
local function lum(r: number, g: number, b: number): number
return 0.3 * r + 0.59 * g + 0.11 * b
end
local function clipColor(r: number, g: number, b: number): (number, number, number)
local l = lum(r, g, b)
local n = min(r, g, b)
local x = max(r, g, b)
if n < 0 and l - n > 1e-12 then
r, g, b = l + (r - l) * l / (l - n), l + (g - l) * l / (l - n), l + (b - l) * l / (l - n)
end
if x > 1 and x - l > 1e-12 then
r, g, b = l + (r - l) * (1 - l) / (x - l), l + (g - l) * (1 - l) / (x - l), l + (b - l) * (1 - l) / (x - l)
end
return r, g, b
end
local function setLum(r: number, g: number, b: number, l: number): (number, number, number)
local d = l - lum(r, g, b)
return clipColor(r + d, g + d, b + d)
end
local function setSat(r: number, g: number, b: number, s: number): (number, number, number)
local mx = max(r, g, b)
local mn = min(r, g, b)
if mx - mn <= 1e-12 then
return 0, 0, 0
end
local k = s / (mx - mn)
return (r - mn) * k, (g - mn) * k, (b - mn) * k
end
-- composite(dst, dw, dh, src, sw, sh, x, y, opacity, mode, opts?): blends the sw x sh rgba8 src onto the dw x dh rgba8
-- dst with its top-left at (x, y). opacity 0..1. opts.clip: keep the backdrop's alpha (clipping masks). opts.mask:
-- { pixels: buffer (1 byte per pixel), width, height, x, y, default: 0..255 } in dst coordinates (outside it: default).
local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: number, sh: number, x: number, y: number, opacity: number, mode: string?, opts: { clip: boolean?, mask: any? }?)
x, y = floor(x), floor(y)
if opacity <= 0 or dw <= 0 or dh <= 0 or sw <= 0 or sh <= 0 then
return
end
if blen(dst) < dw * dh * 4 or blen(src) < sw * sh * 4 then
return
end
local op = min(1, opacity)
local m = IDS[mode or "normal"] or 0
local clip = opts ~= nil and opts.clip == true
local mask = if opts ~= nil then opts.mask else nil
local mbuf: buffer? = nil
local mx0, my0, mw, mh, mdef = 0, 0, 0, 0, 1
if type(mask) == "table" and type(mask.pixels) == "buffer" and type(mask.width) == "number" and type(mask.height) == "number" then
mw, mh = floor(mask.width), floor(mask.height) :: number
if mw > 0 and mh > 0 and blen(mask.pixels) >= mw * mh then
mbuf = mask.pixels
end
mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) :: number
mdef = (tonumber(mask.default) or 255) / 255
elseif type(mask) == "table" then
mdef = (tonumber(mask.default) or 255) / 255
end
local x0, y0 = max(0, x), max(0, y)
local x1, y1 = min(dw, x + sw), min(dh, y + sh)
for py = y0, y1 - 1 do
local so = ((py - y) * sw + (x0 - x)) * 4
local do_ = (py * dw + x0) * 4
for px = x0, x1 - 1 do
local sa8 = readu8(src, so + 3)
if sa8 ~= 0 then
local sa = sa8 / 255 * op
if mbuf ~= nil or mdef ~= 1 then
local mv = mdef
local mxx, myy = px - mx0, py - my0
if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then
mv = readu8(mbuf, myy * mw + mxx) / 255
end
sa *= mv
end
if m == 1 then -- dissolve: a hash threshold per pixel, full alpha where it shows
local h = (px * 73856093 + py * 19349663) % 65536 / 65536
sa = if h < sa then 1 else 0
end
local ba8 = readu8(dst, do_ + 3)
if sa > 0 and not (clip and ba8 == 0) then
local sr, sg, sb = readu8(src, so) / 255, readu8(src, so + 1) / 255, readu8(src, so + 2) / 255
if ba8 == 0 then
-- empty backdrop: the source as it is (alpha scaled)
writeu32(dst, do_, readu32(src, so))
writeu8(dst, do_ + 3, floor(sa * 255 + 0.5))
else
local ba = ba8 / 255
local br, bg, bb = readu8(dst, do_) / 255, readu8(dst, do_ + 1) / 255, readu8(dst, do_ + 2) / 255
local mr, mg, mb = sr, sg, sb
if m >= 2 and m ~= 6 and m ~= 11 and m < 23 then
mr, mg, mb = sep(m, br, sr), sep(m, bg, sg), sep(m, bb, sb) :: number
elseif m == 6 then
if lum(sr, sg, sb) >= lum(br, bg, bb) then
mr, mg, mb = br, bg, bb
end
elseif m == 11 then
if lum(sr, sg, sb) < lum(br, bg, bb) then
mr, mg, mb = br, bg, bb
end
elseif m == 23 then
local s = max(br, bg, bb) - min(br, bg, bb)
local r1, g1, b1 = setSat(sr, sg, sb, s)
mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb))
elseif m == 24 then
local s = max(sr, sg, sb) - min(sr, sg, sb)
local r1, g1, b1 = setSat(br, bg, bb, s)
mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb))
elseif m == 25 then
mr, mg, mb = setLum(sr, sg, sb, lum(br, bg, bb))
elseif m == 26 then
mr, mg, mb = setLum(br, bg, bb, lum(sr, sg, sb))
end
local orr, og, ob, oa
if clip then
-- source-atop: the backdrop's alpha; the mixed colour where the backdrop is opaque
orr = sa * mr + (1 - sa) * br
og = sa * mg + (1 - sa) * bg
ob = sa * mb + (1 - sa) * bb
oa = ba
else
oa = sa + ba * (1 - sa)
local ws, wm, wb = sa * (1 - ba), sa * ba, (1 - sa) * ba
orr = (ws * sr + wm * mr + wb * br) / oa
og = (ws * sg + wm * mg + wb * bg) / oa
ob = (ws * sb + wm * mb + wb * bb) / oa
end
writeu8(dst, do_, floor(max(0, min(1, orr)) * 255 + 0.5))
writeu8(dst, do_ + 1, floor(max(0, min(1, og)) * 255 + 0.5))
writeu8(dst, do_ + 2, floor(max(0, min(1, ob)) * 255 + 0.5))
writeu8(dst, do_ + 3, floor(max(0, min(1, oa)) * 255 + 0.5))
end
end
end
so += 4
do_ += 4
end
end
end
-- lerp(dst, from, t, n): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity)
local function lerp(dst: buffer, from: buffer, t: number, n: number)
if blen(dst) < n * 4 or blen(from) < n * 4 then
return
end
for i = 0, n * 4 - 1 do
local a = readu8(from, i)
writeu8(dst, i, floor(a + (readu8(dst, i) - a) * t + 0.5))
end
end
Blend.composite = composite
Blend.lerp = lerp
-- ------------------------------------------------------------------------------------------------ layer trees
local function isImage(v: any): boolean
return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and buffer.len(v.pixels) >= v.width * v.height * 4
end
local function maskOf(l: any): any
local m = l.mask
if type(m) ~= "table" or m.disabled or type(m.image) ~= "table" or type(m.image.pixels) ~= "buffer" then
return nil
end
local img = m.image
local px = img.pixels
if img.format == "rgba8" then -- use the red channel
local n = img.width * img.height
local g = buffer.create(n)
for i = 0, n - 1 do
buffer.writeu8(g, i, buffer.readu8(px, i * 4))
end
px = g
end
return { pixels = px, width = img.width, height = img.height, x = m.x or 0, y = m.y or 0, default = m.default or 255 }
end
local function compose(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean)
local i = 1
while i <= #layers do
local l = layers[i]
i += 1
if type(l) ~= "table" or (l.visible == false and not hidden) then
-- clipped layers above a hidden base are hidden too
while i <= #layers and type(layers[i]) == "table" and layers[i].clip do
i += 1
end
continue
end
local opacity = (tonumber(l.opacity) or 1) * (tonumber(l.fillOpacity) or 1)
local mode = if type(l.blend) == "string" then l.blend else "normal"
-- the layer's own pixels, as an isolated w x h buffer
local src: buffer? = nil
if type(l.children) == "table" then
if mode == "passThrough" then
local before = buffer.create(w * h * 4)
buffer.copy(before, 0, canvas, 0, w * h * 4)
compose(l.children, canvas, w, h, hidden)
if opacity < 1 then
lerp(canvas, before, opacity, w * h)
end
continue
end
src = buffer.create(w * h * 4)
compose(l.children, src :: buffer, w, h, hidden)
elseif isImage(l.image) then
if l.image.width > 0 and l.image.height > 0 then
local b = buffer.create(w * h * 4)
composite(b, w, h, l.image.pixels, l.image.width, l.image.height, tonumber(l.x) or 0, tonumber(l.y) or 0, 1, "normal")
src = b
end
end
-- clipping layers above this one: composited onto it with their alpha limited to it
while i <= #layers and type(layers[i]) == "table" and layers[i].clip do
local c = layers[i]
i += 1
if src and (c.visible ~= false or hidden) and isImage(c.image) then
composite(src :: buffer, w, h, c.image.pixels, c.image.width, c.image.height, tonumber(c.x) or 0, tonumber(c.y) or 0, (tonumber(c.opacity) or 1) * (tonumber(c.fillOpacity) or 1), c.blend, { clip = true, mask = maskOf(c) })
end
end
if src then
composite(canvas, w, h, src :: buffer, w, h, 0, 0, opacity, mode, { mask = maskOf(l) })
end
end
end
-- flatten(layers, canvas, w, h, hidden): composites a Types.Layer tree (bottom to top) onto the w x h rgba8 canvas:
-- blend modes, opacity x fillOpacity, groups (isolated, or "passThrough": blended straight onto the canvas, the group
-- opacity then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks.
-- hidden = true includes invisible layers.
function Blend.flatten(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean)
if blen(canvas) >= w * h * 4 then
compose(layers, canvas, w, h, hidden)
end
end
return Blend
+392
View File
@@ -0,0 +1,392 @@
--!strict
--!native
--!optimize 2
-- codecs/image/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) :: number
d4, d5, d6, d7 = readu8(src, p + 4), readu8(src, p + 5), readu8(src, p + 6), readu8(src, p + 7) :: number
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
+414
View File
@@ -0,0 +1,414 @@
--!strict
--!native
--!optimize 2
-- codecs/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
+229
View File
@@ -0,0 +1,229 @@
--!strict
--!native
--!optimize 2
-- codecs/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
+762
View File
@@ -0,0 +1,762 @@
--!strict
-- codecs/image/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan /
-- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended:
-- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM
-- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a
-- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows
-- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/image/Jpeg/Decode for the video formats.
local Scan = require("@formats/codecs/image/Jpeg/Scan")
local Arith = require("@formats/codecs/image/Jpeg/Arith")
local Color = require("@formats/codecs/image/Jpeg/Color")
local Tables = require("@formats/codecs/image/Jpeg/Tables")
local Yuv = require("@formats/codecs/image/Jpeg/Yuv")
local Dct = require("@formats/codecs/image/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: { Comp } = {}
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) :: number
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) :: number
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,
}, nil, nil
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,
avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back)
endPos: number, -- the byte after the EOI marker (or the end of the data)
}
-- 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: number = (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,
avi1 = nil,
endPos = n,
}
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
st.endPos = pos
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) }
elseif e - p >= 5 and buffer.readstring(b, p, 4) == "AVI1" then
st.avi1 = readu8(b, p + 4)
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, nil, nil
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: { Comp } = {}
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, nil, nil
end
if scans == 0 then
return nil, "truncated", "no image data"
end
return st, nil, nil
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
-- outputYuv(st) -> width, height, yuv420p pixels, sampling | nil when the frame has no direct yuv420p form (the
-- caller falls back to output). The IDCT output planes as they are, cropped to the image, without colour conversion
-- or upsampling: 8-bit YCbCr whose chroma is sampled at half the luma rate both ways ("420", 2x2 / 1x1); half
-- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma
-- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: each 2 x 2 chroma block averaged, rounding to nearest); grey ("gray":
-- chroma 128). Full scale only (opts.scale = 1).
-- one IDCT plane at a time is live (each is cropped into the output before the next component): frame-sized planes
-- (up to 4 MB) are kept between calls, so a stream of video frames does not allocate them per frame
local scratch: buffer? = nil
local function scratchPlane(n: number): buffer
local sc = scratch
if sc and buffer.len(sc) >= n then
return sc
end
local b = buffer.create(n)
if n <= 4 * 1024 * 1024 then
scratch = b
end
return b
end
function Decode.outputYuv(st: State): (number?, number?, buffer?, string?)
local f: Frame = st.frame
if st.scale ~= 1 or f.precision ~= 8 then
return nil, nil, nil, nil
end
local comps = f.comps
local space = colorSpaceOf(f, st.adobe, st.jfif)
local mode = nil
if space == "gray" then
mode = "gray"
elseif space == "ycbcr" then
-- the ratios of luma to chroma sampling (ffmpeg writes 4:2:2 as 2x2 / 1x2 and 4:4:4 as 1x2 everywhere)
local l, cb, cr = comps[1], comps[2], comps[3]
if l.h == f.hmax and l.v == f.vmax and cb.h == cr.h and cb.v == cr.v then
local rh, rv = f.hmax // cb.h, f.vmax // cb.v
if rh * cb.h ~= f.hmax or rv * cb.v ~= f.vmax then
mode = nil
elseif rh == 2 and rv == 2 then
mode = "420"
elseif rh == 2 and rv == 1 then
mode = "422"
elseif rh == 1 and rv == 1 then
mode = "444"
end
end
end
if not mode then
return nil, nil, nil, nil
end
for _, c in comps do
if c.coef and not c.quant then
return nil, nil, nil, nil -- output() reports the missing table
end
end
local w, h = f.width, f.height
local cw, ch = (w + 1) // 2, (h + 1) // 2
local out = buffer.create(w * h + 2 * cw * ch)
local zeroQ: buffer? = nil
for i, c in comps do
local stride, rows = c.bpl * 8, c.bpc * 8
local plane = scratchPlane(stride * rows * 2)
local coef = c.coef or buffer.create(c.bpl * c.bpc * 128)
local q = c.quant
if not q then
zeroQ = zeroQ or buffer.create(128) -- the component never appeared in a scan: mid grey
q = zeroQ
end
Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, 8, plane, 2, 128, 255)
if i == 1 then
Yuv.crop(plane, stride, w, h, out, 0)
elseif mode == "420" then
Yuv.crop(plane, stride, cw, ch, out, w * h + (i - 2) * cw * ch)
elseif mode == "422" then
Yuv.rows(plane, stride, cw, h, out, w * h + (i - 2) * cw * ch)
else
Yuv.box(plane, stride, w, h, out, w * h + (i - 2) * cw * ch)
end
c.coef = nil
end
if mode == "gray" then
buffer.fill(out, w * h, 128, 2 * cw * ch)
end
return w, h, out, mode
end
return Decode
+899
View File
@@ -0,0 +1,899 @@
--!strict
--!native
--!optimize 2
-- codecs/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, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG
-- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/image/Jpeg/Encode. 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/image/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/image/Dct")
local Tables = require("@formats/codecs/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 = table.create(1000, 0) :: { number }
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), or bpp 0:
-- yuv420p (w * h luma, then ceil(w / 2) * ceil(h / 2) Cb and Cr; opts.sampling must be "420" unless opts.gray). The
-- caller validated sizes (1..65535), the buffer length 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 yuv = bpp == 0
local Y, Cb, Cr
if yuv then
local n, cn = w * h, ((w + 1) // 2) * ((h + 1) // 2)
Y = px
if not o.gray then
Cb, Cr = buffer.create(cn), buffer.create(cn)
buffer.copy(Cb :: buffer, 0, px, n, cn)
buffer.copy(Cr :: buffer, 0, px, n + cn, cn)
end
else
Y, Cb, Cr = planes(px, w, h, bpp, o.gray)
end
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 yuv and i > 1 then
pw, ph = (w + 1) // 2, (h + 1) // 2 -- already 4:2:0: fdctQuantize repeats the edges as jcsample.c does
elseif 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: { Comp } = {}
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
+456
View File
@@ -0,0 +1,456 @@
--!strict
--!native
--!optimize 2
-- codecs/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
+77
View File
@@ -0,0 +1,77 @@
--!strict
-- codecs/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
+76
View File
@@ -0,0 +1,76 @@
--!strict
--!native
--!optimize 2
-- codecs/image/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16
-- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4
-- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG).
-- The callers (codecs/image/Jpeg/Decode, codecs/image/Jpeg) size every buffer; each loop reads and writes inside those sizes.
local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32
local Yuv = {}
-- crop(src, stride, w, h, dst, doff): the top-left w x h samples of a u16 plane (stride samples per row) into u8
-- samples at dst[doff], w per row
function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
local quads = w // 4
local rest = w - quads * 4
for y = 0, h - 1 do
local s = y * stride * 2
local d = doff + y * w
-- four samples (two u32 reads of two u16 samples, each 0..255) per u32 write
for _ = 1, quads do
local a, b = readu32(src, s), readu32(src, s + 4)
writeu32(dst, d, a % 65536 + (a // 65536) * 256 + (b % 65536) * 65536 + (b // 65536) * 16777216)
s += 8
d += 4
end
for k = 0, rest - 1 do
writeu8(dst, d + k, readu16(src, s + k * 2))
end
end
end
-- rows(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:2:2 chroma) -> u8 w x ceil(h / 2), each output
-- row the rounded mean of two source rows (the last row alone when h is odd)
function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
local oh = (h + 1) // 2
for y = 0, oh - 1 do
local a = 2 * y * stride * 2
local b = if 2 * y + 1 < h then a + stride * 2 else a
local d = doff + y * w
for x = 0, w - 1 do
writeu8(dst, d + x, (readu16(src, a + x * 2) + readu16(src, b + x * 2) + 1) // 2)
end
end
end
-- box(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:4:4 chroma) -> u8 ceil(w / 2) x ceil(h / 2),
-- each output sample the rounded mean of a 2 x 2 block (edges repeat the last row / column)
function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
local ow, oh = (w + 1) // 2, (h + 1) // 2
for y = 0, oh - 1 do
local a = 2 * y * stride * 2
local b = if 2 * y + 1 < h then a + stride * 2 else a
local d = doff + y * ow
for x = 0, ow - 1 do
local x0 = 2 * x * 2
local x1 = if 2 * x + 1 < w then x0 + 2 else x0
writeu8(dst, d + x, (readu16(src, a + x0) + readu16(src, a + x1) + readu16(src, b + x0) + readu16(src, b + x1) + 2) // 4)
end
end
end
-- weave(top, toff, bottom, boff, rowBytes, rows, dst, doff): interleave rows of two planes (field 1 on the even rows, field
-- 2 on the odd rows) into rows output rows at dst[doff]; top holds ceil(rows / 2) rows, bottom floor(rows / 2)
function Yuv.weave(top: buffer, toff: number, bottom: buffer, boff: number, rowBytes: number, rows: number, dst: buffer, doff: number)
for y = 0, rows - 1 do
local k = y // 2
if y % 2 == 0 then
buffer.copy(dst, doff + y * rowBytes, top, toff + k * rowBytes, rowBytes)
else
buffer.copy(dst, doff + y * rowBytes, bottom, boff + k * rowBytes, rowBytes)
end
end
end
return Yuv
+385
View File
@@ -0,0 +1,385 @@
--!strict
-- codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
-- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and
-- arithmetic scan decoding, IDCTs through codecs/image/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder)
-- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's
-- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md.
--
-- local img, err = Jpeg.decode(buf, off?, len?, opts?) -- one JPEG -> rgba8 (or gray8 / yuv420p) Types.Image
-- local img = Jpeg.decode(frame, 0, n, { yuv = true }) -- video: yuv420p straight from the IDCT planes
-- local out, err = Jpeg.encode(img, opts?) -- rgba8 / rgb8 / gray8 / yuv420p Image -> buffer
-- local info, err = Jpeg.info(buf, off?, len?) -- the headers up to the frame header
--
-- 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), EXIF orientation
-- (meta.orientation, applied with opts.orient). Truncated or corrupt scans decode as far as they go
-- (meta.truncated = true).
-- Motion-JPEG: frames without DHT segments use the T.81 annex K tables; the AVI1 APP0 segment is read (its field
-- polarity) and data after EOI is ignored. Two fields back to back (AVI1 interlaced: two JPEGs of half the frame
-- height, polarity 1 or 2, or opts.fields = true) are decoded and woven into one frame, the first field on the even
-- rows (top field first, as ffmpeg, which ignores the polarity value); a missing or different-sized second field
-- leaves the first field alone (meta.source.fields = 1).
-- opts.yuv: 8-bit YCbCr frames come out as yuv420p (full-range BT.601, meta.source.range = "full") without colour
-- conversion or upsampling: 4:2:0 (2x2 luma) as the planes are; 4:2:2 (2x1 luma, the usual Motion-JPEG camera
-- layout) with each pair of chroma rows averaged; 4:4:4 with 2 x 2 chroma averages; grey with chroma 128. Other
-- layouts (RGB, CMYK, 4:1:1, 4:4:0, 12-bit) and scaled decodes fall back to rgba8 (check img.format).
-- 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, extra APPn / COM segments
-- (opts.segments); yuv420p input is coded from its planes as they are (4:2:0, no colour conversion).
-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, 12-bit or CMYK encoding.
-- Never throws: bad data or arguments return nil, Err.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Decode = require("@formats/codecs/image/Jpeg/Decode")
local Encode = require("@formats/codecs/image/Jpeg/Encode")
local Yuv = require("@formats/codecs/image/Jpeg/Yuv")
local Jpeg = {}
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; rgba8 / gray8)
native: boolean?, -- grey files decode to gray8 (default false: rgba8)
yuv: boolean?, -- 8-bit YCbCr / grey frames decode to yuv420p (default false); see the header for the layouts
fields: boolean?, -- two JPEGs back to back are two fields of one frame (default: when the AVI1 segment says so)
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"; yuv420p input is always 4:2:0)
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)
density: { unit: number, x: number, y: number }?, -- the JFIF density (default unit 0, 1 x 1)
segments: { { marker: number, data: buffer } }?, -- APPn / COM segments written after the JFIF header
}
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,
avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header
}
local function range(buf: buffer, off: number?, len: number?): (number, number)
local n = buffer.len(buf)
local o = math.clamp(math.floor(tonumber(off) or 0), 0, n)
return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o)
end
-- the marker parser over [o, o + l): State | nil, Err
local function parse(buf: buffer, o: number, l: number, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?)
local ok, st, code, msg = pcall(Decode.parse, buf, o, o + l, opts, headerOnly)
if not ok then
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st))
end
if not st then
return nil, Err.from(msg or "decode failed", o, code)
end
return st, nil
end
local function samplingOf(f: any): { { number } }
local sampling = {}
for _, c in f.comps do
table.insert(sampling, { c.h, c.v })
end
return sampling
end
-- info(buf, off?, len?) -> Info | nil, Err (reads the headers up to the frame header)
function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?)
if type(buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "expected a buffer")
end
local o, l = range(buf, off, len)
local st, err = parse(buf, o, l, nil, true)
if not st then
return nil, err
end
local f = st.frame
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 = samplingOf(f),
orientation = st.orientation,
adobe = st.adobe,
jfif = st.jfif,
avi1 = st.avi1,
},
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
-- one JPEG at [o, o + l): Image, State | nil, Err
local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions?): (Types.Image?, any)
local st, err = parse(buf, o, l, opts, false)
if not st then
return nil, err
end
local s = st :: Decode.State
local img = Types.Image.new(0, 0)
local space, mode = nil, nil
if opts and opts.yuv then
local ok, w, h, px, m = pcall(Decode.outputYuv, s)
if not ok then
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
end
if w then
img.width, img.height, img.pixels, img.format = w, h :: number, px :: buffer, "yuv420p"
mode = m
space = Decode.colorSpaceOf(s.frame, s.adobe, s.jfif)
end
end
if not mode then
local ok, w, h, px, sp = pcall(Decode.output, s)
if not ok then
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
end
if not w then
return nil, Err.from(px, o, h)
end
space = sp
if opts and opts.orient then
px, w, h = orient(px, w, h, s.orientation)
end
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
end
local f = s.frame
local meta = img.meta
meta.orientation = s.orientation
meta.oriented = (opts and opts.orient and not mode) or false
meta.exif = s.exif
meta.icc = s.icc
if #s.comments > 0 then
meta.text = { comment = table.concat(s.comments, "\n") }
end
if s.density and s.density.unit > 0 and s.density.x > 0 and s.density.y > 0 then
local k = if s.density.unit == 2 then 2.54 else 1
meta.dpi = { x = s.density.x * k, y = s.density.y * k }
end
meta.truncated = s.truncated
meta.source = {
format = "jpeg",
bitDepth = f.precision,
colorType = space,
components = #f.comps,
progressive = f.progressive,
arithmetic = f.arithmetic,
sampling = samplingOf(f),
scale = s.scale,
adobe = s.adobe,
jfif = s.jfif,
avi1 = s.avi1,
yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv)
range = if mode then "full" else nil,
fields = 1,
}
return img, s
end
-- the start of a second JPEG (FF D8 FF) at or after p, before e; -1 if none
local function nextSoi(buf: buffer, p: number, e: number): number
local readu8 = buffer.readu8
while p + 3 <= e do
if readu8(buf, p) == 0xFF and readu8(buf, p + 1) == 0xD8 and readu8(buf, p + 2) == 0xFF then
return p
end
p += 1
end
return -1
end
-- two fields (same size and format) -> one frame of twice the height, field a on the even rows
local function weave(a: Types.Image, b: Types.Image): Types.Image
local w, hf = a.width, a.height
local h = hf * 2
local out = Types.Image.new(w, h, a.format)
local dst = out.pixels
if a.format == "yuv420p" then
local cw, chf = (w + 1) // 2, (hf + 1) // 2
local ch = (h + 1) // 2 -- = hf
Yuv.weave(a.pixels, 0, b.pixels, 0, w, h, dst, 0)
for k = 0, 1 do
Yuv.weave(a.pixels, w * hf + k * cw * chf, b.pixels, w * hf + k * cw * chf, cw, ch, dst, w * h + k * cw * ch)
end
else
local bpp = Types.Image.bpp(a.format) or 4
Yuv.weave(a.pixels, 0, b.pixels, 0, w * bpp, h, dst, 0)
end
out.meta = a.meta
return out
end
-- decode(buf, off?, len?, opts?) -> Image | nil, Err: one JPEG (or one interlaced Motion-JPEG frame) in [off, off + len)
function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOptions?): (Types.Image?, Err.Err?)
if type(buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "expected a buffer")
end
if opts ~= nil and type(opts) ~= "table" then
return nil, Err.new(Err.ARG, "options must be a table")
end
local o, l = range(buf, off, len)
local img, st = decodeOne(buf, o, l, opts)
if not img then
return nil, st
end
local s = st :: Decode.State
local wantFields = if opts and opts.fields ~= nil then opts.fields else (s.avi1 == 1 or s.avi1 == 2)
if wantFields and not (opts and opts.orient) then
local e = o + l
local p = nextSoi(buf, s.endPos, e)
if p >= 0 then
local o2 = table.clone(opts or {}) :: any
if o2.maxPixels then
o2.maxPixels = math.max(0, o2.maxPixels - img.width * img.height)
end
local b = decodeOne(buf, p, e - p, o2)
if b and b.width == img.width and b.height == img.height and b.format == img.format then
local truncated = img.meta.truncated or b.meta.truncated
img = weave(img, b)
img.meta.truncated = truncated
local source: any = img.meta.source
source.fields = 2
end
end
end
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 }
-- encode(img, opts?) -> buffer | nil, Err: an rgba8 / rgb8 / gray8 / yuv420p Image as a baseline or progressive JPEG
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, gray8 or yuv420p Image (got " .. tostring(img.format) .. ")")
end
local w, h = img.width, img.height
local need = if bpp == 0 then w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) else w * h * bpp
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) < need then
return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
end
if opts ~= nil and type(opts) ~= "table" then
return nil, Err.new(Err.ARG, "options must be a table")
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
if bpp == 0 then
sub = "420"
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 = {}
if o.segments ~= nil then
if type(o.segments) ~= "table" then
return nil, Err.new(Err.ARG, "segments must be a list of { marker, data }")
end
for _, sg in o.segments do
if type(sg) ~= "table" or type(sg.data) ~= "buffer" or buffer.len(sg.data) > 65533 or type(sg.marker) ~= "number" then
return nil, Err.new(Err.ARG, "bad segment (marker 0xE0..0xEF / 0xFE, at most 65533 bytes)")
end
if not ((sg.marker >= 0xE0 and sg.marker <= 0xEF) or sg.marker == 0xFE) then
return nil, Err.new(Err.ARG, "bad segment marker (0xE0..0xEF / 0xFE)")
end
table.insert(segments, sg)
end
end
local density = o.density
if density ~= nil then
if type(density) ~= "table" or type(density.unit) ~= "number" or type(density.x) ~= "number" or type(density.y) ~= "number" then
return nil, Err.new(Err.ARG, "bad density")
end
density = {
unit = math.clamp(math.floor(density.unit), 0, 2),
x = math.clamp(math.floor(density.x), 1, 65535),
y = math.clamp(math.floor(density.y), 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
+262
View File
@@ -0,0 +1,262 @@
--!strict
--!native
--!optimize 2
-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP,
-- the DIBs inside ICO / CUR, ...): 1 / 2 / 4 / 8-bit indexes through a palette, BGR / BGRA, 5-5-5, bit-masked 16 /
-- 24 / 32-bit pixels, RLE4 / RLE8, rows bottom-up or top-down; and the encoder direction (rgba8 -> BGR / BGRA /
-- 8-bit indexes, bottom-up). Absorbed from bmp-luau b86aed6 (same author, no third-party code); the encoder loops
-- are new. They never throw: the caller validates every size first and hands in a source buffer that holds every
-- byte an uncompressed loop can read (a truncated file is copied into a zero-padded buffer); the RLE loop checks each
-- read against its end offset. Output: rgba8, top-down rows, one u32 per pixel (bytes R, G, B, A).
local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8
local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift
local Pixels = {}
-- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal)
function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number,
topDown: boolean, pal: buffer)
local mask = lshift(1, bpp) - 1
for r = 0, h - 1 do
local so = base + r * stride
local d = (if topDown then r else h - 1 - r) * w * 4
if bpp == 8 then
for x = 0, w - 1 do
writeu32(dst, d + x * 4, readu32(pal, readu8(src, so + x) * 4))
end
elseif bpp == 4 then
for x = 0, w - 1 do
local b = readu8(src, so + rshift(x, 1))
local i = if band(x, 1) == 0 then rshift(b, 4) else band(b, 15)
writeu32(dst, d + x * 4, readu32(pal, i * 4))
end
else
for x = 0, w - 1 do
local bit = x * bpp
local b = readu8(src, so + rshift(bit, 3))
local i = band(rshift(b, 8 - bpp - band(bit, 7)), mask)
writeu32(dst, d + x * 4, readu32(pal, i * 4))
end
end
end
end
-- 16 bpp X-R-G-B 1-5-5-5 (BI_RGB 16-bit), opaque; 5-bit channels scaled to 8 bits with rounding
function Pixels.rgb555(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean)
for r = 0, h - 1 do
local so = base + r * stride
local d = (if topDown then r else h - 1 - r) * w * 4
for x = 0, w - 1 do
local s = readu16(src, so + x * 2)
local cr, cg, cb = band(rshift(s, 10), 31), band(rshift(s, 5), 31), band(s, 31)
writeu32(dst, d + x * 4, (cr * 255 + 15) // 31 + ((cg * 255 + 15) // 31) * 256 + ((cb * 255 + 15) // 31) * 65536 + 0xFF000000)
end
end
end
-- 24 bpp BI_RGB: B, G, R
function Pixels.bgr24(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean)
for r = 0, h - 1 do
local so = base + r * stride
local d = (if topDown then r else h - 1 - r) * w * 4
for x = 0, w - 1 do
local s = so + x * 3
writeu32(dst, d + x * 4,
bor(readu8(src, s + 2), lshift(readu8(src, s + 1), 8), lshift(readu8(src, s), 16), 0xFF000000))
end
end
end
-- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks). Returns the OR of every alpha byte.
function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number,
topDown: boolean): number
local aor = 0
for r = 0, h - 1 do
local so = base + r * stride
local d = (if topDown then r else h - 1 - r) * w * 4
for x = 0, w - 1 do
local p = readu32(src, so + x * 4)
-- swap R and B: B G R A -> R G B A
writeu32(dst, d + x * 4, bor(band(p, 0xFF00FF00), band(rshift(p, 16), 0xFF), lshift(band(p, 0xFF), 16)))
aor = bor(aor, p)
end
end
return rshift(aor, 24)
end
-- 16 / 24 / 32 bpp through bit masks. sh* = shift of each mask, m* = mask >> shift, t* = scale tables (u8, one entry
-- per masked value). A channel without a mask has m = 0 and a 1-entry table (0 for colour, 255 for alpha).
-- Returns the OR of every masked alpha value (before scaling).
function Pixels.masked(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number,
topDown: boolean, shr: number, mr: number, tr: buffer, shg: number, mg: number, tg: buffer, shb: number,
mb: number, tb: buffer, sha: number, ma: number, ta: buffer): number
local bytes = rshift(bpp, 3)
local aor = 0
for r = 0, h - 1 do
local so = base + r * stride
local d = (if topDown then r else h - 1 - r) * w * 4
for x = 0, w - 1 do
local s = so + x * bytes
local p
if bytes == 2 then
p = readu16(src, s)
elseif bytes == 4 then
p = readu32(src, s)
else
p = bor(readu16(src, s), lshift(readu8(src, s + 2), 16))
end
local a = band(rshift(p, sha), ma)
aor = bor(aor, a)
local o = d + x * 4
writeu8(dst, o, readu8(tr, band(rshift(p, shr), mr)))
writeu8(dst, o + 1, readu8(tg, band(rshift(p, shg), mg)))
writeu8(dst, o + 2, readu8(tb, band(rshift(p, shb), mb)))
writeu8(dst, o + 3, readu8(ta, a))
end
end
return aor
end
-- Sets every alpha byte to 255 (32-bit images whose alpha channel is all zero are opaque).
function Pixels.opaque(dst: buffer, n: number)
for i = 0, n - 1 do
writeu8(dst, i * 4 + 3, 255)
end
end
-- RLE8 / RLE4 from src[pos, stop) into dst (pre-filled with transparent black; pixels the stream skips with a
-- delta, an early end of line or an early end of bitmap stay transparent). Malformed or truncated data stops the
-- decode and keeps what was drawn. Returns the number of pixels written.
function Pixels.rle(src: buffer, pos: number, stop: number, rle4: boolean, dst: buffer, w: number, h: number,
topDown: boolean, pal: buffer): number
local x, y = 0, 0
local written = 0
local row = (if topDown then 0 else h - 1) * w * 4
local rowStep = if topDown then w * 4 else -w * 4
while y < h and pos + 1 < stop do
local n = readu8(src, pos)
local v = readu8(src, pos + 1)
pos += 2
if n > 0 then
-- encoded run: n pixels of index v (RLE4: alternating high / low nibble)
local e = math.min(x + n, w)
if rle4 then
local hi, lo = readu32(pal, rshift(v, 4) * 4), readu32(pal, band(v, 15) * 4)
for i = x, e - 1 do
writeu32(dst, row + i * 4, if band(i - x, 1) == 0 then hi else lo)
end
else
local c = readu32(pal, v * 4)
for i = x, e - 1 do
writeu32(dst, row + i * 4, c)
end
end
if e > x then
written += e - x
end
x += n
elseif v == 0 then
-- end of line
x = 0
y += 1
row += rowStep
elseif v == 1 then
break -- end of bitmap
elseif v == 2 then
-- delta: right dx, up (in file rows) dy
if pos + 1 >= stop then
break
end
local dx, dy = readu8(src, pos), readu8(src, pos + 1)
pos += 2
x += dx
y += dy
row += rowStep * dy
else
-- absolute run of v pixels, padded to a 16-bit boundary
local nb = if rle4 then rshift(v + 1, 1) else v
if pos + nb > stop then
break
end
local e = math.min(x + v, w)
for i = x, e - 1 do
local k = i - x
local idx
if rle4 then
local b = readu8(src, pos + rshift(k, 1))
idx = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
else
idx = readu8(src, pos + k)
end
writeu32(dst, row + i * 4, readu32(pal, idx * 4))
end
if e > x then
written += e - x
end
x += v
pos += nb + band(nb, 1)
end
end
return written
end
-- Encoder: rgba8 (top-down) -> 24 bpp BGR rows, bottom-up, each padded to stride (dst is zero-filled)
function Pixels.encode24(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number)
for y = 0, h - 1 do
local s = y * w * 4
local d = base + (h - 1 - y) * stride
for x = 0, w - 1 do
local v = readu32(src, s + x * 4)
writeu8(dst, d, band(rshift(v, 16), 255))
writeu8(dst, d + 1, band(rshift(v, 8), 255))
writeu8(dst, d + 2, band(v, 255))
d += 3
end
end
end
-- rgba8 -> 32 bpp BGRA, bottom-up
function Pixels.encode32(src: buffer, w: number, h: number, dst: buffer, base: number)
for y = 0, h - 1 do
local s = y * w * 4
local d = base + (h - 1 - y) * w * 4
for x = 0, w - 1 do
local v = readu32(src, s + x * 4)
-- R G B A (little-endian u32: R | G << 8 | B << 16 | A << 24) -> B G R A
writeu32(dst, d + x * 4, bor(band(v, 0xFF00FF00), band(rshift(v, 16), 255), lshift(band(v, 255), 16)))
end
end
end
-- rgba8 -> 8 bpp indexes through idx (a table colour -> index, colours as R | G << 8 | B << 16), bottom-up
function Pixels.encode8(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number, idx: { [number]: number })
for y = 0, h - 1 do
local s = y * w * 4
local d = base + (h - 1 - y) * stride
for x = 0, w - 1 do
writeu8(dst, d + x, idx[band(readu32(src, s + x * 4), 0xFFFFFF)] or 0)
end
end
end
-- colours(src, n, max) -> the distinct RGB colours in first-appearance order (R | G << 8 | B << 16), whether any
-- alpha is below 255; stops counting at max + 1 colours
function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boolean)
local seen: { [number]: boolean } = {}
local list: { number } = {}
local alpha = false
for i = 0, n - 1 do
local v = readu32(src, i * 4)
if v < 0xFF000000 then
alpha = true
end
local c = band(v, 0xFFFFFF)
if #list <= max and not seen[c] then
seen[c] = true
list[#list + 1] = c
end
end
return list, alpha
end
return Pixels
+483
View File
@@ -0,0 +1,483 @@
--!strict
--!native
--!optimize 2
-- codecs/image/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) :: { number }
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) :: { Color }
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) :: { { any } }
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: { number }, pg: { number }, pb: { number }, pi: { number } = {}, {}, {}, {}
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) :: { number }
for k = 1, np do
order[k] = pg[k] * 65536 + k
end
table.sort(order)
local r2, g2, b2, i2 = table.create(np) :: { number }, table.create(np) :: { number }, table.create(np) :: { number }, table.create(np) :: { number }
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
+744
View File
@@ -0,0 +1,744 @@
--!strict
--!native
--!optimize 2
-- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
-- transform, with the nonzero and even-odd fill rules, plus a polygon stroker. Used by the fonts (glyph outlines) and
-- by vector/svg. New code; the coverage accumulation is the signed-area method of font-rs (Raph Levien, Apache-2.0 /
-- MIT, an algorithm description, no code copied) and of stb_truetype v2: every edge adds its exact signed area to an
-- accumulation row; a running sum along the row gives the winding coverage of each pixel. The rules map the summed
-- coverage a as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2.
--
-- local R = require("@formats/codecs/image/Raster")
-- local p = R.path():moveTo(0, 0):lineTo(10, 0):quadTo(10, 10, 0, 10):close() -- or a plain command list:
-- local cmds = { { op = "moveTo", 0, 0 }, { op = "lineTo", 10, 0 }, { op = "cubicTo", 12, 2, 12, 8, 10, 10 },
-- { op = "close" } } -- (the Font:outline() format)
-- local m = R.mask(cmds, { transform = { 2, 0, 0, 2, 5, 5 }, rule = "evenodd", clip = { 0, 0, 64, 64 } })
-- -- m = { x, y, width, height, coverage: buffer (u8, width * height) } in device pixels, or nil when empty
-- R.fill(img, cmds, { 255, 0, 0, 255 }, { transform = t }) -- composite onto an rgba8 Image (source over)
-- R.fill(img, cmds, function(x, y) return r, g, b, a end) -- a paint function per covered pixel (gradients)
-- local outline = R.stroke(cmds, { width = 2, join = "round", cap = "butt" }) -- a path to fill (nonzero)
--
-- Transforms are { a, b, c, d, e, f } (SVG matrix order): x' = a x + c y + e, y' = b x + d y + f. Coordinates are
-- pixels with y down; a pixel (i, j) covers [i, i+1) x [j, j+1). Curves are flattened in device space to
-- opts.tolerance (default 0.1 px). Subpaths are implicitly closed for filling.
--
-- Never throws: malformed commands (missing or non-number operands) are skipped, non-finite coordinates drop the
-- edge, sizes are bounded by opts.maxPixels (default 2^26), so it is safe for native code and untrusted paths.
local Raster = {}
local floor, ceil, min, max, abs, sqrt = math.floor, math.ceil, math.min, math.max, math.abs, math.sqrt
local readf32, writef32, readu8, writeu8 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8
local bcreate = buffer.create
export type Cmd = { op: string, [number]: number }
export type Path = { Cmd }
export type Transform = { number }
export type Mask = { x: number, y: number, width: number, height: number, coverage: buffer }
export type Options = {
transform: Transform?, -- default identity
rule: ("nonzero" | "evenodd")?, -- default "nonzero"
clip: { number }?, -- { x0, y0, x1, y1 } device pixel bounds (integers); default: the path's bounds (fill: the image)
tolerance: number?, -- curve flattening tolerance in device pixels (default 0.1)
maxPixels: number?, -- largest mask (default 2^26)
opacity: number?, -- fill: multiplies the coverage (0..1, default 1)
}
local LIMIT = 1e7 -- coordinates beyond this (device pixels) are treated as broken
-- ------------------------------------------------------------------------------------------------ transforms
Raster.IDENTITY = table.freeze({ 1, 0, 0, 1, 0, 0 })
-- multiply(m, n) -> m * n (apply n first, then m)
function Raster.multiply(m: Transform, n: Transform): Transform
return {
m[1] * n[1] + m[3] * n[2],
m[2] * n[1] + m[4] * n[2],
m[1] * n[3] + m[3] * n[4],
m[2] * n[3] + m[4] * n[4],
m[1] * n[5] + m[3] * n[6] + m[5],
m[2] * n[5] + m[4] * n[6] + m[6],
}
end
function Raster.translate(tx: number, ty: number): Transform
return { 1, 0, 0, 1, tx, ty }
end
function Raster.scale(sx: number, sy: number?): Transform
return { sx, 0, 0, sy or sx, 0, 0 }
end
function Raster.rotate(radians: number): Transform
local c, s = math.cos(radians), math.sin(radians)
return { c, s, -s, c, 0, 0 }
end
-- invert(m) -> m^-1 | nil (singular)
function Raster.invert(m: Transform): Transform?
local det = m[1] * m[4] - m[2] * m[3]
if det == 0 or det ~= det then
return nil
end
local id = 1 / det
local a, b, c, d = m[4] * id, -m[2] * id, -m[3] * id, m[1] * id
return { a, b, c, d, -(a * m[5] + c * m[6]), -(b * m[5] + d * m[6]) }
end
-- apply(m, x, y) -> x', y'
function Raster.apply(m: Transform, x: number, y: number): (number, number)
return m[1] * x + m[3] * y + m[5], m[2] * x + m[4] * y + m[6]
end
-- ------------------------------------------------------------------------------------------------ path builder
local Builder = {}
Builder.__index = Builder
export type Builder = typeof(setmetatable({} :: { cmds: Path }, Builder))
-- path() -> a Builder; every method returns the builder; builder.cmds is the command list (any API taking a path
-- takes a builder too)
function Raster.path(): Builder
return setmetatable({ cmds = {} :: Path }, Builder)
end
function Builder.moveTo(self: Builder, x: number, y: number): Builder
table.insert(self.cmds, { op = "moveTo", x, y })
return self
end
function Builder.lineTo(self: Builder, x: number, y: number): Builder
table.insert(self.cmds, { op = "lineTo", x, y })
return self
end
function Builder.quadTo(self: Builder, cx: number, cy: number, x: number, y: number): Builder
table.insert(self.cmds, { op = "quadTo", cx, cy, x, y })
return self
end
function Builder.cubicTo(self: Builder, c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): Builder
table.insert(self.cmds, { op = "cubicTo", c1x, c1y, c2x, c2y, x, y })
return self
end
function Builder.close(self: Builder): Builder
table.insert(self.cmds, { op = "close" } :: Cmd)
return self
end
-- rect(x, y, w, h), ellipse(cx, cy, rx, ry): closed subpaths
function Builder.rect(self: Builder, x: number, y: number, w: number, h: number): Builder
return self:moveTo(x, y):lineTo(x + w, y):lineTo(x + w, y + h):lineTo(x, y + h):close()
end
function Builder.ellipse(self: Builder, cx: number, cy: number, rx: number, ry: number): Builder
local k = 0.5522847498307936 -- 4/3 (sqrt 2 - 1): cubic quarter circle
self:moveTo(cx + rx, cy)
self:cubicTo(cx + rx, cy + ry * k, cx + rx * k, cy + ry, cx, cy + ry)
self:cubicTo(cx - rx * k, cy + ry, cx - rx, cy + ry * k, cx - rx, cy)
self:cubicTo(cx - rx, cy - ry * k, cx - rx * k, cy - ry, cx, cy - ry)
self:cubicTo(cx + rx * k, cy - ry, cx + rx, cy - ry * k, cx + rx, cy)
return self:close()
end
local function commands(path: any): Path?
if type(path) ~= "table" then
return nil
end
if type(path.cmds) == "table" then
return path.cmds
end
return path
end
-- n numeric operands of a command, or nil
local function operands(c: any, n: number): boolean
if type(c) ~= "table" then
return false
end
for i = 1, n do
local v = c[i]
if type(v) ~= "number" or v ~= v or abs(v) > 1e15 then
return false
end
end
return true
end
-- ------------------------------------------------------------------------------------------------ flattening
-- flatten(path, transform?, tolerance?) -> polylines: { { x1, y1, x2, y2, ... } } in device space, one per subpath
-- (closed implicitly; the closing point is not repeated), and the bounds x0, y0, x1, y1 (nil when empty)
local function flatten(path: any, transform: Transform?, tolerance: number?, minLen: number): ({ { number } }, number?, number?, number?, number?)
local cmds = commands(path)
local polys: { { number } } = {}
if not cmds then
return polys, nil, nil, nil, nil
end
local m = transform or Raster.IDENTITY
local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6]
if type(a) ~= "number" or type(b) ~= "number" or type(c) ~= "number" or type(d) ~= "number" or type(e) ~= "number" or type(f) ~= "number" then
return polys, nil, nil, nil, nil
end
local tol = tolerance or 0.1
if type(tol) ~= "number" or not (tol > 0.001) then
tol = 0.1
end
local cur: { number }? = nil
local px, py = 0, 0 -- current point (device)
local sx, sy = 0, 0 -- subpath start (device)
local bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge
local function point(x: number, y: number)
local poly = cur :: { number }
local n = #poly
poly[n + 1] = x
poly[n + 2] = y
if x < bx0 then
bx0 = x
end
if x > bx1 then
bx1 = x
end
if y < by0 then
by0 = y
end
if y > by1 then
by1 = y
end
end
local function start(x: number, y: number)
if cur and #cur >= minLen then
table.insert(polys, cur)
end
cur = {}
point(x, y)
sx, sy = x, y
px, py = x, y
end
for _, cmd in cmds do
local op = if type(cmd) == "table" then cmd.op else nil
if op == "moveTo" then
if operands(cmd, 2) then
start(a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f)
end
elseif op == "lineTo" then
if operands(cmd, 2) then
if not cur then
start(px, py)
end
px, py = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f
point(px, py)
end
elseif op == "quadTo" then
if operands(cmd, 4) then
if not cur then
start(px, py)
end
local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f
local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f
local ddx, ddy = px - 2 * x1 + x2, py - 2 * y1 + y2
local n = ceil(sqrt(sqrt(ddx * ddx + ddy * ddy) * 0.25 / tol))
n = if n ~= n then 1 else max(1, min(n, 500))
local x0, y0 = px, py
for i = 1, n - 1 do
local t = i / n
local u = 1 - t
point(u * u * x0 + 2 * u * t * x1 + t * t * x2, u * u * y0 + 2 * u * t * y1 + t * t * y2)
end
point(x2, y2)
px, py = x2, y2
end
elseif op == "cubicTo" then
if operands(cmd, 6) then
if not cur then
start(px, py)
end
local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f
local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f
local x3, y3 = a * cmd[5] + c * cmd[6] + e, b * cmd[5] + d * cmd[6] + f
local ax, ay = px - 2 * x1 + x2, py - 2 * y1 + y2
local bxx, byy = x1 - 2 * x2 + x3, y1 - 2 * y2 + y3
local dd = max(sqrt(ax * ax + ay * ay), sqrt(bxx * bxx + byy * byy))
local n = ceil(sqrt(dd * 0.75 / tol))
n = if n ~= n then 1 else max(1, min(n, 500))
local x0, y0 = px, py
for i = 1, n - 1 do
local t = i / n
local u = 1 - t
local w0, w1, w2, w3 = u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t
point(w0 * x0 + w1 * x1 + w2 * x2 + w3 * x3, w0 * y0 + w1 * y1 + w2 * y2 + w3 * y3)
end
point(x3, y3)
px, py = x3, y3
end
elseif op == "close" then
if cur then
if #cur >= minLen then
table.insert(polys, cur)
end
cur = nil
px, py = sx, sy
end
end
end
if cur and #cur >= minLen then
table.insert(polys, cur)
end
if #polys == 0 or bx0 ~= bx0 or by0 ~= by0 or bx1 ~= bx1 or by1 ~= by1 then
return polys, nil, nil, nil, nil
end
return polys, bx0, by0, bx1, by1
end
function Raster.flatten(path: any, transform: Transform?, tolerance: number?): ({ { number } }, number?, number?, number?, number?)
return flatten(path, transform, tolerance, 6)
end
-- ------------------------------------------------------------------------------------------------ accumulation
-- one edge (x0, y0) -> (x1, y1), already inside [0, W] horizontally, into acc (stride S, H rows): the signed area
-- each pixel gains (font-rs's draw_line)
local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x1: number, y1: number)
if y0 == y1 then
return
end
local W = S - 2
local xl, xr = 0, W -- x stays in [0, W] (rounding in the splits and in x + dxdy * dy must never index outside)
local dir = 1
if y0 > y1 then
dir = -1
x0, x1 = x1, x0
y0, y1 = y1, y0
end
if y1 <= 0 or y0 >= H then
return
end
local dxdy = (x1 - x0) / (y1 - y0)
local x = x0
if y0 < 0 then
x -= y0 * dxdy
end
local ystart = max(0, floor(y0))
local yend = min(H, ceil(y1)) - 1
for y = ystart, yend do
local ls = y * S
local dy = min(y + 1, y1) - max(y, y0)
local xnext = x + dxdy * dy
if xnext < xl then
xnext = xl
elseif xnext > xr then
xnext = xr
end
if x < xl then
x = xl
elseif x > xr then
x = xr
end
local dd = dy * dir
local xa, xb = x, xnext
if xa > xb then
xa, xb = xb, xa
end
local xaf = floor(xa)
local xai = xaf
local xbc = ceil(xb)
local xbi = xbc
if xbi <= xai + 1 then
local xmf = 0.5 * (x + xnext) - xaf
local o = (ls + xai) * 4
writef32(acc, o, readf32(acc, o) + dd - dd * xmf)
writef32(acc, o + 4, readf32(acc, o + 4) + dd * xmf)
else
local s = 1 / (xb - xa)
local x0f = xa - xaf
local a0 = 0.5 * s * (1 - x0f) * (1 - x0f)
local x1f = xb - xbc + 1
local am = 0.5 * s * x1f * x1f
local o = (ls + xai) * 4
writef32(acc, o, readf32(acc, o) + dd * a0)
if xbi == xai + 2 then
writef32(acc, o + 4, readf32(acc, o + 4) + dd * (1 - a0 - am))
else
local a1 = s * (1.5 - x0f)
writef32(acc, o + 4, readf32(acc, o + 4) + dd * (a1 - a0))
local ds = dd * s
for xi = xai + 2, xbi - 2 do
local q = (ls + xi) * 4
writef32(acc, q, readf32(acc, q) + ds)
end
local a2 = a1 + (xbi - xai - 3) * s
local q = (ls + xbi - 1) * 4
writef32(acc, q, readf32(acc, q) + dd * (1 - a2 - am))
end
local q = (ls + xbi) * 4
writef32(acc, q, readf32(acc, q) + dd * am)
end
x = xnext
end
end
-- an edge in mask coordinates, split where it crosses x = 0 and x = W (in its own order: the direction is the
-- winding sign); the parts outside are pushed onto the border (their area lies outside the mask, their cover still
-- applies to the row)
local function clampx(x: number, W: number): number
return if x < 0 then 0 elseif x > W then W else x
end
local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0: number, x1: number, y1: number)
if y0 == y1 or not (abs(x0) < LIMIT and abs(y0) < LIMIT and abs(x1) < LIMIT and abs(y1) < LIMIT) then
return -- horizontal, or non-finite (NaN fails every comparison)
end
if (y0 <= 0 and y1 <= 0) or (y0 >= H and y1 >= H) then
return
end
local dx = x1 - x0
local ta, tb = 2, 2 -- parameters of the crossings with x = 0 and x = W (2 = none)
if dx ~= 0 then
local t0 = (0 - x0) / dx
local tw = (W - x0) / dx
if t0 > 0 and t0 < 1 then
ta = t0
end
if tw > 0 and tw < 1 then
tb = tw
end
if ta > tb then
ta, tb = tb, ta
end
end
local dy = y1 - y0
local px, py = x0, y0
if ta < 1 then
local qx, qy = x0 + dx * ta, y0 + dy * ta
line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy)
px, py = qx, qy
end
if tb < 1 then
local qx, qy = x0 + dx * tb, y0 + dy * tb
line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy)
px, py = qx, qy
end
line(acc, S, H, clampx(px, W), py, clampx(x1, W), y1)
end
-- ------------------------------------------------------------------------------------------------ masks
-- mask(path, opts?) -> Mask | nil (empty, or over the size limit: then the second result is "limit")
function Raster.mask(path: any, opts: Options?): (Mask?, string?)
local o: Options = opts or {}
local polys, bx0, by0, bx1, by1 = Raster.flatten(path, o.transform, o.tolerance)
if not bx0 then
return nil, nil
end
if abs(bx0 :: number) > LIMIT or abs(by0 :: number) > LIMIT or abs(bx1 :: number) > LIMIT or abs(by1 :: number) > LIMIT then
return nil, "coordinates out of range"
end
local X0, Y0, X1, Y1 = floor(bx0 :: number), floor(by0 :: number), ceil(bx1 :: number), ceil(by1 :: number)
local clip = o.clip
if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then
Y0 = max(Y0, floor(clip[2]))
Y1 = min(Y1, ceil(clip[4]))
X1 = min(X1, ceil(clip[3]))
local cx0 = floor(clip[1])
X0 = max(X0, cx0)
end
local W, H = X1 - X0, Y1 - Y0
if W <= 0 or H <= 0 then
return nil, nil
end
local maxPixels = if type(o.maxPixels) == "number" then o.maxPixels else 2 ^ 26
if W * H > maxPixels then
return nil, "limit"
end
local S = W + 2
local acc = bcreate(S * H * 4)
for _, poly in polys do
local n = #poly
local lx, ly = poly[n - 1] - X0, poly[n] - Y0
for i = 1, n - 1, 2 do
local x, y = poly[i] - X0, poly[i + 1] - Y0
edge(acc, S, W, H, lx, ly, x, y)
lx, ly = x, y
end
end
local cov = bcreate(W * H)
local evenodd = o.rule == "evenodd"
for y = 0, H - 1 do
local sum = 0
local ls = y * S
local os = y * W
for x = 0, W - 1 do
sum += readf32(acc, (ls + x) * 4)
local v = abs(sum)
if evenodd then
v = v % 2
if v > 1 then
v = 2 - v
end
elseif v > 1 then
v = 1
end
writeu8(cov, os + x, floor(v * 255 + 0.5))
end
end
return { x = X0, y = Y0, width = W, height = H, coverage = cov }, nil
end
-- ------------------------------------------------------------------------------------------------ filling
-- fill(img, path, paint, opts?) -> true | false, message. img: an rgba8 Image ({ width, height, pixels }); paint: an
-- { r, g, b, a } colour (0..255) or a function(x, y) -> r, g, b, a called per covered pixel (pixel centres in
-- device space: x + 0.5, y + 0.5). Composites source-over onto the straight-alpha pixels. opts.clip defaults to the
-- image; opts.opacity scales the coverage.
function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, string?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then
return false, "fill: expected an rgba8 image"
end
local iw, ih = img.width, img.height
local px = img.pixels
if buffer.len(px) < iw * ih * 4 then
return false, "fill: image pixels too short"
end
local o: Options = table.clone(opts or {} :: Options)
local clip = o.clip
if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then
o.clip = { max(0, clip[1]), max(0, clip[2]), min(iw, clip[3]), min(ih, clip[4]) }
else
o.clip = { 0, 0, iw, ih }
end
local m, why = Raster.mask(path, o)
if not m then
return why == nil, why
end
local opacity = if type(o.opacity) == "number" then math.clamp(o.opacity, 0, 1) else 1
local fn: any = nil
local cr, cg, cb, ca = 0, 0, 0, 255
if type(paint) == "function" then
fn = paint
elseif type(paint) == "table" then
cr, cg, cb = tonumber(paint[1]) or 0, tonumber(paint[2]) or 0, tonumber(paint[3]) or 0
ca = tonumber(paint[4]) or 255
else
return false, "fill: paint must be a colour or a function"
end
local cov = m.coverage
local mw = m.width
for y = 0, m.height - 1 do
local iy = m.y + y
for x = 0, mw - 1 do
local cv = readu8(cov, y * mw + x)
if cv > 0 then
local ix = m.x + x
local r, g, b, a = cr, cg, cb, ca
if fn then
local ok, r2, g2, b2, a2 = pcall(fn, ix + 0.5, iy + 0.5)
if not ok then
return false, "fill: paint function failed"
end
r, g, b, a = tonumber(r2) or 0, tonumber(g2) or 0, tonumber(b2) or 0, tonumber(a2) or 255
end
local sa = math.clamp(a, 0, 255) / 255 * cv / 255 * opacity
if sa > 0 then
local p = (iy * iw + ix) * 4
local da = readu8(px, p + 3) / 255
local oa = sa + da * (1 - sa)
local k = da * (1 - sa)
writeu8(px, p, floor((math.clamp(r, 0, 255) * sa + readu8(px, p) * k) / oa + 0.5))
writeu8(px, p + 1, floor((math.clamp(g, 0, 255) * sa + readu8(px, p + 1) * k) / oa + 0.5))
writeu8(px, p + 2, floor((math.clamp(b, 0, 255) * sa + readu8(px, p + 2) * k) / oa + 0.5))
writeu8(px, p + 3, floor(oa * 255 + 0.5))
end
end
end
end
return true, nil
end
-- ------------------------------------------------------------------------------------------------ stroking
export type StrokeOptions = {
width: number?, -- default 1
join: ("miter" | "round" | "bevel")?, -- default "miter"
cap: ("butt" | "round" | "square")?, -- default "butt"
miterLimit: number?, -- default 4 (SVG)
tolerance: number?, -- flattening tolerance in path units (default 0.1); scale it down for magnified strokes
closed: boolean?, -- treat every subpath as closed (default: only subpaths ending with "close")
}
-- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up
-- under the nonzero rule
local function polygon(out: Path, pts: { number })
local n = #pts
if n < 6 then
return
end
local area = 0
for i = 1, n - 1, 2 do
local j = if i + 2 > n then 1 else i + 2
area += pts[i] * pts[j + 1] - pts[j] * pts[i + 1]
end
if area == 0 then
return
end
if area > 0 then
table.insert(out, { op = "moveTo", pts[1], pts[2] })
for i = 3, n - 1, 2 do
table.insert(out, { op = "lineTo", pts[i], pts[i + 1] })
end
else
table.insert(out, { op = "moveTo", pts[n - 1], pts[n] })
for i = n - 3, 1, -2 do
table.insert(out, { op = "lineTo", pts[i], pts[i + 1] })
end
end
table.insert(out, { op = "close" } :: Cmd)
end
local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: number, tol: number, pts: { number })
local da = a1 - a0
local step = 2 * math.acos(math.clamp(1 - tol / max(r, 1e-9), -1, 1))
local n = max(1, min(256, ceil(abs(da) / max(step, 0.01))))
for i = 0, n do
local t = a0 + da * i / n
table.insert(pts, cx + r * math.cos(t))
table.insert(pts, cy + r * math.sin(t))
end
end
-- stroke(path, opts?) -> Path: the outline of the stroke as pieces to fill with the nonzero rule (in the path's own
-- coordinate space: transform it like the path). Dashes are the caller's job (split the path first).
function Raster.stroke(path: any, opts: StrokeOptions?): Path
local o: StrokeOptions = opts or {}
local hw = (if type(o.width) == "number" and o.width > 0 then o.width else 1) / 2
local join = o.join or "miter"
local cap = o.cap or "butt"
local miterLimit = if type(o.miterLimit) == "number" and o.miterLimit >= 1 then o.miterLimit else 4
local tol = if type(o.tolerance) == "number" and o.tolerance > 0.0005 then o.tolerance else 0.1
local out: Path = {}
local cmds = commands(path)
if not cmds then
return out
end
-- subpaths with their closed flag (flatten loses it, so split here)
local subs: { { cmds: Path, closed: boolean } } = {}
local cur: Path? = nil
local lx, ly = 0, 0
for _, c in cmds do
local op = if type(c) == "table" then c.op else nil
if op == "moveTo" and operands(c, 2) then
cur = { c }
table.insert(subs, { cmds = cur :: Path, closed = o.closed == true })
lx, ly = c[1], c[2]
elseif op == "close" then
if cur then
subs[#subs].closed = true
cur = nil
end
elseif op == "lineTo" or op == "quadTo" or op == "cubicTo" then
if not cur then
cur = { { op = "moveTo", lx, ly } }
table.insert(subs, { cmds = cur :: Path, closed = o.closed == true })
end
table.insert(cur :: Path, c)
end
end
for _, sub in subs do
local polys = flatten(sub.cmds, nil, tol, 4)
local pts = polys[1]
if not pts then
-- a degenerate subpath (a single point): round / square caps draw a dot
local m = sub.cmds[1]
if #sub.cmds >= 1 and operands(m, 2) and cap ~= "butt" then
local d = {}
if cap == "round" then
arcPoints(m[1], m[2], hw, 0, 2 * math.pi, tol, d)
else
d = { m[1] - hw, m[2] - hw, m[1] + hw, m[2] - hw, m[1] + hw, m[2] + hw, m[1] - hw, m[2] + hw }
end
polygon(out, d)
end
continue
end
-- drop repeated points
local p: { number } = { pts[1], pts[2] }
for i = 3, #pts - 1, 2 do
if abs(pts[i] - p[#p - 1]) > 1e-9 or abs(pts[i + 1] - p[#p]) > 1e-9 then
table.insert(p, pts[i])
table.insert(p, pts[i + 1])
end
end
local closed = sub.closed
if closed and #p >= 4 and abs(p[1] - p[#p - 1]) < 1e-9 and abs(p[2] - p[#p]) < 1e-9 then
table.remove(p)
table.remove(p)
end
local n = #p // 2
if n < 2 then
continue
end
local segs = if closed then n else n - 1
-- segment bodies
local dirs: { number } = {}
for s = 0, segs - 1 do
local i, j = s, (s + 1) % n
local x0, y0, x1, y1 = p[2 * i + 1], p[2 * i + 2], p[2 * j + 1], p[2 * j + 2]
local dx, dy = x1 - x0, y1 - y0
local len = sqrt(dx * dx + dy * dy)
local ux, uy = dx / len, dy / len
dirs[2 * s + 1], dirs[2 * s + 2] = ux, uy
local nx, ny = -uy * hw, ux * hw
polygon(out, { x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny })
end
-- joins
local function joinAt(k: number, s0: number, s1: number)
local x, y = p[2 * k + 1], p[2 * k + 2]
local ax, ay = dirs[2 * s0 + 1], dirs[2 * s0 + 2]
local bx, by = dirs[2 * s1 + 1], dirs[2 * s1 + 2]
local cross = ax * by - ay * bx
if abs(cross) < 1e-12 and ax * bx + ay * by > 0 then
return
end
-- the outer side: left normals when turning right (cross < 0)
local sgn = if cross < 0 then 1 else -1
local n0x, n0y = -ay * hw * sgn, ax * hw * sgn
local n1x, n1y = -by * hw * sgn, bx * hw * sgn
if join == "round" then
local d = { x, y }
local a0 = math.atan2(n0y, n0x)
local a1 = math.atan2(n1y, n1x)
local da = a1 - a0
while da > math.pi do
da -= 2 * math.pi
end
while da < -math.pi do
da += 2 * math.pi
end
arcPoints(x, y, hw, a0, a0 + da, tol, d)
polygon(out, d)
else
local cosT = ax * bx + ay * by -- angle between directions
local miter = if join == "miter" then 1 / sqrt(max(1e-12, (1 + cosT) / 2)) else math.huge
if join == "miter" and miter <= miterLimit then
local mx, my = n0x + n1x, n0y + n1y
local ml = sqrt(mx * mx + my * my)
if ml > 1e-12 then
local scale = hw * miter / ml
polygon(out, { x, y, x + n0x, y + n0y, x + mx * scale, y + my * scale, x + n1x, y + n1y })
return
end
end
polygon(out, { x, y, x + n0x, y + n0y, x + n1x, y + n1y })
end
end
if closed then
for k = 0, n - 1 do
joinAt(k, (k - 1) % n, k)
end
else
for k = 1, n - 2 do
joinAt(k, k - 1, k)
end
-- caps
if cap ~= "butt" then
for _, endInfo in { { 0, 0, -1 }, { n - 1, segs - 1, 1 } } do
local k, s, sgn = endInfo[1], endInfo[2], endInfo[3]
local x, y = p[2 * k + 1], p[2 * k + 2]
local ux, uy = dirs[2 * s + 1] * sgn, dirs[2 * s + 2] * sgn -- pointing outwards
local nx, ny = -uy * hw, ux * hw
if cap == "square" then
polygon(out, { x + nx, y + ny, x + nx + ux * hw, y + ny + uy * hw, x - nx + ux * hw, y - ny + uy * hw, x - nx, y - ny })
else
local d = {}
local a0 = math.atan2(ny, nx)
arcPoints(x, y, hw, a0, a0 - math.pi, tol, d)
polygon(out, d)
end
end
end
end
end
return out
end
return Raster
File diff suppressed because it is too large. Load diff
+274
View File
@@ -0,0 +1,274 @@
--!strict
--!native
--!optimize 2
-- codecs/image/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the
-- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the
-- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and
-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels
-- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the
-- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a
-- block whose taps leave it is first copied with clamped coordinates. Never throws.
local Tables = require("@formats/codecs/image/Vp8/Tables")
local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill
local readu32, writeu32 = buffer.readu32, buffer.writeu32
local rshift, band = bit32.rshift, bit32.band
local SIX, BIL = Tables.SIXTAP, Tables.BILINEAR
local Predict = {}
local BORDER = 32
Predict.BORDER = BORDER
-- the work buffer stride (codecs/image/Vp8/Decode: BPS)
local BPS = 32
local emu = bcreate(32 * 32) -- a block with its taps, edges replicated
local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional filter
-- the six-tap filter along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7). Each output reads
-- its six pixels (a sliding window of locals is no faster in Luau and stops LuaJIT's register allocator).
local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
local k = f * 6
local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6]
for _ = 1, h do
for i = so - 2, so + w - 3 do
local v = readu8(src, i) * t0 + readu8(src, i + 1) * t1 + readu8(src, i + 2) * t2 + readu8(src, i + 3) * t3
+ readu8(src, i + 4) * t4 + readu8(src, i + 5) * t5 + 64
writeu8(dst, d + i - so + 2, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7))
end
so += ss
d += ds
end
end
-- the six-tap filter along columns
local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
local k = f * 6
local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6]
local s1, s2, s3 = ss, 2 * ss, 3 * ss
for _ = 1, h do
local p = so - s2
for i = 0, w - 1 do
local q = p + i
local v = readu8(src, q) * t0 + readu8(src, q + s1) * t1 + readu8(src, q + s2) * t2 + readu8(src, q + s3) * t3
+ readu8(src, q + s2 + s2) * t4 + readu8(src, q + s2 + s3) * t5 + 64
writeu8(dst, d + i, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7))
end
so += ss
d += ds
end
end
-- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7
local function bilH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2]
for _ = 1, h do
for i = 0, w - 1 do
writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + i + 1) * t1 + 64, 7))
end
so += ss
d += ds
end
end
local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2]
for _ = 1, h do
for i = 0, w - 1 do
writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + ss + i) * t1 + 64, 7))
end
so += ss
d += ds
end
end
-- block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil): predicts the w x h block at plane pixel
-- (x, y) moved by (mvx, mvy) eighth pixels into dst at d (stride BPS). base: the offset of plane pixel (0, 0); wmax,
-- hmax: the last pixel column / row of the (macroblock aligned) plane.
local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean)
local fx, fy = band(mvx, 7), band(mvy, 7)
local px, py = x + (mvx - fx) // 8, y + (mvy - fy) // 8
local sb, so, ss = src, 0, stride
if px >= 2 - BORDER and py >= 2 - BORDER and px + w + 3 <= wmax + 1 + BORDER and py + h + 3 <= hmax + 1 + BORDER then
so = base + py * stride + px
else
for r = 0, h + 4 do
local sy = py - 2 + r
if sy < 0 then
sy = 0
elseif sy > hmax then
sy = hmax
end
local row = base + sy * stride
local o = r * 32
for c = 0, w + 4 do
local sx = px - 2 + c
if sx < 0 then
sx = 0
elseif sx > wmax then
sx = wmax
end
writeu8(emu, o + c, readu8(src, row + sx))
end
end
sb, so, ss = emu, 66, 32
end
if fx == 0 then
if fy == 0 then
for _ = 1, h do
for i = 0, w - 4, 4 do
writeu32(dst, d + i, readu32(sb, so + i))
end
so += ss
d += BPS
end
elseif bil then
bilV(sb, so, ss, dst, d, BPS, w, h, fy)
else
sixV(sb, so, ss, dst, d, BPS, w, h, fy)
end
elseif fy == 0 then
if bil then
bilH(sb, so, ss, dst, d, BPS, w, h, fx)
else
sixH(sb, so, ss, dst, d, BPS, w, h, fx)
end
elseif bil then
bilH(sb, so, ss, tmp, 0, 32, w, h + 1, fx)
bilV(tmp, 0, 32, dst, d, BPS, w, h, fy)
else
sixH(sb, so - 2 * ss, ss, tmp, 0, 32, w, h + 5, fx)
sixV(tmp, 64, 32, dst, d, BPS, w, h, fy)
end
end
local function chroma16(v: number): number
-- the chroma vector of a whole macroblock: half the luma one, rounded away from zero
if v < 0 then
return -((1 - v) // 2)
end
return (v + 1) // 2
end
local function chroma4(s: number): number
-- the chroma vector of a 2x2 group of luma blocks: the sum of their 4 vectors / 8, rounded half away from zero
if s < 0 then
return -((4 - s) // 8)
end
return (s + 4) // 8
end
export type Planes = {
Y: buffer,
U: buffer,
V: buffer,
ys: number, -- luma stride
uvs: number, -- chroma stride
yb: number, -- offset of luma pixel (0, 0)
uvb: number,
mbw: number,
mbh: number,
}
-- mb(ref, mbx, mby, mvr, mvc, split, subR, subC, sb, dst, yo, uo, vo, bil, full): the prediction of one inter
-- macroblock into the work buffer (luma at yo, chroma at uo / vo). Not split: one vector (mvr, mvc) in eighth pixels;
-- split: the 16 block vectors subR / subC[sb + 1 .. sb + 16] (part < 3: the four 8x8 quarters share them).
function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean)
local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb
local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1
local wc, hc = ref.mbw * 8 - 1, ref.mbh * 8 - 1
local x, y = mbx * 16, mby * 16
local cx, cy = mbx * 8, mby * 8
if part < 0 then
block(Y, ys, yb, wl, hl, x, y, mvc, mvr, 16, 16, dst, yo, bil)
local cr, cc = chroma16(mvr), chroma16(mvc)
if full then
cr -= band(cr, 7)
cc -= band(cc, 7)
end
block(U, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, uo, bil)
block(V, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, vo, bil)
return
end
if part < 3 then
for q = 0, 3 do
local bx, by = (q % 2) * 8, (q // 2) * 8
local k = sb + by + bx // 4 + 1
block(Y, ys, yb, wl, hl, x + bx, y + by, subC[k], subR[k], 8, 8, dst, yo + by * BPS + bx, bil)
end
else
for b = 0, 15, 2 do
local k = sb + b + 1
local bx, by = (b % 4) * 4, (b // 4) * 4
local r0, c0 = subR[k], subC[k]
if r0 == subR[k + 1] and c0 == subC[k + 1] then
block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 8, 4, dst, yo + by * BPS + bx, bil)
else
block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 4, 4, dst, yo + by * BPS + bx, bil)
block(Y, ys, yb, wl, hl, x + bx + 4, y + by, subC[k + 1], subR[k + 1], 4, 4, dst, yo + by * BPS + bx + 4, bil)
end
end
end
for i = 0, 1 do
local rr, rc = 0, 0
for j = 0, 1 do
local k = sb + i * 8 + j * 2 + 1
local cr = chroma4(subR[k] + subR[k + 1] + subR[k + 4] + subR[k + 5])
local cc = chroma4(subC[k] + subC[k + 1] + subC[k + 4] + subC[k + 5])
if full then
cr -= band(cr, 7)
cc -= band(cc, 7)
end
if j == 0 then
rr, rc = cr, cc
elseif cr == rr and cc == rc then
-- both 4x4 chroma blocks of the row share one vector: one 8x4 block
block(U, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, uo + i * 4 * BPS, bil)
block(V, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, vo + i * 4 * BPS, bil)
else
block(U, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, uo + i * 4 * BPS, bil)
block(V, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, vo + i * 4 * BPS, bil)
block(U, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, uo + i * 4 * BPS + 4, bil)
block(V, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, vo + i * 4 * BPS + 4, bil)
end
end
end
end
-- row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full): predicts the
-- inter macroblocks of a row (ref[mbx + 1] > 0: refs[ref]) into pred, macroblock mbx at mbx * chunk + yo / uo / vo;
-- mi0 + mbx + 1: the mode info index of macroblock mbx. A loop of its own (LuaJIT traces it apart from the decoder).
function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }, part: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, miSubC: { number }, mi0: number, pred: buffer, chunk: number, yo: number, uo: number, vo: number, bil: boolean, full: boolean)
for mbx = 0, mbw - 1 do
local rf = ref[mbx + 1]
if rf > 0 then
local mi = mi0 + mbx + 1
local o = mbx * chunk
Predict.mb(refs[rf], mbx, mby, miMvR[mi], miMvC[mi], part[mbx + 1], miSubR, miSubC, (mi - 1) * 16, pred, o + yo, o + uo, o + vo, bil, full)
end
end
end
-- extend(P, stride, base, w, h): fills the BORDER pixels around a w x h plane with its edge pixels
local function extend(P: buffer, stride: number, base: number, w: number, h: number)
for r = 0, h - 1 do
local o = base + r * stride
bfill(P, o - BORDER, readu8(P, o), BORDER)
bfill(P, o + w, readu8(P, o + w - 1), BORDER)
end
local top = base - BORDER
local bottom = base + (h - 1) * stride - BORDER
for r = 1, BORDER do
bcopy(P, top - r * stride, P, top, stride)
bcopy(P, bottom + r * stride, P, bottom, stride)
end
end
function Predict.extend(ref: Planes)
extend(ref.Y, ref.ys, ref.yb, ref.mbw * 16, ref.mbh * 16)
extend(ref.U, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8)
extend(ref.V, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8)
end
return Predict
+249
View File
@@ -0,0 +1,249 @@
--!strict
-- codecs/image/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6
-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables
-- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from
-- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c;
-- BSD-3-Clause, licenses/libvpx-LICENSE.txt). Flat 1-based arrays.
local Tables = {}
-- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1
Tables.COEFF_PROBA0 = {
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128,
189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128, 106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128,
1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128, 181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128,
78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128, 1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128,
184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128, 77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128,
1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128, 170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128,
37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128, 1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128,
207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128, 102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128,
1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128, 177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128,
80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62, 131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1,
68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128, 1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128,
184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128, 81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128,
1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128, 99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128,
23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128, 1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128,
109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128, 44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128,
1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128, 94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128,
22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128, 1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128,
124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128, 35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128,
1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128, 121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128,
45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128, 1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128,
203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128, 137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128,
253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128, 175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128,
73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128, 1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128,
239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128, 155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128,
1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128, 201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128,
69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128, 1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128,
223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128, 141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128,
1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128, 190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128,
149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128,
247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128, 240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128,
1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128, 213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128,
55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255, 126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128,
61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128, 1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128,
166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128, 39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128,
1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128, 124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128,
24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128, 1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128,
149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128, 28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128,
1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128, 123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128,
20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128, 1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128,
168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128, 47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128,
1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128, 141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128,
42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
}
-- token probability update probabilities, same layout
Tables.COEFF_UPDATE_PROBA = {
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255,
223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255, 249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255,
255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255, 234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255,
239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255, 250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255,
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255,
234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255,
255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255,
247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255, 234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255,
251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255,
255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255,
248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255,
246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255,
255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255, 248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255,
253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255,
245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255,
249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
}
-- 4x4 intra mode probabilities [top 10][left 10][9]: index (top * 10 + left) * 9 + i + 1
Tables.BMODES_PROBA = {
231, 120, 48, 89, 115, 113, 120, 152, 112, 152, 179, 64, 126, 170, 118, 46, 70, 95, 175, 69, 143, 80,
85, 82, 72, 155, 103, 56, 58, 10, 171, 218, 189, 17, 13, 152, 114, 26, 17, 163, 44, 195, 21, 10,
173, 121, 24, 80, 195, 26, 62, 44, 64, 85, 144, 71, 10, 38, 171, 213, 144, 34, 26, 170, 46, 55,
19, 136, 160, 33, 206, 71, 63, 20, 8, 114, 114, 208, 12, 9, 226, 81, 40, 11, 96, 182, 84, 29,
16, 36, 134, 183, 89, 137, 98, 101, 106, 165, 148, 72, 187, 100, 130, 157, 111, 32, 75, 80, 66, 102,
167, 99, 74, 62, 40, 234, 128, 41, 53, 9, 178, 241, 141, 26, 8, 107, 74, 43, 26, 146, 73, 166,
49, 23, 157, 65, 38, 105, 160, 51, 52, 31, 115, 128, 104, 79, 12, 27, 217, 255, 87, 17, 7, 87,
68, 71, 44, 114, 51, 15, 186, 23, 47, 41, 14, 110, 182, 183, 21, 17, 194, 66, 45, 25, 102, 197,
189, 23, 18, 22, 88, 88, 147, 150, 42, 46, 45, 196, 205, 43, 97, 183, 117, 85, 38, 35, 179, 61,
39, 53, 200, 87, 26, 21, 43, 232, 171, 56, 34, 51, 104, 114, 102, 29, 93, 77, 39, 28, 85, 171,
58, 165, 90, 98, 64, 34, 22, 116, 206, 23, 34, 43, 166, 73, 107, 54, 32, 26, 51, 1, 81, 43,
31, 68, 25, 106, 22, 64, 171, 36, 225, 114, 34, 19, 21, 102, 132, 188, 16, 76, 124, 62, 18, 78,
95, 85, 57, 50, 48, 51, 193, 101, 35, 159, 215, 111, 89, 46, 111, 60, 148, 31, 172, 219, 228, 21,
18, 111, 112, 113, 77, 85, 179, 255, 38, 120, 114, 40, 42, 1, 196, 245, 209, 10, 25, 109, 88, 43,
29, 140, 166, 213, 37, 43, 154, 61, 63, 30, 155, 67, 45, 68, 1, 209, 100, 80, 8, 43, 154, 1,
51, 26, 71, 142, 78, 78, 16, 255, 128, 34, 197, 171, 41, 40, 5, 102, 211, 183, 4, 1, 221, 51,
50, 17, 168, 209, 192, 23, 25, 82, 138, 31, 36, 171, 27, 166, 38, 44, 229, 67, 87, 58, 169, 82,
115, 26, 59, 179, 63, 59, 90, 180, 59, 166, 93, 73, 154, 40, 40, 21, 116, 143, 209, 34, 39, 175,
47, 15, 16, 183, 34, 223, 49, 45, 183, 46, 17, 33, 183, 6, 98, 15, 32, 183, 57, 46, 22, 24,
128, 1, 54, 17, 37, 65, 32, 73, 115, 28, 128, 23, 128, 205, 40, 3, 9, 115, 51, 192, 18, 6,
223, 87, 37, 9, 115, 59, 77, 64, 21, 47, 104, 55, 44, 218, 9, 54, 53, 130, 226, 64, 90, 70,
205, 40, 41, 23, 26, 57, 54, 57, 112, 184, 5, 41, 38, 166, 213, 30, 34, 26, 133, 152, 116, 10,
32, 134, 39, 19, 53, 221, 26, 114, 32, 73, 255, 31, 9, 65, 234, 2, 15, 1, 118, 73, 75, 32,
12, 51, 192, 255, 160, 43, 51, 88, 31, 35, 67, 102, 85, 55, 186, 85, 56, 21, 23, 111, 59, 205,
45, 37, 192, 55, 38, 70, 124, 73, 102, 1, 34, 98, 125, 98, 42, 88, 104, 85, 117, 175, 82, 95,
84, 53, 89, 128, 100, 113, 101, 45, 75, 79, 123, 47, 51, 128, 81, 171, 1, 57, 17, 5, 71, 102,
57, 53, 41, 49, 38, 33, 13, 121, 57, 73, 26, 1, 85, 41, 10, 67, 138, 77, 110, 90, 47, 114,
115, 21, 2, 10, 102, 255, 166, 23, 6, 101, 29, 16, 10, 85, 128, 101, 196, 26, 57, 18, 10, 102,
102, 213, 34, 20, 43, 117, 20, 15, 36, 163, 128, 68, 1, 26, 102, 61, 71, 37, 34, 53, 31, 243,
192, 69, 60, 71, 38, 73, 119, 28, 222, 37, 68, 45, 128, 34, 1, 47, 11, 245, 171, 62, 17, 19,
70, 146, 85, 55, 62, 70, 37, 43, 37, 154, 100, 163, 85, 160, 1, 63, 9, 92, 136, 28, 64, 32,
201, 85, 75, 15, 9, 9, 64, 255, 184, 119, 16, 86, 6, 28, 5, 64, 255, 25, 248, 1, 56, 8,
17, 132, 137, 255, 55, 116, 128, 58, 15, 20, 82, 135, 57, 26, 121, 40, 164, 50, 31, 137, 154, 133,
25, 35, 218, 51, 103, 44, 131, 131, 123, 31, 6, 158, 86, 40, 64, 135, 148, 224, 45, 183, 128, 22,
26, 17, 131, 240, 154, 14, 1, 209, 45, 16, 21, 91, 64, 222, 7, 1, 197, 56, 21, 39, 155, 60,
138, 23, 102, 213, 83, 12, 13, 54, 192, 255, 68, 47, 28, 85, 26, 85, 85, 128, 128, 32, 146, 171,
18, 11, 7, 63, 144, 171, 4, 4, 246, 35, 27, 10, 146, 174, 171, 12, 26, 128, 190, 80, 35, 99,
180, 80, 126, 54, 45, 85, 126, 47, 87, 176, 51, 41, 20, 32, 101, 75, 128, 139, 118, 146, 116, 128,
85, 56, 41, 15, 176, 236, 85, 37, 9, 62, 71, 30, 17, 119, 118, 255, 17, 18, 138, 101, 38, 60,
138, 55, 70, 43, 26, 142, 146, 36, 19, 30, 171, 255, 97, 27, 20, 138, 45, 61, 62, 219, 1, 81,
188, 64, 32, 41, 20, 117, 151, 142, 20, 21, 163, 112, 19, 12, 61, 195, 128, 48, 4, 24,
}
-- DC dequantization factors, index q + 1 (q 0..127)
Tables.DC_TABLE = {
4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21,
22, 22, 23, 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89, 91, 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114,
116, 118, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157,
}
-- AC dequantization factors, index q + 1
Tables.AC_TABLE = {
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80,
82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128,
131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201,
205, 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284,
}
-- coefficient band of each position (with a sentinel for position 16)
Tables.BANDS = { 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0 }
-- zigzag scan: coefficient n goes to position ZIGZAG[n + 1]
Tables.ZIGZAG = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 }
-- extra bits probabilities for the DCT_CAT3..6 tokens
Tables.CAT3 = { 173, 148, 140 }
Tables.CAT4 = { 176, 155, 140, 135 }
Tables.CAT5 = { 180, 157, 141, 134, 130 }
Tables.CAT6 = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 }
-- inter frames: default intra mode probabilities (16x16 / chroma, kept in the frame context) and the fixed 4x4 ones
Tables.YMODE_PROB = { 112, 86, 140, 37 }
Tables.UVMODE_PROB = { 162, 101, 204 }
Tables.BMODE_PROB = { 120, 90, 79, 133, 87, 85, 80, 111, 151 }
-- motion vector probabilities, row then column (19 each): is short, sign, short tree (7), long bits (10)
Tables.MV_DEFAULT = {
162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254,
164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, 254,
}
Tables.MV_UPDATE = {
237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254,
231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254,
}
-- mode contexts [count 0..5][tree node 0..3]: index count * 4 + node + 1
Tables.MODE_CONTEXTS = {
7, 1, 1, 143,
14, 18, 14, 107,
135, 64, 57, 68,
60, 56, 128, 65,
159, 134, 128, 34,
234, 188, 128, 28,
}
-- sub-block motion vector reference probabilities [(above zero << 2) | (left zero << 1) | (left == above)][3]
Tables.SUB_MV_REF_PROB = {
147, 136, 18,
223, 1, 34,
106, 145, 1,
208, 1, 1,
179, 121, 1,
223, 1, 34,
179, 121, 1,
208, 1, 1,
}
-- split partitions (16x8, 8x16, 8x8, 4x4): the first block of each partition [s * 16 + j + 1], the blocks of each
-- partition in order [s * 16 + j * count + i + 1], and the number of blocks per partition
Tables.SPLIT_OFFSET = {
0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
}
Tables.SPLIT_FILL = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15,
0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
}
Tables.SPLIT_COUNT = { 8, 8, 4, 1 }
-- the six-tap sub-pixel filters [fraction 0..7][tap 0..5] and the bilinear ones [fraction][2] (versions 1-3)
Tables.SIXTAP = {
0, 0, 128, 0, 0, 0,
0, -6, 123, 12, -1, 0,
2, -11, 108, 36, -8, 1,
0, -9, 93, 50, -6, 0,
3, -16, 77, 77, -16, 3,
0, -6, 50, 93, -9, 0,
1, -8, 36, 108, -11, 2,
0, -1, 12, 123, -6, 0,
}
Tables.BILINEAR = { 128, 0, 112, 16, 96, 32, 80, 48, 64, 64, 48, 80, 32, 96, 16, 112 }
return Tables
+123
View File
@@ -0,0 +1,123 @@
--!strict
--!native
--!optimize 2
-- codecs/image/Vp8/Yuv: 4:2:0 Y'CbCr (BT.601, limited range) to rgba8 the way libwebp's decoder does it, bit-exact: the
-- 14-bit fixed-point VP8YuvToRgb of src/dsp/yuv.h, with either the "fancy" upsampler (src/dsp/upsampling.c: a 9-3-3-1
-- bilinear filter on the chroma, libwebp's default) or point sampling (dwebp -nofancy). A port of libwebp 1.6
-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt).
local rshift = bit32.rshift
local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
local bcreate = buffer.create
local Yuv = {}
local function clip(v: number): number
-- VP8Clip8: v in 14-bit fixed point
if v >= 0 and v < 16384 then
return rshift(v, 6)
end
return if v < 0 then 0 else 255
end
-- (v * coeff) >> 8 for non-negative v
local function mulHi(v: number, c: number): number
return rshift(v * c, 8)
end
-- rgba(y, u, v) -> the pixel as a little-endian u32 (bytes R G B 255)
local function rgba(y: number, u: number, v: number): number
local yy = mulHi(y, 19077)
local r = clip(yy + mulHi(v, 26149) - 14234)
local g = clip(yy - mulHi(u, 6419) - mulHi(v, 13320) + 8708)
local b = clip(yy + mulHi(u, 33050) - 17685)
return r + g * 256 + b * 65536 + 0xff000000
end
Yuv.rgba = rgba
-- upsamplePair: libwebp UPSAMPLE_FUNC for one or two output rows. ty / by: offsets of the top / bottom luma rows
-- (by < 0: no bottom row), tu / cu: offsets of the top / current chroma rows; dt / db: output row offsets.
local function upsamplePair(Y: buffer, U: buffer, V: buffer, ty: number, by: number, tu: number, cu: number, out: buffer, dt: number, db: number, len: number)
local last = rshift(len - 1, 1)
local tlu, tlv = readu8(U, tu), readu8(V, tu)
local lu, lv = readu8(U, cu), readu8(V, cu)
do
local u0 = rshift(3 * tlu + lu + 2, 2)
local v0 = rshift(3 * tlv + lv + 2, 2)
writeu32(out, dt, rgba(readu8(Y, ty), u0, v0))
end
if by >= 0 then
local u0 = rshift(3 * lu + tlu + 2, 2)
local v0 = rshift(3 * lv + tlv + 2, 2)
writeu32(out, db, rgba(readu8(Y, by), u0, v0))
end
for x = 1, last do
local tu1, tv1 = readu8(U, tu + x), readu8(V, tu + x)
local u1, v1 = readu8(U, cu + x), readu8(V, cu + x)
local avgU = tlu + tu1 + lu + u1 + 8
local avgV = tlv + tv1 + lv + v1 + 8
local d12u = rshift(avgU + 2 * (tu1 + lu), 3)
local d03u = rshift(avgU + 2 * (tlu + u1), 3)
local d12v = rshift(avgV + 2 * (tv1 + lv), 3)
local d03v = rshift(avgV + 2 * (tlv + v1), 3)
local px = 2 * x
writeu32(out, dt + (px - 1) * 4, rgba(readu8(Y, ty + px - 1), rshift(d12u + tlu, 1), rshift(d12v + tlv, 1)))
writeu32(out, dt + px * 4, rgba(readu8(Y, ty + px), rshift(d03u + tu1, 1), rshift(d03v + tv1, 1)))
if by >= 0 then
writeu32(out, db + (px - 1) * 4, rgba(readu8(Y, by + px - 1), rshift(d03u + lu, 1), rshift(d03v + lv, 1)))
writeu32(out, db + px * 4, rgba(readu8(Y, by + px), rshift(d12u + u1, 1), rshift(d12v + v1, 1)))
end
tlu, tlv, lu, lv = tu1, tv1, u1, v1
end
if len % 2 == 0 then
local u0 = rshift(3 * tlu + lu + 2, 2)
local v0 = rshift(3 * tlv + lv + 2, 2)
writeu32(out, dt + (len - 1) * 4, rgba(readu8(Y, ty + len - 1), u0, v0))
if by >= 0 then
u0 = rshift(3 * lu + tlu + 2, 2)
v0 = rshift(3 * lv + tlv + 2, 2)
writeu32(out, db + (len - 1) * 4, rgba(readu8(Y, by + len - 1), u0, v0))
end
end
end
-- toRgba(y, u, v, w, h, fancy, out?) -> rgba8 (alpha 255). Planes are tightly packed (chroma ceil(w / 2) wide).
function Yuv.toRgba(Y: buffer, U: buffer, V: buffer, w: number, h: number, fancy: boolean, out: buffer?): buffer
local o = out or bcreate(w * h * 4)
local cw = (w + 1) // 2
local stride = w * 4
if fancy then
-- libwebp EmitFancyRGB over the whole picture: row 0 alone (chroma mirrored), then pairs of rows between two
-- chroma rows, then the last row of an even height alone
upsamplePair(Y, U, V, 0, -1, 0, 0, o, 0, -1, w)
local y = 1
local cu = 0
while y + 1 < h do
upsamplePair(Y, U, V, y * w, (y + 1) * w, cu, cu + cw, o, y * stride, (y + 1) * stride, w)
cu += cw
y += 2
end
if h % 2 == 0 and h > 1 then
upsamplePair(Y, U, V, (h - 1) * w, -1, cu, cu, o, (h - 1) * stride, -1, w)
end
else
for y = 0, h - 1 do
local cu = (y // 2) * cw
local yo = y * w
local oo = y * stride
for x = 0, w - 1 do
local c = cu + x // 2
writeu32(o, oo + x * 4, rgba(readu8(Y, yo + x), readu8(U, c), readu8(V, c)))
end
end
end
return o
end
-- setAlpha(rgba, a8, n): copy an alpha plane into the A bytes
function Yuv.setAlpha(o: buffer, a: buffer, n: number)
for i = 0, n - 1 do
writeu8(o, i * 4 + 3, readu8(a, i))
end
end
return Yuv
+158
View File
@@ -0,0 +1,158 @@
--!strict
-- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
-- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause,
-- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals
-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause,
-- licenses/libvpx-LICENSE.txt), bit-exact with libvpx / ffmpeg on the official test vectors and libvpx streams.
-- Supports: key and inter frames of every version / profile (0: six-tap filters, normal loop filter; 1-2: bilinear;
-- 3: bilinear with full pixel chroma; the loop filter type is the header's), last / golden / altref references with
-- sign bias, hidden (altref) frames, token partitions, segments, loop filter deltas, probability context save /
-- restore. Not supported: the horizontal / vertical scale bits (ignored, as libwebp and ffmpeg do), error
-- concealment (a damaged frame returns an Err).
-- Speed (one Zen 5 core): 640x480 inter frames ~190 fps under luau --codegen, ~220 fps under LuaJIT with the trace
-- limits the host module sets (maxtrace=8000; with LuaJIT's default 1000 traces the decoder thrashes: ~70 fps).
--
-- local Vp8 = require("@formats/codecs/image/Vp8")
-- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image
-- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling)
-- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames
-- local img, err = dec:decodeFrame(buf, off, len) -- img.meta.source.show == false: a hidden frame
-- dec:reset() -- after a seek: the next frame must be a key frame
--
-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG).
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Decode = require("@formats/codecs/image/Vp8/Decode")
local Yuv = require("@formats/codecs/image/Vp8/Yuv")
local Vp8 = {}
local DEFAULT_MAX_PIXELS = 2 ^ 28
export type Options = {
maxPixels: number?, -- default 2^28
}
local function fail(msg: string?, offset: number?): Err.Err
local m = msg or "bad data"
if string.sub(m, 1, 11) == "truncated: " then
return Err.new(Err.TRUNCATED, string.sub(m, 12), offset)
elseif string.sub(m, 1, 7) == "limit: " then
return Err.new(Err.LIMIT, string.sub(m, 8), offset)
elseif string.sub(m, 1, 13) == "unsupported: " then
return Err.new(Err.UNSUPPORTED, string.sub(m, 14), offset)
end
return Err.new(Err.CORRUPT, m, offset)
end
local function range(buf: buffer, off: number?, len: number?): (number, number)
local n = buffer.len(buf)
local o = math.clamp(off or 0, 0, n)
return o, math.clamp(len or (n - o), 0, n - o)
end
-- info(buf, off?, len?) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, Err
function Vp8.info(buf: buffer, off: number?, len: number?): (any, Err.Err?)
if type(buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "info: expected a buffer")
end
local o, l = range(buf, off, len)
local h, err = Decode.header(buf, o, l)
if not h then
return nil, fail(err, o)
end
return h, nil
end
local DecoderMeta = {}
DecoderMeta.__index = DecoderMeta
export type Decoder = typeof(setmetatable({} :: { state: Decode.State }, DecoderMeta))
-- newDecoder() -> Decoder: decodes successive frames of one stream
function Vp8.newDecoder(): Decoder
return setmetatable({ state = Decode.new() }, DecoderMeta)
end
-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image (a fresh buffer) | nil, Err. Key and inter frames;
-- meta.source = { format = "vp8", keyFrame, show (false: a hidden frame, decoded as a reference but not displayed),
-- profile, width, height }. An inter frame before the first key frame (or after reset) returns CORRUPT.
function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?)
if type(buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer")
end
local o, l = range(buf, off, len)
local f, err = Decode.decodeFrame(self.state, buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS)
if not f then
return nil, fail(err, o)
end
local img = Types.Image.new(f.width, f.height, "yuv420p")
local ny = f.width * f.height
local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2)
Decode.cropTo(f, img.pixels, 0, img.pixels, ny, img.pixels, ny + nc)
local h = f.header
img.meta.source = { format = "vp8", keyFrame = h.keyFrame, show = h.show, profile = h.profile, width = f.width, height = f.height }
return img, nil
end
-- decoder:reset(): drops the reference frames (after a seek); the next frame must be a key frame
function DecoderMeta.reset(self: Decoder)
Decode.reset(self.state)
end
-- decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err (one key frame)
function Vp8.decodeFrame(buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?)
return Vp8.newDecoder():decodeFrame(buf, off, len, opts)
end
-- decodePlanes(buf, off?, len?, opts?) -> y, u, v, width, height | nil, Err: one key frame as separate planes
function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options?): (buffer?, any, buffer?, number?, number?)
if type(buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "decodePlanes: expected a buffer")
end
local o, l = range(buf, off, len)
local f, err = Decode.decodeFrame(Decode.new(), buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS)
if not f then
return nil, fail(err, o)
end
local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2)
local y, u, v = buffer.create(f.width * f.height), buffer.create(nc), buffer.create(nc)
Decode.cropTo(f, y, 0, u, 0, v, 0)
return y, u, v, f.width, f.height
end
-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height
function Vp8.planes(img: Types.Image): (number, number, number, number, number)
local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2
local ny = img.width * img.height
return 0, ny, ny + cw * ch, cw, ch
end
-- toRgba(yuvImage, fancy?) -> rgba8 Image. fancy (default true): libwebp's bilinear chroma upsampling; false: point
-- sampling (dwebp -nofancy)
function Vp8.toRgba(img: Types.Image, fancy: boolean?): (Types.Image?, Err.Err?)
if type(img) ~= "table" or img.format ~= "yuv420p" then
return nil, Err.new(Err.ARG, "toRgba: needs a yuv420p Image")
end
local w, h = img.width, img.height
local _, uo, vo, cw, ch = Vp8.planes(img)
local y = buffer.create(w * h)
local u = buffer.create(cw * ch)
local v = buffer.create(cw * ch)
buffer.copy(y, 0, img.pixels, 0, w * h)
buffer.copy(u, 0, img.pixels, uo, cw * ch)
buffer.copy(v, 0, img.pixels, vo, cw * ch)
local out = Types.Image.new(w, h, "rgba8")
Yuv.toRgba(y, u, v, w, h, fancy ~= false, out.pixels)
out.meta.source = img.meta.source
return out, nil
end
-- yuvToRgba(y, u, v, w, h, fancy?) -> rgba8 pixels from separate planes (alpha 255)
function Vp8.yuvToRgba(y: buffer, u: buffer, v: buffer, w: number, h: number, fancy: boolean?): buffer
return Yuv.toRgba(y, u, v, w, h, fancy ~= false)
end
Vp8.setAlpha = Yuv.setAlpha
return Vp8
+873
View File
@@ -0,0 +1,873 @@
--!strict
--!native
--!optimize 2
-- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes,
-- LZ77 backward references with the 2-D distance map, the colour cache, and the four inverse transforms (predictor,
-- cross colour, subtract green, colour indexing with pixel bundling). A port of libwebp 1.6 src/dec/vp8l_dec.c,
-- src/utils/huffman_utils.c and src/dsp/lossless.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); bit-exact with it.
--
-- Pixels are ARGB u32 values (0xAARRGGBB) in a buffer, 4 bytes each, rows top to bottom. Never throws: every
-- function returns nil, "message" (prefixed "truncated: " when the data ends early) on bad data.
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
local Decode = {}
local ROOT_BITS = 8
local MAX_LEN = 15
local NUM_LITERAL = 256
local NUM_LENGTH = 24
local NUM_DISTANCE = 40
local MAX_CACHE_BITS = 11
local ARGB_BLACK = 0xff000000
local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
local CODE_TO_PLANE = {
0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36,
0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34,
0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67,
0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79,
0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52,
0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61,
0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70,
}
-- distance map (x offset 8 - (v & 15), y offset v >> 4) as a plain distance for a row width: done per image
Decode.CODE_TO_PLANE = CODE_TO_PLANE
-- ------------------------------------------------------------------------------------------------ bit reader
-- LSB-first; bytes past the end read as zero and are counted in `over`: the stream is overrun when fewer bits are
-- left in the buffer than phantom bits were added (bitcnt < over * 8).
export type State = {
buf: buffer,
pos: number,
limit: number,
bitbuf: number,
bitcnt: number,
over: number,
-- prefix code tables (u32 entries value * 32 + bits), shared by every group of every level
tab: buffer,
tabUsed: number,
maxPixels: number,
}
local function fill(d: State)
local bitbuf, bitcnt = d.bitbuf, d.bitcnt
while bitcnt <= 24 do
local p = d.pos
local b = 0
if p < d.limit then
b = readu8(d.buf, p)
d.pos = p + 1
else
d.over += 1
end
bitbuf += lshift(b, bitcnt)
bitcnt += 8
end
d.bitbuf, d.bitcnt = bitbuf, bitcnt
end
-- readBits(d, n) n <= 24
local function readBits(d: State, n: number): number
if d.bitcnt < n then
fill(d)
end
local v = band(d.bitbuf, lshift(1, n) - 1)
d.bitbuf = rshift(d.bitbuf, n)
d.bitcnt -= n
return v
end
local function eos(d: State): boolean
return d.bitcnt < d.over * 8
end
-- ------------------------------------------------------------------------------------------------ prefix codes
local count = table.create(MAX_LEN + 1, 0)
local offset = table.create(MAX_LEN + 2, 0)
local function ensure(d: State, n: number)
local cap = blen(d.tab) // 4
if d.tabUsed + n > cap then
local nb = bcreate(math.max(cap * 2, d.tabUsed + n) * 4)
bcopy(nb, 0, d.tab, 0, d.tabUsed * 4)
d.tab = nb
end
end
local function replicate(tab: buffer, at: number, step: number, size: number, entry: number)
local e = size
repeat
e -= step
writeu32(tab, (at + e) * 4, entry)
until e <= 0
end
local function nextKey(key: number, len: number): number
local step = lshift(1, len - 1)
while band(key, step) ~= 0 do
step = rshift(step, 1)
end
return if step ~= 0 then band(key, step - 1) + step else key
end
-- build(d, lens (0-based Lua array), n) -> table offset in d.tab, or -1 for an invalid code set (libwebp
-- BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits)
local sorted = table.create(2400, 0)
local function build(d: State, lens: { number }, n: number): number
for l = 0, MAX_LEN do
count[l + 1] = 0
end
for s = 0, n - 1 do
local l = lens[s + 1]
if l > MAX_LEN then
return -1
end
count[l + 1] += 1
end
if count[1] == n then
return -1
end
offset[2] = 0
for len = 1, MAX_LEN - 1 do
if count[len + 1] > lshift(1, len) then
return -1
end
offset[len + 2] = offset[len + 1] + count[len + 1]
end
for s = 0, n - 1 do
local l = lens[s + 1]
if l > 0 then
sorted[offset[l + 1] + 1] = s
offset[l + 1] += 1
end
end
local long = 0
for len = ROOT_BITS + 1, MAX_LEN do
long += count[len + 1]
end
ensure(d, lshift(1, ROOT_BITS) + long * lshift(1, MAX_LEN - ROOT_BITS))
local tab = d.tab
local root = d.tabUsed
local totalSize = lshift(1, ROOT_BITS)
if offset[MAX_LEN + 1] == 1 then
replicate(tab, root, 1, totalSize, sorted[1] * 32)
d.tabUsed = root + totalSize
return root
end
local key = 0
local numNodes, numOpen = 1, 1
local tableBits = ROOT_BITS
local tableSize = lshift(1, tableBits)
local tableAt = root
local low = -1
local mask = totalSize - 1
local symbol = 1
local step = 2
for len = 1, ROOT_BITS do
numOpen *= 2
numNodes += numOpen
numOpen -= count[len + 1]
if numOpen < 0 then
return -1
end
while count[len + 1] > 0 do
replicate(tab, root + key, step, tableSize, sorted[symbol] * 32 + len)
symbol += 1
key = nextKey(key, len)
count[len + 1] -= 1
end
step *= 2
end
step = 2
for len = ROOT_BITS + 1, MAX_LEN do
numOpen *= 2
numNodes += numOpen
numOpen -= count[len + 1]
if numOpen < 0 then
return -1
end
while count[len + 1] > 0 do
if band(key, mask) ~= low then
tableAt += tableSize
-- NextTableBitSize
local l2 = len
local left = lshift(1, l2 - ROOT_BITS)
while l2 < MAX_LEN do
left -= count[l2 + 1]
if left <= 0 then
break
end
l2 += 1
left *= 2
end
tableBits = l2 - ROOT_BITS
tableSize = lshift(1, tableBits)
totalSize += tableSize
low = band(key, mask)
writeu32(tab, (root + low) * 4, (tableAt - root - low) * 32 + tableBits + ROOT_BITS)
end
replicate(tab, tableAt + rshift(key, ROOT_BITS), step, tableSize, sorted[symbol] * 32 + len - ROOT_BITS)
symbol += 1
key = nextKey(key, len)
count[len + 1] -= 1
end
step *= 2
end
if numNodes ~= 2 * offset[MAX_LEN + 1] - 1 then
return -1
end
d.tabUsed = root + totalSize
return root
end
-- readSymbol(d, at) -> symbol (the reader is refilled to >= 15 bits first)
local function readSymbol(d: State, at: number): number
if d.bitcnt < MAX_LEN then
fill(d)
end
local tab = d.tab
local bitbuf = d.bitbuf
local idx = at + band(bitbuf, 255)
local e = readu32(tab, idx * 4)
local nb = band(e, 31)
if nb > ROOT_BITS then
bitbuf = rshift(bitbuf, ROOT_BITS)
d.bitcnt -= ROOT_BITS
e = readu32(tab, (idx + rshift(e, 5) + band(bitbuf, lshift(1, nb - ROOT_BITS) - 1)) * 4)
nb = band(e, 31)
end
d.bitbuf = rshift(bitbuf, nb)
d.bitcnt -= nb
return rshift(e, 5)
end
local codeLengths = table.create(2400, 0)
local clLens = table.create(19, 0)
-- readCode(d, alphabetSize) -> table offset, or -1
local function readCode(d: State, size: number): number
for i = 1, size do
codeLengths[i] = 0
end
if readBits(d, 1) == 1 then
local numSymbols = readBits(d, 1) + 1
local first = readBits(d, 1)
local s = readBits(d, if first == 0 then 1 else 8)
if s < size then
codeLengths[s + 1] = 1
end
if numSymbols == 2 then
s = readBits(d, 8)
if s < size then
codeLengths[s + 1] = 1
end
end
else
for i = 1, 19 do
clLens[i] = 0
end
local numCodes = readBits(d, 4) + 4
for i = 1, numCodes do
clLens[CODE_LENGTH_ORDER[i] + 1] = readBits(d, 3)
end
local mark = d.tabUsed
local clt = build(d, clLens, 19)
if clt < 0 then
return -1
end
local maxSymbol = size
if readBits(d, 1) == 1 then
local nbits = 2 + 2 * readBits(d, 3)
maxSymbol = 2 + readBits(d, nbits)
if maxSymbol > size then
return -1
end
end
local prev = 8
local s = 0
while s < size do
if maxSymbol == 0 then
break
end
maxSymbol -= 1
local cl = readSymbol(d, clt)
if cl < 16 then
codeLengths[s + 1] = cl
s += 1
if cl ~= 0 then
prev = cl
end
else
local rep, len
if cl == 16 then
rep, len = readBits(d, 2) + 3, prev
elseif cl == 17 then
rep, len = readBits(d, 3) + 3, 0
else
rep, len = readBits(d, 7) + 11, 0
end
if s + rep > size then
return -1
end
for k = s + 1, s + rep do
codeLengths[k] = len
end
s += rep
end
end
d.tabUsed = mark -- the code length table is temporary
end
if eos(d) then
return -1
end
return build(d, codeLengths, size)
end
-- ------------------------------------------------------------------------------------------------ pixel data
local function subSample(size: number, bits: number): number
return rshift(size + lshift(1, bits) - 1, bits)
end
Decode.subSample = subSample
local function cacheKey(argb: number, shift: number): number
-- (0x1e35a7bd * argb) mod 2^32 >> shift, exact in doubles
local lo = argb % 65536
local hi = (argb - lo) / 65536
local m = (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296
return rshift(m, shift)
end
Decode.cacheKey = cacheKey
-- decodeData: the entropy-coded pixels of one level into `data` (w * h u32)
local function decodeData(d: State, data: buffer, w: number, h: number, cacheBits: number, groups: { number }, himg: buffer?, hbits: number, hxs: number): (boolean, string?)
local total = w * h
local cache: buffer? = if cacheBits > 0 then bcreate(lshift(1, cacheBits) * 4) else nil
local cshift = 32 - cacheBits
local lenLimit = NUM_LITERAL + NUM_LENGTH
local cacheLimit = lenLimit + (if cacheBits > 0 then lshift(1, cacheBits) else 0)
local hmask = if himg then lshift(1, hbits) - 1 else -1
local i, col, row = 0, 0, 0
local gG, gR, gB, gA, gD = groups[1], groups[2], groups[3], groups[4], groups[5]
local function setGroup()
if himg then
local g = readu32(himg, (hxs * rshift(row, hbits) + rshift(col, hbits)) * 4) * 5
gG, gR, gB, gA, gD = groups[g + 1], groups[g + 2], groups[g + 3], groups[g + 4], groups[g + 5]
end
end
while i < total do
if band(col, hmask) == 0 then
setGroup()
end
local code = readSymbol(d, gG)
if code < NUM_LITERAL then
local r = readSymbol(d, gR)
local b = readSymbol(d, gB)
local a = readSymbol(d, gA)
if d.bitcnt < d.over * 8 then
break
end
local argb = a * 16777216 + r * 65536 + code * 256 + b
writeu32(data, i * 4, argb)
if cache then
writeu32(cache, cacheKey(argb, cshift) * 4, argb)
end
i += 1
col += 1
if col >= w then
col = 0
row += 1
end
elseif code < lenLimit then
local ls = code - NUM_LITERAL
local length
if ls < 4 then
length = ls + 1
else
local eb = rshift(ls - 2, 1)
length = lshift(2 + band(ls, 1), eb) + readBits(d, eb) + 1
end
local ds = readSymbol(d, gD)
local dc
if ds < 4 then
dc = ds + 1
else
local eb = rshift(ds - 2, 1)
dc = lshift(2 + band(ds, 1), eb) + readBits(d, eb) + 1
end
local dist
if dc > 120 then
dist = dc - 120
else
local v = CODE_TO_PLANE[dc]
dist = rshift(v, 4) * w + 8 - band(v, 15)
if dist < 1 then
dist = 1
end
end
if d.bitcnt < d.over * 8 then
break
end
if i < dist or total - i < length then
return false, "bad backward reference"
end
if dist >= length then
bcopy(data, i * 4, data, (i - dist) * 4, length * 4)
else
for k = i, i + length - 1 do
writeu32(data, k * 4, readu32(data, (k - dist) * 4))
end
end
if cache then
for k = i, i + length - 1 do
local argb = readu32(data, k * 4)
writeu32(cache, cacheKey(argb, cshift) * 4, argb)
end
end
i += length
col += length
while col >= w do
col -= w
row += 1
end
if band(col, hmask) ~= 0 then
setGroup()
end
elseif code < cacheLimit and cache then
if d.bitcnt < d.over * 8 then
break
end
local argb = readu32(cache, (code - lenLimit) * 4)
writeu32(data, i * 4, argb)
writeu32(cache, cacheKey(argb, cshift) * 4, argb)
i += 1
col += 1
if col >= w then
col = 0
row += 1
end
else
return false, "bad symbol"
end
end
if eos(d) then
return false, "truncated: pixel data"
end
return true, nil
end
-- ------------------------------------------------------------------------------------------------ transforms
local function addPixels(a: number, b: number): number
return band(band(a, 0xff00ff00) + band(b, 0xff00ff00), 0xff00ff00) + band(band(a, 0x00ff00ff) + band(b, 0x00ff00ff), 0x00ff00ff)
end
Decode.addPixels = addPixels
local function average2(a: number, b: number): number
return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b)
end
Decode.average2 = average2
local function clip255(v: number): number
return if v < 0 then 0 elseif v > 255 then 255 else v
end
local function sub3(a: number, b: number, c: number): number
local pb, pa = b - c, a - c
return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa)
end
-- select(T, L, TL)
local function select3(a: number, b: number, c: number): number
local s = sub3(rshift(a, 24), rshift(b, 24), rshift(c, 24))
+ sub3(band(rshift(a, 16), 255), band(rshift(b, 16), 255), band(rshift(c, 16), 255))
+ sub3(band(rshift(a, 8), 255), band(rshift(b, 8), 255), band(rshift(c, 8), 255))
+ sub3(band(a, 255), band(b, 255), band(c, 255))
return if s <= 0 then a else b
end
local function clampedFull(c0: number, c1: number, c2: number): number
local a = clip255(rshift(c0, 24) + rshift(c1, 24) - rshift(c2, 24))
local r = clip255(band(rshift(c0, 16), 255) + band(rshift(c1, 16), 255) - band(rshift(c2, 16), 255))
local g = clip255(band(rshift(c0, 8), 255) + band(rshift(c1, 8), 255) - band(rshift(c2, 8), 255))
local b = clip255(band(c0, 255) + band(c1, 255) - band(c2, 255))
return a * 16777216 + r * 65536 + g * 256 + b
end
local function half(a: number, b: number): number
local dd = a - b
-- C division truncates toward zero
local q = if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1)
return clip255(a + q)
end
local function clampedHalf(c0: number, c1: number, c2: number): number
local ave = average2(c0, c1)
local a = half(rshift(ave, 24), rshift(c2, 24))
local r = half(band(rshift(ave, 16), 255), band(rshift(c2, 16), 255))
local g = half(band(rshift(ave, 8), 255), band(rshift(c2, 8), 255))
local b = half(band(ave, 255), band(c2, 255))
return a * 16777216 + r * 65536 + g * 256 + b
end
-- predict(mode, L, T, TR, TL) -> the predicted pixel (libwebp VP8LPredictors; 14 and 15 are black)
local function predict(mode: number, L: number, T: number, TR: number, TL: number): number
if mode == 0 then
return ARGB_BLACK
elseif mode == 1 then
return L
elseif mode == 2 then
return T
elseif mode == 3 then
return TR
elseif mode == 4 then
return TL
elseif mode == 5 then
return average2(average2(L, TR), T)
elseif mode == 6 then
return average2(L, TL)
elseif mode == 7 then
return average2(L, T)
elseif mode == 8 then
return average2(TL, T)
elseif mode == 9 then
return average2(T, TR)
elseif mode == 10 then
return average2(average2(L, TL), average2(T, TR))
elseif mode == 11 then
return select3(T, L, TL)
elseif mode == 12 then
return clampedFull(L, T, TL)
elseif mode == 13 then
return clampedHalf(L, T, TL)
end
return ARGB_BLACK
end
Decode.predict = predict
local function inversePredictor(data: buffer, w: number, h: number, bits: number, sub: buffer)
local tw = subSample(w, bits)
-- first row: black, then L
writeu32(data, 0, addPixels(readu32(data, 0), ARGB_BLACK))
for x = 1, w - 1 do
writeu32(data, x * 4, addPixels(readu32(data, x * 4), readu32(data, (x - 1) * 4)))
end
for y = 1, h - 1 do
local row = y * w
local up = row - w
writeu32(data, row * 4, addPixels(readu32(data, row * 4), readu32(data, up * 4)))
local trow = rshift(y, bits) * tw
local x = 1
while x < w do
local mode = band(rshift(readu32(sub, (trow + rshift(x, bits)) * 4), 8), 15)
local xe = math.min(w, lshift(rshift(x, bits) + 1, bits))
local L = readu32(data, (row + x - 1) * 4)
if mode == 1 then
for k = x, xe - 1 do
L = addPixels(readu32(data, (row + k) * 4), L)
writeu32(data, (row + k) * 4, L)
end
elseif mode == 2 then
for k = x, xe - 1 do
writeu32(data, (row + k) * 4, addPixels(readu32(data, (row + k) * 4), readu32(data, (up + k) * 4)))
end
else
for k = x, xe - 1 do
local p = predict(mode, L, readu32(data, (up + k) * 4), readu32(data, (up + k + 1) * 4), readu32(data, (up + k - 1) * 4))
L = addPixels(readu32(data, (row + k) * 4), p)
writeu32(data, (row + k) * 4, L)
end
end
x = xe
end
end
end
local function sint8(v: number): number
return if v >= 128 then v - 256 else v
end
local function inverseCrossColor(data: buffer, w: number, h: number, bits: number, sub: buffer)
local tw = subSample(w, bits)
for y = 0, h - 1 do
local trow = rshift(y, bits) * tw
local x = 0
while x < w do
local m = readu32(sub, (trow + rshift(x, bits)) * 4)
local g2r = sint8(band(m, 255))
local g2b = sint8(band(rshift(m, 8), 255))
local r2b = sint8(band(rshift(m, 16), 255))
local xe = math.min(w, lshift(rshift(x, bits) + 1, bits))
for k = y * w + x, y * w + xe - 1 do
local argb = readu32(data, k * 4)
local g = sint8(band(rshift(argb, 8), 255))
local r = band(band(rshift(argb, 16), 255) + ((g2r * g) // 32), 255)
local b = band(band(argb, 255) + ((g2b * g) // 32) + ((r2b * sint8(r)) // 32), 255)
writeu32(data, k * 4, band(argb, 0xff00ff00) + r * 65536 + b)
end
x = xe
end
end
end
local function inverseSubtractGreen(data: buffer, n: number)
for k = 0, n - 1 do
local argb = readu32(data, k * 4)
local g = band(rshift(argb, 8), 255)
writeu32(data, k * 4, band(argb, 0xff00ff00) + band(band(argb, 0x00ff00ff) + g * 65537, 0x00ff00ff))
end
end
-- inverseColorIndexing(src (sw x h), w, h, bits, map (2^(8 >> bits) u32)) -> w x h
local function inverseColorIndexing(src: buffer, sw: number, w: number, h: number, bits: number, map: buffer): buffer
local out = bcreate(w * h * 4)
if bits == 0 then
for k = 0, w * h - 1 do
writeu32(out, k * 4, readu32(map, band(rshift(readu32(src, k * 4), 8), 255) * 4))
end
return out
end
local bpp = rshift(8, bits)
local cmask = lshift(1, bits) - 1
local vmask = lshift(1, bpp) - 1
for y = 0, h - 1 do
local packed = 0
local s = y * sw
local o = y * w
for x = 0, w - 1 do
if band(x, cmask) == 0 then
packed = band(rshift(readu32(src, s * 4), 8), 255)
s += 1
end
writeu32(out, (o + x) * 4, readu32(map, band(packed, vmask) * 4))
packed = rshift(packed, bpp)
end
end
return out
end
-- ------------------------------------------------------------------------------------------------ image stream
type Transform = { kind: number, xsize: number, bits: number, data: buffer? }
local decodeStream: (d: State, xs: number, ys: number, level0: boolean) -> (buffer?, string?)
-- readCodes(d, xs, ys, cacheBits, level0) -> groups (5 table offsets each), huffman image, bits, image width
local function readCodes(d: State, xs: number, ys: number, cacheBits: number, level0: boolean): ({ number }?, buffer?, number, number, string?)
local himg: buffer? = nil
local hbits, hxs = 0, 0
local numGroups = 1
local mapping: { number }? = nil
local numMax = 1
if level0 and readBits(d, 1) == 1 then
hbits = readBits(d, 3) + 2
hxs = subSample(xs, hbits)
local hys = subSample(ys, hbits)
local img, err = decodeStream(d, hxs, hys, false)
if not img then
return nil, nil, 0, 0, err
end
local n = hxs * hys
for k = 0, n - 1 do
local g = band(rshift(readu32(img, k * 4), 8), 0xffff)
writeu32(img, k * 4, g)
if g >= numMax then
numMax = g + 1
end
end
if numMax > 1000 or numMax > xs * ys then
-- remap the used groups to [0, numGroups); unused ones are read and checked but not kept
local map = table.create(numMax, -1) :: { number }
numGroups = 0
for k = 0, n - 1 do
local g = readu32(img, k * 4)
if map[g + 1] == -1 then
map[g + 1] = numGroups
numGroups += 1
end
writeu32(img, k * 4, map[g + 1])
end
mapping = map
else
numGroups = numMax
end
himg = img
end
if eos(d) then
return nil, nil, 0, 0, "truncated: meta codes"
end
local groups = table.create(numGroups * 5, 0) :: { number }
local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0
for i = 0, numMax - 1 do
local slot = if mapping then mapping[i + 1] else i
local mark = d.tabUsed
for j = 0, 4 do
local size = if j == 0 then NUM_LITERAL + NUM_LENGTH + cacheSize elseif j == 4 then NUM_DISTANCE else NUM_LITERAL
local at = readCode(d, size)
if at < 0 then
return nil, nil, 0, 0, if eos(d) then "truncated: prefix code" else "bad prefix code"
end
if slot >= 0 then
groups[slot * 5 + j + 1] = at
end
end
if slot < 0 then
d.tabUsed = mark
end
end
return groups, himg, hbits, hxs, nil
end
decodeStream = function(d: State, xs: number, ys: number, level0: boolean): (buffer?, string?)
local transforms: { Transform } = {}
local seen = 0
local txs = xs
if level0 then
while readBits(d, 1) == 1 do
local kind = readBits(d, 2)
if band(seen, lshift(1, kind)) ~= 0 then
return nil, "repeated transform"
end
seen = bor(seen, lshift(1, kind))
local t: Transform = { kind = kind, xsize = txs, bits = 0, data = nil }
if kind == 0 or kind == 1 then
t.bits = readBits(d, 3) + 2
local sub, err = decodeStream(d, subSample(txs, t.bits), subSample(ys, t.bits), false)
if not sub then
return nil, err
end
t.data = sub
elseif kind == 3 then
local num = readBits(d, 8) + 1
local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3
t.bits = bits
local pal, err = decodeStream(d, num, 1, false)
if not pal then
return nil, err
end
local final = lshift(1, rshift(8, bits))
local map = bcreate(final * 4)
local prev = 0
for k = 0, num - 1 do
prev = addPixels(readu32(pal, k * 4), prev)
writeu32(map, k * 4, prev)
end
t.data = map
txs = subSample(txs, bits)
end
table.insert(transforms, t)
if eos(d) then
return nil, "truncated: transforms"
end
end
end
local cacheBits = 0
if readBits(d, 1) == 1 then
cacheBits = readBits(d, 4)
if cacheBits < 1 or cacheBits > MAX_CACHE_BITS then
return nil, "bad colour cache size"
end
end
local mark = d.tabUsed
local groups, himg, hbits, hxs, err = readCodes(d, txs, ys, cacheBits, level0)
if not groups then
return nil, err
end
local data = bcreate(txs * ys * 4)
local ok, derr = decodeData(d, data, txs, ys, cacheBits, groups, himg, hbits, hxs)
if not ok then
return nil, derr
end
d.tabUsed = mark
-- inverse transforms, last read first
for k = #transforms, 1, -1 do
local t = transforms[k]
if t.kind == 0 then
inversePredictor(data, t.xsize, ys, t.bits, t.data :: buffer)
elseif t.kind == 1 then
inverseCrossColor(data, t.xsize, ys, t.bits, t.data :: buffer)
elseif t.kind == 2 then
inverseSubtractGreen(data, t.xsize * ys)
else
data = inverseColorIndexing(data, subSample(t.xsize, t.bits), t.xsize, ys, t.bits, t.data :: buffer)
end
end
return data, nil
end
local function newState(buf: buffer, off: number, len: number, maxPixels: number): State
return {
buf = buf,
pos = off,
limit = off + len,
bitbuf = 0,
bitcnt = 0,
over = 0,
tab = bcreate(4096 * 4),
tabUsed = 0,
maxPixels = maxPixels,
}
end
-- header(buf, off, len) -> width, height, alphaHint | nil, message
function Decode.header(buf: buffer, off: number, len: number): (number?, number, boolean, string?)
if len < 5 then
return nil, 0, false, "truncated: header"
end
if readu8(buf, off) ~= 0x2f then
return nil, 0, false, "bad VP8L signature"
end
local v = readu32(buf, off + 1)
local w = band(v, 0x3fff) + 1
local h = band(rshift(v, 14), 0x3fff) + 1
local alpha = band(rshift(v, 28), 1) == 1
if rshift(v, 29) ~= 0 then
return nil, 0, false, "bad VP8L version"
end
return w, h, alpha, nil
end
-- argb(buf, off, len, maxPixels) -> ARGB pixels, width, height, alphaHint | nil, message
function Decode.argb(buf: buffer, off: number, len: number, maxPixels: number): (buffer?, number, number, boolean, string?)
local w, h, alpha, err = Decode.header(buf, off, len)
if not w then
return nil, 0, 0, false, err
end
if w * h > maxPixels then
return nil, w, h, alpha, "limit: " .. w .. " x " .. h .. " is over maxPixels"
end
local d = newState(buf, off + 5, len - 5, maxPixels)
local data, derr = decodeStream(d, w, h, true)
if not data then
return nil, w, h, alpha, derr
end
return data, w, h, alpha, nil
end
-- stream(buf, off, len, w, h) -> ARGB pixels | nil, message: a headerless image stream (the ALPH chunk's payload)
function Decode.stream(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, string?)
local d = newState(buf, off, len, w * h)
return decodeStream(d, w, h, true)
end
-- toRgba(argb, n, out?, outOff?) -> rgba8 bytes
function Decode.toRgba(argb: buffer, n: number, out: buffer?, outOff: number?): buffer
local o = out or bcreate(n * 4)
local base = outOff or 0
for k = 0, n - 1 do
local v = readu32(argb, k * 4)
-- 0xAARRGGBB (bytes B G R A) -> bytes R G B A
writeu32(o, base + k * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536)
end
return o
end
-- green(argb, n) -> the green channel as bytes (alpha planes)
function Decode.green(argb: buffer, n: number): buffer
local o = bcreate(n)
for k = 0, n - 1 do
writeu8(o, k, band(rshift(readu32(argb, k * 4), 8), 255))
end
return o
end
return Decode
+976
View File
@@ -0,0 +1,976 @@
--!strict
--!native
--!optimize 2
-- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from the specification (RFC 9649 section 3).
-- Transforms: colour indexing with pixel bundling (<= 256 colours), else subtract green + predictor (per-tile mode
-- chosen from a residual cost) + cross colour (per-tile least-squares multipliers). Entropy coding: LZ77 with hash
-- chains, the left / up run candidates and the 2-D distance codes, a colour cache whose size is chosen by an entropy
-- estimate, one prefix code group per image, code lengths limited to 15 bits (codecs/entropy/Huffman) and run-length coded.
-- Never throws (the init module validates the arguments).
local Huffman = require("@formats/codecs/entropy/Huffman")
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
local readu32, writeu8, writeu32 = buffer.readu32, buffer.writeu8, buffer.writeu32
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
local log = math.log
local Encode = {}
local NUM_LITERAL = 256
local NUM_LENGTH = 24
local NUM_DISTANCE = 40
local MAX_LENGTH = 4096
local WINDOW = 1048576 - 120
local ARGB_BLACK = 0xff000000
local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
local CODE_TO_PLANE = {
0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36,
0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34,
0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67,
0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79,
0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52,
0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61,
0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70,
}
-- PLANE_TO_CODE[v + 1] = the distance code (1..120) of the plane offset v = yoffset * 16 + 8 - xoffset
local PLANE_TO_CODE = table.create(128, 0)
for i, v in CODE_TO_PLANE do
PLANE_TO_CODE[v + 1] = i
end
-- ------------------------------------------------------------------------------------------------ bit writer
type W = { buf: buffer, pos: number, acc: number, cnt: number }
local function newWriter(cap: number): W
return { buf = bcreate(math.max(64, cap)), pos = 0, acc = 0, cnt = 0 }
end
-- put(w, v, n): the n <= 24 low bits of v, LSB first
local function put(w: W, v: number, n: number)
local acc = w.acc + v * 2 ^ w.cnt
local cnt = w.cnt + n
if cnt >= 8 then
local pos = w.pos
local buf = w.buf
if pos + 8 > blen(buf) then
local nb = bcreate(blen(buf) * 2)
bcopy(nb, 0, buf, 0, pos)
buf = nb
w.buf = nb
end
repeat
local byte = acc % 256
writeu8(buf, pos, byte)
pos += 1
acc = (acc - byte) / 256
cnt -= 8
until cnt < 8
w.pos = pos
end
w.acc, w.cnt = acc, cnt
end
local function finish(w: W): buffer
if w.cnt > 0 then
put(w, 0, 8 - w.cnt)
end
local out = bcreate(w.pos)
bcopy(out, 0, w.buf, 0, w.pos)
return out
end
-- ------------------------------------------------------------------------------------------------ helpers
local function subSample(size: number, bits: number): number
return rshift(size + lshift(1, bits) - 1, bits)
end
-- (0x1e35a7bd * v) mod 2^32: the colour cache hash before its shift
local function mulHash(v: number): number
local lo = v % 65536
local hi = (v - lo) / 65536
return (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296
end
-- prefix(v) -> code, extra bits, extra value of a length or distance code value v >= 1
local function prefix(v: number): (number, number, number)
local d = v - 1
if d < 4 then
return d, 0, 0
end
local hb = 0
local t = d
while t >= 2 do
t = rshift(t, 1)
hb += 1
end
local second = band(rshift(d, hb - 1), 1)
local eb = hb - 1
return 2 * hb + second, eb, band(d, lshift(1, eb) - 1)
end
-- distCode(xs, dist) -> the distance code value (1..120 for the 2-D plane offsets, else dist + 120)
local function distCode(xs: number, dist: number): number
local yo = dist // xs
local xo = dist - yo * xs
if xo <= 8 and yo < 8 then
return PLANE_TO_CODE[yo * 16 + 8 - xo + 1]
elseif xo > xs - 8 and yo < 7 then
return PLANE_TO_CODE[(yo + 1) * 16 + 8 + (xs - xo) + 1]
end
return dist + 120
end
local function subPixels(a: number, b: number): number
return band(bor(a, 0x00ff00ff) - band(b, 0xff00ff00), 0xff00ff00) + band(bor(a, 0xff00ff00) - band(b, 0x00ff00ff), 0x00ff00ff)
end
local function average2(a: number, b: number): number
return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b)
end
local function clip255(v: number): number
return if v < 0 then 0 elseif v > 255 then 255 else v
end
local function sub3(a: number, b: number, c: number): number
local pb, pa = b - c, a - c
return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa)
end
local function half(x: number, y: number): number
local dd = x - y
return clip255(x + (if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1)))
end
-- predict(mode, L, T, TR, TL): the decoder's predictors (codecs/image/Vp8L/Decode)
local function predict(mode: number, L: number, T: number, TR: number, TL: number): number
if mode == 1 then
return L
elseif mode == 2 then
return T
elseif mode == 3 then
return TR
elseif mode == 4 then
return TL
elseif mode == 5 then
return average2(average2(L, TR), T)
elseif mode == 6 then
return average2(L, TL)
elseif mode == 7 then
return average2(L, T)
elseif mode == 8 then
return average2(TL, T)
elseif mode == 9 then
return average2(T, TR)
elseif mode == 10 then
return average2(average2(L, TL), average2(T, TR))
elseif mode == 11 then
local s = sub3(rshift(T, 24), rshift(L, 24), rshift(TL, 24))
+ sub3(band(rshift(T, 16), 255), band(rshift(L, 16), 255), band(rshift(TL, 16), 255))
+ sub3(band(rshift(T, 8), 255), band(rshift(L, 8), 255), band(rshift(TL, 8), 255))
+ sub3(band(T, 255), band(L, 255), band(TL, 255))
return if s <= 0 then T else L
elseif mode == 12 then
local a = clip255(rshift(L, 24) + rshift(T, 24) - rshift(TL, 24))
local r = clip255(band(rshift(L, 16), 255) + band(rshift(T, 16), 255) - band(rshift(TL, 16), 255))
local g = clip255(band(rshift(L, 8), 255) + band(rshift(T, 8), 255) - band(rshift(TL, 8), 255))
local b = clip255(band(L, 255) + band(T, 255) - band(TL, 255))
return a * 16777216 + r * 65536 + g * 256 + b
elseif mode == 13 then
local ave = average2(L, T)
local a = half(rshift(ave, 24), rshift(TL, 24))
local r = half(band(rshift(ave, 16), 255), band(rshift(TL, 16), 255))
local g = half(band(rshift(ave, 8), 255), band(rshift(TL, 8), 255))
local b = half(band(ave, 255), band(TL, 255))
return a * 16777216 + r * 65536 + g * 256 + b
end
return ARGB_BLACK
end
-- COST[v + 1]: an estimate of the bits of a residual byte v (small magnitudes, mod 256, are cheap)
local COST = table.create(256, 0)
for v = 0, 255 do
local m = math.min(v, 256 - v)
COST[v + 1] = log(1 + m) / log(2)
end
local function residualCost(r: number): number
return COST[band(r, 255) + 1] + COST[band(rshift(r, 8), 255) + 1] + COST[band(rshift(r, 16), 255) + 1] + COST[rshift(r, 24) + 1]
end
-- ------------------------------------------------------------------------------------------------ transforms
local MODES_FAST = { 1, 2, 11 }
local MODES_MID = { 0, 1, 2, 4, 5, 7, 10, 11, 12, 13 }
local MODES_ALL = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }
-- predictorTransform(px, w, h, bits, effort) -> the modes sub-image; px becomes the residuals
local function predictorTransform(px: buffer, w: number, h: number, bits: number, effort: number): buffer
local tw, th = subSample(w, bits), subSample(h, bits)
local modesImg = bcreate(tw * th * 4)
local modes = if effort <= 2 then MODES_FAST elseif effort <= 6 then MODES_MID else MODES_ALL
local ts = lshift(1, bits)
for ty = 0, th - 1 do
for tx = 0, tw - 1 do
local x0, y0 = tx * ts, ty * ts
local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts)
local best, bestCost = 1, math.huge
for _, m in modes do
local cost = 0
for y = math.max(y0, 1), y1 - 1 do
local row = y * w
for x = math.max(x0, 1), x1 - 1 do
local i = row + x
local up = i - w
local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4))
cost += residualCost(subPixels(readu32(px, i * 4), p))
end
if cost >= bestCost then
break
end
end
if cost < bestCost then
best, bestCost = m, cost
end
end
writeu32(modesImg, (ty * tw + tx) * 4, ARGB_BLACK + best * 256)
end
end
-- residuals with the chosen modes (and the decoder's fixed first row and column)
local res = bcreate(w * h * 4)
writeu32(res, 0, subPixels(readu32(px, 0), ARGB_BLACK))
for x = 1, w - 1 do
writeu32(res, x * 4, subPixels(readu32(px, x * 4), readu32(px, (x - 1) * 4)))
end
for y = 1, h - 1 do
local row = y * w
writeu32(res, row * 4, subPixels(readu32(px, row * 4), readu32(px, (row - w) * 4)))
local trow = rshift(y, bits) * tw
for x = 1, w - 1 do
local m = band(rshift(readu32(modesImg, (trow + rshift(x, bits)) * 4), 8), 15)
local i = row + x
local up = i - w
local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4))
writeu32(res, i * 4, subPixels(readu32(px, i * 4), p))
end
end
bcopy(px, 0, res, 0, w * h * 4)
return modesImg
end
local function sint8(v: number): number
return if v >= 128 then v - 256 else v
end
local function clampM(v: number): number
local m = math.floor(v + 0.5)
return if m < -128 then -128 elseif m > 127 then 127 else m
end
-- crossColorTransform(px, w, h, bits) -> the multipliers sub-image; px is transformed in place. Per tile: the
-- least-squares multipliers (r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32), kept when they lower the cost
local function crossColorTransform(px: buffer, w: number, h: number, bits: number): buffer
local tw, th = subSample(w, bits), subSample(h, bits)
local img = bcreate(tw * th * 4)
local ts = lshift(1, bits)
local function tileCost(x0: number, y0: number, x1: number, y1: number, g2r: number, g2b: number, r2b: number): number
local c = 0
for y = y0, y1 - 1 do
for x = x0, x1 - 1 do
local argb = readu32(px, (y * w + x) * 4)
local g = sint8(band(rshift(argb, 8), 255))
local r = band(rshift(argb, 16), 255)
local b = band(argb, 255)
local nr = band(r - ((g2r * g) // 32), 255)
local nb = band(b - ((g2b * g) // 32) - ((r2b * sint8(r)) // 32), 255)
c += COST[nr + 1] + COST[nb + 1]
end
end
return c
end
for ty = 0, th - 1 do
for tx = 0, tw - 1 do
local x0, y0 = tx * ts, ty * ts
local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts)
local sgg, sgr, sgb, srr, srb = 0, 0, 0, 0, 0
for y = y0, y1 - 1 do
for x = x0, x1 - 1 do
local argb = readu32(px, (y * w + x) * 4)
local g = sint8(band(rshift(argb, 8), 255))
local r = sint8(band(rshift(argb, 16), 255))
local b = sint8(band(argb, 255))
sgg += g * g
sgr += g * r
sgb += g * b
srr += r * r
srb += r * b
end
end
local g2r, g2b, r2b = 0, 0, 0
if sgg > 0 then
g2r = clampM(32 * sgr / sgg)
local det = sgg * srr - sgr * sgr
if det > 0 then
g2b = clampM(32 * (sgb * srr - srb * sgr) / det)
r2b = clampM(32 * (srb * sgg - sgb * sgr) / det)
else
g2b = clampM(32 * sgb / sgg)
end
end
if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then
if tileCost(x0, y0, x1, y1, g2r, g2b, r2b) >= tileCost(x0, y0, x1, y1, 0, 0, 0) then
g2r, g2b, r2b = 0, 0, 0
end
end
writeu32(img, (ty * tw + tx) * 4, ARGB_BLACK + band(r2b, 255) * 65536 + band(g2b, 255) * 256 + band(g2r, 255))
if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then
for y = y0, y1 - 1 do
for x = x0, x1 - 1 do
local k = (y * w + x) * 4
local argb = readu32(px, k)
local g = sint8(band(rshift(argb, 8), 255))
local r = band(rshift(argb, 16), 255)
local b = band(argb, 255)
local nr = band(r - ((g2r * g) // 32), 255)
local nb = band(b - ((g2b * g) // 32) - ((r2b * sint8(r)) // 32), 255)
writeu32(px, k, band(argb, 0xff00ff00) + nr * 65536 + nb)
end
end
end
end
end
return img
end
-- ------------------------------------------------------------------------------------------------ LZ77
-- tokens: L[i] >= 0 is a literal ARGB pixel; L[i] < 0 is a copy of -L[i] pixels with the distance code value D[i]
local HASH_BITS = 16
local function hash2(a: number, b: number): number
return rshift(mulHash(bxor(a, (b * 31) % 4294967296)), 32 - HASH_BITS)
end
local function matchLen(px: buffer, i: number, j: number, max: number): number
local n = 0
while n < max and readu32(px, (i + n) * 4) == readu32(px, (j + n) * 4) do
n += 1
end
return n
end
local function lz77(px: buffer, xs: number, n: number, effort: number): ({ number }, { number })
local L: { number } = {}
local D: { number } = {}
if effort == 0 then
for i = 0, n - 1 do
L[i + 1] = readu32(px, i * 4)
D[i + 1] = 0
end
return L, D
end
local head = table.create(lshift(1, HASH_BITS), -1)
local prev = table.create(n, -1)
local maxIter = if effort <= 2 then 4 elseif effort <= 5 then 16 elseif effort <= 7 then 48 else 128
local function insert(i: number)
if i + 1 < n then
local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1
prev[i + 1] = head[h]
head[h] = i
end
end
-- best(i) -> length, distance (0, 0 when no useful match)
local function best(i: number): (number, number)
local max = math.min(MAX_LENGTH, n - i)
if max < 2 then
return 0, 0
end
local bl, bd, bc = 0, 0, math.huge
local function try(j: number)
local d = i - j
if d < 1 or d > WINDOW then
return
end
local l = matchLen(px, i, j, max)
if l >= 2 then
local c = distCode(xs, d)
if l > bl or (l == bl and c < bc) then
bl, bd, bc = l, d, c
end
end
end
if i >= 1 then
try(i - 1)
end
if i >= xs then
try(i - xs)
end
if bl < max then
local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1
local j = head[h]
local it = 0
while j >= 0 and it < maxIter and i - j <= WINDOW do
if j ~= i - 1 and j ~= i - xs then
try(j)
if bl >= max then
break
end
end
j = prev[j + 1]
it += 1
end
end
-- a 2-pixel copy only pays with a short 2-D distance code
if bl == 2 and bc > 120 then
return 0, 0
end
return bl, bd
end
local i = 0
local k = 0
local lazy = effort >= 4
local nl, nd = 0, 0
local haveNext = false
while i < n do
local l, d
if haveNext then
l, d = nl, nd
haveNext = false
else
l, d = best(i)
end
if l >= 2 and lazy and l < 64 and i + 1 < n then
insert(i)
nl, nd = best(i + 1)
if nl > l + 1 then
-- a literal now, the longer match next
k += 1
L[k] = readu32(px, i * 4)
D[k] = 0
i += 1
haveNext = true
else
k += 1
L[k] = -l
D[k] = distCode(xs, d)
for t = i + 1, i + l - 1 do
insert(t)
end
i += l
end
elseif l >= 2 then
k += 1
L[k] = -l
D[k] = distCode(xs, d)
local stop = i + l
if effort <= 2 and l > 16 then
insert(i)
insert(stop - 1)
else
for t = i, stop - 1 do
insert(t)
end
end
i = stop
else
insert(i)
k += 1
L[k] = readu32(px, i * 4)
D[k] = 0
i += 1
end
end
return L, D
end
-- ------------------------------------------------------------------------------------------------ prefix codes
local function entropy(h: { number }): number
local total = 0
for _, c in h do
total += c
end
if total == 0 then
return 0
end
local bits = 0
local lt = log(total)
for _, c in h do
if c > 0 then
bits += c * (lt - log(c))
end
end
return bits / log(2)
end
-- chooseCache(px, L, effort) -> the colour cache bits (0..10) with the smallest estimated literal cost
local function chooseCache(px: buffer, L: { number }, effort: number): number
if effort < 2 then
return 0
end
local cands = if effort < 5 then { 0, 4, 7, 10 } else { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
local caches: { { number } } = {}
local hg: { { number } } = {}
local hr: { { number } } = {}
local hb: { { number } } = {}
local ha: { { number } } = {}
for c, bits in cands do
caches[c] = table.create(lshift(1, bits), -1)
hg[c] = table.create(256 + lshift(1, bits), 0)
hr[c] = table.create(256, 0)
hb[c] = table.create(256, 0)
ha[c] = table.create(256, 0)
end
local pos = 0
for _, t in L do
if t >= 0 then
local hsh = mulHash(t)
for c, bits in cands do
local cache = caches[c]
local key = if bits > 0 then rshift(hsh, 32 - bits) else 0
if bits > 0 and cache[key + 1] == t then
hg[c][257 + key] += 1
else
hg[c][band(rshift(t, 8), 255) + 1] += 1
hr[c][band(rshift(t, 16), 255) + 1] += 1
hb[c][band(t, 255) + 1] += 1
ha[c][rshift(t, 24) + 1] += 1
end
if bits > 0 then
cache[key + 1] = t
end
end
pos += 1
else
for p = pos, pos - t - 1 do
local v = readu32(px, p * 4)
local hsh = mulHash(v)
for c, bits in cands do
if bits > 0 then
caches[c][rshift(hsh, 32 - bits) + 1] = v
end
end
end
pos -= t
end
end
local bestBits, bestCost = 0, math.huge
for c, bits in cands do
-- + a rough price for the longer green code lengths
local cost = entropy(hg[c]) + entropy(hr[c]) + entropy(hb[c]) + entropy(ha[c]) + lshift(1, bits) * 0.5
if cost < bestCost then
bestBits, bestCost = bits, cost
end
end
return bestBits
end
type Code = { lens: { number }, codes: { number }, single: boolean }
-- buildCode(freqs, maxLen) -> code lengths, reversed (LSB-first) codes, single (<= 1 used symbol: 0 bits each)
local function buildCode(freqs: { number }, maxLen: number): Code
local lens = Huffman.lengths(freqs, maxLen)
local used = 0
for _, l in lens do
if l > 0 then
used += 1
end
end
local codes = Huffman.codes(lens)
for i, l in lens do
if l > 0 then
codes[i] = Huffman.reverse(codes[i], l)
end
end
return { lens = lens, codes = codes, single = used <= 1 }
end
local function emit(w: W, c: Code, sym: number)
if not c.single then
put(w, c.codes[sym + 1], c.lens[sym + 1])
end
end
local function zeroRun(tok: { number }, ext: { number }, run: number)
local r = run
while r > 0 do
if r >= 11 then
local k = math.min(r, 138)
table.insert(tok, 18)
table.insert(ext, k - 11)
r -= k
elseif r >= 3 then
table.insert(tok, 17)
table.insert(ext, r - 3)
r = 0
else
table.insert(tok, 0)
table.insert(ext, 0)
r -= 1
end
end
end
-- writeCode(w, code, alphabetSize): the code lengths (a simple code when possible, else run-length coded)
local function writeCode(w: W, c: Code, size: number)
local syms: { number } = {}
for s = 0, size - 1 do
if (c.lens[s + 1] or 0) > 0 then
table.insert(syms, s)
if #syms > 2 then
break
end
end
end
if #syms == 0 then
-- an unused alphabet: the simple code of symbol 0
put(w, 1, 1)
put(w, 0, 1)
put(w, 0, 1)
put(w, 0, 1)
return
end
if #syms <= 2 and syms[#syms] < 256 then
put(w, 1, 1)
put(w, #syms - 1, 1)
if syms[1] <= 1 then
put(w, 0, 1)
put(w, syms[1], 1)
else
put(w, 1, 1)
put(w, syms[1], 8)
end
if #syms == 2 then
put(w, syms[2], 8)
end
return
end
-- run-length tokens of every length: 0..15 literal, 16 repeats the previous non-zero length (3..6 times; the
-- decoder's "previous" starts at 8), 17 zeros (3..10), 18 zeros (11..138)
local tok: { number } = {}
local ext: { number } = {}
local keep = 0 -- tokens up to the last non-zero length
local prev = 8
local s = 1
while s <= size do
local l = c.lens[s] or 0
local run = 1
while s + run <= size and (c.lens[s + run] or 0) == l do
run += 1
end
if l == 0 then
zeroRun(tok, ext, run)
else
local r = run
if l ~= prev then
table.insert(tok, l)
table.insert(ext, 0)
r -= 1
prev = l
end
while r > 0 do
if r >= 3 then
local k = math.min(r, 6)
table.insert(tok, 16)
table.insert(ext, k - 3)
r -= k
else
table.insert(tok, l)
table.insert(ext, 0)
r -= 1
end
end
keep = #tok
end
s += run
end
local ntok = #tok
local trim = keep < ntok and keep >= 2
if trim then
ntok = keep
end
local hist = table.create(19, 0)
for i = 1, ntok do
hist[tok[i] + 1] += 1
end
local cl = buildCode(hist, 7)
local nc = 19
while nc > 4 and (cl.lens[CODE_LENGTH_ORDER[nc] + 1] or 0) == 0 do
nc -= 1
end
put(w, 0, 1)
put(w, nc - 4, 4)
for i = 1, nc do
put(w, cl.lens[CODE_LENGTH_ORDER[i] + 1] or 0, 3)
end
if trim then
put(w, 1, 1)
local v = ntok - 2
local nbits = 0
while lshift(1, nbits) <= v do
nbits += 1
end
local pairs = math.max(1, (nbits + 1) // 2)
put(w, pairs - 1, 3)
put(w, v, pairs * 2)
else
put(w, 0, 1)
end
for i = 1, ntok do
local t = tok[i]
emit(w, cl, t)
if t == 16 then
put(w, ext[i], 2)
elseif t == 17 then
put(w, ext[i], 3)
elseif t == 18 then
put(w, ext[i], 7)
end
end
end
-- ------------------------------------------------------------------------------------------------ image data
-- writeImage(w, px, xs, n, effort, level0): colour cache bits, [the meta-code bit], the five codes, the pixels
local function writeImage(w: W, px: buffer, xs: number, n: number, effort: number, level0: boolean)
local L, D = lz77(px, xs, n, effort)
local cacheBits = if level0 then chooseCache(px, L, effort) else 0
if cacheBits > 0 then
put(w, 1, 1)
put(w, cacheBits, 4)
else
put(w, 0, 1)
end
if level0 then
put(w, 0, 1) -- no meta prefix codes
end
local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0
local cshift = 32 - cacheBits
local hg = table.create(NUM_LITERAL + NUM_LENGTH + cacheSize, 0)
local hr = table.create(256, 0)
local hb = table.create(256, 0)
local ha = table.create(256, 0)
local hd = table.create(NUM_DISTANCE, 0)
-- token kinds after the cache: 0 literal, 1 cache hit, 2 copy
local cache: { number }? = if cacheBits > 0 then table.create(cacheSize, -1) else nil
local K = table.create(#L, 0)
local pos = 0
for i, t in L do
if t >= 0 then
local hit = false
if cache then
local key = rshift(mulHash(t), cshift)
if cache[key + 1] == t then
hit = true
hg[NUM_LITERAL + NUM_LENGTH + key + 1] += 1
end
cache[key + 1] = t
end
if hit then
K[i] = 1
else
hg[band(rshift(t, 8), 255) + 1] += 1
hr[band(rshift(t, 16), 255) + 1] += 1
hb[band(t, 255) + 1] += 1
ha[rshift(t, 24) + 1] += 1
end
pos += 1
else
K[i] = 2
hg[NUM_LITERAL + prefix(-t) + 1] += 1
hd[prefix(D[i]) + 1] += 1
if cache then
for p = pos, pos - t - 1 do
local v = readu32(px, p * 4)
cache[rshift(mulHash(v), cshift) + 1] = v
end
end
pos -= t
end
end
local cg, cr, cb, ca, cd = buildCode(hg, 15), buildCode(hr, 15), buildCode(hb, 15), buildCode(ha, 15), buildCode(hd, 15)
writeCode(w, cg, NUM_LITERAL + NUM_LENGTH + cacheSize)
writeCode(w, cr, 256)
writeCode(w, cb, 256)
writeCode(w, ca, 256)
writeCode(w, cd, NUM_DISTANCE)
for i, t in L do
local k = K[i]
if k == 0 then
emit(w, cg, band(rshift(t, 8), 255))
emit(w, cr, band(rshift(t, 16), 255))
emit(w, cb, band(t, 255))
emit(w, ca, rshift(t, 24))
elseif k == 1 then
emit(w, cg, NUM_LITERAL + NUM_LENGTH + rshift(mulHash(t), cshift))
else
local lc, leb, lev = prefix(-t)
emit(w, cg, NUM_LITERAL + lc)
if leb > 0 then
put(w, lev, leb)
end
local dc, deb, dev = prefix(D[i])
emit(w, cd, dc)
if deb > 0 then
put(w, dev, deb)
end
end
end
end
-- ------------------------------------------------------------------------------------------------ encode
-- toArgb(rgba, n, exact) -> ARGB pixels, any alpha < 255. Without exact, fully transparent pixels become 0.
local function toArgb(rgba: buffer, n: number, exact: boolean): (buffer, boolean)
local px = bcreate(n * 4)
local alpha = false
for i = 0, n - 1 do
local v = readu32(rgba, i * 4)
local a = rshift(v, 24)
if a ~= 255 then
alpha = true
end
if a == 0 and not exact then
v = 0
end
-- bytes R G B A (0xAABBGGRR) -> 0xAARRGGBB
writeu32(px, i * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536)
end
return px, alpha
end
-- palette(px, n) -> the sorted colours when there are at most 256, else nil
local function palette(px: buffer, n: number): { number }?
local seen: { [number]: boolean } = {}
local list: { number } = {}
for i = 0, n - 1 do
local v = readu32(px, i * 4)
if not seen[v] then
if #list == 256 then
return nil
end
seen[v] = true
table.insert(list, v)
end
end
table.sort(list)
return list
end
type Config = { palette: { number }?, pbits: number, cc: boolean, ccbits: number }
-- stream(px, w, h, effort, cfg, bw): the transforms and the main image of one configuration (px is consumed)
local function stream(px: buffer, w: number, h: number, effort: number, cfg: Config, bw: W)
local n = w * h
local xs = w
local sub = math.min(effort, 3)
local pal = cfg.palette
if pal then
local num = #pal
local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3
put(bw, 1, 1)
put(bw, 3, 2)
put(bw, num - 1, 8)
local pimg = bcreate(num * 4)
local prevc = 0
local index: { [number]: number } = {}
for i, c in pal do
writeu32(pimg, (i - 1) * 4, subPixels(c, prevc))
prevc = c
index[c] = i - 1
end
writeImage(bw, pimg, num, num, sub, false)
xs = subSample(w, bits)
local packed = bcreate(xs * h * 4)
local bpp = rshift(8, bits)
local cmask = lshift(1, bits) - 1
for y = 0, h - 1 do
local acc = 0
local o = y * xs
for x = 0, w - 1 do
local sh = band(x, cmask)
acc += index[readu32(px, (y * w + x) * 4)] * 2 ^ (bpp * sh)
if sh == cmask or x == w - 1 then
writeu32(packed, (o + rshift(x, bits)) * 4, ARGB_BLACK + acc * 256)
acc = 0
end
end
end
px = packed
elseif cfg.pbits > 0 then
-- subtract green
put(bw, 1, 1)
put(bw, 2, 2)
for i = 0, n - 1 do
local v = readu32(px, i * 4)
local g = band(rshift(v, 8), 255)
writeu32(px, i * 4, band(v, 0xff00ff00) + band(band(v, 0x00ff00ff) + 0x01000100 - g * 65537, 0x00ff00ff))
end
-- predictor
local pbits = cfg.pbits
local modes = predictorTransform(px, w, h, pbits, effort)
put(bw, 1, 1)
put(bw, 0, 2)
put(bw, pbits - 2, 3)
writeImage(bw, modes, subSample(w, pbits), subSample(w, pbits) * subSample(h, pbits), sub, false)
-- cross colour
if cfg.cc then
local cbits = cfg.ccbits
local cimg = crossColorTransform(px, w, h, cbits)
put(bw, 1, 1)
put(bw, 1, 2)
put(bw, cbits - 2, 3)
writeImage(bw, cimg, subSample(w, cbits), subSample(w, cbits) * subSample(h, cbits), sub, false)
end
end
put(bw, 0, 1) -- no more transforms
writeImage(bw, px, xs, xs * h, effort, true)
end
-- encode(rgba, w, h, effort, exact, alphaHint?, headerless) -> the VP8L bitstream (headerless: the image stream only,
-- as an ALPH chunk stores it). Efforts 6+ try several transform configurations and keep the smallest.
function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact: boolean, alphaHint: boolean?, headerless: boolean): buffer
local n = w * h
local px, usesAlpha = toArgb(rgba, n, exact)
local pal = if effort > 0 then palette(px, n) else nil
local configs: { Config } = {}
if effort == 0 then
table.insert(configs, { palette = nil, pbits = 0, cc = false, ccbits = 0 })
else
local pbits = if effort >= 5 then 4 else 5
local plain: Config = { palette = nil, pbits = pbits, cc = effort >= 3, ccbits = if effort >= 6 then 4 else 5 }
if pal then
table.insert(configs, { palette = pal, pbits = 0, cc = false, ccbits = 0 })
if effort >= 6 then
table.insert(configs, plain)
end
else
table.insert(configs, plain)
end
if effort >= 9 then
table.insert(configs, { palette = nil, pbits = 3, cc = true, ccbits = 3 })
table.insert(configs, { palette = nil, pbits = 5, cc = false, ccbits = 0 })
end
end
local best: buffer? = nil
for k, cfg in configs do
local bw = newWriter(n + 256)
if not headerless then
put(bw, 0x2f, 8)
put(bw, w - 1, 14)
put(bw, h - 1, 14)
local hint = if alphaHint == nil then usesAlpha else alphaHint
put(bw, if hint then 1 else 0, 1)
put(bw, 0, 3)
end
local work = px
if k < #configs then
work = bcreate(n * 4)
bcopy(work, 0, px, 0, n * 4)
end
stream(work, w, h, effort, cfg, bw)
local out = finish(bw)
if not best or blen(out) < blen(best) then
best = out
end
end
return best :: buffer
end
return Encode
+120
View File
@@ -0,0 +1,120 @@
--!strict
-- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
-- image/webp uses it for VP8L frames and for compressed ALPH planes; other containers may carry it too.
-- Decoder: a port of libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it. Encoder: new
-- (subtract green, predictor and cross-colour transforms with per-tile mode search, colour indexing with pixel
-- bundling for <= 256 colours, LZ77 with hash chains and the 2-D distance codes, a colour cache chosen by entropy,
-- one prefix code group per image or meta codes for big images).
--
-- local Vp8L = require("@formats/codecs/image/Vp8L")
-- local rgba, w, h, alpha = Vp8L.decode(buf, off, len) -- a VP8L bitstream (0x2f signature) -> rgba8
-- local a8 = Vp8L.decodeAlpha(buf, off, len, w, h) -- a headerless stream's green channel (ALPH)
-- local bits = Vp8L.encode(rgba, w, h, { effort = 4 }) -- rgba8 -> a VP8L bitstream
--
-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / LIMIT / ARG).
local Err = require("@formats/core/Err")
local Decode = require("@formats/codecs/image/Vp8L/Decode")
local Encode = require("@formats/codecs/image/Vp8L/Encode")
local Vp8L = {}
local DEFAULT_MAX_PIXELS = 2 ^ 28
local function fail(msg: string?, offset: number?): Err.Err
local m = msg or "bad data"
if string.sub(m, 1, 11) == "truncated: " then
return Err.new(Err.TRUNCATED, string.sub(m, 12), offset)
elseif string.sub(m, 1, 7) == "limit: " then
return Err.new(Err.LIMIT, string.sub(m, 8), offset)
end
return Err.new(Err.CORRUPT, m, offset)
end
Vp8L.fail = fail
local function range(buf: buffer, off: number?, len: number?): (number, number)
local n = buffer.len(buf)
local o = math.clamp(off or 0, 0, n)
return o, math.clamp(len or (n - o), 0, n - o)
end
-- info(buf, off?, len?) -> { width, height, alpha } | nil, Err: the 5-byte header
function Vp8L.info(buf: buffer, off: number?, len: number?): ({ width: number, height: number, alpha: boolean }?, Err.Err?)
local o, l = range(buf, off, len)
local w, h, alpha, err = Decode.header(buf, o, l)
if not w then
return nil, fail(err, o)
end
return { width = w, height = h, alpha = alpha }, nil
end
-- decodeArgb(buf, off?, len?, maxPixels?) -> ARGB u32 pixels (0xAARRGGBB), width, height, alphaHint | nil, Err
function Vp8L.decodeArgb(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?)
local o, l = range(buf, off, len)
local px, w, h, alpha, err = Decode.argb(buf, o, l, maxPixels or DEFAULT_MAX_PIXELS)
if not px then
return nil, fail(err, o)
end
return px, w, h, alpha
end
-- decode(buf, off?, len?, maxPixels?) -> rgba8 pixels, width, height, alphaHint | nil, Err
function Vp8L.decode(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?)
local px, w, h, alpha = Vp8L.decodeArgb(buf, off, len, maxPixels)
if not px then
return nil, w
end
return Decode.toRgba(px, w * (h :: number)), w, h, alpha
end
-- decodeAlpha(buf, off, len, width, height) -> width * height bytes (the green channel) | nil, Err
function Vp8L.decodeAlpha(buf: buffer, off: number?, len: number?, width: number, height: number): (buffer?, Err.Err?)
local o, l = range(buf, off, len)
local px, err = Decode.stream(buf, o, l, width, height)
if not px then
return nil, fail(err, o)
end
return Decode.green(px, width * height), nil
end
-- toRgba(argb, n) -> rgba8 bytes of n ARGB pixels
Vp8L.toRgba = Decode.toRgba
export type EncodeOptions = {
effort: number?, -- 0..9, default 5: more = smaller and slower (0: no transforms, no LZ77 search)
exact: boolean?, -- default false: keep the RGB of fully transparent pixels (otherwise they may be zeroed)
alphaHint: boolean?, -- the header's "alpha is used" bit; default: any alpha < 255
}
-- encode(rgba, width, height, opts?) -> a VP8L bitstream (signature + header + image stream) | nil, Err
function Vp8L.encode(rgba: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(rgba) ~= "buffer" or type(width) ~= "number" or type(height) ~= "number" then
return nil, Err.new(Err.ARG, "encode: needs rgba8 pixels, width, height")
end
if width < 1 or height < 1 or width > 16384 or height > 16384 or width % 1 ~= 0 or height % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encode: size must be 1..16384")
end
if buffer.len(rgba) < width * height * 4 then
return nil, Err.new(Err.ARG, "encode: pixel buffer too small")
end
local o: EncodeOptions = opts or {} :: EncodeOptions
local effort = o.effort or 5
if type(effort) ~= "number" or effort < 0 or effort > 9 then
return nil, Err.new(Err.ARG, "encode: effort must be 0..9")
end
return Encode.encode(rgba, width, height, effort, o.exact == true, o.alphaHint, false), nil
end
-- encodeAlpha(a8, width, height, opts?) -> a headerless stream of the plane in green (an ALPH payload)
function Vp8L.encodeAlpha(a8: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(a8) ~= "buffer" or buffer.len(a8) < width * height then
return nil, Err.new(Err.ARG, "encodeAlpha: plane too small")
end
local rgba = buffer.create(width * height * 4)
for i = 0, width * height - 1 do
buffer.writeu32(rgba, i * 4, 0xff000000 + buffer.readu8(a8, i) * 256)
end
local effort = opts and opts.effort or 5
return Encode.encode(rgba, width, height, effort, true, false, true), nil
end
return Vp8L
+225
View File
@@ -0,0 +1,225 @@
--!strict
--!native
--!optimize 2
-- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
-- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range.
-- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the
-- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma
-- (ffmpeg's default rgb -> yuv420p chroma siting is close to this).
--
-- Yuv.toRgba(planes, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 buffer (alpha 255)
-- Yuv.fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p buffer (Y, then U, then V; ceil(w/2) x ceil(h/2))
-- Yuv.imageToRgba(img) / Yuv.imageFromRgba(img, range?, matrix?) -> Types.Image
local Types = require("@formats/Types")
local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
local bcreate = buffer.create
local floor = math.floor
local Yuv = {}
-- coefficients (x 65536): r = y' + crv * v; g = y' - cgu * u - cgv * v; b = y' + cbu * u
-- limited: y' = (y - 16) * 255 / 219, chroma scaled by 255 / 224
local MATRIX: { [string]: { kr: number, kb: number } } = {
bt601 = { kr = 0.299, kb = 0.114 },
bt709 = { kr = 0.2126, kb = 0.0722 },
}
type Coeffs = { ys: number, yo: number, crv: number, cgu: number, cgv: number, cbu: number, cs: number }
local cache: { [string]: Coeffs } = {}
local function coeffs(range: string?, matrix: string?): Coeffs
local key = (range or "limited") .. (matrix or "bt601")
local c = cache[key]
if c then
return c
end
local m = MATRIX[matrix or "bt601"] or MATRIX.bt601
local kr, kb = m.kr, m.kb
local kg = 1 - kr - kb
local full = range == "full"
local ys = if full then 1 else 255 / 219
local cs = if full then 1 else 255 / 224
c = {
ys = floor(ys * 65536 + 0.5),
yo = if full then 0 else 16,
crv = floor(2 * (1 - kr) * cs * 65536 + 0.5),
cbu = floor(2 * (1 - kb) * cs * 65536 + 0.5),
cgu = floor(2 * (1 - kb) * kb / kg * cs * 65536 + 0.5),
cgv = floor(2 * (1 - kr) * kr / kg * cs * 65536 + 0.5),
cs = cs,
}
cache[key] = c
return c
end
-- CLIP[v + 1024] = clamp(v, 0, 255) for v in -1024..1279
local CLIP = bcreate(2304)
for i = 0, 2303 do
writeu8(CLIP, i, math.clamp(i - 1024, 0, 255))
end
-- toRgba(src, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 (w * h * 4) from planes in one buffer: Y at 0 with
-- stride w, U at uo and V at vo with stride cw (ceil(w/2) rows of ceil(h/2))
function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer
local dst = out or bcreate(w * h * 4)
local c = coeffs(range, matrix)
local ys, yo, crv, cgu, cgv, cbu = c.ys, c.yo, c.crv, c.cgu, c.cgv, c.cbu
local ch = (h + 1) // 2
if buffer.len(src) < vo + cw * ch or buffer.len(dst) < w * h * 4 or uo + cw * ch > buffer.len(src) then
return dst
end
for y = 0, h - 1 do
local yrow = y * w
local crow = (y // 2) * cw
local o = yrow * 4
for x = 0, w - 1, 2 do
local ci = crow + (x // 2)
local u = readu8(src, uo + ci) - 128
local v = readu8(src, vo + ci) - 128
local rv = (crv * v + 32768) // 65536
local gv = (cgu * u + cgv * v + 32768) // 65536
local bu = (cbu * u + 32768) // 65536
local yy = (ys * (readu8(src, yrow + x) - yo) + 32768) // 65536 + 1024
writeu32(dst, o, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000)
if x + 1 < w then
yy = (ys * (readu8(src, yrow + x + 1) - yo) + 32768) // 65536 + 1024
writeu32(dst, o + 4, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000)
end
o += 8
end
end
return dst
end
-- fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p
function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: string?, out: buffer?): buffer
local cw, ch = (w + 1) // 2, (h + 1) // 2
local uo, vo = w * h, w * h + cw * ch
local dst = out or bcreate(w * h + 2 * cw * ch)
if buffer.len(src) < w * h * 4 or buffer.len(dst) < w * h + 2 * cw * ch then
return dst
end
local m = MATRIX[matrix or "bt601"] or MATRIX.bt601
local kr, kb = m.kr, m.kb
local kg = 1 - kr - kb
local full = range == "full"
local ysc = if full then 1 else 219 / 255
local csc = if full then 1 else 224 / 255
local yof = if full then 0.5 else 16.5
-- fixed point x 65536
local yr, yg, yb = floor(kr * ysc * 65536 + 0.5), floor(kg * ysc * 65536 + 0.5), floor(kb * ysc * 65536 + 0.5)
local yoff = floor(yof * 65536)
local ur = floor(-kr / (2 * (1 - kb)) * csc * 65536 + 0.5)
local ug = floor(-kg / (2 * (1 - kb)) * csc * 65536 + 0.5)
local ub = floor(0.5 * csc * 65536 + 0.5)
local vr = ub
local vg = floor(-kg / (2 * (1 - kr)) * csc * 65536 + 0.5)
local vb = floor(-kb / (2 * (1 - kr)) * csc * 65536 + 0.5)
local coff4 = floor(128.5 * 65536) * 4
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, readu8(CLIP, (yr * r + yg * g + yb * b + yoff) // 65536 + 1024))
end
for cy = 0, ch - 1 do
local y0 = cy * 2
local y1 = if y0 + 1 < h then y0 + 1 else y0
for cx = 0, cw - 1 do
local x0 = cx * 2
local x1 = if x0 + 1 < w then x0 + 1 else x0
local a, b2, c2, d = (y0 * w + x0) * 4, (y0 * w + x1) * 4, (y1 * w + x0) * 4, (y1 * w + x1) * 4
local r = readu8(src, a) + readu8(src, b2) + readu8(src, c2) + readu8(src, d)
local g = readu8(src, a + 1) + readu8(src, b2 + 1) + readu8(src, c2 + 1) + readu8(src, d + 1)
local b = readu8(src, a + 2) + readu8(src, b2 + 2) + readu8(src, c2 + 2) + readu8(src, d + 2)
local i = cy * cw + cx
writeu8(dst, uo + i, readu8(CLIP, (ur * r + ug * g + ub * b + coff4) // 262144 + 1024))
writeu8(dst, vo + i, readu8(CLIP, (vr * r + vg * g + vb * b + coff4) // 262144 + 1024))
end
end
return dst
end
-- the range / matrix an Image's meta records (meta.yuv = { range, matrix }); limited BT.601 when absent
local function info(img: Types.Image): (string, string)
local m = img.meta
local y = m and m.yuv
if type(y) == "table" then
return y.range or "limited", y.matrix or "bt601"
end
local src = m and m.source
if type(src) == "table" and src.range == "full" then
return "full", "bt601"
end
return "limited", "bt601"
end
Yuv.info = info
-- planes(w, h) -> uo, vo, cw, ch of a yuv420p buffer
function Yuv.planes(w: number, h: number): (number, number, number, number)
local cw, ch = (w + 1) // 2, (h + 1) // 2
return w * h, w * h + cw * ch, cw, ch
end
-- FULL_Y / FULL_C: limited -> full range sample maps
local FULL_Y = bcreate(256)
local FULL_C = bcreate(256)
for v = 0, 255 do
writeu8(FULL_Y, v, math.clamp(floor((v - 16) * 255 / 219 + 0.5), 0, 255))
writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255))
end
-- toFullRange(img) -> a yuv420p Image in full range (a limited-range one remapped; a full-range one returned)
function Yuv.toFullRange(img: Types.Image): Types.Image
if img.format ~= "yuv420p" or info(img) == "full" then
return img
end
local w, h = img.width, img.height
local out = Types.Image.new(w, h, "yuv420p")
local src, dst = img.pixels, out.pixels
local ny = w * h
local n = math.min(buffer.len(src), buffer.len(dst))
for i = 0, math.min(ny, n) - 1 do
writeu8(dst, i, readu8(FULL_Y, readu8(src, i)))
end
for i = ny, n - 1 do
writeu8(dst, i, readu8(FULL_C, readu8(src, i)))
end
out.meta.yuv = { range = "full", matrix = select(2, info(img)) }
out.meta.source = img.meta.source
return out
end
-- imageToRgba(img) -> an rgba8 Image (yuv420p converted; rgba8 returned as is; nil for other formats)
function Yuv.imageToRgba(img: Types.Image): Types.Image?
if img.format == "rgba8" then
return img
end
if img.format ~= "yuv420p" then
return nil
end
local w, h = img.width, img.height
local uo, vo, cw = Yuv.planes(w, h)
local range, matrix = info(img)
local out = Types.Image.new(w, h, "rgba8")
Yuv.toRgba(img.pixels, w, h, uo, vo, cw, range, matrix, out.pixels)
out.meta.source = img.meta.source
return out
end
-- imageFromRgba(img, range?, matrix?) -> a yuv420p Image (meta.yuv records the range / matrix)
function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image?
if img.format == "yuv420p" then
return img
end
if img.format ~= "rgba8" then
return nil
end
local out = Types.Image.new(img.width, img.height, "yuv420p")
Yuv.fromRgba(img.pixels, img.width, img.height, range, matrix, out.pixels)
out.meta.yuv = { range = range or "limited", matrix = matrix or "bt601" }
out.meta.source = img.meta.source
return out
end
return Yuv