#!/usr/bin/env node // Checks a finished reveal: size, duration, codec, +faststart and that it is silent; that the first frames hold still; // that the loading bar fills; that a white frame lands on the beat (and matches the edit list and the chapter marker); // that the after part moves; and that there are no black frames or surprise flashes. Writes a contact sheet and a strip // of the frames around the beat. You must open both and look. // // Usage: // node scripts/check-reveal.mjs --file reveal.mp4 [--edl reveal.mp4.edl.json] [--sheet reveal-sheet.jpg] // [--beat-strip reveal-beat.jpg] [--max-mb 8] [--ignore 4.2,5-6] // // --ignore takes seconds (each covers +-0.3 s) or ranges a-b where a brightness jump is real (a light coming on in the // after) and you have looked at it yourself. Ignored moments are still listed as notes. // Requires ffmpeg and ffprobe. Node 18 or newer. Exit code 1 when a check fails. import { spawnSync } from 'node:child_process' import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, readSync, rmSync, statSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' const FLAGS = new Set(['file', 'edl', 'sheet', 'beat-strip', 'max-mb', 'ignore']) const WHITE_MIN = 235 // average luma (0 to 255) of the beat frame const FROZEN_SSIM_MIN = 0.97 const MOVING_SSIM_MAX = 0.995 function fail(message) { console.error(message) process.exit(1) } function parse(argv) { const out = {} for (let i = 0; i < argv.length; i++) { const a = argv[i] if (!a.startsWith('--')) fail(`Unexpected argument "${a}". Flags look like --name value.`) const key = a.slice(2) if (!FLAGS.has(key)) fail(`Unknown flag --${key}. Allowed: ${[...FLAGS].map((f) => `--${f}`).join(', ')}`) const value = argv[i + 1] if (value === undefined || value.startsWith('--')) fail(`--${key} needs a value.`) out[key] = value i++ } return out } function run(cmd, args) { const r = spawnSync(cmd, args, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 }) if (r.error?.code === 'ENOENT') fail(`${cmd} is not installed or not on PATH. Install ffmpeg (it includes ffprobe).`) return r } // True when the moov atom comes before mdat (the file can start playing before it has fully downloaded). function isFaststart(path) { const fd = openSync(path, 'r') const size = statSync(path).size const head = Buffer.alloc(8) let pos = 0 try { while (pos + 8 <= size) { readSync(fd, head, 0, 8, pos) let len = head.readUInt32BE(0) const type = head.toString('ascii', 4, 8) if (type === 'moov') return true if (type === 'mdat') return false if (len === 1) { const big = Buffer.alloc(8) readSync(fd, big, 0, 8, pos + 8) len = Number(big.readBigUInt64BE(0)) } if (len < 8) return false pos += len } } finally { closeSync(fd) } return false } // Average luma per frame of the (optionally cropped) video: [[time, value], ...]. function lumaTrack(file, crop) { const vf = `${crop ? `${crop},` : ''}scale=160:-2:flags=area,signalstats,metadata=print:key=lavfi.signalstats.YAVG` const r = run('ffmpeg', ['-hide_banner', '-nostats', '-i', file, '-vf', vf, '-an', '-f', 'null', '-']) return [...(r.stderr || '').matchAll(/pts_time:([\d.]+)[\s\S]*?YAVG=([\d.]+)/g)].map((m) => [Number(m[1]), Number(m[2])]) } function ssimOf(file, at1, at2, crop, tmp) { const a = join(tmp, 'a.png') const b = join(tmp, 'b.png') const vf = crop ?? 'null' run('ffmpeg', ['-y', '-hide_banner', '-v', 'error', '-ss', at1.toFixed(3), '-i', file, '-vf', vf, '-frames:v', '1', a]) run('ffmpeg', ['-y', '-hide_banner', '-v', 'error', '-ss', at2.toFixed(3), '-i', file, '-vf', vf, '-frames:v', '1', b]) if (!existsSync(a) || !existsSync(b)) return null const r = run('ffmpeg', ['-hide_banner', '-nostats', '-i', a, '-i', b, '-lavfi', 'ssim', '-f', 'null', '-']) const m = (r.stderr || '').match(/All:([\d.]+)/) return m ? Number(m[1]) : null } const o = parse(process.argv.slice(2)) if (!o.file) fail('Usage: node scripts/check-reveal.mjs --file reveal.mp4 [--edl reveal.mp4.edl.json] [--max-mb 8] [--ignore 4.2]') if (!existsSync(o.file)) fail(`File not found: ${o.file}`) if (!/\.(mp4|mov|webm)$/i.test(o.file)) fail(`${o.file} is not a video file. Pass the finished .mp4.`) const maxMb = o['max-mb'] === undefined ? 8 : Number(o['max-mb']) if (!Number.isFinite(maxMb) || maxMb < 0.1) fail('--max-mb must be a number of at least 0.1.') const p = run('ffprobe', ['-v', 'error', '-print_format', 'json', '-show_streams', '-show_format', '-show_chapters', o.file]) if (p.status !== 0) fail(`ffprobe could not read ${o.file}. Is it a video file?`) const info = JSON.parse(p.stdout) const v = info.streams.find((s) => s.codec_type === 'video') if (!v) fail(`${o.file} has no video stream.`) const audio = info.streams.find((s) => s.codec_type === 'audio') const duration = Number(info.format.duration) const [fn, fd] = (v.r_frame_rate || '0/1').split('/').map(Number) const fps = fd ? fn / fd : 0 const mb = statSync(o.file).size / 1024 / 1024 const issues = [] const notes = [] if (Math.abs(v.width / v.height - 9 / 16) > 0.03) issues.push(`Aspect is ${v.width}x${v.height}, expected 9:16.`) if (Math.min(v.width, v.height) < 720) issues.push(`Frame is ${v.width}x${v.height}, under 720 wide.`) if (duration < 5.75 || duration > 8.25) issues.push(`Duration ${duration.toFixed(2)} s is outside the 6 to 8 s format.`) if (mb > maxMb) issues.push(`File is ${mb.toFixed(2)} MB, over the ${maxMb} MB limit. Re-run assemble-reveal.mjs with --max-mb ${maxMb}.`) if (v.codec_name !== 'h264') issues.push(`Video codec is ${v.codec_name}; H.264 plays everywhere, re-export with libx264.`) if (v.pix_fmt !== 'yuv420p') issues.push(`Pixel format is ${v.pix_fmt}; use yuv420p for browser playback.`) if (Math.abs(fps - 24) > 0.05 && Math.abs(fps - 25) > 0.05 && Math.abs(fps - 30) > 0.05) issues.push(`Frame rate ${fps.toFixed(2)} fps is unusual.`) if (!isFaststart(o.file)) issues.push('moov atom is at the end: add -movflags +faststart so the video starts before it fully downloads.') if (audio) issues.push('The file has an audio track. The reveal is silent by design so the user can add a trending sound in the app: re-assemble with assemble-reveal.mjs (it writes no audio).') let edl = null if (o.edl) { if (!existsSync(o.edl)) fail(`Edit list not found: ${o.edl}`) edl = JSON.parse(readFileSync(o.edl, 'utf8')) } const ignored = [] if (o.ignore) { for (const part of String(o.ignore).split(',').map((x) => x.trim()).filter(Boolean)) { const m = part.match(/^(\d+(?:\.\d+)?)(?:-(\d+(?:\.\d+)?))?$/) if (!m) fail(`--ignore takes seconds or ranges like 4.2,5-6, not "${part}".`) const x = Number(m[1]) const y = m[2] === undefined ? undefined : Number(m[2]) if (y !== undefined && y < x) fail(`--ignore range "${part}" ends before it starts.`) ignored.push(y === undefined ? [x - 0.3, x + 0.3] : [x, y]) } } const dismissed = (t) => ignored.some(([s, e]) => t >= s && t <= e) // The beat: the brightest frame in the first half of the video (the white flash). With an edit list it must match. const luma = lumaTrack(o.file) if (luma.length < 24) fail('Could not read the frames of the video for the flash check.') let beatIdx = 0 for (let i = 0; i < luma.length; i++) if (luma[i][1] > luma[beatIdx][1] && luma[i][0] < duration * 0.7) beatIdx = i const [beatT, beatY] = luma[beatIdx] if (beatY < WHITE_MIN) issues.push(`No white flash found: the brightest frame in the first 70% averages ${beatY.toFixed(0)} of 255 (need ${WHITE_MIN}). Re-assemble with assemble-reveal.mjs; the flash is drawn locally, not by the video model.`) else notes.push(`Beat: the first white frame is at ${beatT.toFixed(3)} s (frame ${beatIdx}).`) // If several frames are fully white, the beat is the first of them. for (let i = 0; i < luma.length; i++) { if (luma[i][1] >= WHITE_MIN && luma[i][0] < duration * 0.7) { beatIdx = i break } } const beat = luma[beatIdx][0] if (edl?.beat) { if (Math.abs(edl.beat.seconds - beat) > 1.5 / fps) issues.push(`The edit list puts the beat at ${edl.beat.seconds} s but the first white frame is at ${beat.toFixed(3)} s.`) const chapter = (info.chapters ?? []).find((c) => /beat/i.test(c.tags?.title ?? '')) if (edl.chapters === false) notes.push('Made without chapters (--no-chapters): use the printed beat time.') else if (!chapter) issues.push('No "Beat" chapter in the MP4. It marks the cut point for editors that read chapters: re-assemble without --no-chapters.') else if (Math.abs(Number(chapter.start_time) - edl.beat.seconds) > 0.02) issues.push(`The "Beat" chapter starts at ${chapter.start_time} s, not at the beat (${edl.beat.seconds} s).`) else notes.push(`Chapter "Beat" at ${Number(chapter.start_time).toFixed(3)} s matches.`) } if (beat < 1.4 || beat > 3.2) issues.push(`The beat is at ${beat.toFixed(2)} s. The before frame should hold for about 2 s (1.5 to 3).`) const beforeLen = beat const afterLen = duration - beat if (afterLen < 3.5) issues.push(`The after part is ${afterLen.toFixed(2)} s; keep at least 3.5 s of motion.`) // The before frame is frozen: the part above the loading panel does not move. const tmp = mkdtempSync(join(tmpdir(), 'check-reveal-')) const panelY = edl?.loader?.panel?.[1] ?? Math.round(v.height * 0.5) const topH = Math.max(64, Math.min(v.height, panelY - 8)) const topCrop = `crop=${v.width}:${topH}:0:0` const frozen = ssimOf(o.file, 0.25, Math.max(0.5, beforeLen - 0.45), topCrop, tmp) if (frozen === null) notes.push('Could not compare the before frames.') else if (frozen < FROZEN_SSIM_MIN) issues.push(`The before frame is not frozen: frames at the start and end of the hold differ (SSIM ${frozen.toFixed(3)}, need ${FROZEN_SSIM_MIN}).`) else notes.push(`Before frame frozen (SSIM ${frozen.toFixed(3)}).`) // The loading bar fills, never goes backwards. if (edl?.loader?.fill) { const [fx, fy, fw, fh] = edl.loader.fill const bar = lumaTrack(o.file, `crop=${fw}:${fh}:${fx}:${fy}`).filter(([t]) => t >= 0.1 && t < beforeLen - 0.2) if (bar.length < 8) notes.push('Too few frames to check the bar.') else { let back = 0 for (let i = 1; i < bar.length; i++) if (bar[i][1] < bar[i - 1][1] - 3) back++ const rise = bar[bar.length - 1][1] - bar[0][1] if (back) issues.push(`The loading bar goes backwards in ${back} frame(s).`) if (rise < 40) issues.push(`The loading bar barely fills (brightness rises by ${rise.toFixed(0)}). Check the overlay; a very dark --accent can cause this.`) else notes.push(`Loading bar fills (brightness ${bar[0][1].toFixed(0)} to ${bar[bar.length - 1][1].toFixed(0)}).`) } } else notes.push('No --edl given: the loading bar check was skipped.') // The after part moves. const moving = ssimOf(o.file, beat + 0.9, Math.max(beat + 1.2, duration - 0.3), null, tmp) if (moving === null) notes.push('Could not compare the after frames.') else if (moving >= MOVING_SSIM_MAX) issues.push(`The after part looks frozen (SSIM ${moving.toFixed(4)} between its early and late frames). Re-roll the final with a clearer movement.`) else notes.push(`After part moves (SSIM ${moving.toFixed(3)} between early and late frames).`) rmSync(tmp, { recursive: true, force: true }) // Black frames: none are expected. const black = run('ffmpeg', ['-hide_banner', '-nostats', '-i', o.file, '-vf', 'blackdetect=d=0.25:pix_th=0.06', '-an', '-f', 'null', '-']) for (const m of (black.stderr || '').matchAll(/black_start:([\d.]+) black_end:([\d.]+)/g)) { const [s, e] = [Number(m[1]), Number(m[2])] if (dismissed(s)) notes.push(`Black ${s.toFixed(2)}-${e.toFixed(2)} s (ignored with --ignore).`) else issues.push(`Black frames from ${s.toFixed(2)} s to ${e.toFixed(2)} s. A dark scene can trip this: look, and if the frame is real, re-run with --ignore ${s.toFixed(1)}-${e.toFixed(1)}.`) } // Brightness jumps other than the flash: flicker, a pop or an unplanned cut in the after part. const lo = beat - 3 / fps const hi = beat + (edl?.after?.flash_clear ?? 0.25) + 0.15 let flashes = 0 for (let i = 1; i < luma.length; i++) { const [t, y] = luma[i] const jump = Math.abs(y - luma[i - 1][1]) if (jump <= 14 || (t >= lo && t <= hi)) continue if (dismissed(t)) notes.push(`Brightness jump ${jump.toFixed(1)} at ${t.toFixed(2)} s (ignored with --ignore).`) else { flashes++ if (flashes <= 5) issues.push(`Brightness jumps by ${jump.toFixed(1)} at ${t.toFixed(2)} s outside the flash (flicker, a pop or an unplanned cut). Look at this moment; if it is real, re-run with --ignore ${t.toFixed(1)}.`) } } if (flashes > 5) issues.push(`${flashes - 5} more brightness jumps not listed.`) // Contact sheet (2 fps) and a strip of eight frames around the beat. const sheet = o.sheet || o.file.replace(/\.(mp4|mov|webm)$/i, '') + '-sheet.jpg' const rows = Math.max(1, Math.ceil((duration * 2) / 8)) const s1 = run('ffmpeg', ['-y', '-hide_banner', '-v', 'error', '-i', o.file, '-vf', `fps=2,scale=180:-2,tile=8x${rows}`, '-frames:v', '1', sheet]) if (s1.status !== 0) notes.push('Could not write the contact sheet.') const strip = o['beat-strip'] || o.file.replace(/\.(mp4|mov|webm)$/i, '') + '-beat.jpg' const first = Math.max(0, beatIdx - 3) const s2 = run('ffmpeg', ['-y', '-hide_banner', '-v', 'error', '-i', o.file, '-vf', `select='between(n,${first},${first + 7})',scale=180:-2,tile=8x1`, '-frames:v', '1', '-fps_mode', 'passthrough', strip]) if (s2.status !== 0) notes.push('Could not write the beat strip.') console.log('\n-- Reveal check -----------------------------------------') console.log(` File ${o.file}`) console.log(` Duration ${duration.toFixed(2)} s (before ${beforeLen.toFixed(2)} s, after ${afterLen.toFixed(2)} s)`) console.log(` Frame ${v.width}x${v.height}, ${fps.toFixed(2)} fps, ${v.codec_name} ${v.pix_fmt}`) console.log(` Audio ${audio ? `${audio.codec_name} (should be none)` : 'none (silent by design)'}`) console.log(` Size ${mb.toFixed(2)} MB`) console.log(` Beat ${beat.toFixed(3)} s, frame ${beatIdx}`) console.log(` Sheet ${sheet}`) console.log(` Beat strip ${strip}`) for (const n of notes) console.log(` note: ${n}`) console.log('---------------------------------------------------------') console.log('Now open the contact sheet and the beat strip, and watch the reveal twice. Check by eye: the loading label is spelled') console.log('exactly and sits clear of the bottom 20%; the before frame is your photo, still; the after is the same place and subject') console.log('with only the planned change; no extra people or animals; no text, logos or interface drawn by the model; nothing') console.log('essential in the top 12% or bottom 20%; the flash hides the swap instead of showing a jump.') if (issues.length) { console.log('\nFAIL:') for (const i of issues) console.log(` - ${i}`) process.exit(1) } console.log('\nPASS: technical checks.\n')