#!/usr/bin/env node // Pixel comparison of two same-sized screenshots, decoded in headless Chrome // (no npm packages): // // node tool/perf/compare_shots.mjs before.png after.png [diff.png] // // Prints the share of pixels that differ (any channel > 2/255 and > 16/255), // the mean and maximum channel difference, and per 60px horizontal band the // mean difference, so a change confined to the bars shows where it is. With a // third path it writes a diff image (differences amplified 8x). import { readFile, writeFile } from 'node:fs/promises'; import { openBrowser } from '../capture/browser.mjs'; const [a, b, out] = process.argv.slice(2); if (!a || !b) throw new Error('usage: compare_shots.mjs [diff.png]'); const browser = await openBrowser(); try { const url = (buf) => `data:image/png;base64,${buf.toString('base64')}`; const expression = `(async () => { const load = (src) => new Promise((ok, fail) => { const i = new Image(); i.onload = () => ok(i); i.onerror = fail; i.src = src; }); const [ia, ib] = await Promise.all([load(${JSON.stringify(url(await readFile(a)))}), load(${JSON.stringify(url(await readFile(b)))})]); if (ia.width !== ib.width || ia.height !== ib.height) return { error: 'size mismatch' }; const w = ia.width, h = ia.height; const px = (img) => { const c = new OffscreenCanvas(w, h); const g = c.getContext('2d'); g.drawImage(img, 0, 0); return g.getImageData(0, 0, w, h).data; }; const da = px(ia), db = px(ib); const diff = new OffscreenCanvas(w, h); const dg = diff.getContext('2d'); const dd = dg.createImageData(w, h); let over2 = 0, over16 = 0, sum = 0, max = 0; const bands = new Array(Math.ceil(h / 60)).fill(0); for (let i = 0; i < w * h; i++) { let m = 0; for (let k = 0; k < 3; k++) { const d = Math.abs(da[i * 4 + k] - db[i * 4 + k]); m = Math.max(m, d); sum += d; dd.data[i * 4 + k] = Math.min(255, d * 8); } dd.data[i * 4 + 3] = 255; if (m > 2) over2++; if (m > 16) over16++; max = Math.max(max, m); bands[Math.floor(i / w / 60)] += m; } dg.putImageData(dd, 0, 0); const blob = await diff.convertToBlob({ type: 'image/png' }); const bytes = new Uint8Array(await blob.arrayBuffer()); let bin = ''; for (const x of bytes) bin += String.fromCharCode(x); const r = (x) => Math.round(x * 1000) / 1000; return { pixels: w * h, over2: r(over2 / (w * h)), over16: r(over16 / (w * h)), mean: r(sum / (w * h * 3)), max, bands: bands.map((s, i) => r(s / (w * Math.min(60, h - i * 60)))), diff: btoa(bin) }; })()`; const page = await browser.newPage(); const res = await page.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }); await page.close(); const v = res.result.value; if (!v || v.error) throw new Error(v?.error ?? JSON.stringify(res.exceptionDetails ?? res)); if (out) await writeFile(out, Buffer.from(v.diff, 'base64')); delete v.diff; console.log(JSON.stringify(v)); } finally { await browser.close(); }