Add a headless render check for the 16-bit sidecar swap.
The proxy and sidecar reach the GPU through different upload paths, and whether they agree depends on UNPACK_FLIP_Y_WEBGL being ignored for ImageBitmap. A unit test cannot see that, so the picture could silently start flipping again. The check encodes a two-tone sidecar with the server's encoder, serves it beside the matching JPEG and measures the rows that land in a WebGL2 texture in headless Chrome. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
@@ -956,6 +956,7 @@ positions. Camera-lens defaults require both a normalised camera and lens name t
|
||||
| `npm run dev` | Vite HMR on 5173 |
|
||||
| `npm run typecheck` | `tsc --noEmit` |
|
||||
| `npm test` | Vitest, one pass then exit |
|
||||
| `npm run check:render` | Headless Chrome check that the 16-bit sidecar and JPEG proxy upload in the same row order |
|
||||
|
||||
Conventions worth knowing before changing code:
|
||||
|
||||
@@ -991,6 +992,13 @@ Conventions worth knowing before changing code:
|
||||
|
||||
There are no server integration tests; the API is exercised through the UI.
|
||||
|
||||
`npm run check:render` covers the one thing the unit suite cannot: real GPU upload
|
||||
orientation. It encodes a two-tone 16-bit sidecar with the server's own encoder, serves
|
||||
it beside the matching JPEG proxy and measures the rows that reach a WebGL2 texture in
|
||||
headless Chrome. If the sidecar ever lands upside down against the proxy again, it fails
|
||||
with the measured row values. It needs Chrome (`CHROME_PATH` overrides discovery) and
|
||||
skips with a notice when none is installed.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"check:render": "node scripts/render-check.mjs",
|
||||
"build:lens-db": "node scripts/build-lens-db.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Headless render check for the 16-bit proxy swap.
|
||||
*
|
||||
* The editor shows the JPEG proxy first and swaps in the 16-bit sidecar a few
|
||||
* seconds later. Both uploads go through `Renderer.setImage`, and whether they
|
||||
* agree depends on a WebGL detail that no unit test can cover: `UNPACK_FLIP_Y_WEBGL`
|
||||
* is ignored for `ImageBitmap` sources (the proxy) but honoured for typed arrays
|
||||
* (the sidecar). If the two disagree, the picture jumps upside down at the swap.
|
||||
*
|
||||
* This script builds a two-tone 16-bit PNG with the server's own encoder plus the
|
||||
* matching JPEG, serves `parsePreview16` through Vite, and measures the rows that
|
||||
* actually reach the GPU in headless Chrome. It fails if the top row of the proxy
|
||||
* is not the top row of the sidecar.
|
||||
*
|
||||
* Runs outside `npm test` because it needs a WebGL2-capable Chrome:
|
||||
* npm run check:render
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { mkdir, rm, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import sharp from 'sharp';
|
||||
import { createServer } from 'vite';
|
||||
import { encodePng16 } from '../server/imaging.mjs';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const DIR = path.join(ROOT, '.render-check');
|
||||
const PAGE = path.join(DIR, 'index.html');
|
||||
const W = 96;
|
||||
const H = 64;
|
||||
|
||||
const CHROME_CANDIDATES = [
|
||||
process.env.CHROME_PATH,
|
||||
'google-chrome',
|
||||
'google-chrome-stable',
|
||||
'chromium',
|
||||
'chromium-browser',
|
||||
].filter(Boolean);
|
||||
|
||||
async function findChrome() {
|
||||
for (const candidate of CHROME_CANDIDATES) {
|
||||
if (candidate.includes(path.sep)) {
|
||||
if (existsSync(candidate)) return candidate;
|
||||
continue;
|
||||
}
|
||||
if (await spawnSyncOk(candidate)) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function spawnSyncOk(bin) {
|
||||
const probe = spawn(bin, ['--version'], { stdio: 'ignore' });
|
||||
return new Promise((resolve) => {
|
||||
probe.on('error', () => resolve(false));
|
||||
probe.on('exit', (code) => resolve(code === 0));
|
||||
});
|
||||
}
|
||||
|
||||
/** Three horizontal bands, so any vertical reversal changes every row band. */
|
||||
function buildSource() {
|
||||
const rgb16 = new Uint16Array(W * H * 3);
|
||||
const rgb8 = new Uint8Array(W * H * 3);
|
||||
const bands = [
|
||||
[0.86, 0.22, 0.16],
|
||||
[0.24, 0.70, 0.28],
|
||||
[0.16, 0.26, 0.88],
|
||||
];
|
||||
for (let y = 0; y < H; y++) {
|
||||
const band = bands[Math.min(bands.length - 1, Math.floor((y / H) * bands.length))];
|
||||
for (let x = 0; x < W; x++) {
|
||||
const i = (y * W + x) * 3;
|
||||
for (let c = 0; c < 3; c++) {
|
||||
rgb16[i + c] = Math.round(band[c] * 65535);
|
||||
rgb8[i + c] = Math.round(band[c] * 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { rgb8, rgb16 };
|
||||
}
|
||||
|
||||
const PAGE_HTML = `<!doctype html>
|
||||
<meta charset="utf-8" />
|
||||
<pre id="out">boot</pre>
|
||||
<script type="module">
|
||||
import { parsePreview16 } from '/src/lib/preview16.ts';
|
||||
const pre = document.getElementById('out');
|
||||
const half = (bits) => {
|
||||
const s = bits >> 15 ? -1 : 1;
|
||||
const e = (bits >> 10) & 0x1f;
|
||||
const m = bits & 0x3ff;
|
||||
if (e === 0) return s * m * Math.pow(2, -24);
|
||||
if (e === 31) return m ? NaN : s * Infinity;
|
||||
return s * (1 + m / 1024) * Math.pow(2, e - 15);
|
||||
};
|
||||
try {
|
||||
const canvas = document.createElement('canvas');
|
||||
const gl = canvas.getContext('webgl2', { alpha: false, antialias: false });
|
||||
if (!gl) { pre.textContent = 'ERROR no WebGL2 in this Chrome'; throw new Error('no webgl2'); }
|
||||
const makeTex = () => {
|
||||
const t = gl.createTexture();
|
||||
gl.bindTexture(gl.TEXTURE_2D, t);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
return t;
|
||||
};
|
||||
// readPixels rows start at the framebuffer's bottom row, which is texel row 0.
|
||||
const rowLuma = (tex, y, w) => {
|
||||
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||||
const fb = gl.createFramebuffer();
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
|
||||
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
|
||||
throw new Error('framebuffer incomplete');
|
||||
}
|
||||
const buf = new Uint8Array(w * 4);
|
||||
gl.readPixels(0, y, w, 1, gl.RGBA, gl.UNSIGNED_BYTE, buf);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||
gl.deleteFramebuffer(fb);
|
||||
let sum = 0;
|
||||
for (let i = 0; i < w; i++) {
|
||||
sum += 0.2126 * buf[i * 4] + 0.7152 * buf[i * 4 + 1] + 0.0722 * buf[i * 4 + 2];
|
||||
}
|
||||
return sum / w / 255;
|
||||
};
|
||||
|
||||
const blob = await (await fetch('/.render-check/proxy.jpg')).blob();
|
||||
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
||||
const w = bitmap.width;
|
||||
const h = bitmap.height;
|
||||
|
||||
// Exactly what Renderer.setImage does for the JPEG proxy.
|
||||
const texFlip = makeTex();
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
|
||||
const texNoFlip = makeTex();
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
|
||||
|
||||
const png = await (await fetch('/.render-check/side.p16.png')).arrayBuffer();
|
||||
const parsed = await parsePreview16(png);
|
||||
if (!parsed) throw new Error('parsePreview16 returned null');
|
||||
if (parsed.width !== w || parsed.height !== h) {
|
||||
throw new Error('sidecar ' + parsed.width + 'x' + parsed.height + ' vs proxy ' + w + 'x' + h);
|
||||
}
|
||||
// Exactly what Renderer.setImage does for the sidecar: rows in parser order, unflipped.
|
||||
const sideRow = (y) => {
|
||||
const out = new Uint8Array(w * 4);
|
||||
for (let x = 0; x < w; x++) {
|
||||
const i = (y * w + x) * 4;
|
||||
const toByte = (bits) => Math.round(Math.min(1, Math.max(0, half(bits))) * 255);
|
||||
out[x * 4] = toByte(parsed.rgba[i]);
|
||||
out[x * 4 + 1] = toByte(parsed.rgba[i + 1]);
|
||||
out[x * 4 + 2] = toByte(parsed.rgba[i + 2]);
|
||||
out[x * 4 + 3] = 255;
|
||||
}
|
||||
const tex = makeTex();
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, out);
|
||||
return tex;
|
||||
};
|
||||
const sideTopTex = sideRow(0);
|
||||
const sideBottomTex = sideRow(h - 1);
|
||||
|
||||
const proxyTop = rowLuma(texFlip, 0, w);
|
||||
const proxyBottom = rowLuma(texFlip, h - 1, w);
|
||||
const proxyNoFlipTop = rowLuma(texNoFlip, 0, w);
|
||||
const sideTop = rowLuma(sideTopTex, 0, w);
|
||||
const sideBottom = rowLuma(sideBottomTex, 0, w);
|
||||
const same = (a, b) => Math.abs(a - b) < 0.02;
|
||||
|
||||
pre.textContent = 'RESULT ' + JSON.stringify({
|
||||
flagHonouredForBitmap: !same(proxyTop, proxyNoFlipTop),
|
||||
proxyTop: +proxyTop.toFixed(4),
|
||||
sidecarTop: +sideTop.toFixed(4),
|
||||
proxyBottom: +proxyBottom.toFixed(4),
|
||||
sidecarBottom: +sideBottom.toFixed(4),
|
||||
matchTop: same(proxyTop, sideTop),
|
||||
matchBottom: same(proxyBottom, sideBottom),
|
||||
reversed: same(proxyTop, sideBottom) && same(proxyBottom, sideTop),
|
||||
});
|
||||
} catch (err) {
|
||||
if (!String(pre.textContent).startsWith('ERROR')) {
|
||||
pre.textContent = 'ERROR ' + (err && err.message ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
</script>`;
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
async function drive(chromeBin, url) {
|
||||
const port = 9333 + Math.floor(Math.random() * 200);
|
||||
const child = spawn(
|
||||
chromeBin,
|
||||
[
|
||||
'--headless=new',
|
||||
'--no-sandbox',
|
||||
'--disable-gpu-sandbox',
|
||||
'--use-gl=angle',
|
||||
'--use-angle=swiftshader',
|
||||
'--enable-unsafe-swiftshader',
|
||||
`--remote-debugging-port=${port}`,
|
||||
`--user-data-dir=${path.join(DIR, 'profile')}`,
|
||||
'about:blank',
|
||||
],
|
||||
{ stdio: 'ignore' },
|
||||
);
|
||||
|
||||
try {
|
||||
let target = null;
|
||||
for (let i = 0; i < 120 && !target; i++) {
|
||||
try {
|
||||
const res = await fetch(`http://127.0.0.1:${port}/json/list`);
|
||||
target = (await res.json()).find((t) => t.type === 'page') ?? null;
|
||||
} catch {
|
||||
/* devtools not up yet */
|
||||
}
|
||||
if (!target) await sleep(250);
|
||||
}
|
||||
if (!target) throw new Error('Chrome DevTools endpoint never came up');
|
||||
|
||||
const ws = new WebSocket(target.webSocketDebuggerUrl);
|
||||
await new Promise((resolve, reject) => {
|
||||
ws.onopen = resolve;
|
||||
ws.onerror = () => reject(new Error('DevTools websocket failed'));
|
||||
});
|
||||
let nextId = 1;
|
||||
const pending = new Map();
|
||||
ws.onmessage = (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.id && pending.has(message.id)) {
|
||||
pending.get(message.id)(message);
|
||||
pending.delete(message.id);
|
||||
}
|
||||
};
|
||||
const send = (method, params = {}) => {
|
||||
const id = nextId++;
|
||||
return new Promise((resolve) => {
|
||||
pending.set(id, resolve);
|
||||
ws.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
};
|
||||
|
||||
await send('Page.enable');
|
||||
await send('Runtime.enable');
|
||||
await send('Page.navigate', { url });
|
||||
|
||||
let text = '';
|
||||
const deadline = Date.now() + 90000;
|
||||
while (Date.now() < deadline) {
|
||||
const res = await send('Runtime.evaluate', {
|
||||
expression: "document.getElementById('out')?.textContent ?? ''",
|
||||
returnByValue: true,
|
||||
});
|
||||
text = res.result?.result?.value ?? '';
|
||||
if (text.includes('RESULT') || text.startsWith('ERROR')) break;
|
||||
await sleep(500);
|
||||
}
|
||||
ws.close();
|
||||
return text;
|
||||
} finally {
|
||||
child.kill('SIGKILL');
|
||||
// Chrome writes its profile until the process is gone; give it a moment so
|
||||
// the cleanup below does not race the file handles it still holds.
|
||||
await sleep(500);
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const chromeBin = await findChrome();
|
||||
const { rgb8, rgb16 } = buildSource();
|
||||
await mkdir(DIR, { recursive: true });
|
||||
await writeFile(path.join(DIR, 'proxy.jpg'), await sharp(rgb8, { raw: { width: W, height: H, channels: 3 } })
|
||||
.jpeg({ quality: 96, chromaSubsampling: '4:4:4' })
|
||||
.toBuffer());
|
||||
await writeFile(path.join(DIR, 'side.p16.png'), encodePng16(rgb16, W, H));
|
||||
await writeFile(PAGE, PAGE_HTML);
|
||||
|
||||
const server = await createServer({
|
||||
root: ROOT,
|
||||
logLevel: 'error',
|
||||
server: { host: '127.0.0.1', port: 5199, strictPort: false },
|
||||
});
|
||||
await server.listen();
|
||||
const base = server.resolvedUrls?.local?.[0] ?? 'http://127.0.0.1:5199/';
|
||||
|
||||
let text = '';
|
||||
try {
|
||||
if (!chromeBin) {
|
||||
console.log('render check SKIPPED: no Chrome/Chromium found (set CHROME_PATH to run it).');
|
||||
return 0;
|
||||
}
|
||||
text = await drive(chromeBin, `${base.replace(/\/$/, '')}/.render-check/`);
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
|
||||
if (text.startsWith('ERROR')) {
|
||||
console.error(`render check FAILED: ${text.slice(6)}`);
|
||||
return 1;
|
||||
}
|
||||
const marker = text.indexOf('RESULT');
|
||||
if (marker < 0) {
|
||||
console.error('render check FAILED: the probe never reported a result.');
|
||||
console.error(text.slice(0, 500));
|
||||
return 1;
|
||||
}
|
||||
const result = JSON.parse(text.slice(marker + 7));
|
||||
console.log(
|
||||
`render check: proxy top=${result.proxyTop} bottom=${result.proxyBottom}` +
|
||||
` | sidecar top=${result.sidecarTop} bottom=${result.sidecarBottom}` +
|
||||
` | flip flag honoured for ImageBitmap=${result.flagHonouredForBitmap}`,
|
||||
);
|
||||
if (!result.matchTop || !result.matchBottom) {
|
||||
console.error(
|
||||
result.reversed
|
||||
? 'render check FAILED: the sidecar lands upside down against the proxy.'
|
||||
: 'render check FAILED: proxy and sidecar rows do not line up.',
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
console.log('render check PASSED: proxy and sidecar upload in the same row order.');
|
||||
return 0;
|
||||
}
|
||||
|
||||
let code = 1;
|
||||
try {
|
||||
code = await main();
|
||||
} catch (err) {
|
||||
console.error(`render check FAILED: ${err instanceof Error ? err.message : String(err)}`);
|
||||
} finally {
|
||||
await rm(DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(() => {
|
||||
/* a stray Chrome profile is not worth failing the check over */
|
||||
});
|
||||
}
|
||||
process.exit(code);
|
||||
Reference in New Issue
Block a user