/**
* Minimal PNG codec for the fidelity bench: 8-bit, non-interlaced greyscale,
* RGB, palette, grey+alpha and RGBA in; always RGBA out. Uses fflate (already a
* dependency) for zlib so the bench needs nothing new.
*/
import { unzlibSync, zlibSync } from 'fflate'
export interface Image {
width: number
height: number
/** RGBA, row-major, 4 bytes per pixel. */
data: Uint8Array
}
const SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10]
const CHANNELS: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }
export function decodePng(bytes: Uint8Array): Image {
for (let i = 0; i < 8; i++) if (bytes[i] !== SIGNATURE[i]) throw new Error('not a PNG')
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
let width = 0, height = 0, depth = 0, type = 0, interlace = 0
let palette: Uint8Array | undefined
let alpha: Uint8Array | undefined
const idat: Uint8Array[] = []
for (let p = 8; p < bytes.length;) {
const len = view.getUint32(p)
const kind = String.fromCharCode(...bytes.subarray(p + 4, p + 8))
const body = bytes.subarray(p + 8, p + 8 + len)
if (kind === 'IHDR') {
width = view.getUint32(p + 8)
height = view.getUint32(p + 12)
depth = body[8]!
type = body[9]!
interlace = body[12]!
} else if (kind === 'PLTE') palette = body
else if (kind === 'tRNS') alpha = body
else if (kind === 'IDAT') idat.push(body)
else if (kind === 'IEND') break
p += 12 + len
}
const channels = CHANNELS[type]
if (depth !== 8 || channels === undefined || interlace !== 0) {
throw new Error(`unsupported PNG: depth ${depth}, colour type ${type}, interlace ${interlace}`)
}
const raw = unzlibSync(concat(idat))
const stride = width * channels
const px = new Uint8Array(stride * height)
for (let y = 0; y < height; y++) {
const filter = raw[y * (stride + 1)]!
const src = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1))
const row = px.subarray(y * stride, (y + 1) * stride)
const prev = y > 0 ? px.subarray((y - 1) * stride, y * stride) : undefined
for (let i = 0; i < stride; i++) {
const a = i >= channels ? row[i - channels]! : 0
const b = prev ? prev[i]! : 0
const c = prev && i >= channels ? prev[i - channels]! : 0
const x = src[i]!
let v: number
if (filter === 0) v = x
else if (filter === 1) v = x + a
else if (filter === 2) v = x + b
else if (filter === 3) v = x + ((a + b) >> 1)
else if (filter === 4) v = x + paeth(a, b, c)
else throw new Error(`bad PNG filter ${filter}`)
row[i] = v & 255
}
}
const data = new Uint8Array(width * height * 4)
for (let i = 0; i < width * height; i++) {
const s = i * channels, d = i * 4
if (type === 6) data.set(px.subarray(s, s + 4), d)
else if (type === 2) { data[d] = px[s]!; data[d + 1] = px[s + 1]!; data[d + 2] = px[s + 2]!; data[d + 3] = 255 }
else if (type === 0) { data[d] = data[d + 1] = data[d + 2] = px[s]!; data[d + 3] = 255 }
else if (type === 4) { data[d] = data[d + 1] = data[d + 2] = px[s]!; data[d + 3] = px[s + 1]! }
else {
const k = px[s]!
if (!palette) throw new Error('palette PNG without PLTE')
data[d] = palette[k * 3]!; data[d + 1] = palette[k * 3 + 1]!; data[d + 2] = palette[k * 3 + 2]!
data[d + 3] = alpha && k < alpha.length ? alpha[k]! : 255
}
}
return { width, height, data }
}
export function encodePng(img: Image): Uint8Array {
const stride = img.width * 4
const raw = new Uint8Array((stride + 1) * img.height)
for (let y = 0; y < img.height; y++) raw.set(img.data.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1)
const ihdr = new Uint8Array(13)
const v = new DataView(ihdr.buffer)
v.setUint32(0, img.width)
v.setUint32(4, img.height)
ihdr[8] = 8
ihdr[9] = 6
return concat([new Uint8Array(SIGNATURE), chunk('IHDR', ihdr), chunk('IDAT', zlibSync(raw)), chunk('IEND', new Uint8Array(0))])
}
export function crop(img: Image, x: number, y: number, w: number, h: number): Image {
if (x < 0 || y < 0 || x + w > img.width || y + h > img.height) {
throw new Error(`crop ${x},${y} ${w}x${h} is outside ${img.width}x${img.height}`)
}
const data = new Uint8Array(w * h * 4)
for (let r = 0; r < h; r++) data.set(img.data.subarray(((y + r) * img.width + x) * 4, ((y + r) * img.width + x + w) * 4), r * w * 4)
return { width: w, height: h, data }
}
/** Nearest-neighbour upscale, so single pixels stay visible when an agent reads the image. */
export function zoom(img: Image, factor: number): Image {
const w = img.width * factor, h = img.height * factor
const data = new Uint8Array(w * h * 4)
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const s = (Math.floor(y / factor) * img.width + Math.floor(x / factor)) * 4
data.set(img.data.subarray(s, s + 4), (y * w + x) * 4)
}
}
return { width: w, height: h, data }
}
export function pixelHex(img: Image, x: number, y: number): string {
const i = (y * img.width + x) * 4
const hex = (n: number) => n.toString(16).padStart(2, '0')
const a = img.data[i + 3]!
return `#${hex(img.data[i]!)}${hex(img.data[i + 1]!)}${hex(img.data[i + 2]!)}${a === 255 ? '' : hex(a)}`
}
function paeth(a: number, b: number, c: number): number {
const p = a + b - c
const pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c)
return pa <= pb && pa <= pc ? a : pb <= pc ? b : c
}
function concat(parts: Uint8Array[]): Uint8Array {
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
let o = 0
for (const p of parts) { out.set(p, o); o += p.length }
return out
}
const CRC = (() => {
const t = new Uint32Array(256)
for (let n = 0; n < 256; n++) {
let c = n
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
t[n] = c >>> 0
}
return t
})()
function chunk(kind: string, body: Uint8Array): Uint8Array {
const out = new Uint8Array(12 + body.length)
const v = new DataView(out.buffer)
v.setUint32(0, body.length)
for (let i = 0; i < 4; i++) out[4 + i] = kind.charCodeAt(i)
out.set(body, 8)
let c = 0xffffffff
for (let i = 4; i < 8 + body.length; i++) c = CRC[(c ^ out[i]!) & 255]! ^ (c >>> 8)
v.setUint32(8 + body.length, (c ^ 0xffffffff) >>> 0)
return out
}