// WHERE THE RENDER WILL CUT EACH CLIP, before it renders (umtool/docs/knobs.md, // "Play the cut"): the edges the Play view plays and the clip bench draws as // ghost markers. The build snaps every clip edge to the nearest silence // within `render.snapWindow` (measured on the Huck cut: starts up to 1.0 s // earlier, ends up to 1.0 s later than the manifest's), and a preview that // plays the manifest's edges plays a different cut -- the join is where it // differs most, and the join is what a preview is for. // // ONE IMPLEMENTATION. Everything that decides an edge is the build's own code: // the same file over the same span (build-video.mjs onDiskClipSource and // alignedClipSource -- the build's resolution, never the bench's widest // window: the silence threshold is relative to what is measured), the same // silencedetect (cut-points.mjs detectSilence), the same snap (snap.mjs // renderCut), room at the edges (cut-points.mjs roomOfCut) and the loudness // gain (render.loudness). cutPoints.test.mjs renders a fixture and checks the // cut records against this, edge for edge. // // CACHED ON DISK, per measurement, under UMTOOL_CACHE_DIR/cut-points/: the // silences by (file, its mtime and size, the span measured, silenceMinDur, // silenceRelDb); a file's clock offset by (file, mtime, size); a loudness by // (file, mtime, size, span). The snap itself is arithmetic on the cached // silences, so moving a clip's cut (the bench's edge drag) costs nothing, and // only a change of its extent -- a different span to measure -- runs ffmpeg // again. Nothing here fetches: a clip with no source on disk is `missing`. 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, 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"; import { clipAudioOf } from "umtool-report-to-video/clip-audio"; import { createLocalMedia, hasLocalMedia } from "umtool-report-to-video/local-media"; import { loudnessGain, montageOn, parseIntegratedLoudness } from "umtool-report-to-video/montage"; import { loudnessTargetOf } from "umtool-report-to-video/look"; import { ROOM, clipRoom } from "umtool-report-to-video/room"; import { lockedEdges, soundOnSegment } from "umtool-report-to-video/mute"; import { gapSeconds, gapsOnSegment, renderGaps } from "umtool-report-to-video/gaps"; import { renderCut, snapKnobs } from "umtool-report-to-video/snap"; import { transitionStyleOf } from "umtool-report-to-video/transition"; import { CACHE_DIR } from "../paths.mjs"; import { channelsDirFor, cuesForSource, hasShadowChannels, readManifest } from "../projects/report.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Bump when what is cached changes shape. */ const CACHE_VERSION = 1; const fin = (v) => typeof v === "number" && Number.isFinite(v); const r3 = (v) => Number(v.toFixed(3)); /** The cache directory (a function: the env is read when the route runs, as the e2e fixture sets it). */ const cacheDir = () => path.join(/* turbopackIgnore: true */ CACHE_DIR, "cut-points"); /** A file's identity for a cache key: the path, its mtime and size. null when it is gone. */ async function fileKey(file) { const st = await stat(/* turbopackIgnore: true */ file).catch(() => null); return st ? `${file}|${Math.round(st.mtimeMs)}|${st.size}` : null; } /** * A value computed once per key and kept on disk (tmp + rename), and in this * process while it lives. A failed computation is not cached. * * @template T * @param {string} kind * @param {string} key * @param {() => Promise} make * @returns {Promise} */ const memo = new Map(); async function cached(kind, key, make) { const h = createHash("sha1").update(`${CACHE_VERSION}|${kind}|${key}`).digest("hex"); if (memo.has(h)) return memo.get(h); const file = path.join(/* turbopackIgnore: true */ cacheDir(), `${kind}-${h}.json`); const p = (async () => { const have = await readFile(/* turbopackIgnore: true */ file, "utf8").then((t) => JSON.parse(t), () => null); if (have && have.key === key) return have.value; const value = await make(); try { await mkdir(/* turbopackIgnore: true */ cacheDir(), { recursive: true }); const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify({ key, value })); await rename(/* turbopackIgnore: true */ tmp, file); } catch { // A cache that cannot be written is a slower route, not a broken one. } return value; })(); memo.set(h, p); p.catch(() => memo.delete(h)); if (memo.size > 2000) memo.delete(memo.keys().next().value); return p; } /** * The manifest Play plays (the project's, or a take's, the default cut) and * where the build would look for each clip's source. * * @param {{ id: string, dir: string }} project * @param {string | null} take */ async function cutContext(project, take) { let manifest = await readManifest(project.dir); if (!manifest) throw new Error("this project has no video.manifest.json"); let outRoot = path.join(/* turbopackIgnore: true */ project.dir, "out"); if (take) { const { resolveTakeManifest, takePlayDir } = await import("./takeManifest.mjs"); manifest = (await resolveTakeManifest(project.dir, take)).manifest; outRoot = path.join(/* turbopackIgnore: true */ takePlayDir(project.dir, take), "out"); } const selected = selectVariant(manifest, DEFAULT_VARIANT); const render = selected.render ?? {}; const provenance = selected.provenance ?? {}; const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); // A take renders into its own out/ (its clips-raw empty, as a rule: its // sources are the corpus's windows or the project's cache); the project's // raw cache is looked in after it, as the bench does. const locals = [...new Set([outRoot, path.join(/* turbopackIgnore: true */ project.dir, "out")])].map((root) => localSources({ rawDir: path.join(/* turbopackIgnore: true */ root, "clips-raw"), channelsDir, channelSlug: provenance.channelSlug ?? null, render }), ); const localMedia = createLocalMedia({ baseDir: project.dir, allowAbsolute: render.allowAbsoluteSrc === true }); // 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 }; } /** * Each clip's render cut, in SOURCE seconds: * * cutStart / cutEnd where its segment starts and ends (`.cut.json`'s * `start`/`end`): the picture's span, room included * footage the segment's length in the cut: that span in whole * frames, as the encode makes it * snapped { start, end }: which edge moved to a silence * sound [from, to] the sound is heard over, when room mutes * an edge (else the whole segment) * gaps [{from, to}] the seconds its segment leaves out * (gaps.mjs; the build's frame-grid edges), absent * without any -- `footage` is already less them * gainDb render.loudness's gain for the cut (none: absent) * audio the clip's own audio knobs (clip-audio.mjs), absent when none * playFrom / playTo the play window it was snapped from (deck.mjs playWindow) * silences, fetchStart, window what was measured, so a client (the * bench, dragging an edge) can snap a new cut itself * with snap.mjs, on the same numbers * montage true when render.montage cuts it (a phrase cut this * does not model: its edges are snapped as a plain cut) * missing no source on disk (nothing else is said) * * @param {{ id: string, dir: string }} project * @param {{ take?: string | null, clips?: string[] | null, concurrency?: number }} [opts] */ export async function cutPointsFor(project, { take = null, clips = null, concurrency = 2 } = {}) { const ctx = await cutContext(project, take); const { selected, render } = ctx; const timeline = (selected.timeline ?? []).filter((e) => e && typeof e.id === "string"); const want = clips ? new Set(clips) : null; const montage = montageOn(render); const D = transitionOf(render); const first = timeline[0]?.id ?? null; const targets = timeline.filter((e) => e.type === "clip" && (hasLocalMedia(e) || (fin(e.start) && fin(e.end))) && (!want || want.has(e.id))); const look = { promise: null }; const out = new Array(targets.length); let next = 0; const work = async () => { for (;;) { const i = next++; if (i >= targets.length) return; const e = targets[i]; try { out[i] = await clipCutPoints(e, { ...ctx, montage, D, first: first === e.id, look, projectDir: project.dir }); } catch (err) { out[i] = { id: e.id, error: err instanceof Error ? err.message : String(err) }; } } }; await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, targets.length)) }, work)); return { knobs: snapKnobs(render), leadIn: fin(render.leadIn) ? render.leadIn : 0.4, transition: D, transitionStyle: transitionStyleOf(render), montage, clips: out, }; } /** * A clip's source on disk as the build would cut it: the file, its key, the * source second its first frame plays (`fetchStart`, the file's clock * aligned) and the span silence detection measures. null: nothing on disk. */ async function diskSourceOf(entry, ctx) { const { render, locals, localMedia } = ctx; let src = null; for (const local of locals) { src = await onDiskClipSource(entry, null, render, local, { localMedia }); if (src) break; } if (!src) return piecedDiskSourceOf(entry, ctx); const fk = await fileKey(src.path); if (!fk) return null; const { log: _log, ...disk } = src; // The file's clock (a late-starting picture moves fetchStart), once per file. const offset = await cached("offset", fk, async () => (await alignedClipSource(disk)).startOffset ?? 0); const fetchStart = disk.fetchStart + offset; const scan = disk.scan ? { from: Math.max(0, disk.scan.from - offset), to: disk.scan.to - offset } : null; // A file ending the recording (the last clip's pad past it): where its footage stops, the build's own hold. return { path: src.path, fk, fetchStart, scan, ...(Number.isFinite(disk.sourceEnd) ? { sourceEnd: disk.sourceEnd } : {}) }; } /** * 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 * cut has no such clip. * * @param {{ id: string, dir: string }} project * @param {string} clipId * @param {{ take?: string | null }} [opts] */ export async function clipSourceOf(project, clipId, { take = null } = {}) { const ctx = await cutContext(project, take); const entry = (ctx.selected.timeline ?? []).find((e) => e && e.type === "clip" && e.id === clipId) ?? null; const disk = entry ? await diskSourceOf(entry, ctx) : null; return { entry, render: ctx.render, provenance: ctx.provenance, // `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(real, ctx) { const { render, montage, D } = ctx; 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, sourceEnd } = disk; const k = snapKnobs(render); const sil = await cached( "silences", `${fk}|${scan ? `${scan.from}-${scan.to}` : "whole"}|${k.silenceMinDur}|${k.silenceRelDb}`, () => detectSilence(src.path, render, scan, { ffmpeg: FFMPEG_BIN }), ); const pw = playWindow(entry, render); const locked = lockedEdges(entry, render); // A clip's gaps (gaps.mjs): no edge snaps across one, as in the build. None in a montage. const clipGaps = montage ? [] : renderGaps(entry, render); const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render, locked, ...(clipGaps.length ? { gaps: clipGaps } : {}), ...(Number.isFinite(sourceEnd) ? { sourceEnd } : {}) }); const { cutA, cutB } = cut.file; let segA = cutA; let segB = cutB; /** @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 && !pieced && clipRoom(entry, render)) { if (!ctx.look.promise) ctx.look.promise = readLookSources(ctx.projectDir); const lookSrc = await ctx.look.promise; const provenance = ctx.provenance; const room = await roomOfCut({ entry, render, D, first: ctx.first, fetchStart, cutA, cutB, file: src.path, duration: await cached("duration", fk, async () => (await probeMedia(src.path)).duration ?? null), words: (from, to) => lookWords(entry, provenance, lookSrc, from, to, { channelsDir: ctx.channelsDir, cues: async (e) => (await cuesForSource(ctx.projectDir, { video: e.video, channel: e.channel ?? provenance.channelSlug ?? null }, -Infinity, Infinity))?.cues ?? [], }), silences: (from, to) => detectRoomSilences(src.path, from, to, { ffmpeg: FFMPEG_BIN }), }); if (room) { segA = room.plan.picA; segB = room.plan.picB; sound = room.record.sound; } } // The segment's length as its encode makes it: whole frames, the last one // begun counted (the build's cutOffsets sums the probed frames; measured on // the Huck walk, 34 of 51 segments exactly this, the rest one frame more). const fps = fin(render.fps) && render.fps > 0 ? render.fps : 30; // 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: real.id, window: path.basename(src.path), footage: Number((Math.ceil((segB - segA - gapSeconds(segGaps)) * fps - 1e-6) / fps).toFixed(6)), 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 } : {}), ...(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); if (!montage && target != null) { const from = cutA; const to = sound ? sound[1] - fetchStart : cutB; const measured = await cached("loudness", `${fk}|${from.toFixed(3)}-${to.toFixed(3)}`, () => measureLoudnessWith(src.path, from, to, parseIntegratedLoudness, { ffmpeg: FFMPEG_BIN }), ); row.gainDb = loudnessGain(measured, target); } 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(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; } /** Room's fade (seconds) at a muted edge, for the player: the build's afade length. */ export const ROOM_FADE = ROOM.fade;