#!/usr/bin/env node // Assembles one episode: raw X11 recording + edge-tts narration + subtitles. // Cuts are driven by raw//markers.json; optional speedup-start/end // markers compress repetitive UI stretches. import fs from "node:fs"; import path from "node:path"; import { spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; const here = path.dirname(fileURLToPath(import.meta.url)); const webRoot = path.resolve(here, "../.."); const args = process.argv.slice(2); const option = (name, fallback = "") => { const index = args.indexOf(name); return index < 0 ? fallback : args[index + 1] ?? fallback; }; const episodeId = option("--episode"); if (!episodeId) throw new Error("--episode is required"); const course = JSON.parse(fs.readFileSync(path.join(here, "course.json"), "utf8")); const episode = course.episodes.find(item => item.id === episodeId); if (!episode) throw new Error(`unknown episode ${episodeId}`); const episodeDir = path.join(here, "episodes", episodeId); const rawDir = path.join(here, "raw", episodeId); const segmentsDir = path.join(episodeDir, "segments"); const audioDir = path.join(episodeDir, "audio"); const mediaDir = path.join(webRoot, "teaching", "media", "line-course"); const ffmpeg = "ffmpeg"; const ffprobe = "ffprobe"; const readJson = file => JSON.parse(fs.readFileSync(file, "utf8")); const script = readJson(path.join(episodeDir, "script.zh.json")); const durations = readJson(path.join(episodeDir, "audio-durations.json")).scenes; const markerFile = readJson(path.join(rawDir, "markers.json")); const markers = markerFile.markers; const order = script.scenes.map(scene => scene.id); const sceneStart = id => markers.find(entry => entry.id === "scene-start" && entry.scene === id); const marker = id => markers.find(entry => entry.id === id); for (const id of order) if (!sceneStart(id)) throw new Error(`missing scene-start ${id}`); if (!marker("end")) throw new Error("recording is incomplete: missing end marker"); const captureStart = marker("captureStart")?.offset ?? 0; const rawVideo = path.join(rawDir, "screen-recording.mp4"); if (!fs.existsSync(rawVideo)) throw new Error(`raw video missing: ${rawVideo}`); for (const directory of [segmentsDir, mediaDir]) fs.mkdirSync(directory, { recursive: true }); const run = (command, argv, label) => { const result = spawnSync(command, argv, { encoding: "utf8", maxBuffer: 512 * 1024 * 1024 }); if (result.status !== 0) throw new Error(`${label} failed (${result.status})\n${(result.stderr || "").slice(-5000)}`); return result.stdout; }; const probe = file => { const text = String(run(ffprobe, ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", file], `probe ${path.basename(file)}`)).trim(); const value = Number(text); if (!Number.isFinite(value) || value <= 0) throw new Error(`bad duration for ${file}: ${text}`); return value; }; const round = value => Math.round(value * 1000) / 1000; const concatList = (files, listPath) => { fs.writeFileSync(listPath, files.map(file => `file '${file.replace(/'/g, "'\\''")}'`).join("\n") + "\n"); return listPath; }; const videoArgs = output => ["-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-pix_fmt", "yuv420p", "-profile:v", "high", "-level", "4.2", "-g", "60", "-r", "30", "-movflags", "+faststart", output]; // Scene spans, with optional speedup compression. const spans = []; for (let index = 0; index < order.length; index++) { const id = order[index]; const start = sceneStart(id).offset - captureStart; const end = index + 1 < order.length ? sceneStart(order[index + 1]).offset - captureStart : marker("end").offset - captureStart; if (end <= start) throw new Error(`invalid span for ${id}: ${start}..${end}`); spans.push({ id, start, end }); } const segments = []; for (const span of spans) { const speedups = markers .filter(entry => entry.id === "speedup-start" && entry.scene === span.id) .map(entry => ({ start: entry.offset - captureStart, end: (markers.find(other => other.id === "speedup-end" && other.scene === span.id && other.offset > entry.offset)?.offset ?? span.end) - captureStart, factor: entry.factor ?? 6 })) .filter(entry => entry.end > entry.start) .sort((a, b) => a.start - b.start); const parts = []; let cursor = span.start; const addCut = (from, to, factor, suffix) => { if (to - from < 0.05) return; const file = path.join(segmentsDir, `${span.id}${suffix}.mp4`); const filter = factor > 1 ? `setpts=(PTS-STARTPTS)/${factor},fps=30,crop=1600:860:0:40,scale=1600:900` : "setpts=PTS-STARTPTS,fps=30,crop=1600:860:0:40,scale=1600:900"; run(ffmpeg, ["-y", "-ss", String(from), "-t", String(to - from), "-i", rawVideo, "-vf", filter, ...videoArgs(file)], `${span.id} cut ${suffix}`); parts.push({ file, duration: probe(file) }); }; for (const speed of speedups) { if (speed.start > cursor) addCut(cursor, speed.start, 1, `-pre${parts.length}`); addCut(speed.start, speed.end, speed.factor, `-fast${parts.length}`); cursor = Math.max(cursor, speed.end); } if (cursor < span.end) addCut(cursor, span.end, 1, `-post${parts.length}`); if (!parts.length) throw new Error(`no parts for ${span.id}`); segments.push({ id: span.id, parts, duration: parts.reduce((sum, part) => sum + part.duration, 0) }); } // Keep narration intact: when a scene is shorter than its voice-over, clone // the last frame instead of letting the audio trim cut the sentence off. for (const segment of segments) { const narration = durations[segment.id]?.duration ?? 0; const pad = narration + 0.3 - segment.duration; if (pad > 0.1) { const last = segment.parts.at(-1); const padded = path.join(segmentsDir, `${segment.id}-pad.mp4`); const before = probe(last.file); run(ffmpeg, ["-y", "-i", last.file, "-vf", `tpad=stop_mode=clone:stop_duration=${pad.toFixed(3)}`, ...videoArgs(padded)], `${segment.id} pad`); segment.duration = segment.duration - before + probe(padded); last.file = padded; console.log(`padded ${segment.id} by ${pad.toFixed(2)}s for narration`); } } const videoOnly = path.join(segmentsDir, "video-only.mp4"); run(ffmpeg, ["-y", "-f", "concat", "-safe", "0", "-i", concatList(segments.flatMap(item => item.parts.map(part => part.file)), path.join(segmentsDir, "video-list.txt")), "-c", "copy", videoOnly], "concat video"); const totalVideo = probe(videoOnly); let cursor = 0; for (const segment of segments) { segment.start = round(cursor); segment.end = round(cursor + segment.duration); cursor += segment.duration; } const narrationWavs = []; for (const segment of segments) { const source = path.join(audioDir, `${segment.id}.mp3`); if (!fs.existsSync(source)) throw new Error(`missing narration ${source}`); const wav = path.join(segmentsDir, `audio-${segment.id}.wav`); run(ffmpeg, ["-y", "-i", source, "-af", `apad=whole_dur=${segment.duration.toFixed(3)},atrim=0:${segment.duration.toFixed(3)}`, "-ar", "48000", "-ac", "2", "-c:a", "pcm_s16le", wav], `audio ${segment.id}`); narrationWavs.push(wav); } const narration = path.join(segmentsDir, "narration.wav"); run(ffmpeg, ["-y", "-f", "concat", "-safe", "0", "-i", concatList(narrationWavs, path.join(segmentsDir, "audio-list.txt")), "-c:a", "pcm_s16le", narration], "concat narration"); const base = `${episode.id}-${episode.slug}`; const mp4 = path.join(mediaDir, `${base}.mp4`); run(ffmpeg, ["-y", "-i", videoOnly, "-i", narration, "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-shortest", "-movflags", "+faststart", mp4], "mux mp4"); const webm = path.join(mediaDir, `${base}.webm`); run(ffmpeg, ["-y", "-i", mp4, "-c:v", "libvpx-vp9", "-crf", "38", "-b:v", "0", "-row-mt", "1", "-deadline", "good", "-cpu-used", "6", "-c:a", "libopus", "-b:a", "112k", webm], "webm"); const posterTime = (segments.find(item => item.id === "S02")?.start ?? 10) + 5; const poster = path.join(mediaDir, `${base}-poster.png`); run(ffmpeg, ["-y", "-ss", String(Math.min(posterTime, Math.max(totalVideo - 1, 0))), "-i", mp4, "-frames:v", "1", "-q:v", "2", poster], "poster"); // Merge SRT cues into one timeline. Speedup regions are remapped by the // ratio between the raw span and the assembled segment duration. const toSeconds = text => { const match = /^(\d+):(\d+):(\d+)[,.](\d+)$/.exec(text.trim()); if (!match) return null; return Number(match[1]) * 3600 + Number(match[2]) * 60 + Number(match[3]) + Number(match[4]) / 1000; }; const fmt = seconds => { const ms = Math.round(seconds * 1000); const h = Math.floor(ms / 3600000), m = Math.floor((ms % 3600000) / 60000), s = Math.floor((ms % 60000) / 1000), milli = ms % 1000; return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}.${String(milli).padStart(3, "0")}`; }; const cues = []; for (const segment of segments) { const srtPath = path.join(audioDir, `${segment.id}.srt`); if (!fs.existsSync(srtPath)) continue; const blocks = fs.readFileSync(srtPath, "utf8").replace(/\r/g, "").trim().split(/\n\n+/); for (const block of blocks) { const lines = block.split("\n"); const timing = lines.find(line => line.includes("-->")); if (!timing) continue; const [fromText, toText] = timing.split("-->").map(value => value.trim()); const from = toSeconds(fromText), to = toSeconds(toText); if (from === null || to === null) continue; cues.push({ from: segment.start + from, to: segment.start + to, text: lines.slice(lines.indexOf(timing) + 1).join("\n").trim() }); } } const vtt = ["WEBVTT", "", ...cues.map((cue, index) => `${index + 1}\n${fmt(cue.from)} --> ${fmt(cue.to)}\n${cue.text}\n`)].join("\n"); const vttPath = path.join(mediaDir, `${base}.zh.vtt`); fs.writeFileSync(vttPath, vtt); const srtPath = path.join(mediaDir, `${base}.zh.srt`); fs.writeFileSync(srtPath, cues.map((cue, index) => `${index + 1}\n${fmt(cue.from).replace(".", ",")} --> ${fmt(cue.to).replace(".", ",")}\n${cue.text}\n`).join("\n")); const assembly = { schema: "freecad-web-line-course/video-assembly/v1", generatedAt: new Date().toISOString(), episode: episodeId, title: episode.title, status: "assembled", source: path.relative(here, rawVideo), captureStart, totalVideo: round(totalVideo), scenes: segments.map(segment => ({ id: segment.id, start: segment.start, end: segment.end, duration: round(segment.duration), narration: durations[segment.id]?.duration ?? null })), outputs: { mp4: path.relative(webRoot, mp4), webm: path.relative(webRoot, webm), vtt: path.relative(webRoot, vttPath), srt: path.relative(webRoot, srtPath), poster: path.relative(webRoot, poster) }, cues: cues.length, }; fs.writeFileSync(path.join(episodeDir, "assembly.json"), `${JSON.stringify(assembly, null, 2)}\n`); console.log(JSON.stringify({ ok: true, episode: episodeId, totalVideo: assembly.totalVideo, scenes: assembly.scenes, outputs: assembly.outputs, cues: cues.length }, null, 2));