commit 552dc00028cf373a0e2015e675b90e80b48b1c36 parent c93bf3175c545178ba24d0962efacc602742e1fb Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Thu, 29 Oct 2026 16:07:27 -0400 Merge lane/locked-end-mute: locked clip edges are exact -- no snap across sound, silence past a locked end and before a locked start, in the build and in Play the cut Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
15 files changed, 471 insertions(+), 61 deletions(-)
diff --git a/umtool/components/projects/bench/RenderGhosts.tsx b/umtool/components/projects/bench/RenderGhosts.tsx @@ -20,6 +20,8 @@ type Row = { fetchStart?: number; sound?: [number, number]; montage?: boolean; + /** Which edges are the author's (mute.mjs lockedEdges): each snaps only outward, inside its own silence. */ + locked?: { start: boolean; end: boolean }; missing?: boolean; error?: string; }; @@ -79,7 +81,7 @@ export function useRenderEdges( snapLead: got.knobs.snapLead ?? undefined, snapTail: got.knobs.snapTail ?? undefined, }; - const cut = renderCut({ sil: row.silences, fetchStart: row.fetchStart, playFrom: pw.from, playTo: pw.to, render }); + const cut = renderCut({ sil: row.silences, fetchStart: row.fetchStart, playFrom: pw.from, playTo: pw.to, render, locked: row.locked ?? null }); return { start: { at: cut.start, offset: Number((cut.start - pw.from).toFixed(3)), snapped: cut.snapped.start }, end: { at: cut.end, offset: Number((cut.end - pw.to).toFixed(3)), snapped: cut.snapped.end }, diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -652,6 +652,16 @@ manifest locks 100%*. - **`lockStart` / `lockEnd`** — pin one edge exactly. Needed because sentence detection is only as good as the ASR's punctuation, and some uploads have none. +**A locked edge is exact when the cut is built and played, too.** The silence +snap moves it only outward inside the silence it already sits in -- never across +a sound, never into the window; +nothing past a locked end is heard (an implicit `muteFrom` at the end -- the +snapped tail and the outgoing half of the dissolve are silent) and nothing +before a locked start (a short fade rising from it). The picture is untouched. +An earlier `muteFrom` wins. `render.lockedEdges: false` opts a cut out. (Operator, +2026-10-29: a locked end was snapped 1.29 s later, across the next sentence's +"She", and Play the cut played it under the dissolve.) + `lockEnd` is also how the "ends mid-sentence" warning is *acknowledged*: setting it is the author saying "I meant to cut here", and it suppresses the warning. This matters — one 14-clip cut shipped with 8 clips ending mid-thought. diff --git a/umtool/e2e/fixtures/play-cut-fixture.mjs b/umtool/e2e/fixtures/play-cut-fixture.mjs @@ -43,7 +43,12 @@ export function makePlayCutFixture({ reports, deckManifest, cachedWindow, name = m.render.fetchPad = 0; // One counter, as the Huck cut has: the reel strip's staircase steps 1 at c02, 2 more at c04. m.render.chrome = { ...m.render.chrome, factcheck: { verdicts: { CORROBORATED: { label: "Seizures", color: "#6fa8dc" } }, stamp: { seconds: 1 } }, ...(chrome ?? {}) }; - writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + // Every clip is locked, and c02's and c04's locked edges sit in the tone: a + // locked edge never snaps across a sound (mute.mjs lockedEdges), which would + // move every number play-cut.spec.ts reads off this clock. Its cut keeps the + // plain snap (`render.lockedEdges: false`); play-engine-fixture below keeps + // the rule, and play-engine.spec.ts checks c02 stays at its locked edges. + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify({ ...m, render: { ...m.render, lockedEdges: false } }, null, 2) + "\n"); mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", `${video}_0.00-9.00.mp4`)); // A made take with its own timeline (a JSON merge patch replaces the list). diff --git a/umtool/e2e/play-engine.spec.ts b/umtool/e2e/play-engine.spec.ts @@ -20,8 +20,10 @@ import * as urls from "./urls"; // // Fixture: e2e/fixtures/play-cut-fixture.mjs's play-engine-fixture (the // play-cut cut, which this spec WRITES). On the fixture's window (playvid; silences -// 2.90-3.11, 5.92-6.11) the render cuts c01 at 1.000-3.082, c02 3.011-6.101, -// c04 6.007-8.000; in whole frames at 15 fps c01 lasts 2.133 s, so c02's +// 2.90-3.11, 5.92-6.11) the render cuts c01 at 1.000-3.082 (its locked end +// snapped outward, inside the silence it sits in), c02 3.5-5.5 (locked, both +// edges in the tone: never snapped across it), c04 6.000-8.000 (a locked start +// never snaps inward); in whole frames at 15 fps c01 lasts 2.133 s, so c02's // segment starts at 1.933 (the 0.2 s crossfade before c01's end). // --------------------------------------------------------------------------- @@ -54,12 +56,17 @@ test("the render's edges: Play schedules each clip as the build cuts it, and say // c01's end snapped into the pause after it; its start had none near. await expect(root(page)).toHaveAttribute("data-play-span", "1-3.082"); await page.locator('[data-play-row="c02"]').press("Enter"); - await expect(root(page)).toHaveAttribute("data-play-span", "3.011-6.101"); + // Locked: the snap would reach across the tone to 3.011 and 6.101 (as play-cut's + // unlocked-edges copy does); a locked edge stays where the author put it. + await expect(root(page)).toHaveAttribute("data-play-span", "3.5-5.5"); await expect(page.locator("[data-play-approximate]")).toContainText("edges are the render's, snapped to silence"); // The route itself: the silences it snapped on, and which edge moved. const got = await (await page.request.get(`/api/report/cut-points?project=${encodeURIComponent(PROJECT)}`)).json(); const c01 = got.clips.find((c: { id: string }) => c.id === "c01"); - expect(c01).toMatchObject({ cutStart: 1, cutEnd: 3.082, snapped: { start: false, end: true }, playFrom: 1, playTo: 3 }); + expect(c01).toMatchObject({ cutStart: 1, cutEnd: 3.082, snapped: { start: false, end: true }, playFrom: 1, playTo: 3, locked: { start: true, end: true } }); + // c01's locked end: silent from 3.0 (the snapped breath past it is not heard), as the build mutes it. + expect(c01.muteFrom).toBe(3); + expect(got.clips.find((c: { id: string }) => c.id === "c02")).toMatchObject({ cutStart: 3.5, cutEnd: 5.5, snapped: { start: false, end: false } }); expect(got.clips.find((c: { id: string }) => c.id === "c03")).toEqual({ id: "c03", missing: true }); }); diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs @@ -35,6 +35,7 @@ import { createLocalMedia, hasLocalMedia } from "umtool-report-to-video/local-me 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 { renderCut, snapKnobs } from "umtool-report-to-video/snap"; import { transitionStyleOf } from "umtool-report-to-video/transition"; import { CACHE_DIR } from "../paths.mjs"; @@ -196,7 +197,8 @@ async function clipCutPoints(entry, ctx) { () => detectSilence(src.path, render, scan, { ffmpeg: FFMPEG_BIN }), ); const pw = playWindow(entry, render); - const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render }); + const locked = lockedEdges(entry, render); + const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render, locked }); const { cutA, cutB } = cut.file; let segA = cutA; let segB = cutB; @@ -237,6 +239,8 @@ async function clipCutPoints(entry, ctx) { cutStart: r3(fetchStart + segA), cutEnd: r3(fetchStart + segB), 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 } : {}), ...(montage ? { montage: true } : {}), }; @@ -251,8 +255,12 @@ async function clipCutPoints(entry, ctx) { } const audio = clipAudioOf(entry); if (audio) row.audio = audio; - // The mute mark (a finale's ending sound): the build fades the sound out to it at the join. - if (fin(entry.muteFrom)) row.muteFrom = entry.muteFrom; + // 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); + 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/playCut.mjs b/umtool/lib/report/playCut.mjs @@ -45,7 +45,7 @@ const round = (v) => Math.round(v * 1000) / 1000; /** * @typedef {{ cutStart: number, cutEnd: number, footage?: number, snapped?: { start: boolean, end: boolean }, - * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number }} RenderCut + * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number, soundFrom?: number }} RenderCut */ /** @@ -96,6 +96,7 @@ export function playPlan(segments, entries, { leadIn = 0.4, cuts = null } = {}) ...(c.audio ? { audio: c.audio } : {}), ...(c.snapped ? { snapped: c.snapped } : {}), ...(fin(c.muteFrom) ? { muteFrom: c.muteFrom } : {}), + ...(fin(c.soundFrom) ? { soundFrom: c.soundFrom } : {}), }, est: estAt, }; diff --git a/umtool/lib/report/playSchedule.mjs b/umtool/lib/report/playSchedule.mjs @@ -8,7 +8,7 @@ // that context's time mapped through the plan. These are the numbers: where // each clip's sound sits on the cut's clock, what its level does over it (the // crossfade's ramps, room's muted edges, the loudness gain, the clip's own -// audio knobs, the mute mark), and, from a cut second and a speed, when each +// audio knobs, the mute mark, a locked edge's silence), and, from a cut second and a speed, when each // node starts, at what offset into its buffer, for how long, with which // gain breakpoints. Pure: no Web Audio, so it is unit-tested // (playSchedule.test.mjs) and the engine only applies it. @@ -75,7 +75,7 @@ const ramp = (a, b, down = false) => (b > a ? [[a, down ? 1 : 0], [b, down ? 0 : * * @param {{ items: Array<{ id: string, start: number, end: number, clip: null | { * sourceFrom: number, sourceTo: number, playEnd: number, hold: number, - * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number } }> }} plan + * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number, soundFrom?: number } }> }} plan * @returns {Array<{ id: string, index: number, from: number, to: number, src: number, srcTo: number, env: Envelope, gain: number }>} */ export function audioSpans(plan) { @@ -108,7 +108,10 @@ export function audioSpans(plan) { if (fin(a.fadeIn) && a.fadeIn > 0) envs.push(ramp(from, from + Math.min(a.fadeIn, to - from))); if (fin(a.fadeOut) && a.fadeOut > 0) envs.push(ramp(to - Math.min(a.fadeOut, to - from), to, true)); // The mute mark: silent from it on, the fade ending AT it. + // A locked end is one too (the route sends the build's rule, mute.mjs soundOnSegment). if (fin(c.muteFrom)) envs.push(ramp(at(/** @type {number} */ (c.muteFrom)) - MUTE_FADE, at(/** @type {number} */ (c.muteFrom)), true)); + // A locked start: silent before it, the fade rising FROM it (the build's soundFromAudioFilter). + if (fin(c.soundFrom)) envs.push(ramp(at(/** @type {number} */ (c.soundFrom)), at(/** @type {number} */ (c.soundFrom)) + MUTE_FADE)); const db = (fin(c.gainDb) ? /** @type {number} */ (c.gainDb) : 0) + (fin(a.gain) ? a.gain : 0); const shift = fin(a.offset) ? a.offset / 1000 : 0; out.push({ diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -89,6 +89,17 @@ Three stages, because a cue span is the wrong answer twice over. long lead lets the next clip fade in before its first word. Pair them with a `silenceMinDur` that finds real pauses (~0.3 s), not the gaps between words. + **A locked edge is exact** (`lock`, `lockStart` / `lockEnd`; a cut's + `lockCut` -- `mute.mjs` `lockedEdges`). It snaps only outward, inside the + silence it already sits in -- never across a sound, never into the window -- and nothing outside + it is heard: a locked end is an implicit `muteFrom` at the end (the 0.04 s + fade ending AT it, digital silence after, through the snapped tail and the + outgoing half of the crossfade), a locked start a fade rising FROM it with + silence before. An earlier `muteFrom` of the clip's own wins. The picture, + durations and dissolves are untouched. One rule (`soundEdges`), read by the + build's joins, the podcast and Play the cut's schedule. + `render.lockedEdges: false` turns it off: locked edges snap and sound as any. + **The silence threshold is relative, and it has to be.** These are game streams: the gaps between words are full of game audio and music — quiet, but nowhere near silent. A fixed absolute threshold sits below the noise floor and diff --git a/umtool/report-to-video/build-podcast.mjs b/umtool/report-to-video/build-podcast.mjs @@ -39,7 +39,7 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import { promisify } from "node:util"; -import { deckOn, deckQrUrl, muteSegmentSeconds, teaserTitle } from "./deck.mjs"; +import { deckOn, deckQrUrl, segmentSoundEdits, soundEdges, teaserTitle } from "./deck.mjs"; import { hasNarration, narrationsOf } from "./narration.mjs"; import { narrationDir, readCutDisclosure } from "./narration-store.mjs"; @@ -325,10 +325,12 @@ export async function buildPodcast({ manifestPath, variant = "sourced", out = nu const d = await probeSeconds(seg); durations.push(d); const e = entries[it.index]; - if (e.type === "clip" && e.muteFrom != null) { - const m = muteSegmentSeconds({ entry: e, record: await readCutRecord(seg), render, seconds: d }); - if (m.note) emit("note", { id: e.id, message: m.note }); - mutes.push(m.at < d ? m.at : null); + // The one rule (mute.mjs soundEdges): its own muteFrom, or its locked end. + const se = soundEdges(e, render); + if (e.type === "clip" && se.muteFrom != null) { + const ed = segmentSoundEdits({ entry: e, record: await readCutRecord(seg), render, seconds: d }); + for (const message of ed.notes) emit("note", { id: e.id, message }); + mutes.push(ed.mute != null && ed.mute < d ? ed.mute : null); } else { mutes.push(null); } diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -151,7 +151,7 @@ import { ensureWriteDir } from "../lib/report/storage.mjs"; // the schedule down -- it never has a copy of the arithmetic. import { assertChrome, deckGeometry, deckOn, deckSchedule, endFadeOf, feedGeometry, feedOn, frameCount, hidesDeck, MUTE_FADE, - dipOf, estimatedDuration, muteSegmentSeconds, playWindow, postsGeometry, postWindows, resolveDeck, scheduleFrom, snapWindow, stampGeometry, + dipOf, estimatedDuration, lockedEdges, playWindow, segmentSoundEdits, soundEdges, postsGeometry, postWindows, resolveDeck, scheduleFrom, snapWindow, stampGeometry, statsGeometry, teaserHits, teaserSeconds, teaserTitle, threadsGeometry, validateCutEdits, validateDeckMarkers, validatePosts, validateTeasers, fxGeometry, even as evenPx, claimRecordNotes, deckClaimClips, validateDeckClaims, @@ -1300,7 +1300,8 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, })); } // Snapped, and never inverted or collapsed (snap.mjs snapCut: the cut-points route's own). - const snapped = mont ? null : snapCut({ sil, wantA, wantB, render }); + // A locked edge snaps only outward, inside the silence it sits in (mute.mjs lockedEdges). + const snapped = mont ? null : snapCut({ sil, wantA, wantB, render, locked: lockedEdges(entry, render) }); const a = mont ? mont.win.start : snapped.a; const b = mont ? mont.win.end : snapped.b; const cutA = mont ? mont.win.cutA : snapped.cutA; @@ -3803,6 +3804,14 @@ export const muteAudioFilter = (at) => { }; /** + * A locked start on a segment's sound (mute.mjs `soundEdges`' `soundFrom`): + * silent before `at` (segment seconds), then a MUTE_FADE rising FROM `at`. + * `afade` in writes digital silence before its start and copies every sample + * after its fade. + */ +export const soundFromAudioFilter = (at) => `afade=t=in:st=${exprNum(Math.max(0, at))}:d=${exprNum(MUTE_FADE)}`; + +/** * A `#rrggbb` colour as 8-bit limited-range BT.601 Y′CbCr -- what `pad` and a * `color` source write for it into the segments' yuv420p (`#12101a` is * 31/132/128 in both, measured). @@ -3896,6 +3905,7 @@ export function joinInputChain(i, join, render, { only = null } = {}) { const v = vf.length ? `[j${i}v]` : vin; if (vf.length) parts.push(`${vin}${vf.join(",")}${v}`); const af = [ + join.soundFrom != null ? soundFromAudioFilter(join.soundFrom) : null, join.mute != null ? muteAudioFilter(join.mute) : null, join.hold > 0 ? holdAudioFilter(join.hold) : null, join.fade ? endFadeAudioFilter(join.fade, render) : null, @@ -3946,10 +3956,11 @@ export function punchInParts(i, zooms, render, vin) { * keeps exactly the joins (and the graph, and the hard-cut record) it had; * null when nothing is joined at all. */ -export function withCutEdits(joins, n, { mutes = new Map(), fade = null, dips = new Map() } = {}) { - if (!mutes.size && !fade && !dips.size) return joins; +export function withCutEdits(joins, n, { mutes = new Map(), sounds = new Map(), fade = null, dips = new Map() } = {}) { + if (!mutes.size && !sounds.size && !fade && !dips.size) return joins; const out = Array.from({ length: n }, (_, i) => joins?.[i] ?? null); for (const [i, at] of mutes) out[i] = { hold: 0, move: null, ...(out[i] ?? {}), mute: at }; + for (const [i, at] of sounds) out[i] = { hold: 0, move: null, ...(out[i] ?? {}), soundFrom: at }; if (fade) out[n - 1] = { hold: 0, move: null, ...(out[n - 1] ?? {}), fade }; for (const [i, dip] of dips) out[i] = { hold: 0, move: null, ...(out[i] ?? {}), dip }; return out.some(Boolean) ? out : null; @@ -3966,23 +3977,18 @@ export function withCutEdits(joins, n, { mutes = new Map(), fade = null, dips = export async function cutJoins({ schedule = null, entries, segments, render }) { const base = schedule ? segmentJoins(schedule) : null; const mutes = new Map(); - for (let i = 0; i < entries.length; i += 1) { + const sounds = new Map(); + for (let i = 0; i < entries.length && i < segments.length; i += 1) { const e = entries[i]; - if (e.type !== "clip" || e.muteFrom == null) continue; + // The one rule (mute.mjs soundEdges): the clip's own muteFrom, and its + // locked edges -- nothing past a locked end, nothing before a locked start. + const se = soundEdges(e, render); + if (e.type !== "clip" || (se.muteFrom == null && se.soundFrom == null)) continue; const seconds = await probeDuration(segments[i], render.fps); - const m = muteSegmentSeconds({ entry: e, record: await readCutRecord(segments[i]), render, seconds }); - if (m.note) EMIT("note", { id: e.id, message: m.note }); - const from = m.source === "record" ? "from its cut record" : "from the unsnapped start"; - // Validation allows the clip's whole extent, but only the played window is - // in the segment: a mark past the cut's end mutes nothing, and saying - // "muted from" would claim otherwise. - EMIT("note", { - id: e.id, - message: m.at >= seconds - ? `${e.id}: muteFrom ${e.muteFrom} will not be heard -- it lies ${m.at}s into a segment ${seconds}s long, past the cut's end (${from})` - : `${e.id}: muted from ${m.at}s into its segment (muteFrom ${e.muteFrom}, ${from})`, - }); - mutes.set(i, m.at); + const ed = segmentSoundEdits({ entry: e, record: await readCutRecord(segments[i]), render, seconds }); + for (const message of ed.notes) EMIT("note", { id: e.id, message }); + if (ed.mute != null) mutes.set(i, ed.mute); + if (ed.soundFrom != null) sounds.set(i, ed.soundFrom); } // A segment's frames in the cut, its hold's clones included. const cutFrames = async (i) => Math.round((await probeDuration(segments[i], render.fps)) * render.fps) + @@ -4000,7 +4006,7 @@ export async function cutJoins({ schedule = null, entries, segments, render }) { if (!dip) continue; dips.set(i - 1, { seconds: dip.fade, lastFrame: (await cutFrames(i - 1)) - 1, black: dip.black }); } - return withCutEdits(base, segments.length, { mutes, fade, dips }); + return withCutEdits(base, segments.length, { mutes, sounds, fade, dips }); } /** `--clip-preview`'s own directory under a variant's out dir: its schedule, chrome and `<id>.mp4`s. */ @@ -5438,6 +5444,7 @@ export function concatRecordText(segments, joins = null) { ? [`# join ${i} ${JSON.stringify({ hold: joins[i].hold, move: joins[i].move, ...(joins[i].mute != null ? { mute: joins[i].mute } : {}), + ...(joins[i].soundFrom != null ? { soundFrom: joins[i].soundFrom } : {}), ...(joins[i].fade ? { fade: joins[i].fade } : {}), ...(joins[i].dip ? { dip: joins[i].dip } : {}), ...(joins[i].zoom ? { zoom: joins[i].zoom } : {}), diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -15,6 +15,7 @@ // No ffmpeg, no fs, no network. If a function here needs one, it belongs in // build-video.mjs or compose-chrome.mjs instead. import { createHash } from "node:crypto"; +import { playEdges, soundEdges as soundEdgesOf, soundOnSegment } from "./mute.mjs"; import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs"; @@ -803,12 +804,8 @@ export function estimatedDuration(entry, render = {}, D = transitionOf(render)) * one beside the segment (`<id>.cut.json`). */ export function playWindow(entry, render = {}) { - const hasCut = Number.isFinite(entry.cutStart) && Number.isFinite(entry.cutEnd); - const lead = render.leadIn ?? 0.4; - return { - from: hasCut ? Math.max(entry.start, entry.cutStart - lead) : entry.start, - to: hasCut ? Math.min(entry.end, entry.cutEnd) : entry.end, - }; + // mute.mjs's, dependency-free: the locked edges' sound rule reads the same window. + return playEdges(entry, render); } /** The crossfade a build of this render block will use. */ @@ -2252,7 +2249,7 @@ export function footageMoves({ posts, segments, render }) { // --------------------------------------------------------------------------- /** The fade into a `muteFrom`'s silence (`mute.mjs`, dependency-free so a client bundle can take it alone). */ -export { MUTE_FADE } from "./mute.mjs"; +export { MUTE_FADE, lockedEdges, soundEdges, soundOnSegment } from "./mute.mjs"; /** `render.endFade`'s upper bound, in seconds. */ export const END_FADE_MAX = 10; @@ -2293,6 +2290,10 @@ export function validateCutEdits(manifest) { if (e?.type !== "teaser") errors.push(...validateDip(e, `timeline[${i}] (${e?.id ?? "?"})`)); }); errors.push(...validateEndFade(manifest?.render)); + const le = manifest?.render?.lockedEdges; + if (le !== undefined && le !== null && typeof le !== "boolean") { + errors.push("render.lockedEdges must be true (the default: a locked edge is exact, nothing past it heard) or false"); + } return errors; } @@ -2315,12 +2316,12 @@ export const endFadeOf = (render) => (numIn(render?.endFade, 0, END_FADE_MAX) ? * `at` in segment seconds, never below 0 (a muteFrom before the segment's * start mutes it from its first sample). */ -export function muteSegmentSeconds({ entry, record = null, render = {}, seconds = null }) { +export function muteSegmentSeconds({ entry, record = null, render = {}, seconds = null, source = entry.muteFrom }) { const fps = render.fps ?? 30; const ok = record && record.video === entry.video && Number.isFinite(record.start) && Number.isFinite(record.end) && (seconds == null || Math.abs(record.end - record.start - seconds) <= 2 / fps); - const at = (from) => Math.max(0, Math.round((entry.muteFrom - from) * 1000) / 1000); + const at = (from) => Math.max(0, Math.round((source - from) * 1000) / 1000); if (ok) return { at: at(record.start), source: "record" }; const { from } = playWindow(entry, render); return { @@ -2333,6 +2334,55 @@ export function muteSegmentSeconds({ entry, record = null, render = {}, seconds }; } +/** + * A clip's sound edits on its SEGMENT's clock (mute.mjs `soundEdges`, the one + * rule): `mute` (segment seconds; silent from there, the fade ending at it) + * and `soundFrom` (silent before it, the fade rising from it), each null when + * it changes nothing in this segment. The clip's own `muteFrom` is placed as + * ever (`muteSegmentSeconds`, a note when it lies past the cut); a LOCKED + * edge's is placed only from a cut record that matches -- measured from the + * unsnapped start it could land up to snapWindow inside the speech the author + * kept -- and only where the segment reaches past the edge. + * + * @returns {{ mute: number | null, soundFrom: number | null, notes: string[] }} + */ +export function segmentSoundEdits({ entry, record = null, render = {}, seconds }) { + const out = { mute: null, soundFrom: null, notes: [] }; + if (entry?.type !== "clip") return out; + const se = soundEdgesOf(entry, render); + if (se.muteFrom == null && se.soundFrom == null) return out; + // Where the segment starts: its record's (snapped) start, else the unsnapped window's. + const probe = muteSegmentSeconds({ entry, record, render, seconds, source: se.muteFrom ?? se.soundFrom }); + const fromRecord = probe.source === "record"; + if (probe.note && entry.muteFrom != null) out.notes.push(probe.note); + const on = soundOnSegment(entry, render, fromRecord ? record.start : playEdges(entry, render).from, seconds); + if (se.muteFrom != null && !se.implicit) { + const from = fromRecord ? "from its cut record" : "from the unsnapped start"; + // Validation allows the clip's whole extent, but only the played window is + // in the segment: a mark past the cut's end mutes nothing, and saying + // "muted from" would claim otherwise. + out.notes.push(on.mute >= seconds + ? `${entry.id}: muteFrom ${entry.muteFrom} will not be heard -- it lies ${on.mute}s into a segment ${seconds}s long, past the cut's end (${from})` + : `${entry.id}: muted from ${on.mute}s into its segment (muteFrom ${entry.muteFrom}, ${from})`); + out.mute = on.mute; + } + if (!fromRecord) { + if (se.implicit || se.soundFrom != null) { + out.notes.push(`${entry.id}: its locked edges are not muted -- no cut record matches its segment; rebuild the clip`); + } + return out; + } + if (se.implicit && on.mute != null) { + out.mute = on.mute; + out.notes.push(`${entry.id}: locked end ${se.muteFrom} -- silent from ${on.mute}s into its ${seconds}s segment (the tail past it is not heard)`); + } + if (on.soundFrom != null) { + out.soundFrom = on.soundFrom; + out.notes.push(`${entry.id}: locked start ${se.soundFrom} -- heard from ${on.soundFrom}s into its segment (the head before it is not)`); + } + return out; +} + // --------------------------------------------------------------------------- // The teaser: a full-frame graphic card -- a season teaser's "coming soon" // screen -- whose words are the manifest's. Its segment is a HyperFrames diff --git a/umtool/report-to-video/locked-edges.test.mjs b/umtool/report-to-video/locked-edges.test.mjs @@ -0,0 +1,178 @@ +// A LOCKED edge is the author's, exact (mute.mjs lockedEdges / soundEdges): +// nothing past a locked end is heard -- not the snapped tail, not the outgoing +// half of a crossfade -- nothing before a locked start, and the snap moves a +// locked edge only inside the silence it already sits in. One rule, read by +// the build's joins (cutJoins → segmentSoundEdits → joinInputChain), the +// podcast, and Play the cut (cut-points route → playPlan → audioSpans); the +// last test checks the build and Play mute at the same cut second. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { cutJoins, cutRecordPath, joinInputChain, muteAudioFilter, soundFromAudioFilter, xfadeGraph } from "./build-video.mjs"; +import { MUTE_FADE, segmentSoundEdits } from "./deck.mjs"; +import { lockedEdges, soundEdges, soundOnSegment } from "./mute.mjs"; +import { renderCut, snap, snapCut } from "./snap.mjs"; +import { playPlan } from "../lib/report/playCut.mjs"; +import { audioSpans, levelAt } from "../lib/report/playSchedule.mjs"; + +// ag1 of emberparadox/in-her-words: locked 579.68–589.21; the next sentence +// ("She is …") starts at 589.92. +const AG1 = { id: "ag1", type: "clip", video: "VMspX2rOyVg", start: 579.68, end: 589.21, lock: true, lockEnd: true }; +const R = { fps: 30, transition: 0.4, snapLead: 0.45, snapTail: 0.55 }; + +test("lockedEdges: lock locks both, lockStart / lockEnd one; a cut is locked by lockCut; off with render.lockedEdges false or a montage", () => { + assert.deepEqual(lockedEdges(AG1), { start: true, end: true }); + assert.deepEqual(lockedEdges({ ...AG1, lock: undefined }), { start: false, end: true }); + assert.deepEqual(lockedEdges({ ...AG1, lock: undefined, lockEnd: undefined, lockStart: true }), { start: true, end: false }); + assert.deepEqual(lockedEdges({ ...AG1, lock: undefined, lockEnd: undefined }), { start: false, end: false }); + assert.deepEqual(lockedEdges({ ...AG1, cutStart: 581, cutEnd: 585 }), { start: false, end: false }, "lock is the extent's"); + assert.deepEqual(lockedEdges({ ...AG1, cutStart: 581, cutEnd: 585, lockCut: true }), { start: true, end: true }); + assert.deepEqual(lockedEdges(AG1, { lockedEdges: false }), { start: false, end: false }); + assert.deepEqual(lockedEdges(AG1, { montage: {} }), { start: false, end: false }); + assert.deepEqual(lockedEdges({ ...AG1, type: "card" }), { start: false, end: false }); +}); + +test("soundEdges: a locked end mutes at the end, an earlier muteFrom wins, an unlocked end is unchanged", () => { + assert.deepEqual(soundEdges(AG1, R), { muteFrom: 589.21, soundFrom: 579.68, implicit: true }); + assert.deepEqual(soundEdges({ ...AG1, muteFrom: 587 }, R), { muteFrom: 587, soundFrom: 579.68, implicit: false }, "the earlier mark wins"); + assert.deepEqual(soundEdges({ ...AG1, muteFrom: 589.21 }, R).muteFrom, 589.21); + const open = { ...AG1, lock: undefined, lockEnd: undefined }; + assert.deepEqual(soundEdges(open, R), { muteFrom: null, soundFrom: null, implicit: false }); + assert.deepEqual(soundEdges({ ...open, muteFrom: 588 }, R), { muteFrom: 588, soundFrom: null, implicit: false }); + assert.deepEqual(soundEdges(AG1, { ...R, lockedEdges: false }), { muteFrom: null, soundFrom: null, implicit: false }); + // A locked cut: its play window's edges (the lead-in before cutStart). + assert.deepEqual(soundEdges({ ...AG1, cutStart: 581, cutEnd: 585, lockCut: true }, R), { muteFrom: 585, soundFrom: 580.6, implicit: true }); +}); + +test("soundOnSegment: the locked end only where the segment reaches past it; the locked start only where it reaches before", () => { + // The draft-3 cut: snapped 579.289–590.5 (11.233 s). + assert.deepEqual(soundOnSegment(AG1, R, 579.289, 11.233), { + mute: 9.921, soundFrom: 0.391, edges: { muteFrom: 589.21, soundFrom: 579.68, implicit: true }, + }); + // A segment that ends at the locked end (or before it): nothing to mute. + assert.equal(soundOnSegment(AG1, R, 579.289, 9.921).mute, null); + // One that starts AT the locked start: nothing before it. + assert.equal(soundOnSegment(AG1, R, 579.68, 9.53).soundFrom, null); + // The clip's own mark is placed wherever it falls, as it always was. + assert.equal(soundOnSegment({ ...AG1, lock: false, lockEnd: false, muteFrom: 590.4 }, R, 579.289, 11).mute, 11.111); +}); + +test("snap: a locked edge moves only inside its own silence -- never across a sound", () => { + // Silences: one after "respect." that does NOT contain the locked end, and + // the breath before the first word that DOES contain the locked start. + const sil = [{ s: 0.2, e: 0.45 }, { s: 10.66, e: 11.5 }]; + // Unlocked, the end reaches across 0.74 s of sound to the next silence. + assert.deepEqual(snap(9.92, sil, "end", 1.6, R), { at: 11.21, snapped: true }); + assert.deepEqual(snap(9.92, sil, "end", 1.6, R, { pinned: true }), { at: 9.92, snapped: false }); + // Inside its silence it keeps the breath, outward, as ever. + assert.equal(snap(0.39, sil, "start", 1.6, R, { pinned: true }).at, 0.2); + assert.equal(snap(10.8, sil, "end", 1.6, R, { pinned: true }).at, 11.21); + // Never inward: a long "silence" (quiet last words read as one -- ag1's + // 589.21 sat in one from 587.92, and the snap cut it to 588.47) leaves it. + assert.deepEqual(snap(11.4, sil, "end", 1.6, R, { pinned: true }), { at: 11.4, snapped: false }); + assert.deepEqual(snap(11.4, sil, "end", 1.6, R), { at: 11.21, snapped: true }, "unlocked: inward, as before"); + assert.deepEqual(snap(0.5, [{ s: 0.2, e: 2 }], "start", 1.6, R, { pinned: true }), { at: 0.5, snapped: false }); + const c = snapCut({ sil, wantA: 0.39, wantB: 9.92, render: R, locked: { start: true, end: true } }); + assert.equal(c.cutB, 9.92); + assert.equal(c.b.snapped, false); + const rc = renderCut({ sil, fetchStart: 579.29, playFrom: 579.68, playTo: 589.21, render: R, locked: { end: true } }); + assert.equal(rc.end, 589.21); + assert.equal(renderCut({ sil, fetchStart: 579.29, playFrom: 579.68, playTo: 589.21, render: R }).end, 590.5, "unlocked: as before"); +}); + +test("segmentSoundEdits: from a matching cut record only; a missing record mutes no locked edge and says so", () => { + const record = { video: AG1.video, start: 579.289, end: 590.5 }; + const ed = segmentSoundEdits({ entry: AG1, record, render: R, seconds: 11.2 }); + assert.equal(ed.mute, 9.921); + assert.equal(ed.soundFrom, 0.391); + const none = segmentSoundEdits({ entry: AG1, record: null, render: R, seconds: 11.2 }); + assert.equal(none.mute, null); + assert.equal(none.soundFrom, null); + assert.match(none.notes.join("\n"), /locked edges are not muted -- no cut record/); + // An explicit mark still places itself from the unsnapped start, as ever. + const own = segmentSoundEdits({ entry: { ...AG1, lock: false, lockEnd: false, muteFrom: 588 }, record: null, render: R, seconds: 11.2 }); + assert.equal(own.mute, 8.32); +}); + +test("joinInputChain: the locked start's fade rises from it, the mute's fade ends at it", () => { + assert.equal(soundFromAudioFilter(0.391), `afade=t=in:st=0.391:d=${MUTE_FADE}`); + const c = joinInputChain(0, { hold: 0, move: null, soundFrom: 0.391, mute: 9.921 }, { fps: 30 }); + assert.deepEqual(c.parts, [`[0:a]${soundFromAudioFilter(0.391)},${muteAudioFilter(9.921)}[j0a]`]); +}); + +const haveFfmpeg = spawnSync("ffmpeg", ["-version"], { stdio: "ignore" }).status === 0; +const ff = (args, opts = {}) => { + const r = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", ...args], { maxBuffer: 1 << 28, ...opts }); + assert.equal(r.status, 0, String(r.stderr)); + return r.stdout; +}; + +test("build/play parity: the build's join and Play's envelope go silent at the same cut second, and sound from the same one", + { skip: !haveFfmpeg }, async () => { + const dir = mkdtempSync(path.join(tmpdir(), "locked-edges-")); + try { + // Two 2 s segments: a (locked 100.3–101.4, cut from 100.0 to 102.0) and b. + // As the build writes them (mp4, a cut record beside each), and losslessly + // (mov) for the sound the graph is measured on. + const make = (name, hz, ext) => { + const f = path.join(dir, `${name}.${ext}`); + const codec = ext === "mov" ? ["-c:v", "ffv1", "-c:a", "pcm_s16le"] : ["-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac"]; + ff(["-f", "lavfi", "-i", "testsrc2=s=64x36:r=30:d=2", "-f", "lavfi", "-i", `sine=frequency=${hz}:sample_rate=48000:duration=2`, + ...codec, "-ac", "2", f]); + return f; + }; + const segs = [make("a", 440, "mp4"), make("b", 660, "mp4")]; + const lossless = [make("a", 440, "mov"), make("b", 660, "mov")]; + const entries = [ + { id: "a", type: "clip", video: "va", start: 100.3, end: 101.4, lock: true }, + { id: "b", type: "clip", video: "vb", start: 200, end: 202 }, + ]; + writeFileSync(cutRecordPath(segs[0]), JSON.stringify({ version: 1, id: "a", video: "va", start: 100, end: 102 })); + const render = { fps: 30, transition: 0.4 }; + const joins = await cutJoins({ entries, segments: segs, render }); + assert.deepEqual(joins[0], { hold: 0, move: null, mute: 1.4, soundFrom: 0.3 }); + assert.equal(joins[1], null); + // With the knob off, the joins are what they were: none. + assert.equal(await cutJoins({ entries, segments: segs, render: { ...render, lockedEdges: false } }), null); + + // The build: a's sound, crossfaded into b over 0.4 s. + const g = xfadeGraph([2, 2], 0.4, joins, render, { video: false }); + const pcm = ff([...lossless.flatMap((s) => ["-i", s]), "-filter_complex", g.parts.join(";"), "-map", g.alab, + "-f", "s16le", "-ac", "1", "-ar", "48000", "-"], { encoding: "buffer" }); + const peak = (a, b) => { + let m = 0; + for (let i = Math.round(a * 48000); i < Math.min(pcm.length / 2, Math.round(b * 48000)); i += 1) m = Math.max(m, Math.abs(pcm.readInt16LE(i * 2))); + return m; + }; + assert.equal(peak(0, 0.3), 0, "nothing before the locked start"); + assert.ok(peak(0.35, 1.35) > 1000, "the locked window sounds"); + // From the locked end to the dissolve's end: a is gone; b fades in from 1.6. + assert.equal(peak(1.4, 1.6), 0, "nothing past the locked end before b comes in"); + + // Play the cut: the route's row as cutPoints.mjs builds it, through the plan. + const on = soundOnSegment(entries[0], render, 100, 2); + const cuts = { + a: { cutStart: 100, cutEnd: 102, footage: 2, muteFrom: on.edges.muteFrom, soundFrom: on.edges.soundFrom }, + b: { cutStart: 200, cutEnd: 202, footage: 2 }, + }; + const plan = playPlan([{ id: "a", start: 0, duration: 2 }, { id: "b", start: 1.6, duration: 2 }], entries, { cuts }); + const span = audioSpans(plan).find((s) => s.id === "a"); + // The same cut seconds as the build's join: a starts at 0 on both clocks. + const muteAt = joins[0].mute; + const soundAt = joins[0].soundFrom; + assert.equal(levelAt(span.env, soundAt - 0.01), 0); + assert.equal(levelAt(span.env, soundAt), 0); + assert.ok(Math.abs(levelAt(span.env, soundAt + MUTE_FADE) - 1) < 1e-9); + assert.ok(Math.abs(levelAt(span.env, muteAt - MUTE_FADE) - 1) < 1e-9); + assert.equal(levelAt(span.env, muteAt), 0); + assert.equal(levelAt(span.env, 1.8), 0, "silent under the dissolve"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); diff --git a/umtool/report-to-video/mute.mjs b/umtool/report-to-video/mute.mjs @@ -1,7 +1,117 @@ -// The mute mark's fade, alone: no imports, so a client bundle (umtool's clip -// bench previews the mute as the build makes it) can take it without pulling -// in deck.mjs and what deck.mjs imports (node:crypto, attribution). -// deck.mjs re-exports it; the build and the bench read the same number. +// The mute mark's fade, and where a clip's sound is heard, alone: no imports, +// so a client bundle (umtool's clip bench previews the mute as the build makes +// it; Play the cut's schedule) can take it without pulling in deck.mjs and +// what deck.mjs imports (node:crypto, attribution). deck.mjs re-exports it; +// the build, the cut-points route and Play the cut read the same numbers. /** The fade into a `muteFrom`'s silence, in seconds: long enough not to click, short enough to keep the next word out. */ export const MUTE_FADE = 0.04; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); + +/** + * A clip's play window in source seconds: its cut with the lead-in when it + * has both cut fields, else its extent. deck.mjs `playWindow` is this. + * + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @returns {{ from: number, to: number }} + */ +export function playEdges(entry, render = {}) { + const hasCut = fin(entry?.cutStart) && fin(entry?.cutEnd); + const lead = render?.leadIn ?? 0.4; + return { + from: hasCut ? Math.max(entry.start, entry.cutStart - lead) : entry?.start, + to: hasCut ? Math.min(entry.end, entry.cutEnd) : entry?.end, + }; +} + +/** + * Which edges of a clip's play window are LOCKED -- the author's, exact. A + * locked edge is snapped only OUTWARD, inside the silence it sits in (snap.mjs: + * never across a sound), and nothing outside it is heard (`soundEdges`). + * + * With a cut (`cutStart` + `cutEnd`) the played edges are the cut's, and + * `lockCut` locks both; without, `lock` locks both and `lockStart` / + * `lockEnd` one each. `render.lockedEdges: false` turns all of it off -- the + * edges snap and sound as they did before (any silence within snapWindow, + * heard to the segment's end). A montage cuts to its phrase: nothing here. + * + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @returns {{ start: boolean, end: boolean }} + */ +export function lockedEdges(entry, render = {}) { + const off = { start: false, end: false }; + if (!entry || entry.type !== "clip" || render?.lockedEdges === false) return off; + if (render?.montage != null && typeof render.montage === "object" && !Array.isArray(render.montage)) return off; + if (fin(entry.cutStart) && fin(entry.cutEnd)) { + return entry.lockCut === true ? { start: true, end: true } : off; + } + return { start: entry.lock === true || entry.lockStart === true, end: entry.lock === true || entry.lockEnd === true }; +} + +/** + * Where a clip's sound is heard, in SOURCE seconds -- THE rule the build's + * joins (build-video.mjs cutJoins), the podcast and Play the cut's schedule + * (cut-points route → playSchedule.mjs) all apply, so they cannot differ: + * + * muteFrom silent from here on, after a MUTE_FADE that ENDS here: the + * earlier of the clip's own `muteFrom` and its locked end. A + * locked end means nothing past it is heard -- not the snapped + * tail, not the outgoing half of a crossfade. + * soundFrom silent before here, a MUTE_FADE rising FROM here: a locked + * start, so nothing before it is heard under the dissolve in. + * implicit muteFrom is the locked end's (no `muteFrom` of its own, or a later one) + * + * null where nothing is muted. The picture is untouched: durations, the + * dissolves and every timing stay as they were. + * + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @returns {{ muteFrom: number | null, soundFrom: number | null, implicit: boolean }} + */ +export function soundEdges(entry, render = {}) { + const own = entry?.type === "clip" && fin(entry.muteFrom) ? entry.muteFrom : null; + const locked = lockedEdges(entry, render); + const w = locked.start || locked.end ? playEdges(entry, render) : { from: null, to: null }; + let muteFrom = own; + let implicit = false; + if (locked.end && fin(w.to) && (muteFrom == null || w.to < muteFrom)) { + muteFrom = w.to; + implicit = true; + } + const soundFrom = locked.start && fin(w.from) ? w.from : null; + return { muteFrom, soundFrom, implicit }; +} + +/** + * `soundEdges` on one SEGMENT's clock: the segment starts at source second + * `segStart` and is `seconds` long. `mute` (segment seconds, never below 0: + * silent from there, the fade ending at it) and `soundFrom` (silent before + * it, the fade rising from it), each null when it changes nothing here: a + * locked end the segment does not reach past, a locked start it does not + * reach before. The clip's own `muteFrom` is placed wherever it falls, as it + * always was. The build's joins (deck.mjs segmentSoundEdits, from the cut + * record) and the cut-points route (from the cut it computes) both call this. + * + * @param {Record<string, any>} entry + * @param {Record<string, any>} render + * @param {number} segStart + * @param {number} seconds + */ +export function soundOnSegment(entry, render, segStart, seconds) { + const se = soundEdges(entry, render); + const at = (src) => Math.max(0, Math.round((src - segStart) * 1000) / 1000); + let mute = null; + let soundFrom = null; + if (se.muteFrom != null) { + const m = at(se.muteFrom); + if (!se.implicit || m < seconds) mute = m; + } + if (se.soundFrom != null) { + const m = at(se.soundFrom); + if (m > 0 && m < seconds) soundFrom = m; + } + return { mute, soundFrom, edges: se }; +} diff --git a/umtool/report-to-video/presets.mjs b/umtool/report-to-video/presets.mjs @@ -119,7 +119,7 @@ export function presetManifest(manifest) { /** The render keys a preset keeps: the look (sizes, faces, palette, pacing, encode, QR, intro, the deck's settings). */ export const PRESET_RENDER_KEYS = Object.freeze([ "width", "height", "fps", "audioRate", "audioChannels", "maxHeightSource", "fontRegular", "fontBold", "palette", - "transition", "transitionStyle", "fetchPad", "snapWindow", "silenceMinDur", "silenceRelDb", "snapLead", "snapTail", + "transition", "transitionStyle", "fetchPad", "snapWindow", "silenceMinDur", "silenceRelDb", "snapLead", "snapTail", "lockedEdges", "footerHeight", "headerHeight", "slideSeconds", "crf", "preset", "audioBitrate", "qr", "endFade", "loudness", "captions", "intro", "chrome", "brand", ]); diff --git a/umtool/report-to-video/snap.mjs b/umtool/report-to-video/snap.mjs @@ -37,12 +37,22 @@ export const SNAP_DEFAULTS = Object.freeze({ * @param {Array<{ s: number, e: number }>} intervals the silences, file seconds * @param {"start" | "end"} kind * @param {number} window how far a silence may be (render.snapWindow) + * A PINNED edge (a locked one, mute.mjs `lockedEdges`) never moves across a + * sound and never INTO the window: it may only move outward, inside the + * silence it already sits in (an end later, a start earlier) -- breath for + * the crossfade, which the locked edge's mute keeps silent. Anything else + * (no silence around it, or a snap that would cut into what the author kept: + * the silence threshold is relative, and quiet last words read as silence) + * leaves it exactly where it is. + * * @param {{ snapLead?: number, snapTail?: number }} [render] + * @param {{ pinned?: boolean }} [opts] * @returns {{ at: number, snapped: boolean }} */ -export function snap(desired, intervals, kind, window, render = {}) { +export function snap(desired, intervals, kind, window, render = {}, { pinned = false } = {}) { let best = null; for (const iv of intervals) { + if (pinned && !(iv.s <= desired + 1e-9 && desired <= iv.e + 1e-9)) continue; // Starting: we want to resume just before speech does -> the silence's END. // Ending: we want to stop just after speech does -> the silence's START. const point = kind === "start" ? iv.e : iv.s; @@ -57,7 +67,9 @@ export function snap(desired, intervals, kind, window, render = {}) { const room = best.iv.e - best.iv.s; lead = (kind === "start" ? -1 : 1) * Math.min(set, room); } - return { at: Math.max(0, best.point + lead), snapped: true }; + const at = Math.max(0, best.point + lead); + if (pinned && (kind === "start" ? at > desired : at < desired)) return { at: desired, snapped: false }; + return { at, snapped: true }; } /** @@ -65,13 +77,16 @@ export function snap(desired, intervals, kind, window, render = {}) { * never inverted or collapsed -- the start at least a second before the * desired end, the end at least a second after the start. * - * @param {{ sil: Array<{ s: number, e: number }>, wantA: number, wantB: number, render?: Record<string, any> }} o - * `wantA`/`wantB`: the play window's edges in the file's seconds + * @param {{ sil: Array<{ s: number, e: number }>, wantA: number, wantB: number, render?: Record<string, any>, + * locked?: { start?: boolean, end?: boolean } | null }} o + * `wantA`/`wantB`: the play window's edges in the file's seconds; `locked`: + * which of them are the author's, exact (mute.mjs lockedEdges) -- each + * snapped only outward, inside its own silence */ -export function snapCut({ sil, wantA, wantB, render = {} }) { +export function snapCut({ sil, wantA, wantB, render = {}, locked = null }) { const win = render.snapWindow ?? SNAP_DEFAULTS.snapWindow; - const a = snap(wantA, sil, "start", win, render); - const b = snap(wantB, sil, "end", win, render); + const a = snap(wantA, sil, "start", win, render, { pinned: !!locked?.start }); + const b = snap(wantB, sil, "end", win, render, { pinned: !!locked?.end }); const cutA = Math.min(a.at, wantB - 1); const cutB = Math.max(b.at, cutA + 1); return { win, a, b, cutA, cutB }; @@ -87,10 +102,11 @@ export const recordSecond = (fetchStart, t) => Number((fetchStart + t).toFixed(3 * the play window (deck.mjs playWindow); `fetchStart` the file's first * second in the recording. * - * @param {{ sil: Array<{ s: number, e: number }>, fetchStart: number, playFrom: number, playTo: number, render?: Record<string, any> }} o + * @param {{ sil: Array<{ s: number, e: number }>, fetchStart: number, playFrom: number, playTo: number, render?: Record<string, any>, + * locked?: { start?: boolean, end?: boolean } | null }} o */ -export function renderCut({ sil, fetchStart, playFrom, playTo, render = {} }) { - const c = snapCut({ sil, wantA: playFrom - fetchStart, wantB: playTo - fetchStart, render }); +export function renderCut({ sil, fetchStart, playFrom, playTo, render = {}, locked = null }) { + const c = snapCut({ sil, wantA: playFrom - fetchStart, wantB: playTo - fetchStart, render, locked }); return { start: recordSecond(fetchStart, c.cutA), end: recordSecond(fetchStart, c.cutB),