#!/usr/bin/env node // Checks one pet clip: duration, size, codec, frame rate, file size, +faststart and sound (present, not // silent), looks for cuts, black frames and flashes (the format is one unbroken take), and writes // - a pet board: the pet photo, the keyframe, and the clip's first, middle and last frames (compare coat, // markings and size), and // - a contact sheet: 2 frames a second over the whole clip (look at paws, extra animals or people, text). // Open both images and go through references/output-spec.md before delivering. // // Usage: // node scripts/check-clip.mjs --file clip.mp4 --pet pet.jpg [--keyframe keyframe.jpg] [--board board.jpg] // [--sheet sheet.jpg] [--seconds 8] [--aspect 9:16] [--resolution 720p] [--max-mb 8] [--muted] // [--ignore 5.2,6-7] // // --ignore takes seconds (each covers +-0.3 s) or ranges a-b where a brightness jump is real and you have // looked at it: a fridge door opening, a lamp switched on. Ignored moments are still listed as notes. // --muted checks a silent web preview instead of the delivered clip (which must have sound). // 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, readSync, rmSync, statSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' const FLAGS = new Set(['file', 'pet', 'keyframe', 'board', 'sheet', 'seconds', 'aspect', 'resolution', 'max-mb', 'muted', 'ignore']) const SWITCHES = new Set(['muted']) function fail(message) { console.error(message) process.exit(1) } const o = {} const argv = process.argv.slice(2) 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)) { o[key] = true continue } const value = argv[i + 1] if (value === undefined || value.startsWith('--')) fail(`--${key} needs a value.`) o[key] = value i++ } if (!o.file || !o.pet) fail('Usage: node scripts/check-clip.mjs --file clip.mp4 --pet pet.jpg [--keyframe keyframe.jpg] [--board board.jpg] [--sheet sheet.jpg] [--seconds 8] [--aspect 9:16] [--resolution 720p] [--max-mb 8] [--muted] [--ignore 5.2]') for (const key of ['file', 'pet', 'keyframe']) if (o[key] && !existsSync(o[key])) fail(`Not found: ${o[key]}`) if (!/\.(mp4|mov|webm)$/i.test(o.file)) fail(`${o.file} is not a video file. Pass the clip (.mp4).`) for (const key of ['pet', 'keyframe']) if (o[key] && !/\.(jpe?g|png|webp)$/i.test(o[key])) fail(`--${key} must be a .jpg, .png or .webp image.`) const number = (key, fallback, min, max) => { const n = Number(o[key] ?? fallback) if (!Number.isFinite(n) || n < min || n > max) fail(`--${key} must be a number from ${min} to ${max}, got "${o[key]}".`) return n } const seconds = number('seconds', 8, 2, 30) const maxMb = number('max-mb', 8, 0.1, 500) const aspect = o.aspect ?? '9:16' const ratios = { '9:16': 9 / 16, '16:9': 16 / 9, '1:1': 1, '4:5': 4 / 5 } if (!ratios[aspect]) fail(`--aspect must be 9:16, 16:9, 1:1 or 4:5, not "${aspect}".`) const resolution = o.resolution ?? '720p' if (!['480p', '720p', '1080p'].includes(resolution)) fail(`--resolution must be 480p, 720p or 1080p, not "${resolution}".`) 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 clip 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 } 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 short = Math.min(v.width, v.height) const resLabel = short >= 1080 ? '1080p' : short >= 720 ? '720p' : short >= 480 ? '480p' : `${short}p` const issues = [] const notes = [] if (Math.abs(v.width / v.height - ratios[aspect]) > 0.03) issues.push(`Aspect is ${v.width}x${v.height}, expected ${aspect}.`) if (resLabel !== resolution) issues.push(`Resolution is ${resLabel} (${v.width}x${v.height}), expected ${resolution}.`) if (Math.abs(duration - seconds) > 0.5) issues.push(`Duration ${duration.toFixed(2)} s, expected ${seconds} s.`) if (mb > maxMb) issues.push(`File is ${mb.toFixed(2)} MB, over ${maxMb} MB. Re-run finish-clip.mjs (CRF 20, 6 Mbit/s cap).`) if (v.codec_name !== 'h264') issues.push(`Video codec is ${v.codec_name}; run finish-clip.mjs for H.264.`) if (v.pix_fmt !== 'yuv420p') issues.push(`Pixel format is ${v.pix_fmt}; use yuv420p for phones and browsers.`) if (fps < 23.5 || fps > 60.5) issues.push(`Frame rate ${fps.toFixed(2)} fps is unusual.`) if (!isFaststart(o.file)) issues.push('moov atom is at the end: run finish-clip.mjs (it adds +faststart).') let meanDb = null if (o.muted) { if (a) issues.push('The file has a sound track but --muted was asked for. Re-run finish-clip.mjs with --muted.') } else if (!a) { issues.push('No sound track. The format lives on natural room sound: generate the final with sound and finish without --muted.') } else { const vol = run('ffmpeg', ['-hide_banner', '-nostats', '-i', o.file, '-vn', '-af', 'volumedetect', '-f', 'null', '-']) meanDb = Number((vol.stderr || '').match(/mean_volume:\s*(-?[\d.]+) dB/)?.[1]) if (Number.isFinite(meanDb) && meanDb < -55) issues.push(`The sound track is nearly silent (mean ${meanDb.toFixed(1)} dB). Listen to it; re-roll the final if the room sound is missing.`) } const ignored = [] 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 5.2,6-7, not "${part}".`) const s = Number(m[1]) const e = m[2] === undefined ? undefined : Number(m[2]) if (e !== undefined && e < s) fail(`--ignore range "${part}" ends before it starts.`) ignored.push(e === undefined ? [s - 0.3, s + 0.3] : [s, e]) } const dismissed = (t) => ignored.some(([s, e]) => t >= s && t <= e) // Cuts: one unbroken take has no scene changes. const scenes = run('ffmpeg', ['-hide_banner', '-nostats', '-i', o.file, '-an', '-vf', "scale=320:-2,select='gt(scene,0.4)',metadata=print", '-f', 'null', '-']) const cuts = [...(scenes.stderr || '').matchAll(/pts_time:([\d.]+)/g)].map((m) => Number(m[1])) for (const t of cuts) { if (dismissed(t)) notes.push(`Possible cut at ${t.toFixed(2)} s (ignored with --ignore).`) else issues.push(`Possible cut or jump at ${t.toFixed(2)} s. The format is one unbroken take: look at this moment, re-roll if it cuts.`) } // Black frames (a phone take never goes black). const black = run('ffmpeg', ['-hide_banner', '-nostats', '-i', o.file, '-an', '-vf', 'blackdetect=d=0.2:pix_th=0.06', '-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.`) } // Sudden brightness jumps between frames: flicker, a pop or a cut. const stats = run('ffmpeg', ['-hide_banner', '-nostats', '-i', o.file, '-an', '-vf', 'scale=160:-2,signalstats,metadata=print:key=lavfi.signalstats.YAVG', '-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) continue if (dismissed(t)) notes.push(`Brightness jump ${jump.toFixed(1)} at ${t.toFixed(2)} s (ignored with --ignore).`) else if (++flashes <= 3) issues.push(`Brightness jumps by ${jump.toFixed(1)} at ${t.toFixed(2)} s. Look at it; if it is a real light (a fridge door), re-run with --ignore ${t.toFixed(1)}.`) } if (flashes > 3) issues.push(`${flashes - 3} more brightness jumps not listed.`) // Pet board: pet photo | keyframe | first | middle | last. const board = o.board || o.file.replace(/\.(mp4|mov|webm)$/i, '') + '-board.jpg' const sheet = o.sheet || o.file.replace(/\.(mp4|mov|webm)$/i, '') + '-sheet.jpg' const work = mkdtempSync(join(tmpdir(), 'pet-check-')) const h = 480 const times = [0.1, duration / 2, Math.max(0, duration - 0.3)] const frames = times.map((t, i) => { const out = join(work, `f${i}.png`) run('ffmpeg', ['-y', '-v', 'error', '-ss', t.toFixed(3), '-i', o.file, '-frames:v', '1', '-vf', `scale=-2:${h}`, out]) return out }) const stills = [o.pet, ...(o.keyframe ? [o.keyframe] : [])] const inputs = [...stills, ...frames].flatMap((f) => ['-i', f]) const n = stills.length + frames.length const chain = [...Array(n).keys()].map((i) => `[${i}]scale=-2:${h},setsar=1[s${i}]`).join(';') const b = run('ffmpeg', ['-y', '-v', 'error', ...inputs, '-filter_complex', `${chain};${[...Array(n).keys()].map((i) => `[s${i}]`).join('')}hstack=${n}`, '-q:v', '3', board]) if (b.status !== 0) notes.push(`Could not write the pet board: ${(b.stderr || '').trim().slice(0, 200)}`) const count = Math.max(4, Math.round(duration * 2)) const cols = 8 const rows = Math.ceil(count / cols) const s = run('ffmpeg', ['-y', '-v', 'error', '-i', o.file, '-vf', `fps=${(count / duration).toFixed(4)},scale=180:-2,tile=${cols}x${rows}`, '-frames:v', '1', '-q:v', '3', sheet]) if (s.status !== 0) notes.push('Could not write the contact sheet.') rmSync(work, { recursive: true, force: true }) console.log('\n-- Pet clip 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(` Sound ${a ? `${a.codec_name} ${a.channels ?? ''}ch${meanDb !== null && Number.isFinite(meanDb) ? `, mean ${meanDb.toFixed(1)} dB` : ''}` : 'none'}`) console.log(` Size ${mb.toFixed(2)} MB`) console.log(` Board ${board} (pet photo | ${o.keyframe ? 'keyframe | ' : ''}${times.map((t) => `${t.toFixed(1)} s`).join(' | ')})`) console.log(` Sheet ${sheet} (${count} frames)`) for (const note of notes) console.log(` note: ${note}`) console.log('---------------------------------------------------------') console.log('Now open the board and the sheet and check by eye: the same pet as the photo in every frame (coat, markings,') console.log('eyes, size), four legs and natural paws, no extra animals or people, at most a hand, no text or logos, calm') console.log('and playful (no fall, slip or fear), the action reads, the look to camera lands in the last 2 s, nothing') console.log('important in the top 12% or bottom 20%. Then listen: room sound only, no speech, no music unless planned.') if (issues.length) { console.log('\nFAIL:') for (const i of issues) console.log(` - ${i}`) process.exit(1) } console.log('\nPASS: technical checks.\n')