#!/usr/bin/env node // Checks a finished reel: duration, size, frame rate, codec, file size and +faststart; black frames and // sudden flashes outside the planned cuts; the sound (present, not silent, a clear sound in every beat, // not clipped); and, with --loop, that the last frame matches the first so the reel loops without a jump. // Writes a contact sheet that you must open and look at (one object, one material, gloved or no hand, // no extra hands or people, no text). // // Usage: // node scripts/check-reel.mjs --file reel.mp4 [--edl reel.mp4.edl.json] [--sheet reel-sheet.jpg] // [--aspect 9:16|4:5|1:1] [--resolution 720p|1080p] [--min-seconds 15] [--max-seconds 20] // [--max-mb 8] [--muted] [--loop] [--ignore 6.2,11-14.5] // // --muted: the file must have no audio track (landing-page previews). Without it, sound is required. // --ignore takes seconds (each covers +-0.3 s) or ranges a-b where a brightness jump is real (a glint // sweeping across glass) 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', 'aspect', 'resolution', 'min-seconds', 'max-seconds', 'max-mb', 'muted', 'loop', 'ignore']) const SWITCHES = new Set(['muted', 'loop']) // Thresholds. A beat's loudest moment under -35 dBFS means no clear cutting sound was made. const BEAT_PEAK_MIN_DB = -35 const CLIP_DB = -0.3 const LOOP_SSIM_MIN = 0.97 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(', ')}`) if (SWITCHES.has(key)) { out[key] = true; continue } const value = argv[i + 1] if (value === undefined || value.startsWith('--')) fail(`--${key} needs a value.`) out[key] = value i++ } return out } function number(value, name, min, max) { if (value === undefined) return undefined const n = Number(value) if (!Number.isFinite(n) || n < min || n > max) fail(`--${name} must be a number from ${min} to ${max}, got "${value}".`) return n } 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 } // Loudest and mean level (dBFS) of the audio between start and start + len. function levels(file, start, len) { const r = run('ffmpeg', ['-hide_banner', '-nostats', '-ss', start.toFixed(3), '-t', len.toFixed(3), '-i', file, '-vn', '-af', 'volumedetect', '-f', 'null', '-']) const max = (r.stderr || '').match(/max_volume:\s*(-?[\d.]+|-inf) dB/) const mean = (r.stderr || '').match(/mean_volume:\s*(-?[\d.]+|-inf) dB/) const toNum = (m) => (!m ? -Infinity : m[1] === '-inf' ? -Infinity : Number(m[1])) return { max: toNum(max), mean: toNum(mean) } } const o = parse(process.argv.slice(2)) if (!o.file) fail('Usage: node scripts/check-reel.mjs --file reel.mp4 [--edl reel.mp4.edl.json] [--aspect 9:16] [--resolution 720p] [--min-seconds 15] [--max-seconds 20] [--max-mb 8] [--muted] [--loop]') 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 aspect = o.aspect ?? '9:16' if (!['9:16', '1:1', '4:5'].includes(aspect)) fail(`--aspect must be 9:16, 4:5 or 1:1, not "${aspect}".`) const resolution = o.resolution if (resolution && !['720p', '1080p'].includes(resolution)) fail(`--resolution must be 720p or 1080p, not "${resolution}".`) const minS = number(o['min-seconds'], 'min-seconds', 0, 600) const maxS = number(o['max-seconds'], 'max-seconds', 0, 600) const maxMb = number(o['max-mb'], 'max-mb', 0.1, 2000) const p = run('ffprobe', ['-v', 'error', '-print_format', 'json', '-show_streams', '-show_format', 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 a = 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 = [] const short = Math.min(v.width, v.height) const resLabel = short >= 1080 ? '1080p' : short >= 720 ? '720p' : `${short}p` const ratios = { '9:16': 9 / 16, '1:1': 1, '4:5': 4 / 5 } if (Math.abs(v.width / v.height - ratios[aspect]) > 0.03) issues.push(`Aspect is ${v.width}x${v.height}, expected ${aspect}.`) if (resolution && aspect === '9:16' && resLabel !== resolution) issues.push(`Resolution is ${resLabel} (${v.width}x${v.height}), expected ${resolution}.`) if (minS !== undefined && duration < minS - 0.25) issues.push(`Duration ${duration.toFixed(2)} s is under ${minS} s.`) if (maxS !== undefined && duration > maxS + 0.25) issues.push(`Duration ${duration.toFixed(2)} s is over ${maxS} s.`) if (maxMb !== undefined && mb > maxMb) issues.push(`File is ${mb.toFixed(2)} MB, over the ${maxMb} MB limit. Re-run assemble-reel.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.') let edl = null let windows = [] if (o.edl) { if (!existsSync(o.edl)) fail(`Edit list not found: ${o.edl}`) edl = JSON.parse(readFileSync(o.edl, 'utf8')) windows = (edl.joins || []).map((j) => [j.at - 0.12, j.at + (j.d || 0) + 0.12]) } 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 6.2,11-14.5, 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 planned = (t) => windows.some(([s, e]) => t >= s && t <= e) const dismissed = (t) => ignored.some(([s, e]) => t >= s && t <= e) // Sound. if (o.muted) { if (a) issues.push('The file has an audio track but --muted was asked for (landing-page previews must be silent). Re-run assemble-reel.mjs with --audio none.') } else if (!a) { issues.push('No audio track. The cutting sound is the point of the format: assemble with --audio clips (or pass --muted for a silent web preview).') } else { const whole = levels(o.file, 0, duration) notes.push(`Sound: mean ${whole.mean.toFixed(1)} dBFS, peak ${whole.max.toFixed(1)} dBFS.`) if (!Number.isFinite(whole.max) || whole.max < -50) issues.push('The audio track is silent. Check generate_audio was true on every final.') if (whole.max >= CLIP_DB) issues.push(`The sound peaks at ${whole.max.toFixed(1)} dBFS and may clip. Re-assemble with --gain -3.`) if (edl?.shots?.length) { for (const s of edl.shots) { const beat = levels(o.file, s.start, s.length) if (!Number.isFinite(beat.max) || beat.max < BEAT_PEAK_MIN_DB) issues.push(`Shot ${s.n} (${s.beat ?? 'beat'}) has no clear sound (peak ${Number.isFinite(beat.max) ? beat.max.toFixed(1) : '-inf'} dBFS). Listen to it; re-roll with a stronger sound line if the cut is silent.`) else notes.push(`Shot ${s.n} (${s.beat ?? 'beat'}): peak ${beat.max.toFixed(1)} dBFS.`) } } else notes.push('No --edl given: the per-beat sound check was skipped.') } // Loop seam: the last frame should be the first frame. if (o.loop) { const tmp = mkdtempSync(join(tmpdir(), 'check-reel-')) const first = join(tmp, 'first.png') const last = join(tmp, 'last.png') run('ffmpeg', ['-y', '-hide_banner', '-v', 'error', '-i', o.file, '-frames:v', '1', first]) run('ffmpeg', ['-y', '-hide_banner', '-v', 'error', '-sseof', '-0.5', '-i', o.file, '-update', '1', '-q:v', '1', last]) if (!existsSync(first) || !existsSync(last)) issues.push('Could not read the first and last frames for the loop check.') else { const r = run('ffmpeg', ['-hide_banner', '-nostats', '-i', first, '-i', last, '-lavfi', 'ssim', '-f', 'null', '-']) const m = (r.stderr || '').match(/All:([\d.]+)/) const ssim = m ? Number(m[1]) : 0 if (ssim < LOOP_SSIM_MIN) issues.push(`Loop seam: the last frame matches the first at SSIM ${ssim.toFixed(3)} (need ${LOOP_SSIM_MIN}). Assemble with --loop-tail 0.5, or drop --loop if this reel is not meant to loop.`) else notes.push(`Loop seam: last frame matches the first (SSIM ${ssim.toFixed(3)}).`) } rmSync(tmp, { recursive: true, force: true }) } // Black frames (none are expected anywhere in a looping reel). 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 backdrop can trip this: look, and if the frame is real, re-run with --ignore ${s.toFixed(1)}-${e.toFixed(1)}.`) } // Sudden brightness jumps between consecutive frames: flicker, a pop, or an unplanned cut. const stats = run('ffmpeg', ['-hide_banner', '-nostats', '-i', o.file, '-vf', 'scale=160:-2,signalstats,metadata=print:key=lavfi.signalstats.YAVG', '-an', '-f', 'null', '-']) const ys = [...(stats.stderr || '').matchAll(/pts_time:([\d.]+)[\s\S]*?YAVG=([\d.]+)/g)].map((m) => [Number(m[1]), Number(m[2])]) let flashes = 0 for (let i = 1; i < ys.length; i++) { const [t, y] = ys[i] const jump = Math.abs(y - ys[i - 1][1]) if (jump > 14 && !planned(t) && dismissed(t)) notes.push(`Brightness jump ${jump.toFixed(1)} at ${t.toFixed(2)} s (ignored with --ignore).`) else if (jump > 14 && !planned(t)) { flashes++ if (flashes <= 5) issues.push(`Brightness jumps by ${jump.toFixed(1)} at ${t.toFixed(2)} s (flicker, pop or unplanned cut). Look at this moment; if it is a real glint, re-run with --ignore ${t.toFixed(1)}.`) } } if (flashes > 5) issues.push(`${flashes - 5} more brightness jumps not listed.`) // Contact sheet: two frames per second, eight across. const sheet = o.sheet || o.file.replace(/\.(mp4|mov|webm)$/i, '') + '-sheet.jpg' const rows = Math.max(1, Math.ceil((duration * 2) / 8)) const s = run('ffmpeg', ['-y', '-hide_banner', '-v', 'error', '-i', o.file, '-vf', `fps=2,scale=180:-2,tile=8x${rows}`, '-frames:v', '1', sheet]) if (s.status !== 0) notes.push('Could not write the contact sheet.') console.log('\n-- Reel check -------------------------------------------') console.log(` File ${o.file}`) console.log(` Duration ${duration.toFixed(2)} s`) console.log(` Frame ${v.width}x${v.height} (${resLabel}), ${fps.toFixed(2)} fps, ${v.codec_name} ${v.pix_fmt}`) console.log(` Audio ${a ? `${a.codec_name} ${a.channels ?? ''}ch` : 'none'}`) console.log(` Size ${mb.toFixed(2)} MB`) console.log(` Sheet ${sheet}`) for (const n of notes) console.log(` note: ${n}`) console.log('---------------------------------------------------------') console.log('Now open the contact sheet and watch the reel with sound. Check by eye and ear: one object in one material') console.log('in every beat, the knife enters from the frame edge, the hand is gloved and cropped (or absent), fingers never') console.log('near the blade, no extra hands, people, faces or animals, no text or garbled logos, the inside matches the plan,') console.log('one clear sound per beat with no music or voices, nothing essential in the top 12% or bottom 20% of the frame.') if (issues.length) { console.log('\nFAIL:') for (const i of issues) console.log(` - ${i}`) process.exit(1) } console.log('\nPASS: technical checks.\n')