scripts/video-tools.mjs
import { spawnSync, spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
export function validateNarration(shots) {
if (!Array.isArray(shots) || !shots.length) throw Error('Narration needs timed shots.');
let total = 0;
for (const shot of shots) {
if (!(shot.seconds > 0) || !Number.isFinite(shot.seconds) || typeof shot.text !== 'string' || !shot.text.trim()) throw Error('Invalid narration shot.');
total += shot.seconds;
}
if (total >= 180) throw Error('Demo must stay under three minutes.');
return total;
}
function stamp(seconds) {
return new Date(Math.round(seconds * 1000)).toISOString().slice(11, 23).replace('.', ',');
}
export function captionSrt(shots, live, timings) {
let cursor = 0;
return shots.map((shot, i) => {
const start = timings?.[i]?.start ?? cursor;
const end = timings?.[i]?.end ?? (cursor + shot.seconds);
cursor += shot.seconds;
return `${i + 1}\n${stamp(start)} --> ${stamp(end)}\n${live ? shot.liveText || shot.text : shot.text}\n`;
}).join('\n');
}
export function findFfmpeg() {
if (process.env.FFMPEG_EXE && existsSync(process.env.FFMPEG_EXE)) return process.env.FFMPEG_EXE;
if (spawnSync('ffmpeg', ['-version'], { stdio: 'ignore', windowsHide: true }).status === 0) return 'ffmpeg';
const py = spawnSync('python', ['-c', 'import imageio_ffmpeg; print(imageio_ffmpeg.get_ffmpeg_exe())'], { encoding: 'utf8', windowsHide: true });
const path = py.stdout?.trim();
if (py.status === 0 && path && existsSync(path)) return path;
throw Error('MP4 encoder missing. Install FFmpeg or Python imageio-ffmpeg, or set FFMPEG_EXE to its executable. No audio is synthesised.');
}
export function videoDuration(ffmpeg, path) {
const result = spawnSync(ffmpeg, ['-hide_banner', '-i', path], { encoding: 'utf8', windowsHide: true });
const match = /Duration: (\d+):(\d+):(\d+(?:\.\d+)?)/.exec(result.stderr || '');
if (!match) throw Error('Could not verify video duration.');
return Number(match[1]) * 3600 + Number(match[2]) * 60 + Number(match[3]);
}
export async function encodeVideo(ffmpeg, input, output, voiceover) {
const args = ['-hide_banner', '-loglevel', 'error', '-y', '-i', input];
if (voiceover) args.push('-i', voiceover, '-map', '0:v:0', '-map', '1:a:0', '-af', 'apad');
else args.push('-an');
args.push('-c:v', 'libx264', '-preset', 'fast', '-crf', '20', '-pix_fmt', 'yuv420p', '-r', '30');
if (voiceover) args.push('-c:a', 'aac', '-b:a', '160k', '-shortest');
args.push('-movflags', '+faststart', output);
await new Promise((resolve, reject) => {
const child = spawn(ffmpeg, args, { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true });
// Only a bounded encoder error, no HTTP requests or provider diagnostics.
let diagnostic = ''; child.stderr.on('data', chunk => { diagnostic = (diagnostic + chunk).slice(-1000); });
child.once('error', () => reject(Error('FFmpeg could not start.')));
child.once('exit', code => code === 0 ? resolve() : reject(Error('MP4 encoding failed: ' + diagnostic)));
});
}