commit 686eb80b4142613db57e19396c0418aeabd0b7e0
parent c07d665d3a3dcd99329b2439e4f6610157052700
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 00:54:59 -0500
Merge lane/pieced-consumers: a clip fetched per kept piece reads as held everywhere -- check-availability, the raw cache's isFetched (the walk, stand-ins and the cache pill), scenes, cut points, export -- and the bench plays its pieces as one window, the gap skipped
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
14 files changed, 810 insertions(+), 69 deletions(-)
diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md
@@ -63,6 +63,20 @@ gets an empty list — "nothing fetched for this clip yet", which is true — ra
than somebody else's window. A caller with no window at all (a ledger claim asks
for its video's files and picks by cite) still gets every file, widest first.
+**A clip fetched in pieces is one window.** A clip with gaps is fetched per kept
+piece (`umtool fetch`; pieces under 60 s apart as one), so no file holds its
+extent. When every piece it plays is on disk, `windowsFor()` puts first a window
+**on the source's clock** that spans the pieces: each where it was said, and where
+nothing was fetched (inside a gap) black picture and silence. It is named
+`<from>-<to>.<hash>.pieces.mp4`, cut once, lazily, like a long recording's
+excerpt (`out/bench-excerpts/<video>/`, a sidecar of every piece's identity, so
+a refetched piece re-cuts it), and everything on the bench — cues, waveform,
+marks, the edge drag, the gap bands — is true on it unchanged. Playback skips the
+gap as the cut will, so the filler is never the point. Fetched means the same on
+the Cut tab and the walk: the extent in one window, **or every kept piece in some
+window**. Pieces more than 15 minutes apart are not laid on one clock (the
+filler would be the file).
+
## A drag never downloads
Dragging past the cached window **clamps** and offers a button. A handle that
@@ -265,7 +279,7 @@ timeline order — so `p`, `n`, both header links, the start button and the jump
Walking back onto a clip somebody already answered is the round trip the walk
exists to remove.
- **Fetched** means some file in `out/clips-raw` holds this clip's own window
- end to end. Not the *padded* window a build would download, and not an
+ end to end (a clip with gaps fetched per piece: every kept piece is in some file). Not the *padded* window a build would download, and not an
overlap: a half-covered clip cannot be watched through, so there is nothing
to judge. Landing on one is a dead end whose only move is `n` again.
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -117,6 +117,19 @@ seconds (`report-to-video/gaps.mjs` is the rule and both clocks).
fades, the picture past the gap at the join, the clock and the scrub bar in cut seconds, a dashed tick on the reel
strip at each jump.
- **`umtool timeline <p> ls`** shows a clip's gaps and what it then plays.
+- **Fetched in pieces**: `umtool fetch` asks the editor for one window per kept piece (pieces under 60 s apart as
+ one), so a clip with a long gap has no file holding its extent. Every reader asks for the pieces, as the build does:
+ the clip is **cached** (the Cut tab's pill, `data-fetched`, the walk and its `ready N of M`, `umtool walk`, the
+ stand-ins) when its extent is in one window **or every kept piece is in some window**; one piece missing is "not
+ fetched yet". `umtool check`'s availability preflight counts it held when every piece is. `umtool scenes` scans each
+ held piece (`window.kind` `pieces`, one row per piece). The cut points Play draws and **Export one clip** measure
+ the pieces joined as the build joins them (a file in the cut-points cache, never in the project), on that file's
+ clock and mapped back: the row is the build's cut record (the cut's `gaps` include the seconds between pieces),
+ with no `silences` to snap a dragged edge with. **The bench** opens a pieced clip on ONE window on the source's clock:
+ the pieces where they were said and, where nothing was fetched (inside a gap), black, silent filler, cut once (lazily,
+ like a long recording's excerpt, `out/bench-excerpts/<video>/*.pieces.mp4`). Playback skips the gap as the cut will,
+ so the filler is only heard if you choose to hear a gap through ("Hear it") past the fetched edge. Pieces more than
+ 15 minutes apart are not laid on one clock; the bench then shows the windows as before.
### The bench waveform's zoom
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -1889,6 +1889,25 @@ makeCutEditingFixture({ reports, manifest, deckManifest, cachedWindow: path.join
mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "gapvid_0.00-9.00.mp4"));
}
+// A clip fetched PER KEPT PIECE (pieced.spec.ts, fetch-per-piece): no window holds its extent, the
+// pieces do. READ-ONLY (the spec writes nothing), so one project serves it.
+// pc01 pcvid 1-98, gap 8-91 (83 s out): both pieces on disk -- raw windows 0-9 and 90-99
+// pc02 pcvid2 1-98, the same gap: only the first piece on disk (0-9), the second never fetched
+// The windows are the fixture's vid1 tone window (silences 2.9-3.1, 5.9-6.1), 15 fps.
+{
+ const gap = [{ from: 8, to: 91 }];
+ const g = manifest("pieced-fixture", "The Pieced Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "clip", id: "pc01", video: "pcvid", start: 1, end: 98, cite: 1, section: 0, lock: true, quote: "a clip fetched in two pieces", gaps: gap },
+ { type: "clip", id: "pc02", video: "pcvid2", start: 1, end: 98, cite: 1, section: 0, lock: true, quote: "a clip with one piece fetched", gaps: gap },
+ ]);
+ g.render.fetchPad = 0;
+ const dir = writeProject("pieced-fixture", g);
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ const win = path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4");
+ copyFileSync(win, path.join(dir, "out", "clips-raw", "pcvid_0.00-9.00.mp4"));
+ copyFileSync(win, path.join(dir, "out", "clips-raw", "pcvid_90.00-99.00.mp4"));
+ copyFileSync(win, path.join(dir, "out", "clips-raw", "pcvid2_0.00-9.00.mp4"));
+}
// The same cut for Play → Edit this clip → Back (phone-walk.spec.ts), which WRITES
// an edge: its own copy, so play-cut.spec's clock is never moved.
makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), name: "play-edit-fixture", title: "The Play Edit Fixture", video: "vid1" });
diff --git a/umtool/e2e/pieced.spec.ts b/umtool/e2e/pieced.spec.ts
@@ -0,0 +1,84 @@
+import { test, expect } from "@playwright/test";
+import { mkdirSync } from "node:fs";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// A clip fetched PER KEPT PIECE (fetch-per-piece; pieced-consumers.test.mjs is
+// the unit half): no window holds its extent, the pieces do, and every surface
+// that asked for "the window holding the clip" reads them.
+//
+// Fixture: pieced-fixture (make-fixture.mjs), READ-ONLY.
+// pc01 pcvid 1-98 less the gap 8-91: both pieces on disk (raw windows 0-9, 90-99)
+// pc02 pcvid2 1-98, the same gap: only the first piece on disk
+//
+// - the Cut tab's pill: pc01 "cached" (data-fetched 1), pc02 "not fetched yet"
+// - the bench opens pc01 on ONE window on the source's clock (the pieces where
+// they were said, black filler between), plays it across the gap -- the
+// gap skipped as the cut will skip it, seven seconds of sound twice, not 97
+// - pc02 is not offered as playable: it offers to fetch
+// - the walk (`ready N of M`) counts pc01 and not pc02
+// ---------------------------------------------------------------------------
+
+const PROJECT = "reports/pieced-fixture";
+const SHOTS = process.env.PIECED_SHOTS ?? "";
+const shot = async (page: import("@playwright/test").Page, name: string) => {
+ if (!SHOTS) return;
+ mkdirSync(SHOTS, { recursive: true });
+ await page.screenshot({ path: `${SHOTS}/${name}.png`, fullPage: false });
+};
+
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+});
+
+test("the Cut tab: a clip with every piece on disk is cached; one with a piece missing is not fetched yet", async ({ page }) => {
+ await page.goto(urls.section(PROJECT, "timeline"));
+ await expect(page.locator("[data-entry=pc01][data-kind]")).toHaveAttribute("data-fetched", "1");
+ await expect(page.locator("[data-entry=pc01][data-kind]")).toHaveAttribute("data-cached", "1");
+ await expect(page.locator("[data-entry=pc01][data-kind]")).not.toContainText("not fetched yet");
+ await expect(page.locator("[data-entry=pc02][data-kind]")).toHaveAttribute("data-fetched", "0");
+ await expect(page.locator("[data-entry=pc02][data-kind]")).toContainText("not fetched yet");
+ // The walk counts what can be watched end to end: pc01.
+ await expect(page.locator("[data-ready-count]")).toHaveText("ready 1 of 2 needing judgement");
+ await shot(page, "cut-tab-pills");
+});
+
+test("the bench plays a clip fetched in pieces as one timeline: the gap is skipped, not played", async ({ page, request }) => {
+ // The bench's window: one file on the source's clock, named for the pieces it is laid from.
+ const clip = (await (await request.get(`/api/report/clip?project=${encodeURIComponent(PROJECT)}&clip=pc01`)).json()) as {
+ windows?: { name: string; from: number; to: number }[];
+ };
+ const wins = clip.windows ?? [];
+ expect(wins[0]?.name, JSON.stringify(wins)).toMatch(/\.pieces\.mp4$/);
+ expect([wins[0].from, wins[0].to]).toEqual([0, 99]);
+
+ await page.goto(urls.clipBenchHref(PROJECT, "pc01"));
+ const playback = page.locator("[data-playback]");
+ await expect(playback).toHaveAttribute("data-audio-state", "ready", { timeout: 60_000 });
+ await expect(page.locator("[data-gap-band]")).toHaveCount(1);
+ await expect(page.locator("[data-clip-unfetched]")).toHaveCount(0);
+ await shot(page, "bench-pieced");
+ // Keyboard attached (hydration), then play.
+ await expect(async () => {
+ await page.locator("body").press("x");
+ await expect(page.locator("[data-reject-menu]")).toBeVisible({ timeout: 500 });
+ }).toPass({ timeout: 10_000 });
+ await page.locator("body").press("Escape");
+ await page.locator("body").press(" ");
+ await expect(playback).toHaveAttribute("data-play-state", "playing", { timeout: 10_000 });
+ expect(await playback.getAttribute("data-play-engine")).toBe("webaudio");
+ const a = Number(await playback.getAttribute("data-play-ctx-start"));
+ const b = Number(await playback.getAttribute("data-play-ctx-stop"));
+ // 1-98 less the 83 s gap: 14 s of sound (7 + 7), not 97 (the window stays under the 120 s decode cap, else the bench plays through the element).
+ expect(b - a).toBeCloseTo(14, 1);
+ expect(Number(await playback.getAttribute("data-play-to"))).toBeCloseTo(98, 1);
+ await shot(page, "bench-pieced-playing");
+ await page.locator("body").press(" ");
+});
+
+test("a clip with a piece missing is not playable: the bench offers to fetch it", async ({ page }) => {
+ await page.goto(urls.clipBenchHref(PROJECT, "pc02"));
+ await expect(page.locator("[data-bench=pc02]")).toBeVisible();
+ await expect(page.locator("[data-clip-unfetched]")).toHaveCount(1);
+ await shot(page, "bench-part-fetched");
+});
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -7,7 +7,7 @@
// and neither parses JSON.
import { readdir, readFile, stat } from "node:fs/promises";
import path from "node:path";
-import { DEFAULT_VARIANT, cachedWindowsFor } from "umtool-report-to-video/build-video";
+import { DEFAULT_VARIANT, cachedWindowsFor, fetchSpans } from "umtool-report-to-video/build-video";
import {
SHADOW_CHANNELS as SOURCES_SHADOW_CHANNELS,
channelsDirFor as sourcesChannelsDirFor,
@@ -1650,7 +1650,7 @@ export async function readClipDetail(dir, { manifest = null } = {}) {
// ONE listing of out/clips-raw for the whole project. This used to be two
// readdirs PER CLIP -- the padded lookup and the full list -- so a forty-clip
// cut paid eighty directory reads to draw one page.
- const raw = await rawCacheOf(dir, { extraWindows: await clipWindowDirs(m, channelsDir) });
+ const raw = await rawCacheOf(dir, { extraWindows: await clipWindowDirs(m, channelsDir), render: m.render ?? {} });
const segDirs = segmentDirs(path.join(dir, "out"));
const segLists = await Promise.all(segDirs.map((d) => readdir(d).catch(() => [])));
const segWhich = segLists.findIndex((l) => l.length);
@@ -1689,7 +1689,16 @@ export async function readClipDetail(dir, { manifest = null } = {}) {
const pad = m.render?.fetchPad ?? 3.0;
const from = Math.max(0, e.start - pad);
const to = e.end + pad;
- const cached = raw.containing(e.video, from, to);
+ // A clip with gaps is fetched per kept piece (fetchSpans): the padded window
+ // is then each padded piece's, and it is "on disk" when every one is.
+ let cached = raw.containing(e.video, from, to);
+ if (!cached) {
+ const spans = fetchSpans(e, m.render ?? {}, {});
+ if (spans.length > 1) {
+ const wins = spans.map((s) => raw.containing(e.video, s.from, s.to));
+ if (wins.every(Boolean)) cached = wins[0];
+ }
+ }
const allWindows = raw.windows(e.video);
// The bench wants the WIDEST containing file (room to drag); the build wants
// the tightest (least to decode). They are different questions.
diff --git a/umtool/lib/report/clipExport.mjs b/umtool/lib/report/clipExport.mjs
@@ -314,7 +314,13 @@ export async function exportClip(project, clipId, { take = null, kind = "cut", f
row = { error: e instanceof Error ? e.message : String(e) };
}
}
- const plan = planExport({ entry: got.entry, render: got.render, source: got.source, media, row, kind });
+ // A clip cut from its pieces (cutPoints.mjs piecedDiskSourceOf) is a file on its own clock:
+ // the plan is made on that clock -- the clip and the cut's numbers as the build sees them.
+ const pieced = got.source.pieced ?? null;
+ const planRow = pieced && row && !row.error && !row.missing && row.pieced
+ ? { ...row, cutStart: row.pieced.cutStart, cutEnd: row.pieced.cutEnd, gaps: row.pieced.gaps }
+ : row;
+ const plan = planExport({ entry: pieced ? pieced.entry : got.entry, render: got.render, source: got.source, media, row: planRow, kind });
if (!(planSeconds(plan) > 0.05)) throw new ExportRefused(`${clipId}: nothing to export (${planSummary(plan)})`, 422);
const name = exportName(got.entry, { kind, ...(today ? { today } : {}) });
const dir = path.join(/* turbopackIgnore: true */ project.dir, EXPORTS_DIR);
diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs
@@ -26,7 +26,7 @@ import { createHash } from "node:crypto";
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import {
- DEFAULT_VARIANT, FFMPEG_BIN, alignedClipSource, localSources, onDiskClipSource, probeMedia, selectVariant,
+ DEFAULT_VARIANT, FFMPEG_BIN, alignedClipSource, localPieces, localSources, onDiskClipSource, piecedClipSource, probeMedia, selectVariant,
} from "umtool-report-to-video/build-video";
import { detectRoomSilences, detectSilence, lookWords, measureLoudnessWith, readLookSources, roomOfCut } from "umtool-report-to-video/cut-points";
import { playWindow, transitionOf } from "umtool-report-to-video/deck";
@@ -118,7 +118,10 @@ async function cutContext(project, take) {
localSources({ rawDir: path.join(/* turbopackIgnore: true */ root, "clips-raw"), channelsDir, channelSlug: provenance.channelSlug ?? null }),
);
const localMedia = createLocalMedia({ baseDir: project.dir, allowAbsolute: render.allowAbsoluteSrc === true });
- return { selected, render, provenance, channelsDir, locals, localMedia };
+ // Where a gap-joined clip's pieces are joined for measuring (piecedClipSource): beside the other
+ // measurements, one directory per cut, never the project's out/ (nothing here writes a project).
+ const piecesDir = path.join(/* turbopackIgnore: true */ cacheDir(), "pieced", createHash("sha1").update(outRoot).digest("hex").slice(0, 12));
+ return { selected, render, provenance, channelsDir, locals, localMedia, piecesDir };
}
/**
@@ -190,7 +193,7 @@ async function diskSourceOf(entry, ctx) {
src = await onDiskClipSource(entry, null, render, local, { localMedia });
if (src) break;
}
- if (!src) return null;
+ if (!src) return piecedDiskSourceOf(entry, ctx);
const fk = await fileKey(src.path);
if (!fk) return null;
const { log: _log, ...disk } = src;
@@ -202,6 +205,27 @@ async function diskSourceOf(entry, ctx) {
}
/**
+ * A gap-joined clip's source when no window holds its whole extent: its
+ * PIECES, each on disk (fetch-per-piece, build-video.mjs fetchSpans), joined
+ * end to end as the build joins them (piecedClipSource) into a file in the
+ * cut-points cache. `fetchStart` is 0 -- the joined file's own clock -- and
+ * `pieced` carries the clip on that clock (`entry`) and the map back
+ * (`clock`). null: not every piece is on disk (nothing is fetched here).
+ */
+async function piecedDiskSourceOf(entry, ctx) {
+ const { render, locals, localMedia, piecesDir } = ctx;
+ for (const local of locals) {
+ if (!(await localPieces(entry, render, local, { localMedia }))) continue;
+ const joined = await piecedClipSource(entry, null, render, local, { localMedia, noNetwork: true }, piecesDir);
+ if (!joined) continue;
+ const fk = await fileKey(joined.path);
+ if (!fk) continue;
+ return { path: joined.path, fk, fetchStart: 0, scan: null, pieced: { clock: joined.clock, entry: joined.entry } };
+ }
+ return null;
+}
+
+/**
* One clip of the cut (or a take) and the file the build would cut it from
* -- the export of one clip (lib/report/clipExport.mjs) cuts from exactly
* this. `source` is null when nothing on disk holds it; `entry` null when the
@@ -219,15 +243,19 @@ export async function clipSourceOf(project, clipId, { take = null } = {}) {
entry,
render: ctx.render,
provenance: ctx.provenance,
- source: disk ? { path: disk.path, fetchStart: disk.fetchStart } : null,
+ // `pieced`: the file is a gap-joined clip's pieces on their own clock (`entry` is the clip on it).
+ source: disk ? { path: disk.path, fetchStart: disk.fetchStart, ...(disk.pieced ? { pieced: { entry: disk.pieced.entry } } : {}) } : null,
};
}
/** One clip's render cut (cutPointsFor's row). */
-async function clipCutPoints(entry, ctx) {
+async function clipCutPoints(real, ctx) {
const { render, montage, D } = ctx;
- const disk = await diskSourceOf(entry, ctx);
- if (!disk) return { id: entry.id, missing: true };
+ const disk = await diskSourceOf(real, ctx);
+ if (!disk) return { id: real.id, missing: true };
+ // A clip cut from its pieces (piecedDiskSourceOf) is measured on the joined file's clock, as the build does.
+ const pieced = disk.pieced ?? null;
+ const entry = pieced ? pieced.entry : real;
const src = { path: disk.path };
const { fk, fetchStart, scan } = disk;
const k = snapKnobs(render);
@@ -247,7 +275,7 @@ async function clipCutPoints(entry, ctx) {
/** @type {[number, number] | null} */
let sound = null;
// Room at the edges: only with a join to make room for, never in a montage.
- if (D > 0 && !montage && clipRoom(entry, render)) {
+ if (D > 0 && !montage && !pieced && clipRoom(entry, render)) {
if (!ctx.look.promise) ctx.look.promise = readLookSources(ctx.projectDir);
const lookSrc = await ctx.look.promise;
const provenance = ctx.provenance;
@@ -273,21 +301,35 @@ async function clipCutPoints(entry, ctx) {
// The gaps as the build applies them: on the segment's frame grid (build-video.mjs buildClipSegment).
const segGaps = clipGaps.length ? gapsOnSegment(clipGaps, fetchStart + segA, segB - segA, fps) : [];
const gaps = segGaps.map((g) => ({ from: r3(fetchStart + segA + g.from), to: r3(fetchStart + segA + g.to) }));
+ // On the pieces' clock the cut is mapped back to the source's seconds (the build's cut record, toReal),
+ // its gaps are every second left out (the seconds between pieces too), and there are no silences to
+ // hand a client: they are on the joined file's clock. `pieced` keeps the numbers on that clock for the export.
+ const vCutStart = fetchStart + segA;
+ const vCutEnd = fetchStart + segB;
+ const clock = pieced?.clock ?? null;
const row = {
- id: entry.id,
+ id: real.id,
window: path.basename(src.path),
footage: Number((Math.ceil((segB - segA - gapSeconds(segGaps)) * fps - 1e-6) / fps).toFixed(6)),
- fetchStart: r3(fetchStart),
- silences: sil,
- playFrom: pw.from,
- playTo: pw.to,
- cutStart: r3(fetchStart + segA),
- cutEnd: r3(fetchStart + segB),
+ fetchStart: r3(clock ? clock.spans[0].from : fetchStart),
+ silences: clock ? [] : sil,
+ playFrom: clock ? clock.toReal(pw.from) : pw.from,
+ playTo: clock ? clock.toReal(pw.to) : pw.to,
+ cutStart: r3(clock ? clock.toReal(vCutStart) : vCutStart),
+ cutEnd: r3(clock ? clock.toReal(vCutEnd) : vCutEnd),
snapped: cut.snapped,
// Which edges are the author's (mute.mjs lockedEdges): the bench snaps a dragged edge with them.
...(locked.start || locked.end ? { locked } : {}),
...(sound ? { sound } : {}),
- ...(gaps.length ? { gaps } : {}),
+ ...(clock
+ ? { pieced: { file: src.path, cutStart: r3(vCutStart), cutEnd: r3(vCutEnd), gaps } }
+ : {}),
+ ...(clock
+ ? (() => {
+ const left = clock.realGaps(vCutStart, vCutEnd, gaps).map((g) => ({ from: r3(g.from), to: r3(g.to) }));
+ return left.length ? { gaps: left } : {};
+ })()
+ : gaps.length ? { gaps } : {}),
...(montage ? { montage: true } : {}),
};
const target = loudnessTargetOf(render);
@@ -299,12 +341,12 @@ async function clipCutPoints(entry, ctx) {
);
row.gainDb = loudnessGain(measured, target);
}
- const audio = clipAudioOf(entry);
+ const audio = clipAudioOf(real);
if (audio) row.audio = audio;
// Where the sound is heard (mute.mjs soundOnSegment, the build's join rule):
// the mute mark (a finale's ending sound), or a locked end the segment
// reaches past -- silent from it -- and a locked start it reaches before.
- const on = soundOnSegment(entry, render, row.cutStart, row.footage, gaps.length ? gaps : null);
+ const on = soundOnSegment(real, render, row.cutStart, row.footage, row.gaps?.length ? row.gaps : null);
if (on.mute != null && on.edges.muteFrom != null) row.muteFrom = on.edges.muteFrom;
if (on.soundFrom != null && on.edges.soundFrom != null) row.soundFrom = on.edges.soundFrom;
return row;
diff --git a/umtool/lib/report/pieced-consumers.test.mjs b/umtool/lib/report/pieced-consumers.test.mjs
@@ -0,0 +1,259 @@
+// 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));
+});
diff --git a/umtool/lib/report/raw-cache.mjs b/umtool/lib/report/raw-cache.mjs
@@ -8,6 +8,7 @@
// ours but the predicate.
import path from "node:path";
import {
+ keptPieces,
listRawNames,
tightestContaining,
windowsFromNames,
@@ -26,8 +27,16 @@ import {
* mere overlap -- a half-covered clip cannot be watched through, so it is not
* ready to judge.
*
+ * A clip with GAPS fetched PER KEPT PIECE (fetch-per-piece; the render's own
+ * fetchSpans) has no file holding its whole extent, and is fetched when EVERY
+ * piece it plays (its extent less the gaps this render applies, `render`) is
+ * inside some window. The whole extent in one window still answers first, so
+ * a clip fetched whole -- or one whose pieces' pads joined into a window --
+ * reads as before. `piecesOf(clip)` is the same walk, returning the window
+ * each piece is in (null when any is not covered).
+ *
* @param {string} projectDir
- * @param {{ extraWindows?: { video: string, windows: { name: string, path: string, from: number, to: number }[] }[] }} [opts]
+ * @param {{ extraWindows?: { video: string, windows: { name: string, path: string, from: number, to: number }[] }[], render?: Record<string, any> }} [opts]
* Windows OUTSIDE the project that also hold a given video -- the corpus's
* clip windows and a saved whole source, as `clipWindowDirs` lists them
* through the render's own sources.mjs, so the bench and the build agree on
@@ -35,7 +44,7 @@ import {
* source contains every window of its video, which is exactly what the
* predicate needs to know.
*/
-export async function rawCacheOf(projectDir, { extraWindows = [] } = {}) {
+export async function rawCacheOf(projectDir, { extraWindows = [], render = {} } = {}) {
const rawDir = path.join(projectDir, "out", "clips-raw");
const names = await listRawNames(rawDir);
const extra = new Map();
@@ -53,15 +62,29 @@ export async function rawCacheOf(projectDir, { extraWindows = [] } = {}) {
}
return byVideo.get(video);
};
+ /** The window each kept piece of the clip is inside, in order; null when any piece is not covered (or the clip has no window). */
+ const piecesOf = (clip) => {
+ const spans = keptPieces(clip, render);
+ if (!spans.length) return null;
+ const out = [];
+ for (const span of spans) {
+ const win = tightestContaining(windows(clip.video), span.from, span.to);
+ if (!win) return null;
+ out.push({ span, window: win });
+ }
+ return out;
+ };
return {
rawDir,
+ render,
windows,
containing: (video, from, to) => tightestContaining(windows(video), from, to),
+ piecesOf,
isFetched: (clip) => {
const { start, end, video } = clip ?? {};
if (!Number.isFinite(start) || !Number.isFinite(end)) return false;
- return !!tightestContaining(windows(video), start, end);
+ if (tightestContaining(windows(video), start, end)) return true;
+ return !!piecesOf(clip);
},
};
}
-
diff --git a/umtool/lib/report/scenesCli.mjs b/umtool/lib/report/scenesCli.mjs
@@ -23,7 +23,7 @@
// Plain ESM: the CLI runs under bare node.
import { spawn } from "node:child_process";
import { clockOffset } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
-import { fetchSpan } from "umtool-report-to-video/build-video";
+import { fetchSpan, localPieces } from "umtool-report-to-video/build-video";
import { ffprobeSource, resolveLocalSource } from "umtool-report-to-video/sources";
import path from "node:path";
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
@@ -145,38 +145,82 @@ export async function scanClip(project, clipId, opts = {}) {
const hit =
(await resolveLocalSource({ video: entry.video, slug, from: span.from, to: span.to }, config)) ??
(await resolveLocalSource({ video: entry.video, slug, from: entry.start, to: entry.end }, config));
+ const clipRow = {
+ id: clipId,
+ channel: slug,
+ video: entry.video,
+ start: entry.start,
+ end: entry.end,
+ ...(entry.cutStart != null && entry.cutEnd != null ? { cutStart: entry.cutStart, cutEnd: entry.cutEnd } : {}),
+ ...(entry.blur && typeof entry.blur === "object" ? { blur: entry.blur } : {}),
+ };
+ /** One window scanned over [from, to] (clamped into it): its events in source seconds, and what was scanned. */
+ const scanWindow = async (h, wantFrom, wantTo) => {
+ const winFrom = h.windowStart;
+ const winTo = h.windowEnd;
+ const from = Math.max(winFrom, wantFrom);
+ const to = Math.min(winTo, wantTo);
+ if (!(to - from > 0)) return { h, empty: true, from, to, winFrom, winTo };
+ const off = await (opts.clockOffset ?? clockOffset)(h.path);
+ const seek = Math.max(0, from - winFrom - off);
+ const zero = winFrom + off + seek;
+ const log = await runFfmpeg(scanArgs(h.path, { seek, dur: to - from, blackMin, threshold, pixTh }), opts.ffmpeg ? { ffmpeg: opts.ffmpeg } : {});
+ return { h, from, to, winFrom, winTo, off, events: toSourceSeconds(parseSceneLog(log), zero, { start: entry.start, end: entry.end }) };
+ };
if (!hit) {
+ // A clip with gaps is fetched per kept piece (fetchSpans): scan each piece on disk.
+ const local = { resolve: (e, sp) => resolveLocalSource({ video: e.video, slug, from: sp.from, to: sp.to }, config) };
+ const had = await localPieces(entry, manifest.render ?? {}, local);
+ if (had) {
+ const wantFrom = opts.from ?? entry.start - pad;
+ const wantTo = opts.to ?? entry.end + pad;
+ const scans = [];
+ // Two spans may be one window (a long file holds both): scanned once.
+ const done = new Set();
+ for (let k = 0; k < had.hits.length; k += 1) {
+ const h = had.hits[k];
+ const sp = had.spans[k];
+ const key = `${h.path}|${Math.max(sp.from, wantFrom)}|${Math.min(sp.to, wantTo)}`;
+ if (done.has(key)) continue;
+ done.add(key);
+ scans.push(await scanWindow(h, Math.max(sp.from, wantFrom), Math.min(sp.to, wantTo)));
+ }
+ const live = scans.filter((x) => !x.empty);
+ if (!live.length) throw new CliError(`nothing to scan: ${r2(wantFrom)}–${r2(wantTo)} is outside every piece's window`);
+ const cuts = live.flatMap((x) => x.events.cuts).sort((a, b) => a.at - b.at);
+ const black = live.flatMap((x) => x.events.black).sort((a, b) => a.from - b.from);
+ return {
+ project: project.id,
+ clip: clipRow,
+ window: {
+ file: live[0].h.path,
+ kind: "pieces",
+ from: Math.min(...scans.map((x) => x.winFrom)),
+ to: Math.max(...scans.map((x) => x.winTo)),
+ clockOffset: 0,
+ pieces: live.map((x) => ({ file: x.h.path, kind: x.h.kind, from: x.winFrom, to: x.winTo, clockOffset: x.off, scanned: { from: r2(x.from), to: r2(x.to) } })),
+ },
+ scanned: { from: r2(Math.min(...live.map((x) => x.from))), to: r2(Math.max(...live.map((x) => x.to))) },
+ params: { blackMin, threshold, pixTh },
+ cuts,
+ black,
+ };
+ }
// A state, not a usage error: exit 1, as a refused write is.
throw new Error(
`${clipId} (${slug}/${entry.video} ${entry.start}–${entry.end}) has no window on disk — ` +
`\`umtool fetch ${project.id}\` asks the editor for it`,
);
}
- const winFrom = hit.windowStart;
- const winTo = hit.windowEnd;
- const from = Math.max(winFrom, opts.from ?? entry.start - pad);
- const to = Math.min(winTo, opts.to ?? entry.end + pad);
- if (!(to - from > 0)) throw new CliError(`nothing to scan: ${r2(from)}–${r2(to)} is outside the window ${winFrom}–${winTo}`);
- const off = await (opts.clockOffset ?? clockOffset)(hit.path);
- const seek = Math.max(0, from - winFrom - off);
- const zero = winFrom + off + seek;
- const log = await runFfmpeg(scanArgs(hit.path, { seek, dur: to - from, blackMin, threshold, pixTh }), opts.ffmpeg ? { ffmpeg: opts.ffmpeg } : {});
- const events = toSourceSeconds(parseSceneLog(log), zero, { start: entry.start, end: entry.end });
+ const r = await scanWindow(hit, opts.from ?? entry.start - pad, opts.to ?? entry.end + pad);
+ if (r.empty) throw new CliError(`nothing to scan: ${r2(r.from)}–${r2(r.to)} is outside the window ${r.winFrom}–${r.winTo}`);
return {
project: project.id,
- clip: {
- id: clipId,
- channel: slug,
- video: entry.video,
- start: entry.start,
- end: entry.end,
- ...(entry.cutStart != null && entry.cutEnd != null ? { cutStart: entry.cutStart, cutEnd: entry.cutEnd } : {}),
- ...(entry.blur && typeof entry.blur === "object" ? { blur: entry.blur } : {}),
- },
- window: { file: hit.path, kind: hit.kind, from: winFrom, to: winTo, clockOffset: off },
- scanned: { from: r2(from), to: r2(to) },
+ clip: clipRow,
+ window: { file: hit.path, kind: hit.kind, from: r.winFrom, to: r.winTo, clockOffset: r.off },
+ scanned: { from: r2(r.from), to: r2(r.to) },
params: { blackMin, threshold, pixTh },
- ...events,
+ ...r.events,
};
}
@@ -223,7 +267,12 @@ export async function scenesCommand(args, { root = REPORTS_ROOT, out = (s) => co
const c = s.clip;
out(`${c.id} ${c.channel}/${c.video} extent ${c.start}–${c.end}${c.cutStart != null ? ` cut ${c.cutStart}–${c.cutEnd}` : ""}` +
(c.blur ? ` blur ${c.blur.from ?? c.start}–${c.blur.to ?? c.end}` : ""));
- out(`window ${s.window.from}–${s.window.to} (${s.window.kind}) ${s.window.file}${s.window.clockOffset ? ` clock +${s.window.clockOffset}` : ""}`);
+ if (s.window.kind === "pieces") {
+ out(`window ${s.window.from}–${s.window.to} (pieces: ${s.window.pieces.length}, a clip fetched per kept piece)`);
+ for (const p of s.window.pieces) out(` ${p.from}–${p.to} (${p.kind}) ${p.file}${p.clockOffset ? ` clock +${p.clockOffset}` : ""} scanned ${p.scanned.from}–${p.scanned.to}`);
+ } else {
+ out(`window ${s.window.from}–${s.window.to} (${s.window.kind}) ${s.window.file}${s.window.clockOffset ? ` clock +${s.window.clockOffset}` : ""}`);
+ }
out(`scanned ${s.scanned.from}–${s.scanned.to}, source seconds`);
const mark = (inClip) => (inClip ? " in clip" : "");
out(`\nblack (≥ ${s.params.blackMin} s): ${s.black.length || "none"}`);
diff --git a/umtool/lib/report/serve.mjs b/umtool/lib/report/serve.mjs
@@ -14,7 +14,7 @@ import { promisify } from "node:util";
import { Readable } from "node:stream";
import { REPORTS_ROOT, inside, resolveInRoots } from "../paths.mjs";
import { walkProjects } from "../projects/walk.mjs";
-import { DEFAULT_VARIANT, FFMPEG_BIN, VARIANTS, WIN_EPS, variantPaths } from "umtool-report-to-video/build-video";
+import { DEFAULT_VARIANT, FFMPEG_BIN, VARIANTS, WIN_EPS, probeDims, probeMedia, variantPaths } from "umtool-report-to-video/build-video";
import { rawCacheOf } from "./raw-cache.mjs";
import {
channelsDirFor,
@@ -94,7 +94,7 @@ export async function projectCache(project, manifest = null) {
const m = manifest ?? (await readManifest(project.dir));
const shadowExists = await hasShadowChannels(project.dir);
const channelsDir = channelsDirFor(project.dir, m, { shadowExists });
- return rawCacheOf(project.dir, { extraWindows: await clipWindowDirs(m, channelsDir) });
+ return rawCacheOf(project.dir, { extraWindows: await clipWindowDirs(m, channelsDir), render: m?.render ?? {} });
}
/**
@@ -131,10 +131,144 @@ export async function windowsFor(project, clip, cache = null) {
}
const overlap = (w) => Math.max(0, Math.min(w.to, end) - Math.max(w.from, start));
const contains = (w) => (w.from <= start + WIN_EPS && w.to >= end - WIN_EPS ? 1 : 0);
- return all
+ const listed = all
.filter((w) => overlap(w) > 0)
.sort((a, b) => contains(b) - contains(a) || overlap(b) - overlap(a) || width(b) - width(a))
.map((w) => (contains(w) ? excerptOf(w, clip, project.dir) ?? w : w));
+ // No file holds the whole clip, but every piece it plays is held (a clip with
+ // gaps, fetched per kept piece): ONE window on the source's clock, the pieces
+ // where they were said and black, silent filler where nothing was fetched
+ // (inside a gap -- every playback skips it as the cut will).
+ if (!all.some(contains)) {
+ const joined = piecedWindowFor(project, clip, c);
+ if (joined) return [joined, ...listed];
+ }
+ return listed;
+}
+
+// ---------------------------------------------------------------------------
+// A CLIP FETCHED IN PIECES IS ONE WINDOW.
+//
+// A clip with gaps is fetched per kept piece (fetchWindows.mjs): no file holds
+// its extent, so "the widest window containing it" was nothing and the bench
+// offered to fetch what was on disk. Its pieces are all held (raw-cache.mjs
+// piecesOf), and the bench's whole model is a window on the SOURCE's clock --
+// cues, waveform, marks, the gap bands, the edge drag. So the pieces are laid
+// on that clock in one file, like an excerpt: each where it was said, a
+// black, silent filler where nothing was fetched. The gap is skipped on every
+// play (the bench plays what the cut will play), so the filler is never the
+// point; it is what keeps every number in the bench true. Cut once, lazily
+// (ensureWindowFile), from the pieces as they are now.
+// ---------------------------------------------------------------------------
+
+/** A clip whose pieces lie further apart than this (seconds) is not laid on one clock: the filler would be the file. */
+export const PIECES_MAX_S = 900;
+/** Seconds of context kept either side of the clip's extent, as an excerpt keeps. */
+export const PIECES_PAD_S = 45;
+
+/**
+ * Lay windows on [from, to] of the source's clock: each second from the
+ * window that holds it (the one reaching furthest from the cursor), black
+ * filler where none does. Pure.
+ *
+ * @param {{ name: string, path: string, from: number, to: number }[]} wins
+ * @param {number} from
+ * @param {number} to
+ * @returns {Array<{ kind: "file", path: string, winFrom: number, from: number, to: number } | { kind: "fill", from: number, to: number }>}
+ */
+export function layoutPieces(wins, from, to) {
+ const items = [];
+ let at = from;
+ while (to - at > 1e-6) {
+ const here = wins.filter((w) => w.from <= at + WIN_EPS && w.to > at + 1e-6).sort((a, b) => b.to - a.to)[0];
+ if (here) {
+ const next = Math.min(here.to, to);
+ items.push({ kind: "file", path: here.path, winFrom: here.from, from: at, to: next });
+ at = next;
+ continue;
+ }
+ const upcoming = wins.filter((w) => w.from > at).map((w) => w.from).sort((a, b) => a - b)[0];
+ const next = Math.min(upcoming ?? to, to);
+ items.push({ kind: "fill", from: at, to: next });
+ at = next;
+ }
+ return items;
+}
+
+/**
+ * The window standing for a clip fetched in pieces, or null (the clip's
+ * pieces are not all held, or it has fewer than two, or they lie too far
+ * apart for one file). Described only: ensureWindowFile cuts it.
+ *
+ * @param {{ dir: string }} project
+ * @param {{ video: string, start: number, end: number, [k: string]: any }} clip
+ * @param {Awaited<ReturnType<typeof rawCacheOf>>} cache
+ */
+export function piecedWindowFor(project, clip, cache) {
+ const held = cache.piecesOf?.(clip);
+ if (!held || held.length < 2) return null;
+ const used = [...new Map(held.map((h) => [h.window.path, h.window])).values()];
+ const lo = Math.max(Math.min(...used.map((w) => w.from)), clip.start - PIECES_PAD_S);
+ const hi = Math.min(Math.max(...used.map((w) => w.to)), clip.end + PIECES_PAD_S);
+ if (!(hi > lo) || hi - lo > PIECES_MAX_S) return null;
+ const from = Math.min(lo, held[0].span.from);
+ const to = Math.max(hi, held[held.length - 1].span.to);
+ const layout = layoutPieces(used, from, to);
+ const tag = createHash("sha1").update(JSON.stringify(layout)).digest("hex").slice(0, 8);
+ const name = `${from.toFixed(2)}-${to.toFixed(2)}.${tag}.pieces.mp4`;
+ const first = layout.find((i) => i.kind === "file");
+ if (!first) return null;
+ return {
+ name,
+ from,
+ to,
+ path: path.join(project.dir, "out", "bench-excerpts", String(clip.video), name),
+ // Treated as an excerpt by everything that cuts or serves one; `piecesOf` says how this one is cut.
+ excerptOf: { name: used[0].name, path: first.path, from: first.winFrom },
+ piecesOf: layout,
+ };
+}
+
+/** The ffmpeg arguments that lay a pieces window on its clock (one input per file item, filler from lavfi). Pure. */
+export function piecesArgs(win, out, { width, height, hasVideo = true, fps = 30 }) {
+ const inputs = [];
+ const filters = [];
+ const legs = [];
+ let k = 0;
+ win.piecesOf.forEach((it, n) => {
+ const len = (it.to - it.from).toFixed(3);
+ if (it.kind === "file") {
+ inputs.push("-ss", String(Math.max(0, it.from - it.winFrom)), "-t", len, "-i", it.path);
+ if (hasVideo) {
+ filters.push(`[${k}:v]scale=${width}:${height}:force_original_aspect_ratio=decrease,pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${fps},format=yuv420p,tpad=stop_mode=clone:stop_duration=${len},trim=duration=${len},setpts=PTS-STARTPTS[v${n}]`);
+ }
+ filters.push(`[${k}:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,apad=whole_dur=${len},atrim=duration=${len},asetpts=PTS-STARTPTS[a${n}]`);
+ k += 1;
+ } else {
+ if (hasVideo) filters.push(`color=c=black:s=${width}x${height}:r=${fps}:d=${len},format=yuv420p,setsar=1[v${n}]`);
+ filters.push(`anullsrc=r=48000:cl=stereo,atrim=duration=${len},asetpts=PTS-STARTPTS[a${n}]`);
+ }
+ legs.push(`${hasVideo ? `[v${n}]` : ""}[a${n}]`);
+ });
+ filters.push(`${legs.join("")}concat=n=${win.piecesOf.length}:v=${hasVideo ? 1 : 0}:a=1${hasVideo ? "[v]" : ""}[a]`);
+ return [
+ "-v", "error", "-y", ...inputs,
+ "-filter_complex", filters.join(";"),
+ ...(hasVideo ? ["-map", "[v]", "-c:v", "libx264", "-preset", "ultrafast", "-crf", "26", "-threads", "0", "-pix_fmt", "yuv420p"] : []),
+ "-map", "[a]", "-c:a", "aac", "-b:a", "160k", "-ac", "2",
+ "-movflags", "+faststart", out,
+ ];
+}
+
+/** The identities of every file a pieces window is laid from, in layout order (what its sidecar records). */
+async function piecesIdentity(win) {
+ const out = [];
+ for (const p of [...new Set(win.piecesOf.filter((i) => i.kind === "file").map((i) => i.path))]) {
+ const abs = resolveInRoots(p);
+ if (!abs) throw new Error("the recording is outside the roots");
+ out.push(await sourceIdentity(abs));
+ }
+ return out;
}
// ---------------------------------------------------------------------------
@@ -303,6 +437,14 @@ export const excerptSourceOf = (file) => `${file}.src.json`;
* @returns {Promise<string | null>}
*/
export async function windowVersion(win) {
+ if (win?.piecesOf) {
+ try {
+ const ids = await piecesIdentity(win);
+ return createHash("sha1").update(ids.map(identityTag).join("|")).digest("hex").slice(0, 16);
+ } catch {
+ return null;
+ }
+ }
const p = win?.excerptOf ? win.excerptOf.path : win?.path;
const abs = p ? resolveInRoots(p) : null;
if (!abs) return null;
@@ -361,6 +503,13 @@ export function notModified(request, etag) {
*/
export async function windowFileFresh(win) {
if (!win?.excerptOf) return true;
+ if (win.piecesOf) {
+ const now = await piecesIdentity(win);
+ const have = await stat(win.path).catch(() => null);
+ if (!have || !(have.size > 0)) return false;
+ const was = await readFile(excerptSourceOf(win.path), "utf8").then((t) => JSON.parse(t), () => null);
+ return Array.isArray(was) && was.length === now.length && now.every((id, k) => sameIdentity(was[k], id));
+ }
const src = resolveInRoots(win.excerptOf.path);
if (!src) throw new Error("the recording is outside the roots");
const now = await sourceIdentity(src);
@@ -387,8 +536,8 @@ export async function windowFileFresh(win) {
*/
export async function ensureWindowFile(win, { ffmpeg = FFMPEG_BIN, waitMs = CUT_WAIT_MS, pollMs = 250 } = {}) {
if (!win?.excerptOf) return;
- const src = resolveInRoots(win.excerptOf.path);
- if (!src) throw new Error("the recording is outside the roots");
+ const src = win.piecesOf ? null : resolveInRoots(win.excerptOf.path);
+ if (!win.piecesOf && !src) throw new Error("the recording is outside the roots");
if (await windowFileFresh(win)) return;
if (!cutting.has(win.path)) {
const job = (async () => {
@@ -409,10 +558,22 @@ export async function ensureWindowFile(win, { ffmpeg = FFMPEG_BIN, waitMs = CUT_
// The source as it is when the cut starts: what the sidecar says it was
// cut from. Replaced DURING the cut, it no longer matches, and the next
// read cuts again rather than trust these bytes.
- const from = await sourceIdentity(src);
+ const from = win.piecesOf ? await piecesIdentity(win) : await sourceIdentity(src);
// The old record goes first: the excerpt about to land is not the file it describes.
await rm(side, { force: true });
- await execFileP(ffmpeg, [
+ if (win.piecesOf) {
+ // A clip fetched in pieces, laid on the source's clock (piecedWindowFor).
+ const firstFile = win.piecesOf.find((i) => i.kind === "file");
+ const hasVideo = (await probeMedia(firstFile.path).catch(() => ({ hasVideo: true }))).hasVideo;
+ let width = 640;
+ let height = 360;
+ if (hasVideo) {
+ const [w, h] = await probeDims(firstFile.path);
+ height = Math.max(2, 2 * Math.round(Math.min(720, h) / 2));
+ width = Math.max(2, 2 * Math.round((w * height) / h / 2));
+ }
+ await execFileP(ffmpeg, piecesArgs(win, tmp, { width, height, hasVideo }), { maxBuffer: 4 * 1024 * 1024 });
+ } else await execFileP(ffmpeg, [
"-v", "error", "-y",
"-ss", String(win.from - win.excerptOf.from),
"-i", src,
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -880,6 +880,45 @@ export function fetchSpans(entry, render, opts = {}) {
}
/**
+ * A clip's KEPT pieces, unpadded: its extent less the gaps this render
+ * applies (one span for a clip without gaps and in a montage). What "is this
+ * clip held end to end" asks of a cache -- the seconds that PLAY, not the
+ * fetch's padded spans (fetchSpans). Empty when the clip has no window.
+ */
+export function keptPieces(entry, render = {}) {
+ const from = Number(entry?.start);
+ const to = Number(entry?.end);
+ if (!Number.isFinite(from) || !Number.isFinite(to) || !(to > from)) return [];
+ return keptSpans(from, to, renderGaps(entry, render));
+}
+
+/**
+ * A gap-joined clip's PIECES on disk: `local.resolve` for each of fetchSpans'
+ * spans, as piecedClipSource asks. `{ spans, hits }` when the clip has two or
+ * more spans and every one is held; null otherwise (one span, a `src`, any
+ * span not on disk). The whole extent is NOT asked here -- callers ask that
+ * first (onDiskClipSource / local.resolve over fetchSpan), as the build does.
+ *
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} render
+ * @param {{ resolve: Function }} local
+ * @param {Record<string, any>} [opts] fetchSpans' (pad, padBefore, padAfter) and resolve's (noReuse)
+ * @param {{ audio?: boolean }} [more] `audio`: a sound-only source serves a piece
+ */
+export async function localPieces(entry, render, local, opts = {}, { audio = false } = {}) {
+ if (hasLocalMedia(entry)) return null;
+ const spans = fetchSpans(entry, render, opts);
+ if (spans.length < 2) return null;
+ const hits = [];
+ for (const span of spans) {
+ const hit = await local.resolve(entry, span, { exact: !!opts.noReuse, audio });
+ if (!hit) return null;
+ hits.push(hit);
+ }
+ return { spans, hits };
+}
+
+/**
* The clock of a clip cut from its pieces joined end to end (piecedClipSource):
* each span laid after the one before, so the seconds between them -- inside
* a gap, never played -- are not in the file. `toVirtual` maps a source second
@@ -1015,12 +1054,8 @@ export async function planLocalSources(entries, timeline, render, opts, local, m
let hit = await local.resolve(entry, span, { exact, audio: use !== null });
// A gap-joined clip is had when each of its pieces is (fetchSpans, piecedClipSource).
if (!hit) {
- const spans = fetchSpans(entry, render, opts);
- if (spans.length > 1) {
- const hits = [];
- for (const s of spans) hits.push(await local.resolve(entry, s, { exact, audio: use !== null }));
- if (hits.every(Boolean)) hit = hits.find((h) => h.kind !== "audio") ?? hits[0];
- }
+ const had = await localPieces(entry, render, local, opts, { audio: use !== null });
+ if (had) hit = had.hits.find((h) => h.kind !== "audio") ?? had.hits[0];
}
const row = {
// By id: a variant's view may be a copy of the manifest's entry.
@@ -1327,7 +1362,7 @@ async function fetchClip(entry, meta, render, local, opts) {
* clip -- one span, a `src`, a whole window on disk -- which is cut as ever.
* The joined file is made again only when its pieces change (`.pieces.mp4.json`).
*/
-async function piecedClipSource(entry, meta, render, local, opts, outDir) {
+export async function piecedClipSource(entry, meta, render, local, opts, outDir) {
if (hasLocalMedia(entry)) return null;
const spans = fetchSpans(entry, render, opts);
if (spans.length < 2) return null;
@@ -1907,7 +1942,7 @@ async function encodeClipSegment({ seg, argv, record, outDir, render, opts, id }
// and ffmpeg. Reached only when render.captions is set, or for a short.
/** A picture's display size `[w, h]` (its sample aspect applied), for a short's crop. */
-async function probeDims(file) {
+export async function probeDims(file) {
const { stdout } = await execFileP(FFPROBE, [
"-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,sample_aspect_ratio", "-of", "json", file,
]);
diff --git a/umtool/report-to-video/check-availability.mjs b/umtool/report-to-video/check-availability.mjs
@@ -52,7 +52,7 @@ import {
} from "yt-dlp-transcript-common/ytdlp/platformArgs.mjs";
import { jitterSleepArgs } from "yt-dlp-transcript-common/lib/jitter.mjs";
import { detectPlatform } from "yt-dlp-transcript-common/lib/detectPlatform.mjs";
-import { fetchSpan, localSources } from "./build-video.mjs";
+import { fetchSpan, localPieces, localSources } from "./build-video.mjs";
import { SHADOW_CHANNELS, audioUse, channelsDirFor } from "./sources.mjs";
import { manifestSources } from "./manifest-sources.mjs";
@@ -115,7 +115,8 @@ const verdictOf = (state) => (state === "ok" || state === "held-locally" ? true
/**
* Can the build cut every clip of this source from disk? The build's own
- * question (fetchSpan + the local tiers), asked with the network on: a clip
+ * question (fetchSpan + the local tiers, or every piece of a gap-joined clip:
+ * localPieces), asked with the network on: a clip
* that plays from its sound because it has no picture to fetch counts, a
* picture that would be fetched does not. A source with no clips (ledger only)
* has nothing on disk to answer for it.
@@ -125,7 +126,9 @@ async function heldLocally(w, render, local) {
for (const entry of w.entries) {
const span = fetchSpan(entry, render, {});
const audio = audioUse({ entry, render, network: true }) !== null;
- if (!(await local.resolve(entry, span, { audio }))) return false;
+ if (await local.resolve(entry, span, { audio })) continue;
+ // A clip with gaps is fetched per kept piece (fetchSpans): held when every piece is.
+ if (!(await localPieces(entry, render, local, {}, { audio }))) return false;
}
return true;
}
diff --git a/umtool/report-to-video/check-availability.test.mjs b/umtool/report-to-video/check-availability.test.mjs
@@ -129,6 +129,30 @@ test("every clip held on disk: held-locally, and yt-dlp is never run", async ()
assert.deepEqual(clock.sleeps, []);
});
+test("a gap-joined clip fetched per piece is held when every piece is; one missing is a probe", async () => {
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "ca-pieced-"));
+ const fake = await fakeYtdlp(tmp);
+ await cueFile("chan", "pc1", "https://www.youtube.com/watch?v=pc1xxxxxxxx");
+ await cueFile("chan", "pc2", "https://www.youtube.com/watch?v=pc2xxxxxxxx");
+ // 10–200 less a 100 s gap: kept 10–50 and 150–200, padded 3 s: 7–53 and 147–203, 94 s apart (not joined).
+ const gaps = [{ from: 50, to: 150 }];
+ const p = await project("pieced", [
+ { id: "p1", type: "clip", video: "pc1", start: 10, end: 200, gaps },
+ { id: "p2", type: "clip", video: "pc2", start: 10, end: 200, gaps },
+ ]);
+ await mkdir(path.join(p.out, "clips-raw"), { recursive: true });
+ // pc1: both pieces (the build's raw names, one per piece). pc2: the first piece only.
+ await writeFile(path.join(p.out, "clips-raw", rawWindowName("pc1", 7, 53)), "x");
+ await writeFile(path.join(p.out, "clips-raw", rawWindowName("pc1", 147, 203)), "x");
+ await writeFile(path.join(p.out, "clips-raw", rawWindowName("pc2", 7, 53)), "x");
+ const clock = fakeClock();
+ const report = await checkAvailability(p.manifest, { outDir: p.out, ytdlp: fake.bin, ...clock });
+ const byKey = Object.fromEntries(report.sources.map((s) => [s.key, s.state]));
+ assert.equal(byKey["chan/pc1"], "held-locally", "every piece held");
+ assert.notEqual(byKey["chan/pc2"], "held-locally", "the second piece is not on disk");
+ assert.deepEqual(await fake.calls(), ["https://www.youtube.com/watch?v=pc2xxxxxxxx"], "only the half-held source is probed");
+});
+
test("two Rumble sources: the second probe starts at least 120 s after the first ends", async () => {
const tmp = await mkdtemp(path.join(os.tmpdir(), "ca-paced-"));
const fake = await fakeYtdlp(tmp);