#!/usr/bin/env node // Checks a finished stunt clip: duration, size, frame rate, codec, file size and +faststart; the AI-made tag // (recorded in the edit list, and white text found inside its box in the first and last second); black frames // and sudden flashes outside the planned cut; and the sound (present, not silent, audible in every shot, not // clipped). Writes a contact sheet that you must open and look at (one product in every shot, tiny calm // pedestrians, no readable faces, no text or logos, nothing damaged, the tag in place). // // Usage: // node scripts/check-stunt.mjs --file stunt.mp4 [--edl stunt.mp4.edl.json] [--sheet stunt-sheet.jpg] // [--aspect 9:16|4:5|1:1] [--resolution 720p|1080p] [--min-seconds 8] [--max-seconds 11] // [--max-mb 8] [--muted] [--no-tag] [--ignore 4.2,6-7] // // --muted: the file must have no audio track (landing-page previews). Without it, sound is required. // --no-tag: the user asked for no tag (the check then only notes it). Without it, a missing tag fails. // --ignore takes seconds (each covers +-0.3 s) or ranges a-b where a brightness jump is real (a cloud // clearing the sun, a passing tram) and you have looked at it yourself. // // Requires ffmpeg and ffprobe. Node 18 or newer. Exit code 1 when a check fails. import { spawnSync } from 'node:child_process' import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from 'node:fs' const FLAGS = new Set(['file', 'edl', 'sheet', 'aspect', 'resolution', 'min-seconds', 'max-seconds', 'max-mb', 'muted', 'no-tag', 'ignore']) const SWITCHES = new Set(['muted', 'no-tag']) // Street ambience is quieter than a cutting sound: a shot's loudest moment under -40 dBFS means almost nothing was heard. const SHOT_PEAK_MIN_DB = -40 const CLIP_DB = -0.3 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) } } // Brightest luma (0-255 scale) inside a box of one frame at time t. function boxMax(file, t, box) { const r = run('ffmpeg', ['-hide_banner', '-nostats', '-ss', Math.max(0, t).toFixed(3), '-i', file, '-frames:v', '1', '-vf', `crop=${box.w}:${box.h}:${box.x}:${box.y},signalstats,metadata=print:key=lavfi.signalstats.YMAX`, '-an', '-f', 'null', '-']) const m = (r.stderr || '').match(/YMAX=([\d.]+)/) return m ? Number(m[1]) : null } const o = parse(process.argv.slice(2)) if (!o.file) fail('Usage: node scripts/check-stunt.mjs --file stunt.mp4 [--edl stunt.mp4.edl.json] [--aspect 9:16] [--resolution 720p] [--min-seconds 8] [--max-seconds 11] [--max-mb 8] [--muted] [--no-tag]') 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', '4:5', '1:1'].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) ?? 8 const maxS = number(o['max-seconds'], 'max-seconds', 0, 600) ?? 11 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 (duration < minS - 0.25) issues.push(`Duration ${duration.toFixed(2)} s is under ${minS} s. If a shot was trimmed hard, say so; otherwise re-roll the short shot.`) if (duration > maxS + 0.25) issues.push(`Duration ${duration.toFixed(2)} s is over ${maxS} s. The format is about 10 s; trim the hero shot.`) if (maxMb !== undefined && mb > maxMb) issues.push(`File is ${mb.toFixed(2)} MB, over the ${maxMb} MB limit. Re-run assemble-stunt.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 4.2,6-7, 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) // The AI-made tag. On by default: the clip is a realistic fake, so the file says so. if (!edl) { if (o['no-tag']) notes.push('No --edl given and --no-tag set: the tag check was skipped.') else issues.push('No --edl given, so the AI-made tag cannot be checked. Pass the edit list assemble-stunt.mjs wrote (stunt.mp4.edl.json), or --no-tag if the user asked for no tag.') } else if (!edl.tag) { if (o['no-tag']) notes.push('The AI-made tag is off, as the user asked. Remind them to post with the platform\'s AI label and a caption that says it is CGI.') else issues.push('The AI-made tag is off. It is on by default; re-assemble without --tag off, or pass --no-tag here only if the user asked for no tag.') } else { const early = boxMax(o.file, 0.5, edl.tag.box) const late = boxMax(o.file, Math.max(0, duration - 0.6), edl.tag.box) if (early === null || late === null) issues.push('Could not read the tag box from the clip. Is the edit list from this file?') else if (early < 225 || late < 225) issues.push(`No white tag text found in the tag box at the start (peak ${early}) or the end (peak ${late}). Re-assemble, then look at the first and last frame.`) else notes.push(`AI-made tag "${edl.tag.text}" found in its box at the start and the end.`) } // 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-stunt.mjs with --audio none.') } else if (!a) { issues.push('No audio track. The street sound is part 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 < SHOT_PEAK_MIN_DB) issues.push(`Shot ${s.n} (${s.beat ?? 'shot'}) is nearly silent (peak ${Number.isFinite(beat.max) ? beat.max.toFixed(1) : '-inf'} dBFS). Listen to it; re-roll with a stronger sound line if the street is silent.`) else notes.push(`Shot ${s.n} (${s.beat ?? 'shot'}): peak ${beat.max.toFixed(1)} dBFS.`) } } else notes.push('No --edl given: the per-shot sound check was skipped.') } // Black frames (none are expected in a street clip). 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 blue-hour sky 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 an unplanned cut). Look at this moment; if it is real light, 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-- Stunt 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 clip with sound. Check by eye and ear: the same product in both shots') console.log('(shape and colours as in the photo, same size against the buildings), a real-looking street in the same light,') console.log('pedestrians tiny and calm with no face readable, no text, logos, brand names or number plates anywhere, nothing') console.log('damaged, no smoke or emergency vehicles, the AI-made tag in the top left below the app bar, the product and the') console.log('action clear of the top 12% and the bottom 20%, street sound with no music or speech.') if (issues.length) { console.log('\nFAIL:') for (const i of issues) console.log(` - ${i}`) process.exit(1) } console.log('\nPASS: technical checks.\n')