#!/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)); }); } /** * Horizontal bands that exercise both ends of the range: one and two channels * blown, one clean band, then one and two channels crushed, plus a green+blue * crush to check the secondary colour. The same image proves the clipping * overlay names the channels instead of painting every warning one colour. */ const BANDS = [ [1.0, 0.55, 0.08], // highlight: red only [1.0, 1.0, 0.08], // highlight: red + green (yellow) [0.24, 0.28, 0.35], // nothing clipped [0.0, 0.3, 0.35], // shadow: red only [0.0, 0.0, 0.35], // shadow: red + green (yellow) [0.3, 0.0, 0.0], // shadow: green + blue (cyan) ]; function buildSource() { const rgb16 = new Uint16Array(W * H * 3); const rgb8 = new Uint8Array(W * H * 3); const bands = BANDS; 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 = `
boot`; 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}`, ); console.log( `render check: clipping overlay red=${JSON.stringify(result.clipPixels[0])}` + ` yellow=${JSON.stringify(result.clipPixels[1])}` + ` clear=${JSON.stringify(result.clipPixels[2])}` + ` | at +6EV the clear band is ${JSON.stringify(result.brightPixel)}`, ); console.log( `render check: shadow overlay clear=${JSON.stringify(result.shadowPixels[0])}` + ` red=${JSON.stringify(result.shadowPixels[1])}` + ` yellow=${JSON.stringify(result.shadowPixels[2])}` + ` cyan=${JSON.stringify(result.shadowPixels[3])}` + ` | at -9EV the clean band is ${JSON.stringify(result.shadowDarkPixel)}`, ); console.log( `render check: mask curve identity=${JSON.stringify(result.maskIdentityPixel)}` + ` darkened=${JSON.stringify(result.maskCurvePixel)}`, ); console.log( `render check: mask group subtract=${JSON.stringify(result.maskGroupSubtractPixel)}` + ` intersect=${JSON.stringify(result.maskGroupIntersectPixel)}`, ); 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; } if (!result.clipRed || !result.clipYellow || !result.clipClear) { console.error( 'render check FAILED: the clipping overlay lost its channel colours ' + `(red=${result.clipRed}, yellow=${result.clipYellow}, clear=${result.clipClear}).`, ); return 1; } if (!result.shadowClear || !result.shadowRed || !result.shadowYellow || !result.shadowCyan) { console.error( 'render check FAILED: the shadow clipping overlay lost its channel colours ' + `(clear=${result.shadowClear}, red=${result.shadowRed}, ` + `yellow=${result.shadowYellow}, cyan=${result.shadowCyan}).`, ); return 1; } if (!result.maskIdentityFlat || !result.maskCurveDarkens) { console.error( 'render check FAILED: the per-mask curve is not reaching the grade ' + `(identity=${JSON.stringify(result.maskIdentityPixel)}, ` + `curve=${JSON.stringify(result.maskCurvePixel)}).`, ); return 1; } if (!result.maskGroupSubtractCleared || !result.maskGroupIntersectDarkens) { console.error( 'render check FAILED: mask group shapes are not compositing ' + `(subtract=${JSON.stringify(result.maskGroupSubtractPixel)}, ` + `intersect=${JSON.stringify(result.maskGroupIntersectPixel)}).`, ); return 1; } if (!result.shadowFollowsExposure) { console.error( 'render check FAILED: the shadow clipping overlay does not follow Exposure; ' + `at -9EV the clean band stayed ${JSON.stringify(result.shadowDarkPixel)}.`, ); return 1; } if (!result.clipFollowsExposure) { console.error( 'render check FAILED: the clipping overlay does not follow Exposure; ' + `the unclipped band stayed ${JSON.stringify(result.brightPixel)} at +6 EV.`, ); return 1; } console.log( `render check: brush dab hard=${JSON.stringify(result.dabHard)}` + ` outsideHard=${JSON.stringify(result.dabOutsideHard)} soft=${JSON.stringify(result.dabSoft)}` + ` rimSoft=${JSON.stringify(result.dabRimSoft)} outsideSoft=${JSON.stringify(result.dabOutsideSoft)}`, ); console.log( `render check: mask overlay core=${JSON.stringify(result.tintCore)}` + ` rim=${JSON.stringify(result.tintRim)} outside=${JSON.stringify(result.tintOutside)}`, ); console.log( `render check: crop mask tint on=${JSON.stringify(result.cropTintOn)}` + ` off=${JSON.stringify(result.cropTintOff)} ref=${JSON.stringify(result.cropRef)}` + ` | local detail on=${JSON.stringify(result.cropDetailOn)}` + ` off=${JSON.stringify(result.cropDetailOff)}`, ); console.log( `render check: lens mask tint on=${JSON.stringify(result.lensTintOn)}` + ` off=${JSON.stringify(result.lensTintOff)} ref=${JSON.stringify(result.lensRef)}` + ` | tint strength full=${JSON.stringify(result.tintFull)}` + ` half=${JSON.stringify(result.tintCore)}`, ); if ( !result.cropTintAligned || !result.cropTintBounded || !result.cropDetailAligned || !result.cropDetailBounded || !result.lensTintAligned || !result.lensTintBounded || !result.tintStrengthWorks || !result.tintOffMatches ) { console.error( 'render check FAILED: the local mask does not stay on its source pixels ' + 'through a crop or a lens warp ' + `(crop tint ${JSON.stringify(result.cropTintOn)}/${JSON.stringify(result.cropTintOff)}` + ` vs ${JSON.stringify(result.cropRef)}, detail ` + `${JSON.stringify(result.cropDetailOn)}/${JSON.stringify(result.cropDetailOff)}` + `, lens tint ${JSON.stringify(result.lensTintOn)}/${JSON.stringify(result.lensTintOff)}` + ` vs ${JSON.stringify(result.lensRef)}).`, ); return 1; } if (!result.splitShowsBoth) { console.error( 'render check FAILED: the before / after split does not follow its drag line ' + `(left=${JSON.stringify(result.splitLeft)} vs ${JSON.stringify(result.splitBeforeFull)}, ` + `right=${JSON.stringify(result.splitRight)} vs ${JSON.stringify(result.splitAfterFull)}).`, ); return 1; } if ( !result.dabCoreDarkened || !result.dabSoftCoreDarkened || !result.dabRimSmooth || !result.dabBoundedHard || !result.dabBoundedSoft || !result.tintFollowsMask || !result.tintBounded ) { console.error( 'render check FAILED: the brush mask does not follow the brush circle ' + `(hard=${JSON.stringify(result.dabHard)}, rim=${JSON.stringify(result.dabRimSoft)}, ` + `outsideHard=${JSON.stringify(result.dabOutsideHard)}, ` + `outsideSoft=${JSON.stringify(result.dabOutsideSoft)}, ` + `tint=${JSON.stringify(result.tintCore)}/${JSON.stringify(result.tintRim)}/` + `${JSON.stringify(result.tintOutside)}).`, ); return 1; } console.log( `render check: before / after split left=${JSON.stringify(result.splitLeft)}` + ` right=${JSON.stringify(result.splitRight)}`, ); console.log( 'render check PASSED: proxy and sidecar share a row order, the clipping overlay names the channels, and the split keeps each side to its own edit.', ); 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);