Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(timeline): one answer to whether a raw moment is in the film
EtienneLescot1dbf94a284b3
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.tsindex ee46a6cc2..87670128c 100644--- a/src/lib/ai-edition/document/timeline.ts+++ b/src/lib/ai-edition/document/timeline.ts@@ -21,6 +21,8 @@ import type {*/export type PlaybackSegment = AxcutClip & { heldSec?: number };+import { type Interval, subtractInterval } from "../timeline/intervals";+import { keptRawSpans } from "../timeline/programme-time";import {anchoredToRawSpanSec,anchorRegionsWithDerivedMs,@@ -46,10 +48,10 @@ export function byStart(a: { startSec: number }, b: { startSec: number }): numbereturn a.startSec - b.startSec;}-export interface Interval {- startSec: number;- endSec: number;-}+// Re-exported, not redefined: `programme-time.ts` needs the same subtraction and cannot+// import it from here without closing a dependency cycle (this module already imports from+// `../timeline`). Callers of `Interval` / `subtractInterval` from this module are unaffected.+export { type Interval, subtractInterval } from "../timeline/intervals";export function normalizeIntervals(durationSec: number, intervals: Interval[]): Interval[] {const bounded = intervals@@ -145,23 +147,6 @@ export function resequenceClips(clips: AxcutClip[]): AxcutClip[] {});}-export function subtractInterval(intervals: Interval[], cut: Interval): Interval[] {- const output: Interval[] = [];- for (const interval of intervals) {- if (cut.endSec <= interval.startSec || cut.startSec >= interval.endSec) {- output.push(interval);- continue;- }- if (cut.startSec > interval.startSec) {- output.push({ startSec: interval.startSec, endSec: cut.startSec });- }- if (cut.endSec < interval.endSec) {- output.push({ startSec: cut.endSec, endSec: interval.endSec });- }- }- return output;-}-/*** Derived, ephemeral clip list for playback/native/export — never written back to* `document.timeline.clips`. Each clip's own `[sourceStartSec, sourceEndSec]` (its media@@ -358,43 +343,20 @@ export function projectRawTimelineSecToPlayback(let lastRawEnd = 0; // raw end of the last kept segment, for the trailing overhanglet landed: number | null = null; // output(rawSec), once it falls in/before a kept segment- // Each kept segment as a raw extent `{ rawStart, dur }`. Trims only REMOVE, so a kept- // segment's raw length survives here; how long it takes to PLAY is a separate question- // that `outputDurationOfRawSpan` answers, because a speed region scales it.- const keptSegments = (clip: AxcutClip): Array<{ rawStart: number; dur: number }> => {- const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;- if (sourceEnd <= clip.sourceStartSec) {- // Duration not probed yet — the whole raw clip passes through unnarrowed, matching- // `resolvePlaybackSegments`' own pass-through branch.- return [- { rawStart: clip.timelineStartSec, dur: clip.timelineEndSec - clip.timelineStartSec },- ];- }- let ivs: Interval[] = [{ startSec: clip.sourceStartSec, endSec: sourceEnd }];- for (const trim of trimRanges) {- if (!trimAppliesToClip(trim, clip)) continue;- ivs = subtractInterval(ivs, { startSec: trim.startSec, endSec: trim.endSec });- }- // Source time `s` sits at `timelineStartSec + (s − sourceStartSec)` on the raw ruler.- return ivs.map((iv) => ({- rawStart: clip.timelineStartSec + (iv.startSec - clip.sourceStartSec),- dur: iv.endSec - iv.startSec,- }));- };-- for (const clip of ordered) {- for (const seg of keptSegments(clip)) {- if (seg.dur <= 0) continue;- const rawEnd = seg.rawStart + seg.dur;- if (landed === null && rawSec < rawEnd) {- // `rawSec` is inside this segment, or before it in a trimmed/gap region (then- // the span clamps to nothing → the output edge just before the gap).- const within = Math.min(Math.max(rawSec, seg.rawStart), rawEnd);- landed = outCursor + outputDurationOfRawSpan(seg.rawStart, within, speedRegions);- }- outCursor += outputDurationOfRawSpan(seg.rawStart, rawEnd, speedRegions);- lastRawEnd = rawEnd;+ // The kept stretches come from `keptRawSpans`, which is this walk — it was lifted out of+ // here so the transcript lanes and the audio mix could ask the same question and get the+ // same answer (issue #560). Trims only REMOVE, so a kept span's RAW length is what+ // survives; how long it takes to PLAY is a separate question `outputDurationOfRawSpan`+ // answers, because a speed region scales it.+ for (const seg of keptRawSpans(ordered, trimRanges)) {+ if (landed === null && rawSec < seg.endSec) {+ // `rawSec` is inside this segment, or before it in a trimmed/gap region (then+ // the span clamps to nothing → the output edge just before the gap).+ const within = Math.min(Math.max(rawSec, seg.startSec), seg.endSec);+ landed = outCursor + outputDurationOfRawSpan(seg.startSec, within, speedRegions);}+ outCursor += outputDurationOfRawSpan(seg.startSec, seg.endSec, speedRegions);+ lastRawEnd = seg.endSec;}// Past every kept frame: programme end plus whatever raw time hangs off the end (identity when// there are no clips at all). A value ≥ programme length just means the mixer skips the track.diff --git a/src/lib/ai-edition/timeline/intervals.ts b/src/lib/ai-edition/timeline/intervals.tsnew file mode 100644index 000000000..ecd6daad2--- /dev/null+++ b/src/lib/ai-edition/timeline/intervals.ts@@ -0,0 +1,37 @@+// Interval arithmetic, with no opinion about what the numbers mean.+//+// Extracted from `document/timeline.ts` so `programme-time.ts` can reuse the very+// subtraction that `resolvePlaybackSegments` runs. It could not import it from there:+// the dependency runs `document/` → `timeline/` (document/timeline.ts already imports+// `trimAppliesToClip` from this layer), so importing back would close a cycle. A second+// copy of the same twelve lines was the alternative, and two implementations of "what+// survives a cut" is exactly the shape of bug this whole change exists to remove.+//+// `document/timeline.ts` re-exports both names, so its existing callers are unaffected.++export interface Interval {+ startSec: number;+ endSec: number;+}++/**+ * `intervals` minus `cut`. An interval straddling the cut splits in two; one wholly+ * inside it disappears. Inputs are not required to be sorted or disjoint, and the+ * output preserves the order it was given.+ */+export function subtractInterval(intervals: Interval[], cut: Interval): Interval[] {+ const output: Interval[] = [];+ for (const interval of intervals) {+ if (cut.endSec <= interval.startSec || cut.startSec >= interval.endSec) {+ output.push(interval);+ continue;+ }+ if (cut.startSec > interval.startSec) {+ output.push({ startSec: interval.startSec, endSec: cut.startSec });+ }+ if (cut.endSec < interval.endSec) {+ output.push({ startSec: cut.endSec, endSec: interval.endSec });+ }+ }+ return output;+}diff --git a/src/lib/ai-edition/timeline/programme-time.test.ts b/src/lib/ai-edition/timeline/programme-time.test.tsnew file mode 100644index 000000000..5d6faa4ef--- /dev/null+++ b/src/lib/ai-edition/timeline/programme-time.test.ts@@ -0,0 +1,276 @@+// Issue #560. These hold the one claim the whole change rests on: that+// `programme-time.ts` and `resolvePlaybackSegments` answer "is this raw moment in the+// film" the same way. They are the same walk now, so the interesting assertions are the+// ones that would catch it drifting apart again — and the two boundary rules that do NOT+// follow from the definition (a trimmed tail is removed, unfilmed time past the last clip+// is not).++import { describe, expect, it } from "vitest";+import { projectRawTimelineSecToPlayback, resolvePlaybackSegments } from "../document/timeline";+import type { AxcutClip, AxcutTrimRange } from "../schema";+import { keptRawSpans, removalAt, removedRawSpans, subtractRemoved } from "./programme-time";++function clip(over: Partial<AxcutClip> & { id: string }): AxcutClip {+ return {+ assetId: "a1",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 0,+ timelineEndSec: 10,+ wordRefs: [],+ origin: "user",+ reason: "",+ ...over,+ } as AxcutClip;+}++function trim(over: Partial<AxcutTrimRange> & { id: string }): AxcutTrimRange {+ return {+ assetId: "a1",+ startSec: 0,+ endSec: 1,+ origin: "user",+ reason: "",+ ...over,+ } as AxcutTrimRange;+}++/** Two clips laid end to end over one 20s asset, cut at source 10. */+function twoClips(): AxcutClip[] {+ return [+ clip({+ id: "c1",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 0,+ timelineEndSec: 10,+ }),+ clip({+ id: "c2",+ sourceStartSec: 10,+ sourceEndSec: 20,+ timelineStartSec: 10,+ timelineEndSec: 20,+ }),+ ];+}++const total = (spans: Array<{ startSec: number; endSec: number }>) =>+ spans.reduce((sum, s) => sum + (s.endSec - s.startSec), 0);++/** Deterministic LCG — a failure here has to be reproducible, so no Math.random. */+function lcg(seed: number) {+ let state = seed >>> 0;+ return () => {+ state = (state * 1664525 + 1013904223) >>> 0;+ return state / 4294967296;+ };+}++describe("keptRawSpans agrees with playback", () => {+ it("keeps exactly what resolvePlaybackSegments plays, over randomised fixtures", () => {+ for (let seed = 1; seed <= 40; seed++) {+ const rand = lcg(seed);+ const clipCount = 1 + Math.floor(rand() * 3);+ const clips: AxcutClip[] = [];+ let cursor = 0;+ for (let i = 0; i < clipCount; i++) {+ const len = 4 + Math.floor(rand() * 8);+ const sourceStart = Math.floor(rand() * 5);+ clips.push(+ clip({+ id: `c${i}`,+ // Two clips over one asset on purpose: it is the case that separates a+ // per-clip walk from a per-asset one.+ assetId: rand() < 0.5 ? "a1" : "a2",+ sourceStartSec: sourceStart,+ sourceEndSec: sourceStart + len,+ timelineStartSec: cursor,+ timelineEndSec: cursor + len,+ }),+ );+ // Sometimes a gap before the next clip.+ cursor += len + (rand() < 0.3 ? 1 + Math.floor(rand() * 3) : 0);+ }+ const trims: AxcutTrimRange[] = [];+ const trimCount = Math.floor(rand() * 4);+ for (let i = 0; i < trimCount; i++) {+ const host = clips[Math.floor(rand() * clips.length)];+ const start = host.sourceStartSec + rand() * 4;+ trims.push(+ trim({+ id: `t${i}`,+ assetId: host.assetId,+ // Half anchored, half pre-v7 style, so both branches of+ // `trimAppliesToClip` are exercised.+ ...(rand() < 0.5 ? { clipId: host.id } : {}),+ startSec: start,+ endSec: start + 0.5 + rand() * 3,+ }),+ );+ }++ const played = resolvePlaybackSegments(clips, trims).reduce(+ (sum, seg) => sum + ((seg.sourceEndSec ?? seg.sourceStartSec) - seg.sourceStartSec),+ 0,+ );+ const kept = keptRawSpans(clips, trims);+ expect(total(kept), `seed ${seed} total`).toBeCloseTo(played, 6);++ // The sum alone is blind to ORDER, and order is the whole reason this walk was+ // lifted rather than reimplemented: `projectRawTimelineSecToPlayback` accumulates+ // one output cursor across the spans in the order they arrive. So check each+ // span's head projects to the output length of everything before it — which is+ // only true if the walk yields them in playback order.+ let before = 0;+ for (const [i, span] of kept.entries()) {+ expect(+ projectRawTimelineSecToPlayback(clips, trims, span.startSec),+ `seed ${seed} span ${i}`,+ ).toBeCloseTo(before, 6);+ before += span.endSec - span.startSec;+ }+ }+ });++ it("is caught out when the spans arrive in the wrong order", () => {+ // Guards the guard: if `keptRawSpans` ever returned globally sorted spans instead of+ // playback-ordered ones, the assertion above has to fail. Two clips whose ruler order+ // is the reverse of their array order make the two orderings differ.+ const clips = [+ clip({+ id: "late",+ sourceStartSec: 0,+ sourceEndSec: 4,+ timelineStartSec: 6,+ timelineEndSec: 10,+ }),+ clip({+ id: "early",+ sourceStartSec: 0,+ sourceEndSec: 6,+ timelineStartSec: 0,+ timelineEndSec: 6,+ }),+ ];+ expect(keptRawSpans(clips, []).map((s) => s.startSec)).toEqual([0, 6]);+ });++ it("leaves the projection identical to what it produced before the lift", () => {+ const clips = twoClips();+ const trims = [trim({ id: "t1", clipId: "c1", startSec: 2, endSec: 4 })];+ // Raw 2..4 is gone, so everything after it plays 2s earlier; inside the cut the+ // playhead lands on the output edge just before it.+ expect(projectRawTimelineSecToPlayback(clips, trims, 1)).toBeCloseTo(1, 6);+ expect(projectRawTimelineSecToPlayback(clips, trims, 3)).toBeCloseTo(2, 6);+ expect(projectRawTimelineSecToPlayback(clips, trims, 6)).toBeCloseTo(4, 6);+ expect(projectRawTimelineSecToPlayback(clips, trims, 20)).toBeCloseTo(18, 6);+ // Past the programme the projection is the identity, which is what lets a voiceover+ // hang off the end and keep playing.+ expect(projectRawTimelineSecToPlayback(clips, trims, 25)).toBeCloseTo(23, 6);+ });+});++describe("removedRawSpans", () => {+ it("partitions the programme with no overlap and no hole", () => {+ const clips = twoClips();+ const trims = [+ trim({ id: "t1", clipId: "c1", startSec: 2, endSec: 4 }),+ trim({ id: "t2", clipId: "c2", startSec: 15, endSec: 16 }),+ ];+ const kept = [...keptRawSpans(clips, trims)].sort((a, b) => a.startSec - b.startSec);+ const removed = removedRawSpans(clips, trims);+ const all = [...kept, ...removed].sort((a, b) => a.startSec - b.startSec);++ let cursor = 0;+ for (const span of all) {+ expect(span.startSec).toBeCloseTo(cursor, 6); // no hole, no overlap+ cursor = span.endSec;+ }+ expect(cursor).toBeCloseTo(20, 6); // the last clip's raw end+ });++ it("reports an inter-clip gap as removed by nothing", () => {+ const clips = [+ twoClips()[0],+ clip({+ id: "c2",+ sourceStartSec: 10,+ sourceEndSec: 20,+ timelineStartSec: 13,+ timelineEndSec: 23,+ }),+ ];+ const gap = removedRawSpans(clips, []).find((s) => s.startSec === 10);+ expect(gap).toMatchObject({ startSec: 10, endSec: 13 });+ // No trim took it, so the pane must not offer a restore.+ expect(gap?.trimIds).toEqual([]);+ });++ it("removes a trimmed tail of the last clip but never the time past it", () => {+ const clips = [twoClips()[0]];+ const trims = [trim({ id: "t1", clipId: "c1", startSec: 8, endSec: 10 })];+ const removed = removedRawSpans(clips, trims);+ expect(removed).toEqual([{ startSec: 8, endSec: 10, trimIds: ["t1"] }]);+ // Raw 12 is unfilmed, not removed — the distinction a voiceover overhanging the+ // programme depends on.+ expect(removalAt(removed, 12)).toBeNull();+ expect(removalAt(removed, 9)).toMatchObject({ trimIds: ["t1"] });+ });++ it("covers BOTH clips of an asset for a pre-v7 un-anchored trim", () => {+ // The regression guard. `trimToTimelineSpan`'s un-anchored branch resolves such a+ // trim through the FIRST clip whose source range contains its start, so a primitive+ // built on it would leave c2's words reading kept over film that is gone. The+ // playback walk cuts on overlap, per clip, and this must match it.+ const clips = twoClips();+ const trims = [trim({ id: "t1", startSec: 5, endSec: 15 })]; // no clipId+ const removed = removedRawSpans(clips, trims);+ expect(removalAt(removed, 6)).toMatchObject({ trimIds: ["t1"] }); // inside c1+ expect(removalAt(removed, 12)).toMatchObject({ trimIds: ["t1"] }); // inside c2+ expect(removalAt(removed, 2)).toBeNull();+ expect(removalAt(removed, 18)).toBeNull();+ });++ it("names every overlapping trim that took a stretch", () => {+ const clips = [twoClips()[0]];+ const trims = [+ trim({ id: "t1", clipId: "c1", startSec: 2, endSec: 5 }),+ trim({ id: "t2", clipId: "c1", startSec: 4, endSec: 7 }),+ ];+ // `subtractInterval` merges the two into one hole; both ids come with it, so+ // restoring from the pane can drop the whole pill.+ expect(removedRawSpans(clips, trims)).toEqual([+ { startSec: 2, endSec: 7, trimIds: ["t1", "t2"] },+ ]);+ });++ it("returns nothing for a document with no clips", () => {+ expect(removedRawSpans([], [trim({ id: "t1" })])).toEqual([]);+ });+});++describe("subtractRemoved", () => {+ it("splits a span that crosses a cut into the pieces that survive", () => {+ const clips = twoClips();+ const removed = removedRawSpans(clips, [+ trim({ id: "t1", clipId: "c1", startSec: 3, endSec: 5 }),+ ]);+ // A voiceover from raw 1 to raw 8 plays as two pieces, not as one take cut short.+ expect(subtractRemoved(1, 8, removed)).toEqual([+ { startSec: 1, endSec: 3 },+ { startSec: 5, endSec: 8 },+ ]);+ });++ it("yields nothing for a span buried inside a cut, and the whole span when untouched", () => {+ const clips = twoClips();+ const removed = removedRawSpans(clips, [+ trim({ id: "t1", clipId: "c1", startSec: 3, endSec: 8 }),+ ]);+ expect(subtractRemoved(4, 6, removed)).toEqual([]);+ expect(subtractRemoved(10, 14, removed)).toEqual([{ startSec: 10, endSec: 14 }]);+ // Past the programme is not removed, so an overhanging take keeps its tail.+ expect(subtractRemoved(18, 25, removed)).toEqual([{ startSec: 18, endSec: 25 }]);+ });+});diff --git a/src/lib/ai-edition/timeline/programme-time.ts b/src/lib/ai-edition/timeline/programme-time.tsnew file mode 100644index 000000000..60c23f032--- /dev/null+++ b/src/lib/ai-edition/timeline/programme-time.ts@@ -0,0 +1,225 @@+// One answer to "is this raw ruler moment in the film" (issue #560).+//+// Everything that reads the timeline used to answer that question its own way, and the+// answers disagreed. The transcript pane asked it by IDENTITY — does a trim name this+// clip — which is a question a voiceover placement can never answer yes to, since it+// carries an audio fragment id and an audio asset while every trim carries a video clip.+// So the voiceover lane read every word as kept, including words whose moment had been+// cut out of the film, and a cut authored from that lane removed nothing at all.+//+// The fix is not a better identity test. It is to stop asking about identity: a trim is a+// removed span of the RAW RULER, and both lanes lie on that one ruler. A word — from the+// recording or from a voiceover — is removed if and only if the raw moment it occupies is.+//+// `keptRawSpans` is therefore lifted verbatim out of `projectRawTimelineSecToPlayback`,+// which now calls it, rather than reimplemented beside it. Agreement with playback is by+// construction; `programme-time.test.ts` holds the two to it on randomised fixtures.+//+// Storage does not change: a trim stays source-time anchored to a clip. This is the+// derived READING of those rows, computed on demand and never written back.++import type { AxcutClip, AxcutTrimRange } from "../schema";+import { type Interval, subtractInterval } from "./intervals";+import { trimAppliesToClip } from "./trim-mapping";++/** A stretch of the raw ruler, in seconds. */+export interface RawSpan {+ startSec: number;+ endSec: number;+}++/** A stretch the film does not contain, and the trims that took it away. */+export interface RemovedRawSpan extends RawSpan {+ /**+ * The trims covering this stretch — several when they overlap, and EMPTY for a gap+ * between two clips, which is missing from the film without anything having removed+ * it. Callers offering a restore affordance must key it on this being non-empty:+ * there is no pill to click for a gap.+ */+ trimIds: string[];+}++/**+ * The clip's own extent on the raw ruler.+ *+ * Source second `s` sits at `timelineStartSec + (s − sourceStartSec)`, so the extent runs+ * to the source length past the head. An UNPROBED clip (no real `sourceEndSec` yet) has no+ * source length to measure, and falls back to the ruler geometry it was given — matching+ * the pass-through branch `resolvePlaybackSegments` takes for the same clips.+ */+function clipRawExtent(clip: AxcutClip): RawSpan {+ const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;+ if (sourceEnd <= clip.sourceStartSec) {+ return { startSec: clip.timelineStartSec, endSec: clip.timelineEndSec };+ }+ return {+ startSec: clip.timelineStartSec,+ endSec: clip.timelineStartSec + (sourceEnd - clip.sourceStartSec),+ };+}++/** Source interval → raw, through the clip that carries it. */+function sourceToRaw(clip: AxcutClip, interval: Interval): RawSpan {+ return {+ startSec: clip.timelineStartSec + (interval.startSec - clip.sourceStartSec),+ endSec: clip.timelineStartSec + (interval.endSec - clip.sourceStartSec),+ };+}++/** What survives the trims inside one clip, in source order. */+function keptSourceIntervals(clip: AxcutClip, trimRanges: AxcutTrimRange[]): Interval[] {+ const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;+ if (sourceEnd <= clip.sourceStartSec) return [];+ let ivs: Interval[] = [{ startSec: clip.sourceStartSec, endSec: sourceEnd }];+ for (const trim of trimRanges) {+ if (!trimAppliesToClip(trim, clip)) continue;+ ivs = subtractInterval(ivs, { startSec: trim.startSec, endSec: trim.endSec });+ }+ return ivs;+}++/**+ * Every stretch of raw ruler the film actually contains, in PLAYBACK ORDER — clips by+ * `timelineStartSec`, and within a clip by source time.+ *+ * Not globally sorted, on purpose: `projectRawTimelineSecToPlayback` walks these with a+ * single output cursor, so the order has to be the order they play. Two clips that overlap+ * on the ruler (which the model does not produce, but nothing forbids) therefore come back+ * interleaved rather than merged, exactly as the projection has always treated them.+ *+ * Zero-length spans are dropped, so a caller can trust `endSec > startSec`.+ */+export function keptRawSpans(clips: AxcutClip[], trimRanges: AxcutTrimRange[]): RawSpan[] {+ const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);+ const spans: RawSpan[] = [];+ for (const clip of ordered) {+ const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;+ if (sourceEnd <= clip.sourceStartSec) {+ // Duration not probed yet — the whole raw clip passes through unnarrowed.+ const extent = clipRawExtent(clip);+ if (extent.endSec > extent.startSec) spans.push(extent);+ continue;+ }+ for (const iv of keptSourceIntervals(clip, trimRanges)) {+ const span = sourceToRaw(clip, iv);+ if (span.endSec > span.startSec) spans.push(span);+ }+ }+ return spans;+}++/**+ * The complement of {@link keptRawSpans} over `[0, lastClipRawEnd]`, sorted, each stretch+ * carrying the ids of the trims that took it.+ *+ * Two boundaries decide what this does and do not follow from the definition:+ *+ * It stops at the last CLIP's raw end, not the last KEPT span's. A trimmed tail of the+ * last clip is inside the programme's extent and so is genuinely removed; raw time PAST+ * every clip is not removed but simply unfilmed, because `projectRawTimelineSecToPlayback`+ * is the identity there. That is what lets a voiceover hang off the end of the programme+ * and keep playing, its words still reading kept, instead of being silently swallowed.+ *+ * Gaps count as removed, with no trim ids. Nothing plays there, so a word over a gap is+ * not in the film — but there is no trim to restore, and the pane must not offer one.+ */+export function removedRawSpans(+ clips: AxcutClip[],+ trimRanges: AxcutTrimRange[],+): RemovedRawSpan[] {+ const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);+ if (ordered.length === 0) return [];++ const removed: RemovedRawSpan[] = [];+ let cursor = 0; // raw end of the programme walked so far++ for (const clip of ordered) {+ const extent = clipRawExtent(clip);+ // The unfilmed stretch before this clip. `max` rather than a bare subtraction so+ // two clips overlapping on the ruler contribute no negative gap.+ if (extent.startSec > cursor) {+ removed.push({ startSec: cursor, endSec: extent.startSec, trimIds: [] });+ }+ cursor = Math.max(cursor, extent.endSec);++ if (extent.endSec <= extent.startSec) continue;+ const kept = keptSourceIntervals(clip, trimRanges);+ // An unprobed clip has no source interval to cut, and passes through whole.+ if (kept.length === 0 && (clip.sourceEndSec ?? clip.sourceStartSec) <= clip.sourceStartSec) {+ continue;+ }++ // The trims that reach this clip, in raw, so a removed piece can name them.+ const applicable = trimRanges+ .filter((trim) => trimAppliesToClip(trim, clip))+ .map((trim) => ({+ id: trim.id,+ ...sourceToRaw(clip, { startSec: trim.startSec, endSec: trim.endSec }),+ }));++ let holeStart = extent.startSec;+ for (const iv of kept) {+ const span = sourceToRaw(clip, iv);+ if (span.startSec > holeStart) {+ removed.push(taggedHole(holeStart, span.startSec, applicable));+ }+ holeStart = Math.max(holeStart, span.endSec);+ }+ if (extent.endSec > holeStart) {+ removed.push(taggedHole(holeStart, extent.endSec, applicable));+ }+ }++ return removed.sort((a, b) => a.startSec - b.startSec || a.endSec - b.endSec);+}++function taggedHole(+ startSec: number,+ endSec: number,+ applicable: Array<{ id: string; startSec: number; endSec: number }>,+): RemovedRawSpan {+ return {+ startSec,+ endSec,+ trimIds: applicable+ .filter((trim) => trim.endSec > startSec && trim.startSec < endSec)+ .map((trim) => trim.id),+ };+}++/**+ * The stretch removing `rawSec`, or null when the moment is in the film.+ *+ * Half-open: a moment exactly on a removed span's end belongs to what follows, so a word+ * whose centre lands on the far edge of a cut reads as kept.+ */+export function removalAt(removed: RemovedRawSpan[], rawSec: number): RemovedRawSpan | null {+ for (const span of removed) {+ if (rawSec < span.startSec) break; // sorted, so nothing later can contain it+ if (rawSec < span.endSec) return span;+ }+ return null;+}++/**+ * `[startSec, endSec]` with every removed stretch taken out — the pieces of a span that+ * survive into the film, in order.+ *+ * This is what turns one audio track into the several mix entries a cut underneath it+ * demands: a voiceover crossing a trim plays as two pieces, not as one take shortened at+ * the tail.+ */+export function subtractRemoved(+ startSec: number,+ endSec: number,+ removed: RemovedRawSpan[],+): RawSpan[] {+ if (endSec <= startSec) return [];+ let pieces: Interval[] = [{ startSec, endSec }];+ for (const span of removed) {+ if (span.startSec >= endSec) break; // sorted; nothing later overlaps+ if (span.endSec <= startSec) continue;+ pieces = subtractInterval(pieces, { startSec: span.startSec, endSec: span.endSec });+ }+ return pieces.filter((piece) => piece.endSec > piece.startSec);+}