--!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