// A clip with gaps is fetched PER KEPT PIECE (fetchWindows.mjs, the build's // fetchSpans), so no file holds its extent. Every consumer that once asked for // "the window holding the clip" has to ask for its pieces: the cache's // `isFetched` (the walk, the Cut tab's pill), the bench's window (one timeline // on the source's clock), `umtool scenes`, the cut points the Play view draws // and the clip export. Fixture: a 180 s extent (10–190) with 140 s cut out of // its middle (30–170), so the two kept pieces, padded 1 s, lie 138 s apart // (past the 60 s under which a fetch joins them): two windows, 9–31 and // 169–191, and nothing between. // // Run with: pnpm test:scripts import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { readFile, rm, stat, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import test from "node:test"; const CORPUS = mkdtempSync(path.join(os.tmpdir(), "pieced-corpus-")); const CACHE = mkdtempSync(path.join(os.tmpdir(), "pieced-cache-")); process.env.CHANNELS_DIR = CORPUS; process.env.UMTOOL_CACHE_DIR = CACHE; // The read roots (paths.mjs) are read when it loads: the temp dir holds the projects here. process.env.MIX_ROOTS = os.tmpdir(); const { buildVideo, setProgressMode } = await import("umtool-report-to-video/build-video"); const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("umtool-report-to-video/brand"); const { rawCacheOf } = await import("./raw-cache.mjs"); const serve = await import("./serve.mjs"); const { cutPointsFor, clipSourceOf } = await import("./cutPoints.mjs"); const { exportClip } = await import("./clipExport.mjs"); const { scanClip } = await import("./scenesCli.mjs"); const roots = []; test.after(async () => { for (const r of [CORPUS, CACHE, ...roots]) await rm(r, { recursive: true, force: true }); }); const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); const CHANNEL = "synth"; const PALETTE = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" }; const RENDER = { width: 320, height: 180, fps: 30, audioRate: 48000, audioChannels: 2, preset: "ultrafast", headerHeight: 0, footerHeight: 0, qr: false, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE, fetchPad: 1, snapWindow: 0.8, silenceMinDur: 0.15, snapLead: 0.3, snapTail: 0.4, transition: 0, }; const CLIP = { type: "clip", id: "p1", channel: CHANNEL, video: "vid1", start: 10, end: 190, cite: 12, quote: "q", gaps: [{ from: 30, to: 170 }] }; const dir = path.join(CORPUS, CHANNEL, "data", "vid1"); mkdirSync(dir, { recursive: true }); writeFileSync(path.join(CORPUS, CHANNEL, "config.json"), JSON.stringify({ name: "Synth" })); writeFileSync(path.join(dir, "transcript.cues.json"), JSON.stringify({ id: "vid1", title: "Synthetic", duration: 300, uploadDate: "20240102", cues: [] })); writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "vid1", title: "Synthetic", duration: 300 })); /** A window file: gray picture, a 440 Hz tone with pauses at the given seconds (on its own clock). */ function windowFile(file, seconds, pauses, color = "gray") { const vol = pauses.map(([a, b]) => `volume=enable='between(t,${a},${b})':volume=0`).join(","); const r = spawnSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=${color}:s=320x180:r=30:d=${seconds}`, "-f", "lavfi", "-i", `sine=frequency=440:sample_rate=48000:duration=${seconds}`, "-filter_complex", `[1:a]${vol ? `${vol},` : ""}volume=0.5[a]`, "-map", "0:v", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", file, ]); assert.equal(r.status, 0, String(r.stderr)); } /** A project whose raw cache holds the pieces named in `held` (file names under out/clips-raw), as the manifest `timeline` says. */ async function project({ held = ["vid1_9.00-31.00.mp4", "vid1_169.00-191.00.mp4"], timeline = [CLIP], render = {} } = {}) { const root = mkdtempSync(path.join(os.tmpdir(), "pieced-")); roots.push(root); const raw = path.join(root, "out", "clips-raw"); mkdirSync(raw, { recursive: true }); for (const name of held) { // Pauses 0.7–1.2 into each window: 9.7–10.2 for the first (the cut's start), 169.7–170.2 for the second. if (have) windowFile(path.join(raw, name), 22, [[0.7, 1.2], [19.8, 20.4]]); else writeFileSync(path.join(raw, name), "x"); } const manifestPath = path.join(root, "video.manifest.json"); const manifest = { slug: "pieced", title: "Pieced", provenance: { channelSlug: CHANNEL, channelsDir: CORPUS }, render: { ...RENDER, ...render }, timeline, }; await writeFile(manifestPath, JSON.stringify(manifest)); return { root, manifestPath, manifest, project: { id: "pieced", dir: root } }; } test("isFetched: every piece covered is fetched; one missing, or none, is not; a whole window is as ever", async () => { const full = await project(); const c = await rawCacheOf(full.root, { render: full.manifest.render }); assert.equal(c.isFetched(CLIP), true, "both pieces held"); assert.deepEqual(c.piecesOf(CLIP).map((p) => [p.span.from, p.span.to, p.window.name]), [ [10, 30, "vid1_9.00-31.00.mp4"], [170, 190, "vid1_169.00-191.00.mp4"], ]); // Without the render's gaps being read it is still the clip's own gaps (a montage aside). assert.equal((await rawCacheOf(full.root)).isFetched(CLIP), true); const part = await project({ held: ["vid1_9.00-31.00.mp4"] }); const p = await rawCacheOf(part.root, { render: part.manifest.render }); assert.equal(p.isFetched(CLIP), false, "the second piece is not on disk"); assert.equal(p.piecesOf(CLIP), null); assert.equal(p.isFetched({ ...CLIP, gaps: [] }), false, "no gaps: the extent is what must be held, and it is not"); const none = await project({ held: [] }); assert.equal((await rawCacheOf(none.root, { render: none.manifest.render })).isFetched(CLIP), false); // A single window holding the whole extent: unchanged, gaps or not. const whole = await project({ held: ["vid1_5.00-195.00.mp4"] }); const w = await rawCacheOf(whole.root, { render: whole.manifest.render }); assert.equal(w.isFetched(CLIP), true); assert.equal(w.isFetched({ ...CLIP, gaps: [] }), true); // A montage applies no gaps: the pieces do not make the extent. const m = await rawCacheOf(full.root, { render: { montage: { style: "wall" } } }); assert.equal(m.isFetched(CLIP), false); // A piece only partly covered is not covered. const edge = await project({ held: ["vid1_9.00-29.00.mp4", "vid1_169.00-191.00.mp4"] }); assert.equal((await rawCacheOf(edge.root, { render: edge.manifest.render })).isFetched(CLIP), false); }); test("the project cache (serve.projectCache) carries the render, so the walk and the Cut tab's pill read the pieces", async () => { const p = await project(); const cache = await serve.projectCache(p.project, p.manifest); assert.equal(cache.isFetched(CLIP), true); const detail = await (await import("../projects/report.mjs")).readClipDetail(p.root, { manifest: p.manifest }); const row = detail.entries.find((e) => e.id === "p1"); assert.equal(row.fetched, true, "the Cut tab's cached pill"); assert.ok(row.cached, "the padded pieces are on disk"); const part = await project({ held: ["vid1_9.00-31.00.mp4"] }); const d2 = await (await import("../projects/report.mjs")).readClipDetail(part.root, { manifest: part.manifest }); const r2 = d2.entries.find((e) => e.id === "p1"); assert.equal(r2.fetched, false); assert.equal(r2.cached, null); }); test("the walk: a fully fetched pieced clip is on it, a part-fetched one is not", async () => { const { walkOf } = await import("./walkData.mjs"); const full = await project(); const w = await walkOf(full.project); assert.deepEqual(w.clips.map((c) => [c.id, c.fetched, c.onWalk]), [["p1", true, true]]); const part = await project({ held: ["vid1_9.00-31.00.mp4"] }); const w2 = await walkOf(part.project); assert.deepEqual(w2.clips.map((c) => [c.id, c.fetched, c.onWalk]), [["p1", false, false]]); }); test("layoutPieces: each second from the window that holds it, black filler between", () => { const A = { name: "a", path: "/a.mp4", from: 9, to: 31 }; const B = { name: "b", path: "/b.mp4", from: 169, to: 191 }; assert.deepEqual(serve.layoutPieces([A, B], 9, 191), [ { kind: "file", path: "/a.mp4", winFrom: 9, from: 9, to: 31 }, { kind: "fill", from: 31, to: 169 }, { kind: "file", path: "/b.mp4", winFrom: 169, from: 169, to: 191 }, ]); // Overlapping windows: the one reaching furthest carries on. const C = { name: "c", path: "/c.mp4", from: 25, to: 40 }; assert.deepEqual(serve.layoutPieces([A, C], 9, 40), [ { kind: "file", path: "/a.mp4", winFrom: 9, from: 9, to: 31 }, { kind: "file", path: "/c.mp4", winFrom: 25, from: 31, to: 40 }, ]); }); test("windowsFor: a pieced clip is ONE window on the source's clock; a whole window and a part-fetched clip are as ever", async () => { const p = await project(); const cache = await serve.projectCache(p.project, p.manifest); const wins = await serve.windowsFor(p.project, CLIP, cache); const [w] = wins; assert.match(w.name, /^9\.00-191\.00\.[0-9a-f]{8}\.pieces\.mp4$/); assert.equal(w.from, 9); assert.equal(w.to, 191); assert.equal(w.piecesOf.filter((i) => i.kind === "fill").length, 1); assert.ok(w.excerptOf, "served and cut like an excerpt"); assert.equal(wins.length, 3, "then the files it is laid from"); assert.ok(await serve.windowVersion(w), "a version, before it is cut"); // Only one piece held: nothing is one timeline; the overlap list as ever. const part = await project({ held: ["vid1_9.00-31.00.mp4"] }); const pw = await serve.windowsFor(part.project, CLIP, await serve.projectCache(part.project, part.manifest)); assert.deepEqual(pw.map((x) => x.name), ["vid1_9.00-31.00.mp4"]); // A window holding the whole extent: the excerpt/window as ever, no pieces window. const whole = await project({ held: ["vid1_5.00-195.00.mp4"] }); const ww = await serve.windowsFor(whole.project, CLIP, await serve.projectCache(whole.project, whole.manifest)); assert.deepEqual(ww.map((x) => x.name), ["vid1_5.00-195.00.mp4"]); assert.equal(ww[0].piecesOf, undefined); }); test("windowsFor: pieces too far apart for one clock are not laid on one", async () => { const far = { ...CLIP, id: "far", end: 1500, start: 10, gaps: [{ from: 30, to: 1480 }] }; const p = await project({ held: ["vid1_9.00-31.00.mp4", "vid1_1479.00-1501.00.mp4"], timeline: [far] }); const wins = await serve.windowsFor(p.project, far, await serve.projectCache(p.project, p.manifest)); assert.ok(wins.every((x) => !x.piecesOf), "no pieces window"); }); test("the pieces window is cut once from its files: the picture and the sound play, on the source's clock", { skip: !have && "needs ffmpeg" }, async () => { const p = await project(); const cache = await serve.projectCache(p.project, p.manifest); const [w] = await serve.windowsFor(p.project, CLIP, cache); await serve.ensureWindowFile(w); const st = await stat(w.path); assert.ok(st.size > 0); assert.equal(await serve.windowFileFresh(w), true); const probe = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration:stream=codec_type", "-of", "json", w.path]); const doc = JSON.parse(String(probe.stdout)); assert.ok(Math.abs(Number(doc.format.duration) - (w.to - w.from)) < 0.25, `lasts ${doc.format.duration}, wanted ${w.to - w.from}`); assert.deepEqual(doc.streams.map((s) => s.codec_type).sort(), ["audio", "video"]); // Replace one piece: the version moves and the file is stale. const before = await serve.windowVersion(w); windowFile(path.join(p.root, "out", "clips-raw", "vid1_169.00-191.00.mp4"), 22, [], "red"); assert.notEqual(await serve.windowVersion(w), before); assert.equal(await serve.windowFileFresh(w), false); }); test("scenes: a pieced clip's pieces are each scanned, in source seconds", { skip: !have && "needs ffmpeg" }, async () => { const p = await project(); const s = await scanClip(p.project, "p1", {}); assert.equal(s.window.kind, "pieces"); assert.equal(s.window.pieces.length, 2); assert.deepEqual(s.window.pieces.map((x) => [x.from, x.to]), [[9, 31], [169, 191]]); // Scans the extent ± 30 inside each piece: 10–31 and 169–190 (the pads are what is on disk). assert.ok(s.scanned.from >= 9 && s.scanned.to <= 191); const part = await project({ held: ["vid1_9.00-31.00.mp4"] }); await assert.rejects(scanClip(part.project, "p1", {}), /has no window on disk/); }); test("cut points: a pieced clip's edges are the render's cut record, edge for edge", { skip: !have && "needs ffmpeg" }, async () => { setProgressMode(() => {}); const p = await project(); await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, noXfade: true } }); const rec = JSON.parse(await readFile(path.join(p.root, "out", "sourced", "segments", "p1.cut.json"), "utf8")); const got = await cutPointsFor(p.project); const c = got.clips.find((x) => x.id === "p1"); assert.ok(!c.missing && !c.error, JSON.stringify(c)); assert.equal(c.cutStart, rec.start, "start"); assert.equal(c.cutEnd, rec.end, "end"); assert.deepEqual(c.snapped, rec.snapped); assert.deepEqual(c.gaps, rec.gaps, "every second left out, the seconds between the pieces too"); assert.equal(c.pieced.cutEnd - c.pieced.cutStart > 0, true); // The source for the export: the joined file, the clip on its clock. const src = await clipSourceOf(p.project, "p1"); assert.ok(src.source?.pieced, "pieced source"); assert.equal(src.source.fetchStart, 0); // Not all held: missing, as a clip with no window is. const part = await project({ held: ["vid1_9.00-31.00.mp4"] }); assert.equal((await cutPointsFor(part.project)).clips.find((x) => x.id === "p1").missing, true); }); test("export a pieced clip: the kept seconds of both pieces, the cut between them out", { skip: !have && "needs ffmpeg" }, async () => { const p = await project(); const cut = await exportClip(p.project, "p1", { kind: "cut", today: "2026-11-02" }); const probe = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", cut.abs]); const dur = Number(String(probe.stdout).trim()); assert.ok(dur > 30 && dur < 45, `plays the two pieces (~40 s), not the 180 s extent: ${dur}`); assert.ok(Math.abs(dur - cut.seconds) < 0.2, `${dur} vs ${cut.seconds}`); const part = await project({ held: ["vid1_9.00-31.00.mp4"] }); await assert.rejects(exportClip(part.project, "p1"), (e) => e.status === 409 && /fetch it first/.test(e.message)); });