// Contact sheet of filmed frames, drawn on a canvas in a scratch page of the // same Chrome (no image library needed). /** Picks up to [count] frames evenly, always keeping the first and the last. */ export function pickFrames(frames, count) { if (frames.length <= count) return frames; return Array.from({ length: count }, (_, i) => frames[Math.round((i * (frames.length - 1)) / (count - 1))]); } /** * Renders `[{ data: , label }]` at half size in a [columns]-wide * grid with each label in the corner; resolves to a PNG Buffer. */ export async function contactSheet(browser, frames, { columns = 3, scale = 0.5 } = {}) { const page = await browser.newPage(); try { const expression = `(async () => { const frames = ${JSON.stringify(frames)}; const images = await Promise.all(frames.map((f) => new Promise((ok, fail) => { const im = new Image(); im.onload = () => ok(im); im.onerror = fail; im.src = 'data:image/png;base64,' + f.data; }))); const w = Math.round(images[0].width * ${scale}), h = Math.round(images[0].height * ${scale}); const cols = Math.min(${columns}, images.length), rows = Math.ceil(images.length / cols); const canvas = document.createElement('canvas'); canvas.width = w * cols; canvas.height = h * rows; const g = canvas.getContext('2d'); g.fillStyle = '#000'; g.fillRect(0, 0, canvas.width, canvas.height); images.forEach((im, i) => { const x = (i % cols) * w, y = Math.floor(i / cols) * h; g.drawImage(im, x, y, w, h); g.strokeStyle = '#888'; g.strokeRect(x + 0.5, y + 0.5, w - 1, h - 1); g.font = 'bold 14px sans-serif'; const label = frames[i].label, tw = g.measureText(label).width; g.fillStyle = 'rgba(0,0,0,0.7)'; g.fillRect(x + 4, y + 4, tw + 10, 20); g.fillStyle = '#ff0'; g.fillText(label, x + 9, y + 19); }); return canvas.toDataURL('image/png').split(',')[1]; })()`; const r = await page.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }); if (r.exceptionDetails) throw new Error(`contact sheet: ${r.exceptionDetails.text}`); return Buffer.from(r.result.value, 'base64'); } finally { await page.close(); } }