Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 331369f06c0939bb982fa806800fe422dea22b8c
parent eb97327e2e3314c6a1570e15db7534b0d83db85a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun,  1 Nov 2026 00:13:46 -0400

umtool build: a gap-joined clip is cut from its pieces -- fetchSpans (one padded span per kept piece), each piece had on its own (on disk, else fetched: that span only), joined end to end as one input per piece into segments/<id>.pieces.mp4 and cut on that file's clock (piecesClock); the cut record maps back to the recording's seconds, the seconds between pieces as a gap; --no-network counts a clip as had when each piece is

A clip whose extent is on disk whole, a clip without gaps and a montage are
cut as before. Room is not applied to a clip cut from its pieces.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/report-to-video/build-video.mjs | 242+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/report-to-video/gaps-render.test.mjs | 99++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
2 files changed, 324 insertions(+), 17 deletions(-)

diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -165,7 +165,7 @@ import { blurCaptionLayout, blurPictureFilters, blurProblems, blurRecordOf, blur import { validateFinaleEntries } from "./finale.mjs"; // Seconds taken out of a clip's middle (gaps.mjs): pure; the segment's graph is built there too. import { - gapFilterParts, gapSeconds, gapsOnSegment, inGap, offsetIn, recordGaps, renderGaps, validateGapEntries, + fetchPieces, gapFilterParts, gapSeconds, gapsOnSegment, inGap, keptSpans, offsetIn, recordGaps, renderGaps, validateGapEntries, } from "./gaps.mjs"; import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs"; import { validateThreadEntries } from "./threads.mjs"; @@ -545,6 +545,10 @@ const HUMAN = { (e.source === "audio" ? " — audio only, under a poster" : "") + (e.source === "audio-fallback" ? " — AUDIO-FALLBACK: the picture is not on disk; a poster plays" : "") : ` fetch ${e.id}: ${e.video} ${hms(e.from)}–${hms(e.to)} (network)`, + // A gap-joined clip cut from its pieces (piecedClipSource), joined into one file. + pieces: (e) => + ` pieces ${e.id}: ${e.pieces.length} piece(s) ${e.pieces.map(([a, b]) => `${hms(a)}–${hms(b)}`).join(", ")} ` + + `joined in ${e.file}: ${Number(e.seconds).toFixed(1)}s of the ${hms(e.pieces[0][0])}–${hms(e.pieces[e.pieces.length - 1][1])} extent`, snap: (e) => ` snap ${e.id}: ${e.start ? "start✓" : "start–"} ${e.end ? "end✓" : "end–"} ` + `(${Number(e.seconds).toFixed(1)}s)`, @@ -849,6 +853,8 @@ export { AUDIO_ON_CLOCK }; * what was asked for. `--pad` stays the shorthand that sets both. */ export function fetchSpan(entry, render, opts = {}) { + // One piece of a clip fetched in pieces (fetchSpans): that piece's span. + if (opts.span) return { from: opts.span.from, to: opts.span.to }; const pad = opts.pad ?? render.fetchPad ?? 3.0; const padBefore = opts.padBefore ?? pad; const padAfter = opts.padAfter ?? pad; @@ -856,6 +862,100 @@ export function fetchSpan(entry, render, opts = {}) { } /** + * The spans a clip's source is needed over, PER KEPT PIECE (gaps.mjs + * fetchPieces): each piece of its extent less the gaps this render applies, + * padded at its own edges as fetchSpan pads the extent, pieces under a minute + * apart as one. One span -- fetchSpan's -- for a clip without gaps, for one + * whose gaps are short, and in a montage (it applies no gaps). What umtool + * fetch asks the editor for (fetchWindows.mjs), and what a gap-joined clip + * spanning hours is cut from (piecedClipSource). + */ +export function fetchSpans(entry, render, opts = {}) { + if (opts.span) return [fetchSpan(entry, render, opts)]; + const pad = opts.pad ?? render.fetchPad ?? 3.0; + return fetchPieces(entry.start, entry.end, renderGaps(entry, render), { + before: opts.padBefore ?? pad, + after: opts.padAfter ?? pad, + }); +} + +/** + * 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 + * onto the joined file's clock (one between the spans lands on the nearest + * span's edge), `toReal` maps back (past either end it runs on, as a file's + * clock would). Pure. + * + * @param {Array<{ from: number, to: number }>} spans + */ +export function piecesClock(spans) { + const groups = []; + let v = 0; + for (const s of spans) { + groups.push({ from: s.from, to: s.to, v0: v, len: s.to - s.from }); + v += s.to - s.from; + } + const total = v; + const toVirtual = (t) => { + if (!Number.isFinite(t) || !groups.length) return t; + let near = groups[0]; + let dist = Infinity; + for (const g of groups) { + if (t >= g.from && t <= g.to) return g.v0 + (t - g.from); + const d = t < g.from ? g.from - t : t - g.to; + if (d < dist) { + dist = d; + near = g; + } + } + if (t < groups[0].from) return t - groups[0].from; + if (t > groups[groups.length - 1].to) return total + (t - groups[groups.length - 1].to); + return t < near.from ? near.v0 : near.v0 + near.len; + }; + const toReal = (x) => { + if (!Number.isFinite(x) || !groups.length) return x; + if (x < 0) return groups[0].from + x; + for (const g of groups) if (x <= g.v0 + g.len) return g.from + (x - g.v0); + const last = groups[groups.length - 1]; + return last.to + (x - total); + }; + /** + * The source seconds a cut on this clock leaves out between its first and + * last: its own gaps (`gaps`, on this clock) and every second between two + * pieces, as gaps in the source's seconds -- what the cut record says. A + * gap that shrank to nothing on this clock (no pad between two pieces) is + * still the source's seconds between them. + * @param {number} a @param {number} b the cut, on this clock + * @param {Array<{ from: number, to: number }>} gaps on this clock + */ + const realGaps = (a, b, gaps) => { + const kept = []; + for (const k of keptSpans(a, b, gaps)) { + for (const g of groups) { + const lo = Math.max(k.from, g.v0); + const hi = Math.min(k.to, g.v0 + g.len); + if (hi - lo > 1e-9) kept.push({ from: g.from + (lo - g.v0), to: g.from + (hi - g.v0) }); + } + } + const out = []; + for (let i = 1; i < kept.length; i += 1) if (kept[i].from - kept[i - 1].to > 1e-6) out.push({ from: kept[i - 1].to, to: kept[i].from }); + return out; + }; + return { spans: groups.map((g) => ({ from: g.from, to: g.to })), total, toVirtual, toReal, realGaps }; +} + +/** A clip's source seconds on a pieces clock: what the segment's cut reads in place of the entry's own. Pure. */ +export function virtualEntry(entry, clock) { + const v = { ...entry }; + for (const k of ["start", "end", "cutStart", "cutEnd", "cite"]) if (Number.isFinite(entry[k])) v[k] = clock.toVirtual(entry[k]); + if (Array.isArray(entry.gaps)) { + v.gaps = entry.gaps.map((g) => (g && Number.isFinite(g.from) && Number.isFinite(g.to) ? { ...g, from: clock.toVirtual(g.from), to: clock.toVirtual(g.to) } : g)); + } + return v; +} + +/** * Where this build looks for media already on disk: the raw cache, the * channels tree and the clip's channel. One per build; `resolve` is memoised, * so `--no-network`'s up-front pass and the clip's own fetch probe a saved @@ -913,6 +1013,15 @@ export async function planLocalSources(entries, timeline, render, opts, local, m audioUse({ entry, meta, render, network: networkOn(opts), fallback: !!opts.audioFallback }); let use = ask(null); 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 row = { // By id: a variant's view may be a copy of the manifest's entry. index: timeline.findIndex((e) => e === entry || (entry.id != null && e?.id === entry.id)), @@ -1206,6 +1315,89 @@ async function fetchClip(entry, meta, render, local, opts) { return { path: dest, fetchStart: from, cached: false, source: "network" }; } +/** + * A gap-joined clip's source, cut from its PIECES (fetchSpans): when its + * gaps leave more than one span and no window on disk holds the whole extent, + * each span is had on its own (on disk, else fetched -- that span only) and + * the spans are joined end to end into `segments/<id>.pieces.mp4`: one input + * per piece, concatenated, every piece the first one's size and the render's + * fps. The segment is then cut from that file on its pieces clock + * (piecesClock): `entry` is the clip with its seconds on that clock, `clock` + * maps the cut back to the source's for the cut record. Null for every other + * 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) { + if (hasLocalMedia(entry)) return null; + const spans = fetchSpans(entry, render, opts); + if (spans.length < 2) return null; + if (await onDiskClipSource(entry, meta, render, local, opts)) return null; + const parts = []; + for (const span of spans) parts.push({ span, ...(await fetchClipAligned(entry, meta, render, local, { ...opts, span })) }); + const probes = await Promise.all(parts.map((p) => probeMedia(p.path))); + const withPicture = probes.filter((p) => p.hasVideo).length; + if (withPicture && withPicture < parts.length) { + throw new Error( + `${entry.id}: its pieces' sources differ -- ${parts.filter((_, k) => !probes[k].hasVideo).map((p) => path.basename(p.path)).join(", ")} ` + + "has only sound, the others a picture; fetch the piece again (umtool fetch --refetch)", + ); + } + const fps = render.fps ?? 30; + let dims = null; + if (withPicture) { + const [w, h] = await probeDims(parts[0].path); + dims = [Math.max(2, 2 * Math.round(w / 2)), Math.max(2, 2 * Math.round(h / 2))]; + } + const file = path.join(outDir, "segments", `${entry.id}.pieces.mp4`); + const keyFile = `${file}.json`; + const sigs = await Promise.all(parts.map((p) => stat(p.path).then((s) => ({ size: s.size, mtimeMs: Math.round(s.mtimeMs) }), () => null))); + const key = `${JSON.stringify({ + version: 1, fps, dims, + pieces: parts.map((p, k) => ({ file: p.path, fetchStart: p.fetchStart, from: p.span.from, to: p.span.to, ...sigs[k] })), + }, null, 2)}\n`; + const had = await readFile(keyFile, "utf8").catch(() => null); + if (had !== key || !(await exists(file))) { + const inputs = []; + const filters = []; + const legs = []; + parts.forEach((p, k) => { + const len = p.span.to - p.span.from; + const a = p.span.from - p.fetchStart; + inputs.push(...cutArgs(p.path, Math.max(0, a), p.span.to - p.fetchStart)); + const L = len.toFixed(3); + if (dims) { + const [W, H] = dims; + filters.push( + `[${k}:v]scale=${W}:${H}:force_original_aspect_ratio=decrease,pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${fps},format=yuv420p,` + + `tpad=stop_mode=clone:stop_duration=${L},trim=duration=${L},setpts=PTS-STARTPTS[pv${k}]`, + ); + } + // A piece that starts before its media does keeps its place: silence first. + const lead = a < 0 ? `adelay=${Math.round(-a * 1000)}:all=1,` : ""; + filters.push(`[${k}:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,${lead}apad=whole_dur=${L},atrim=duration=${L},asetpts=PTS-STARTPTS[pa${k}]`); + legs.push(`${dims ? `[pv${k}]` : ""}[pa${k}]`); + }); + filters.push(`${legs.join("")}concat=n=${parts.length}:v=${dims ? 1 : 0}:a=1${dims ? "[pv]" : ""}[pa]`); + const tmp = `${file}.tmp.mp4`; + await mkdir(path.dirname(file), { recursive: true }); + await execFileP(FFMPEG, [ + "-nostdin", "-v", "error", "-y", ...inputs, + "-filter_complex", filters.join(";"), + ...(dims ? ["-map", "[pv]", "-c:v", "libx264", "-preset", "veryfast", "-crf", "12", "-pix_fmt", "yuv420p", "-r", String(fps)] : []), + "-map", "[pa]", "-c:a", "aac", "-b:a", "320k", "-ar", "48000", + "-movflags", "+faststart", tmp, + ], { maxBuffer: 1 << 24 }); + await rename(tmp, file); + await writeFile(keyFile, key, "utf8"); + } + const clock = piecesClock(spans); + EMIT("pieces", { + id: entry.id, file: path.basename(file), seconds: Number(clock.total.toFixed(2)), + pieces: spans.map((s) => [Number(s.from.toFixed(2)), Number(s.to.toFixed(2))]), + }); + return { path: file, fetchStart: 0, cached: true, source: "pieces", clock, entry: virtualEntry(entry, clock) }; +} + // The silences of a file, in its own seconds (cut-points.mjs detectSilence, // with this build's ffmpeg). The snap that reads them is snap.mjs's `snap`, // re-exported above for the tests. @@ -1241,7 +1433,13 @@ const encodeArgsVideoOnly = (render) => [ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, provenance, framing = null) { const outDir = dirs.dir; - const { path: raw, fetchStart, scan } = await fetchClipAligned(entry, meta, render, dirs.local, opts); + // A gap-joined clip whose pieces are apart is cut from them joined + // (piecedClipSource): `clipE` is the clip on that file's clock, `toReal` + // maps a cut on it back to the source's. Every other clip: itself, as ever. + const pieced = await piecedClipSource(entry, meta, render, dirs.local, opts, outDir); + const { path: raw, fetchStart, scan } = pieced ?? (await fetchClipAligned(entry, meta, render, dirs.local, opts)); + const clipE = pieced ? pieced.entry : entry; + const toReal = pieced ? pieced.clock.toReal : (t) => t; // Every file this writes in segments/ is written through a rename (the // segment by encodeSegmentCached, the records and texts by replaceFile), so // a link to another take's file -- `umtool take --from` links them in -- is @@ -1264,22 +1462,22 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // starting exactly on the quote's first syllable sounds like a dropped // frame. const hasCut = Number.isFinite(entry.cutStart) && Number.isFinite(entry.cutEnd); - const { from: playFrom, to: playTo } = playWindow(entry, render); + const { from: playFrom, to: playTo } = playWindow(clipE, render); if (hasCut) { EMIT("cut", { id: entry.id, extent: [entry.start, entry.end], - cut: [playFrom, playTo], + cut: pieced ? [toReal(playFrom), toReal(playTo)] : [playFrom, playTo], seconds: Number((playTo - playFrom).toFixed(2)), }); // The header prints a second, and it has to be a second you can hear in // the clip that plays. Kept rather than moved: a cite is a citation, and // silently re-pointing one is worse than saying it is off. - const at = entry.cite ?? entry.start; + const at = clipE.cite ?? clipE.start; if (at < playFrom - 0.05 || at > playTo + 0.05) { EMIT("note", { message: - `${entry.id}: cite ${at} is outside the cut ${playFrom.toFixed(2)}–${playTo.toFixed(2)} ` + + `${entry.id}: cite ${entry.cite ?? entry.start} is outside the cut ${toReal(playFrom).toFixed(2)}–${toReal(playTo).toFixed(2)} ` + `— kept as written; move it or widen the cut`, }); } @@ -1305,7 +1503,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, } // GAPS (gaps.mjs): seconds taken out of the clip's middle, so it plays as one // segment of jump cuts. A montage cuts to its phrase: none there. - const clipGaps = mont ? [] : renderGaps(entry, render); + const clipGaps = mont ? [] : renderGaps(clipE, render); if (mont && Array.isArray(entry.gaps) && entry.gaps.length) { EMIT("note", { message: `${entry.id}: a montage cuts to its phrase — its gaps are not applied` }); } @@ -1313,7 +1511,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // A locked edge snaps only outward, inside the silence it sits in (mute.mjs lockedEdges); // and no edge snaps across a gap (a gap's edges are exact). const snapped = mont ? null : snapCut({ - sil, wantA, wantB, render, locked: lockedEdges(entry, render), + sil, wantA, wantB, render, locked: lockedEdges(clipE, render), ...(clipGaps.length ? { gaps: clipGaps.map((g) => ({ from: g.from - fetchStart, to: g.to - fetchStart })) } : {}), }); const a = mont ? mont.win.start : snapped.a; @@ -1324,7 +1522,8 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // Room at the edges (render.room, room.mjs): the picture widened past the // snapped cut -- to the first silence and a join's length beyond, muted -- // the sound heard over [cutA, soundB] only. Null when off: the cut as ever. - const room = dirs.room && !mont && !dirs.short + // Not for a clip cut from its pieces: room's record is in the source's seconds of one file. + const room = dirs.room && !mont && !dirs.short && !pieced ? await segmentRoom({ entry, raw, render, provenance, look: dirs.look, D: dirs.room.D, first: dirs.room.first === entry.id, fetchStart, cutA, cutB }) : null; const segA = room ? room.plan.picA : cutA; @@ -1341,9 +1540,13 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, id: entry.id, gaps: segGaps.length, cut: Number(gapTotal.toFixed(3)), seconds: Number(segSeconds.toFixed(3)), ...(segGaps.length < clipGaps.length ? { dropped: clipGaps.length - segGaps.length } : {}), }); - const at = entry.cite ?? entry.start; + const at = clipE.cite ?? clipE.start; const g = inGap(at, clipGaps); - if (g) EMIT("note", { message: `${entry.id}: cite ${at} is inside the gap ${g.from}–${g.to}, which never plays — kept as written; move it` }); + if (g) { + EMIT("note", { + message: `${entry.id}: cite ${entry.cite ?? entry.start} is inside the gap ${toReal(g.from)}–${toReal(g.to)}, which never plays — kept as written; move it`, + }); + } } // Where in the SOURCE this segment really starts and ends, snapped: what a // `muteFrom` (source seconds) is measured from at the join, long after this @@ -1351,13 +1554,20 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // picture's span; `room.sound` is the part that is heard. const cutRecord = { version: 1, id: entry.id, video: entry.video, - start: Number((fetchStart + segA).toFixed(3)), end: Number((fetchStart + segB).toFixed(3)), + start: Number(toReal(fetchStart + segA).toFixed(3)), end: Number(toReal(fetchStart + segB).toFixed(3)), snapped: { start: a.snapped, end: b.snapped }, ...(room ? { room: room.record } : {}), // Only with gaps, so a clip without them records what it always did. - ...(segGaps.length - ? { gaps: segGaps.map((g) => ({ from: Number((fetchStart + segA + g.from).toFixed(3)), to: Number((fetchStart + segA + g.to).toFixed(3)) })) } - : {}), + // Cut from its pieces: every source second left out, the seconds between pieces too. + ...(pieced + ? { + gaps: pieced.clock + .realGaps(fetchStart + segA, fetchStart + segB, segGaps.map((g) => ({ from: fetchStart + segA + g.from, to: fetchStart + segA + g.to }))) + .map((g) => ({ from: Number(g.from.toFixed(3)), to: Number(g.to.toFixed(3)) })), + } + : segGaps.length + ? { gaps: segGaps.map((g) => ({ from: Number((fetchStart + segA + g.from).toFixed(3)), to: Number((fetchStart + segA + g.to).toFixed(3)) })) } + : {}), }; // Even loudness for a cut that is not a montage (render.loudness, release // 36): the cut as it will play, measured, one gain toward the target @@ -1453,7 +1663,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // render.blur "off"): every chain below is the one it always was. const blur = clipBlurOf(entry, render); if (blur && !media.hasVideo) EMIT("note", { message: `${entry.id}: no picture to blur in ${path.basename(raw)} — the poster plays as it is` }); - const span = media.hasVideo ? blurSpan(blur, fetchStart + segA, segSeconds, cutRecord.gaps) : null; + const span = media.hasVideo ? blurSpan(blur, toReal(fetchStart + segA), segSeconds, cutRecord.gaps) : null; if (blur) cutRecord.blur = blurRecordOf(blur); /** The blur's filters for a picture fitted into `bw` × `bh` (empty: none). */ const blurPicture = async (bw, bh) => { diff --git a/umtool/report-to-video/gaps-render.test.mjs b/umtool/report-to-video/gaps-render.test.mjs @@ -20,7 +20,7 @@ import test from "node:test"; const CORPUS = mkdtempSync(path.join(os.tmpdir(), "rtv-gaps-corpus-")); process.env.CHANNELS_DIR = CORPUS; -const { buildVideo, probeDuration, setProgressMode } = await import("./build-video.mjs"); +const { buildVideo, fetchSpans, piecesClock, probeDuration, setProgressMode, virtualEntry } = await import("./build-video.mjs"); const { deckSchedule, estimatedDuration, muteSegmentSeconds, segmentSoundEdits } = await import("./deck.mjs"); const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs"); const { renderCut, snapCut } = await import("./snap.mjs"); @@ -149,6 +149,103 @@ test("render: a gap is taken out of ONE segment -- the kept seconds long, no bla } }); +// ---- a gap-joined clip cut from its pieces ----------------------------------------- +// Two moments of one recording joined by a gap: 1–5 s and 190–200 s. Only the +// two pieces are on disk (two windows, the second WHITE with a higher tone), +// never the 185 s between: --no-network builds it from them, one segment, the +// kept 14 s, the record in the recording's own seconds. + +{ + const dir = path.join(CORPUS, CHANNEL, "data", "vid2"); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, "transcript.cues.json"), JSON.stringify({ id: "vid2", title: "Long", duration: 300, uploadDate: "20240102", cues: [{ start: 0.2, end: 299, text: "words" }] })); + writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "vid2", title: "Long", duration: 300 })); +} + +test("render: a gap-joined clip whose pieces are minutes apart is cut from its two pieces -- never the seconds between", { skip: !have && "needs ffmpeg" }, async () => { + const root = mkdtempSync(path.join(os.tmpdir(), "rtv-pieces-")); + const raw = path.join(root, "out", "clips-raw"); + mkdirSync(raw, { recursive: true }); + const window = (name, colour, hz, d) => { + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=${colour}:s=320x180:r=${FPS}:d=${d}`, + "-f", "lavfi", "-i", `sine=frequency=${hz}:sample_rate=48000:duration=${d}`, + "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", path.join(raw, name), + ]); + assert.equal(r.status, 0, String(r.stderr)); + }; + window("vid2_0.00-12.00.mp4", "gray", 440, 12); + window("vid2_185.00-205.00.mp4", "white", 880, 20); + const manifestPath = path.join(root, "video.manifest.json"); + await writeFile(manifestPath, JSON.stringify({ + slug: "pieces", title: "Pieces", + provenance: { channelSlug: CHANNEL, channelsDir: CORPUS }, + render: RENDER, + timeline: [{ type: "clip", id: "j1", channel: CHANNEL, video: "vid2", start: 1, end: 200, cite: 1, quote: "q", gaps: [{ from: 5, to: 190 }] }], + })); + const events = []; + setProgressMode((e) => events.push(e)); + try { + await buildVideo({ manifestPath, opts: { noNetwork: true } }); + const pieces = events.find((e) => e.ev === "pieces"); + assert.ok(pieces, "the clip was cut from its pieces"); + assert.deepEqual(pieces.pieces, [[1, 5], [190, 200]]); + assert.deepEqual(events.filter((e) => e.ev === "fetch").map((e) => [e.from, e.to, e.reuse]), [[1, 5, "vid2_0.00-12.00.mp4"], [190, 200, "vid2_185.00-205.00.mp4"]]); + const seg = path.join(root, "out", "sourced", "segments", "j1.mp4"); + near(await probeDuration(seg, FPS), 14, 1 / FPS + 1e-6, "the kept seconds: 4 + 10"); + const rec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")); + assert.deepEqual([rec.start, rec.end], [1, 200], "the record in the recording's seconds"); + assert.deepEqual(rec.gaps, [{ from: 5, to: 190 }]); + const y = lumas(seg); + const at = (t) => y[Math.floor(t * FPS)]; + assert.ok(at(2) > 60 && at(2) < 200, `the first piece is the grey window (YAVG ${at(2)})`); + assert.ok(at(9) > 200, `the second piece is the white window (YAVG ${at(9)})`); + assert.ok(rms(seg, 0.2, 3.8) > 800 && rms(seg, 4.2, 13.8) > 800, "heard through both pieces"); + // Built again with nothing changed: the joined file and the segment are reused. + events.length = 0; + const before = md5(seg); + await buildVideo({ manifestPath, opts: { noNetwork: true } }); + assert.equal(md5(seg), before); + assert.ok(events.some((e) => e.ev === "note" && / segment unchanged /.test(e.message) && e.message.split(":")[0] === "j1"), "the segment is reused"); + // Padded pieces (fetchPad 3): the pad between them is a gap on the joined clock; the same cut. + const m = JSON.parse(await readFile(manifestPath, "utf8")); + m.render = { ...m.render, fetchPad: 3 }; + await writeFile(manifestPath, JSON.stringify(m)); + events.length = 0; + await buildVideo({ manifestPath, opts: { noNetwork: true } }); + assert.deepEqual(events.find((e) => e.ev === "pieces")?.pieces, [[0, 8], [187, 203]]); + near(await probeDuration(seg, FPS), 14, 1 / FPS + 1e-6, "padded: the kept seconds still"); + const padded = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")); + assert.deepEqual([padded.start, padded.end, padded.gaps], [1, 200, [{ from: 5, to: 190 }]]); + } finally { + quiet(); + await rm(root, { recursive: true, force: true }); + } +}); + +test("piecesClock / virtualEntry / fetchSpans: the pieces laid end to end, and back", () => { + const clip = { type: "clip", id: "j", video: "v", start: 5385, end: 21812, cite: 5390, gaps: [{ from: 5400, to: 21800 }] }; + const spans = fetchSpans(clip, { fetchPad: 3 }); + assert.deepEqual(spans, [{ from: 5382, to: 5403 }, { from: 21797, to: 21815 }]); + assert.deepEqual(fetchSpans({ ...clip, gaps: [] }, { fetchPad: 3 }), [{ from: 5382, to: 21815 }]); + assert.deepEqual(fetchSpans(clip, { fetchPad: 3, montage: { style: "wall" } }), [{ from: 5382, to: 21815 }], "a montage applies no gaps"); + const c = piecesClock(spans); + assert.equal(c.total, 39); + assert.equal(c.toVirtual(5385), 3); + assert.equal(c.toVirtual(21800), 24); + assert.equal(c.toVirtual(10000), 21, "between the pieces: the nearer edge"); + assert.equal(c.toReal(3), 5385); + assert.equal(c.toReal(24), 21800); + assert.equal(c.toReal(-1), 5381); + const v = virtualEntry(clip, c); + assert.deepEqual([v.start, v.end, v.cite, v.gaps], [3, 36, 8, [{ from: 18, to: 24 }]]); + assert.equal(clip.start, 5385, "the entry itself is untouched"); + assert.deepEqual(c.realGaps(3, 36, [{ from: 18, to: 24 }]), [{ from: 5400, to: 21800 }]); + // No pad: the pieces touch on the joined clock, the seconds between are still a gap. + const bare = piecesClock([{ from: 1, to: 5 }, { from: 190, to: 200 }]); + assert.deepEqual(bare.realGaps(0, 14, []), [{ from: 5, to: 190 }]); +}); + // ---- the schedule's mappings, no ffmpeg ------------------------------------------ const CLIP = { type: "clip", id: "c1", video: "v", start: 100, end: 120, cutStart: 102, cutEnd: 118 };