Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(editor): decide a word by the ruler, so both lanes agree

EtienneLescotca66c1de61af
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index dfe3d159c..d9c2fae4d 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -74,10 +74,10 @@ import {
} from "@/lib/ai-edition/timeline/aggregated-transcript";
import { hasAnyClipWithCamera } from "@/lib/ai-edition/timeline/camera";
import { formatMs } from "@/lib/ai-edition/timeline/format";
-import { locateVirtualPosition } from "@/lib/ai-edition/timeline/virtual-preview";
-import {
- type AssetTranscriptionView,
- type TranscriptGateReason,
+import { removedRawSpans } from "@/lib/ai-edition/timeline/programme-time";
+import type {
+ AssetTranscriptionView,
+ TranscriptGateReason,
} from "@/lib/ai-edition/transcription/status";
import { getAssetPath } from "@/lib/assetPath";
import { resolveWebcamLayoutPreset, supportsWebcamReactiveZoom } from "@/lib/compositeLayout";
@@ -875,29 +875,24 @@ export function TranscriptPane({
lane === "voiceover" && voiceover.length === 0 ? "recording" : lane;
const placements = activeLane === "voiceover" ? voiceover : clips;
+ // From the RECORDING clips and the whole trim set, never from `placements`: the
+ // programme is one thing, and the voiceover lane is asking whether the film still
+ // contains a moment — not whether some trim happens to name an audio fragment.
+ const removed = useMemo(() => removedRawSpans(clips, trimRanges), [clips, trimRanges]);
const sections = useMemo(
- () => buildAggregatedSections(placements, transcripts, assets, trimRanges),
- [placements, transcripts, assets, trimRanges],
+ () => buildAggregatedSections(placements, transcripts, assets, removed),
+ [placements, transcripts, assets, removed],
);
- // the cue position is the playback head's location in the current clip's source time.
// `currentTimeSec` is the RAW/document timeline (same referential as the ruler, see
- // NewEditorShell) — looked up against the raw `clips`, matching that referential.
- // `clipId` is what `findCueWordId` keys on — do NOT drop it as unused: source time is
- // per asset, so without it the resolver falls back to the first section of the asset
- // and the cue tracks clip 1 forever on a timeline that plays one media twice.
- const cue = useMemo(() => {
- if (clips.length === 0) return null;
- const position = locateVirtualPosition(clips, currentTimeSec);
- if (!position) return null;
- return {
- assetId: position.clip.assetId,
- clipId: position.clip.id,
- sourceTimeSec: position.sourceTimeSec,
- };
- }, [clips, currentTimeSec]);
-
- const cueWordId = useMemo(() => findCueWordId(sections, cue), [sections, cue]);
+ // NewEditorShell), which is exactly what `findCueWordId` now takes. It used to be
+ // resolved through `locateVirtualPosition` into a clip id + source second, and a clip
+ // id is something only the recording lane has — so the voiceover lane never
+ // highlighted. Raw seconds are the coordinate both lanes share.
+ const cueWordId = useMemo(
+ () => findCueWordId(sections, currentTimeSec),
+ [sections, currentTimeSec],
+ );
const laneSwitch =
voiceover.length > 0 ? <TranscriptLaneSwitch lane={activeLane} onChange={setLane} /> : null;
@@ -1152,8 +1147,12 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
const removeTrimRun = useCallback(
(run: TrimRun) => {
- if (busy || !run.trimId) return;
- onRemoveTrimRange(run.trimId);
+ // An empty set is a gap between clips: removed from the film, but by nothing
+ // there is a pill for. Step 4 of #560 replaces this with a call that drops every
+ // row of the pill at once; today's op takes one id, so overlapping cuts still
+ // need a second click, exactly as before.
+ if (busy || run.trimIds.length === 0) return;
+ onRemoveTrimRange(run.trimIds[0]);
},
[busy, onRemoveTrimRange],
);
@@ -1598,7 +1597,7 @@ const TranscriptWord = memo(function TranscriptWord({
onClick={(e) => {
e.stopPropagation();
onRestore({
- trimId: cw.trimId ?? "",
+ trimIds: cw.trimIds,
assetId: "",
startWordIndex: 0,
endWordIndex: 0,
@@ -1725,7 +1724,7 @@ const TranscriptWord = memo(function TranscriptWord({
data-start-sec={cw.word.startSec}
data-end-sec={cw.word.endSec}
data-inserted="true"
- data-skip-id={cw.trimId ?? undefined}
+ data-skip-id={cw.trimIds[0] ?? undefined}
style={{ display: "inline", opacity: removed ? 0.6 : 1 }}
onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}
@@ -1815,7 +1814,7 @@ const TranscriptWord = memo(function TranscriptWord({
data-word-id={cw.id}
data-start-sec={cw.word.startSec}
data-end-sec={cw.word.endSec}
- data-skip-id={cw.trimId ?? undefined}
+ data-skip-id={cw.trimIds[0] ?? undefined}
data-corrected={corrected ? "true" : undefined}
data-cue={isCue ? "true" : undefined}
title={corrected ? ts("transcript.correctedWord", { original }) : undefined}
@@ -1848,7 +1847,7 @@ const TranscriptWord = memo(function TranscriptWord({
the LLM is the only place that names a word a filler (via the
filler_or_hesitation reason when generating suggestions). */}
{cw.word.text}{" "}
- {removed && hover && cw.trimId ? (
+ {removed && hover && cw.trimIds.length > 0 ? (
<button
type="button"
contentEditable={false}
@@ -1856,10 +1855,10 @@ const TranscriptWord = memo(function TranscriptWord({
aria-label={ts("transcript.restoreWord", { word: cw.word.text })}
onClick={(e) => {
e.stopPropagation();
- // build a minimal TrimRun stub — only trimId is
+ // build a minimal TrimRun stub — only the ids are
// read by onRestore.
onRestore({
- trimId: cw.trimId ?? "",
+ trimIds: cw.trimIds,
assetId: "",
startWordIndex: 0,
endWordIndex: 0,
@@ -2041,7 +2040,7 @@ function findCollapsedDeletionWordId(
): string | null {
// read the kept/skip state from the words array, not the
// DOM's data-skip-id. The DOM may be lagging a render behind (its
- // trimId is only set on the next React commit), so a DOM check would
+ // skip id is only set on the next React commit), so a DOM check would
// re-trim an already-trimmed word. The words array is the React state
// captured at the call site — always current.
const skippedIds = new Set(words.filter((w) => !w.kept).map((w) => w.id));
diff --git a/src/lib/ai-edition/timeline/aggregated-transcript.lanes.test.ts b/src/lib/ai-edition/timeline/aggregated-transcript.lanes.test.ts
index 81db5c0eb..0a458c36a 100644
--- a/src/lib/ai-edition/timeline/aggregated-transcript.lanes.test.ts
+++ b/src/lib/ai-edition/timeline/aggregated-transcript.lanes.test.ts
@@ -7,9 +7,12 @@ import { describe, expect, it } from "vitest";
import type { AxcutAudioTrack } from "../schema";
import {
buildAggregatedSections,
+ findCueWordId,
lanePlacements,
+ placementRawSec,
voiceoverPlacements,
} from "./aggregated-transcript";
+import { removedRawSpans } from "./programme-time";
function track(over: Partial<AxcutAudioTrack> & { id: string }): AxcutAudioTrack {
return {
@@ -121,3 +124,160 @@ describe("lanePlacements", () => {
expect(sections[0].words[0].id.startsWith("t1:")).toBe(true);
});
});
+
+// ─── The bug this parameterisation shipped with ──────────────────────────────
+// `b9e0f1ff` decided kept-or-removed by asking whether a trim NAMED the placement. A
+// voiceover placement carries an audio fragment id and an audio asset; every trim carries
+// a video clip. They never matched, so the voiceover lane read every word as kept — over
+// film that had been cut away — and a cut authored from it removed nothing at all. These
+// hold the ruler-based answer that replaced it.
+
+describe("one programme, two lanes", () => {
+ const CLIPS_2 = [
+ {
+ id: "clip_1",
+ assetId: "asset_rec",
+ sourceStartSec: 0,
+ sourceEndSec: 6,
+ timelineStartSec: 0,
+ timelineEndSec: 6,
+ wordRefs: [],
+ origin: "user" as const,
+ reason: "",
+ },
+ {
+ id: "clip_2",
+ assetId: "asset_rec",
+ sourceStartSec: 6,
+ sourceEndSec: 12,
+ timelineStartSec: 6,
+ timelineEndSec: 12,
+ wordRefs: [],
+ origin: "user" as const,
+ reason: "",
+ },
+ ];
+
+ /** A cut over raw 2..4, anchored the way the transcript pane writes one. */
+ const TRIM = {
+ id: "trim_1",
+ assetId: "asset_rec",
+ clipId: "clip_1",
+ startSec: 2,
+ endSec: 4,
+ origin: "user" as const,
+ reason: "",
+ };
+
+ /** Words at one per second, so a word's index is its second. */
+ function secondsTranscript(assetId: string, count: number, from = 0) {
+ return {
+ assetId,
+ language: "en",
+ segments: [],
+ words: Array.from({ length: count }, (_, i) => ({
+ id: `w${from + i}`,
+ segmentId: "s",
+ text: `w${from + i}`,
+ startSec: from + i + 0.1,
+ endSec: from + i + 0.9,
+ })),
+ };
+ }
+
+ /** A voiceover laid over the whole programme, reading its own file from the head. */
+ const VO = track({ id: "vo_1", startMs: 0, endMs: 12000, offsetMs: 0, durationSec: 12 });
+
+ function lanes(trims: (typeof TRIM)[]) {
+ const removed = removedRawSpans(CLIPS_2, trims);
+ const transcripts = [secondsTranscript("asset_rec", 12), secondsTranscript("asset_vo", 12)];
+ const build = (lane: "recording" | "voiceover") =>
+ buildAggregatedSections(
+ lanePlacements(lane, CLIPS_2, [VO]),
+ // biome-ignore lint/suspicious/noExplicitAny: fixtures, not a schema exercise
+ transcripts as any,
+ [],
+ removed,
+ );
+ return { recording: build("recording"), voiceover: build("voiceover") };
+ }
+
+ const cutWords = (sections: ReturnType<typeof lanes>["recording"]) =>
+ sections
+ .flatMap((s) => s.words)
+ .filter((w) => !w.kept && !w.word.id.startsWith("silence_"))
+ .map((w) => w.word.text);
+
+ it("marks a voiceover word removed when the film under it was cut", () => {
+ // THE bug. Before this, the voiceover lane returned every word kept.
+ const { voiceover } = lanes([TRIM]);
+ expect(cutWords(voiceover)).toEqual(["w2", "w3"]);
+ const w2 = voiceover.flatMap((s) => s.words).find((w) => w.word.id === "w2");
+ expect(w2?.trimIds).toEqual(["trim_1"]);
+ });
+
+ it("greys the same moment on whichever lane you read", () => {
+ const { recording, voiceover } = lanes([TRIM]);
+ expect(cutWords(recording)).toEqual(["w2", "w3"]);
+ expect(cutWords(voiceover)).toEqual(cutWords(recording));
+ });
+
+ it("leaves both lanes whole when nothing is cut", () => {
+ const { recording, voiceover } = lanes([]);
+ expect(cutWords(recording)).toEqual([]);
+ expect(cutWords(voiceover)).toEqual([]);
+ });
+
+ it("removes a word over an inter-clip gap, with nothing to restore", () => {
+ const gapped = [CLIPS_2[0], { ...CLIPS_2[1], timelineStartSec: 8, timelineEndSec: 14 }];
+ const removed = removedRawSpans(gapped, []);
+ const sections = buildAggregatedSections(
+ voiceoverPlacements([track({ id: "vo_1", startMs: 0, endMs: 14000, durationSec: 14 })]),
+ // biome-ignore lint/suspicious/noExplicitAny: fixture, not a schema exercise
+ [secondsTranscript("asset_vo", 14)] as any,
+ [],
+ removed,
+ );
+ const w6 = sections.flatMap((s) => s.words).find((w) => w.word.id === "w6"); // raw 6..7
+ expect(w6?.kept).toBe(false);
+ // Nothing took it, so the pane must offer no bin: a gap is not a pill.
+ expect(w6?.trimIds).toEqual([]);
+ const run = sections.flatMap((s) => s.trimRuns).find((r) => r.trimIds.length === 0);
+ expect(run).toBeDefined();
+ });
+
+ it("keeps a word that hangs past the end of the programme", () => {
+ // The projection is the identity there, so the narration still plays.
+ const over = track({ id: "vo_1", startMs: 0, endMs: 20000, durationSec: 20 });
+ const sections = buildAggregatedSections(
+ voiceoverPlacements([over]),
+ // biome-ignore lint/suspicious/noExplicitAny: fixture, not a schema exercise
+ [secondsTranscript("asset_vo", 20)] as any,
+ [],
+ removedRawSpans(CLIPS_2, []),
+ );
+ const w15 = sections.flatMap((s) => s.words).find((w) => w.word.id === "w15");
+ expect(w15?.kept).toBe(true);
+ });
+
+ it("highlights the voiceover lane from a raw second", () => {
+ // The cue used to be resolved into a clip id, which only the recording lane has —
+ // so this returned null for every moment of every voiceover.
+ const { voiceover } = lanes([]);
+ expect(findCueWordId(voiceover, 4.5)).toBe("vo_1:w4");
+ expect(findCueWordId(voiceover, 0.5)).toBe("vo_1:w0");
+ });
+
+ it("reads a word's raw moment through its own placement", () => {
+ // A take starting 3s along the ruler, 5s into its file: its source 6 is raw 4.
+ const placement = { id: "p", assetId: "a", sourceStartSec: 5, timelineStartSec: 3 };
+ expect(placementRawSec(placement, 6)).toBe(4);
+ });
+
+ it("contributes no placement for a looping take", () => {
+ // `anchorAudioTrackFragments` does not advance `offsetMs` under loop, so a looping
+ // take's later fragments map their words to raw moments the words do not occupy.
+ expect(voiceoverPlacements([{ ...VO, loop: true }])).toEqual([]);
+ expect(voiceoverPlacements([VO])).toHaveLength(1);
+ });
+});
diff --git a/src/lib/ai-edition/timeline/aggregated-transcript.test.ts b/src/lib/ai-edition/timeline/aggregated-transcript.test.ts
index adc70b6cb..1a62d7e4c 100644
--- a/src/lib/ai-edition/timeline/aggregated-transcript.test.ts
+++ b/src/lib/ai-edition/timeline/aggregated-transcript.test.ts
@@ -7,6 +7,7 @@ import {
findCueWordId,
isSilenceWord,
} from "./aggregated-transcript";
+import { removedRawSpans } from "./programme-time";
function makeClip(overrides: Partial<AxcutClip> = {}): AxcutClip {
return {
@@ -78,18 +79,23 @@ describe("buildClipSection", () => {
]);
const trim = makeTrim({ id: "trim_a", startSec: 1, endSec: 4 });
- const section = buildClipSection(clip, transcript, makeAsset(), [trim]);
+ const section = buildClipSection(
+ clip,
+ transcript,
+ makeAsset(),
+ removedRawSpans([clip], [trim]),
+ );
expect(section.words.map((cw) => cw.kept)).toEqual([true, false, false, false, true]);
- expect(section.words.map((cw) => cw.trimId)).toEqual([
- null,
- "trim_a",
- "trim_a",
- "trim_a",
- null,
+ expect(section.words.map((cw) => cw.trimIds)).toEqual([
+ [],
+ ["trim_a"],
+ ["trim_a"],
+ ["trim_a"],
+ [],
]);
expect(section.trimRuns).toHaveLength(1);
expect(section.trimRuns[0]).toMatchObject({
- trimId: "trim_a",
+ trimIds: ["trim_a"],
startWordIndex: 1,
endWordIndex: 3,
durationSec: 3,
@@ -111,15 +117,15 @@ describe("buildClipSection", () => {
makeTrim({ id: "trim_b", startSec: 3, endSec: 4 }),
];
- const section = buildClipSection(clip, transcript, makeAsset(), trims);
+ const section = buildClipSection(clip, transcript, makeAsset(), removedRawSpans([clip], trims));
expect(section.trimRuns).toHaveLength(2);
expect(section.trimRuns[0]).toMatchObject({
- trimId: "trim_a",
+ trimIds: ["trim_a"],
startWordIndex: 1,
endWordIndex: 1,
});
expect(section.trimRuns[1]).toMatchObject({
- trimId: "trim_b",
+ trimIds: ["trim_b"],
startWordIndex: 3,
endWordIndex: 3,
});
@@ -146,29 +152,31 @@ describe("buildClipSection", () => {
it("marks the words removed only in the clip the trim is anchored to", () => {
const trim = makeTrim({ id: "trim_c2", clipId: "clip_2", startSec: 1, endSec: 2 });
+ const clips = [clip1(), clip2()];
const sections = buildAggregatedSections(
- [clip1(), clip2()],
+ clips,
[makeTranscript(words())],
[makeAsset()],
- [trim],
+ removedRawSpans(clips, [trim]),
);
expect(sections[0].words.map((cw) => cw.kept)).toEqual([true, true, true]);
expect(sections[0].trimRuns).toHaveLength(0);
expect(sections[1].words.map((cw) => cw.kept)).toEqual([true, false, true]);
expect(sections[1].trimRuns).toHaveLength(1);
- expect(sections[1].trimRuns[0]).toMatchObject({ trimId: "trim_c2", startWordIndex: 1 });
+ expect(sections[1].trimRuns[0]).toMatchObject({ trimIds: ["trim_c2"], startWordIndex: 1 });
});
it("still marks both clips for a pre-v7 trim that names no clip", () => {
// Back-compat: an un-anchored row keeps the asset-wide meaning it had, so an
// existing document reads exactly as it did before the anchor was introduced.
const trim = makeTrim({ id: "trim_legacy", startSec: 1, endSec: 2 });
+ const clips = [clip1(), clip2()];
const sections = buildAggregatedSections(
- [clip1(), clip2()],
+ clips,
[makeTranscript(words())],
[makeAsset()],
- [trim],
+ removedRawSpans(clips, [trim]),
);
expect(sections[0].trimRuns).toHaveLength(1);
expect(sections[1].trimRuns).toHaveLength(1);
@@ -183,7 +191,12 @@ describe("buildClipSection", () => {
]);
const trim = makeTrim({ id: "trim_x", assetId: "asset_2", startSec: 0.5, endSec: 2.5 });
- const section = buildClipSection(clip, transcript, makeAsset(), [trim]);
+ const section = buildClipSection(
+ clip,
+ transcript,
+ makeAsset(),
+ removedRawSpans([clip], [trim]),
+ );
// Trailing gap 2s→3s is a silence — the different-asset trim doesn't
// cover any of the three entries, so all stay kept.
expect(section.words.map((cw) => cw.kept)).toEqual([true, true, true]);
@@ -201,7 +214,7 @@ describe("buildClipSection", () => {
// ponytail: the LLM (not the renderer) decides what is a filler. Every
// word renders as plain text in the right pane.
expect(section.words.map((cw) => cw.kept)).toEqual([true, true, true]);
- expect(section.words.map((cw) => cw.trimId)).toEqual([null, null, null]);
+ expect(section.words.map((cw) => cw.trimIds)).toEqual([[], [], []]);
});
it("returns an empty words list when the clip has no matching transcript", () => {
@@ -261,10 +274,15 @@ describe("silence gaps", () => {
]);
const trim = makeTrim({ id: "trim_silence", startSec: 1, endSec: 2 });
- const section = buildClipSection(clip, transcript, makeAsset(), [trim]);
+ const section = buildClipSection(
+ clip,
+ transcript,
+ makeAsset(),
+ removedRawSpans([clip], [trim]),
+ );
const silence = section.words.find((cw) => isSilenceWord(cw.word));
expect(silence?.kept).toBe(false);
- expect(silence?.trimId).toBe("trim_silence");
+ expect(silence?.trimIds).toEqual(["trim_silence"]);
});
});
@@ -323,114 +341,164 @@ describe("buildAggregatedSections", () => {
});
describe("findCueWordId", () => {
+ // Takes a RAW ruler second. It used to take a clip id plus a source second, which only
+ // the recording lane could ever produce — so the voiceover lane never highlighted a
+ // word at all. Raw time is the coordinate both lanes share, and it settles the
+ // duplicated-clip case the clip id was introduced for: two sections over one media
+ // have identical source ranges but different raw extents.
function makeSection(
clipId: string,
assetId: string,
wordTimes: Array<[string, number, number]>,
+ clipOverrides: Partial<AxcutClip> = {},
) {
return {
- clip: makeClip({ id: clipId, assetId, sourceStartSec: 0, sourceEndSec: 100 }),
+ clip: makeClip({
+ id: clipId,
+ assetId,
+ sourceStartSec: 0,
+ sourceEndSec: 100,
+ timelineStartSec: 0,
+ timelineEndSec: 100,
+ ...clipOverrides,
+ }),
asset: makeAsset({ id: assetId }),
transcript: null,
words: wordTimes.map(([id, start, end]) => ({
id: clipWordId(clipId, id),
word: { id, segmentId: "s1", startSec: start, endSec: end, text: id },
kept: true,
- trimId: null,
+ trimIds: [],
})),
trimRuns: [],
};
}
- it("returns null when cue is null", () => {
+ it("returns null when there is no playhead", () => {
const section = makeSection("c1", "asset_1", [["w1", 0, 1]]);
expect(findCueWordId([section], null)).toBeNull();
});
- it("returns null when no section matches the cue asset", () => {
- const section = makeSection("c1", "asset_1", [["w1", 0, 1]]);
- const cue = { assetId: "asset_2", sourceTimeSec: 0.5 };
- expect(findCueWordId([section], cue)).toBeNull();
+ it("returns null when the head is before every section", () => {
+ const section = makeSection("c1", "asset_1", [["w1", 0, 1]], {
+ timelineStartSec: 10,
+ timelineEndSec: 110,
+ });
+ expect(findCueWordId([section], 2)).toBeNull();
});
- it("returns the word containing the cue time", () => {
+ it("returns the word containing the head", () => {
const section = makeSection("c1", "asset_1", [
["w1", 0, 1],
["w2", 1, 2],
["w3", 2, 3],
]);
- expect(findCueWordId([section], { assetId: "asset_1", sourceTimeSec: 1.5 })).toBe("c1:w2");
+ expect(findCueWordId([section], 1.5)).toBe("c1:w2");
});
- it("returns the previous word when the cue is between two words", () => {
+ it("returns the previous word when the head is between two words", () => {
const section = makeSection("c1", "asset_1", [
["w1", 0, 1],
["w2", 2, 3],
]);
- expect(findCueWordId([section], { assetId: "asset_1", sourceTimeSec: 1.5 })).toBe("c1:w1");
+ expect(findCueWordId([section], 1.5)).toBe("c1:w1");
});
- it("returns the previous word when the cue is before the first word", () => {
+ it("returns null when the head is before the first word", () => {
const section = makeSection("c1", "asset_1", [
["w1", 5, 6],
["w2", 7, 8],
]);
- expect(findCueWordId([section], { assetId: "asset_1", sourceTimeSec: 0.5 })).toBeNull();
+ expect(findCueWordId([section], 0.5)).toBeNull();
});
- it("returns the last word when the cue is after the last word", () => {
+ it("returns the last word when the head is past the last word", () => {
const section = makeSection("c1", "asset_1", [
["w1", 0, 1],
["w2", 1, 2],
]);
- expect(findCueWordId([section], { assetId: "asset_1", sourceTimeSec: 99 })).toBe("c1:w2");
+ expect(findCueWordId([section], 99)).toBe("c1:w2");
+ });
+
+ it("reads the head through the section's own source clock", () => {
+ // A clip that starts 20s along the ruler and 5s into its media: raw 22 is source 7.
+ const section = makeSection("c1", "asset_1", [["w1", 6, 8]], {
+ sourceStartSec: 5,
+ sourceEndSec: 15,
+ timelineStartSec: 20,
+ timelineEndSec: 30,
+ });
+ expect(findCueWordId([section], 22)).toBe("c1:w1");
+ expect(findCueWordId([section], 2)).toBeNull();
});
// Two clips over the same media project the SAME transcript words twice, so the cue
- // has to be resolved against the clip that is actually playing. Matching on assetId
- // alone always returned the first section — the highlight tracked clip 1 forever.
+ // has to be resolved against the one that is actually playing.
describe("two clips over the same media", () => {
const sections = () => [
- makeSection("c1", "asset_1", [
- ["w1", 0, 1],
- ["w2", 1, 2],
- ]),
- makeSection("c2", "asset_1", [
- ["w1", 0, 1],
- ["w2", 1, 2],
- ]),
+ makeSection(
+ "c1",
+ "asset_1",
+ [
+ ["w1", 0, 1],
+ ["w2", 1, 2],
+ ],
+ { sourceEndSec: 3, timelineStartSec: 0, timelineEndSec: 3 },
+ ),
+ makeSection(
+ "c2",
+ "asset_1",
+ [
+ ["w1", 0, 1],
+ ["w2", 1, 2],
+ ],
+ { sourceEndSec: 3, timelineStartSec: 3, timelineEndSec: 6 },
+ ),
];
- it("resolves the cue against the clip that is playing", () => {
- expect(
- findCueWordId(sections(), { assetId: "asset_1", clipId: "c2", sourceTimeSec: 1.5 }),
- ).toBe("c2:w2");
- expect(
- findCueWordId(sections(), { assetId: "asset_1", clipId: "c1", sourceTimeSec: 1.5 }),
- ).toBe("c1:w2");
+ it("resolves the head against the clip that is playing", () => {
+ // Source 1.5 in both, but raw 4.5 is only inside c2.
+ expect(findCueWordId(sections(), 4.5)).toBe("c2:w2");
+ expect(findCueWordId(sections(), 1.5)).toBe("c1:w2");
});
it("returns an id that cannot match the other clip's copy of the same word", () => {
- const cue = findCueWordId(sections(), {
- assetId: "asset_1",
- clipId: "c2",
- sourceTimeSec: 1.5,
- });
+ const cue = findCueWordId(sections(), 4.5);
// The whole point: `word.id` is "w2" in BOTH sections, so a bare word id lit up
// both blocks. Exactly one rendered word may claim the cue.
const claiming = sections().flatMap((s) => s.words.filter((cw) => cw.id === cue));
expect(claiming).toHaveLength(1);
});
- it("falls back to the asset when the caller names no clip", () => {
- expect(findCueWordId(sections(), { assetId: "asset_1", sourceTimeSec: 1.5 })).toBe("c1:w2");
+ it("returns null rather than another clip's words when the playing clip has none", () => {
+ const withEmptyC2 = [
+ sections()[0],
+ makeSection("c2", "asset_1", [], {
+ sourceEndSec: 3,
+ timelineStartSec: 3,
+ timelineEndSec: 6,
+ }),
+ ];
+ // c2 has no words, and borrowing c1's would point at the wrong text.
+ expect(findCueWordId(withEmptyC2, 4.5)).toBeNull();
});
- it("returns null rather than another clip's words when the playing clip has none", () => {
- const withEmptyC2 = [sections()[0], makeSection("c2", "asset_1", [])];
- expect(
- findCueWordId(withEmptyC2, { assetId: "asset_1", clipId: "c2", sourceTimeSec: 1.5 }),
- ).toBeNull();
+ it("runs an open-ended placement up to the next one", () => {
+ // An unprobed clip has no raw extent of its own; it ends where the next begins.
+ const open = [
+ makeSection("c1", "asset_1", [["w1", 0, 1]], {
+ sourceEndSec: undefined,
+ timelineStartSec: 0,
+ timelineEndSec: 3,
+ }),
+ makeSection("c2", "asset_1", [["w1", 0, 1]], {
+ sourceEndSec: 3,
+ timelineStartSec: 3,
+ timelineEndSec: 6,
+ }),
+ ];
+ expect(findCueWordId(open, 2)).toBe("c1:w1");
+ expect(findCueWordId(open, 3.5)).toBe("c2:w1");
});
});
});
diff --git a/src/lib/ai-edition/timeline/aggregated-transcript.ts b/src/lib/ai-edition/timeline/aggregated-transcript.ts
index 9b59f2bd6..9ecc0d5b5 100644
--- a/src/lib/ai-edition/timeline/aggregated-transcript.ts
+++ b/src/lib/ai-edition/timeline/aggregated-transcript.ts
@@ -14,15 +14,8 @@
// names a word a filler. The transcript view shows plain text for every
// kept word; the user or the LLM decides what to mark as skipped.
-import type {
- AxcutAsset,
- AxcutAudioTrack,
- AxcutClip,
- AxcutTranscript,
- AxcutTrimRange,
- AxcutWord,
-} from "../schema";
-import { trimAppliesToClip } from "./trim-mapping";
+import type { AxcutAsset, AxcutAudioTrack, AxcutClip, AxcutTranscript, AxcutWord } from "../schema";
+import { type RawSpan, type RemovedRawSpan, removalAt } from "./programme-time";
/**
* The unit the aggregation actually runs over: one stretch of ONE asset's source
@@ -53,6 +46,26 @@ export interface TranscriptPlacement {
/** Which lane's speech the transcript tab is reading. */
export type TranscriptLane = "recording" | "voiceover";
+/**
+ * A source second of this placement's asset, as a moment on the RAW ruler.
+ *
+ * The one coordinate both lanes share. Source time is per asset, so it cannot say
+ * whether two things coincide; raw time can, which is why kept-or-removed is asked here
+ * and not in source time (issue #560).
+ */
+export function placementRawSec(placement: TranscriptPlacement, sourceSec: number): number {
+ return placement.timelineStartSec + (sourceSec - placement.sourceStartSec);
+}
+
+/** The placement's own stretch of raw ruler, or null when it runs open-ended. */
+export function placementRawExtent(placement: TranscriptPlacement): RawSpan | null {
+ if (placement.sourceEndSec === undefined) return null;
+ return {
+ startSec: placement.timelineStartSec,
+ endSec: placementRawSec(placement, placement.sourceEndSec),
+ };
+}
+
/** Gaps between words at least this long are surfaced as a `[silence]` token. */
export const SILENCE_THRESHOLD_SEC = 0.2;
@@ -116,8 +129,13 @@ function withSilenceGaps(
/** A contiguous run of removed words inside one clip's source range. */
export interface TrimRun {
- /** Id of the trim range this run came from (used by the bin-icon restore). */
- trimId: string;
+ /**
+ * The trims that took this run — SEVERAL when they overlap, and EMPTY when the run
+ * sits in a gap between clips, which is missing from the film without anything having
+ * removed it. A restore affordance must be keyed on this being non-empty: there is no
+ * pill to click for a gap.
+ */
+ trimIds: string[];
/** Index of the first removed word in `words`. */
startWordIndex: number;
/** Inclusive index of the last removed word in `words`. */
@@ -148,10 +166,10 @@ export interface ClipWord {
/** {@link clipWordId} — the word's identity *in this clip*, unique across the pane. */
id: string;
word: AxcutWord;
- /** Whether the word is inside a trimRange for this clip's asset. */
+ /** Whether the raw moment this word occupies is still in the film. */
kept: boolean;
- /** Id of the trim range that removed this word, if any. */
- trimId: string | null;
+ /** The trims that took it — empty when kept, and empty for a word over a gap. */
+ trimIds: string[];
}
/** One placement's contribution to the aggregated flow. */
@@ -176,37 +194,25 @@ function wordsInRange(transcript: AxcutTranscript, startSec: number, endSec: num
);
}
-/** Find the trim range covering this word's center (returns the deepest match). */
-function findCoveringTrim(word: AxcutWord, trimRanges: AxcutTrimRange[]): AxcutTrimRange | null {
- const center = (word.startSec + word.endSec) / 2;
- for (const trim of trimRanges) {
- if (center >= trim.startSec && center <= trim.endSec) return trim;
- }
- return null;
-}
-
/**
- * Build one clip section. Words inside the clip's source range that fall
- * inside any trim range for the same asset are marked removed; the rest
- * are kept. Contiguous removed words from the same trim range group into
- * one `TrimRun` (for the trim-duration pill + bin-icon restore).
+ * Build one placement's section. A word is removed when the RAW moment it occupies is not
+ * in the film; the rest are kept. Contiguous removed words taken by the same trims group
+ * into one `TrimRun` (for the trim-duration pill + bin-icon restore).
+ *
+ * Takes the precomputed removed set, not the trim rows. Filtering rows by identity —
+ * `trimAppliesToClip`, which is what this did — is a question a voiceover placement can
+ * never answer yes to: it carries an audio fragment id and an audio asset, while every
+ * trim carries a video clip. That is what left the voiceover lane reading every word as
+ * kept over film that had been cut away (issue #560). Asking the ruler instead makes both
+ * lanes agree by construction, and keeps the recording lane's answers identical: the same
+ * per-clip walk decides both.
*/
export function buildClipSection(
clip: TranscriptPlacement,
transcript: AxcutTranscript | null,
asset: AxcutAsset | null,
- trimRanges: AxcutTrimRange[],
+ removed: RemovedRawSpan[],
): ClipSection {
- // `trimAppliesToClip` — not a bare `assetId` match — is what keeps a cut on the
- // second of two clips over the same media from also greying out the first one's
- // words. Same media, same source range: only the clip anchor tells them apart.
- const clipTrims = trimRanges.filter(
- (trim) =>
- trimAppliesToClip(trim, clip) &&
- trim.endSec > clip.sourceStartSec &&
- trim.startSec < (clip.sourceEndSec ?? Infinity),
- );
-
const words = transcript
? withSilenceGaps(
wordsInRange(transcript, clip.sourceStartSec, clip.sourceEndSec ?? Infinity),
@@ -215,25 +221,27 @@ export function buildClipSection(
)
: [];
const tagged: ClipWord[] = words.map((word) => {
- const covering = findCoveringTrim(word, clipTrims);
+ // The word's CENTRE, mirroring the rule the identity filter used, so the recording
+ // lane's tagging does not shift under this change.
+ const covering = removalAt(removed, placementRawSec(clip, (word.startSec + word.endSec) / 2));
return {
id: clipWordId(clip.id, word.id),
word,
kept: covering === null,
- trimId: covering?.id ?? null,
+ trimIds: covering?.trimIds ?? [],
};
});
const trimRuns: TrimRun[] = [];
let runStart = -1;
let runEnd = -1;
- let runTrimId = "";
+ let runTrimIds: string[] = [];
let runMinStart = 0;
let runMaxEnd = 0;
const flush = () => {
if (runStart >= 0) {
trimRuns.push({
- trimId: runTrimId,
+ trimIds: runTrimIds,
assetId: clip.assetId,
startWordIndex: runStart,
endWordIndex: runEnd,
@@ -242,23 +250,26 @@ export function buildClipSection(
}
runStart = -1;
runEnd = -1;
- runTrimId = "";
+ runTrimIds = [];
runMinStart = 0;
runMaxEnd = 0;
};
+ const key = (ids: string[]) => ids.join("|");
tagged.forEach((cw, i) => {
if (cw.kept) {
flush();
return;
}
- // Split the run if the trim range id changes (overlapping trims).
- if (runStart >= 0 && cw.trimId !== runTrimId) {
+ // Split the run when the SET of trims changes, so two cuts meeting at a word
+ // boundary stay two pills. A run whose set is empty is a gap between clips: still
+ // removed, still one run, but with nothing to restore.
+ if (runStart >= 0 && key(cw.trimIds) !== key(runTrimIds)) {
flush();
}
if (runStart < 0) {
runStart = i;
runMinStart = cw.word.startSec;
- runTrimId = cw.trimId ?? "";
+ runTrimIds = cw.trimIds;
}
runEnd = i;
runMaxEnd = Math.max(runMaxEnd, cw.word.endSec);
@@ -277,7 +288,7 @@ export function buildAggregatedSections(
clips: TranscriptPlacement[],
transcripts: AxcutTranscript[],
assets: AxcutAsset[],
- trimRanges: AxcutTrimRange[],
+ removed: RemovedRawSpan[],
): ClipSection[] {
const transcriptById = new Map(transcripts.map((t) => [t.assetId, t]));
const assetById = new Map(assets.map((a) => [a.id, a]));
@@ -286,7 +297,7 @@ export function buildAggregatedSections(
clip,
transcriptById.get(clip.assetId) ?? null,
assetById.get(clip.assetId) ?? null,
- trimRanges,
+ removed,
),
);
}
@@ -304,13 +315,14 @@ export function buildAggregatedSections(
* already carry exactly the source windows this needs, and collapsing them back
* into one pill here would re-read the file from its head at every cut.
*
- * `loop` is ignored on purpose. A looping voiceover would repeat its words, and a
- * transcript that says the same sentence three times is not a transcript of
- * anything — the source window is what was said, however many times it plays.
+ * A LOOPING take contributes nothing at all. `anchorAudioTrackFragments` deliberately
+ * does not advance `offsetMs` across the fragments of a looping track, so their words map
+ * to raw moments the words do not occupy — a placement built from them would read
+ * kept-or-removed on false evidence, and would author a cut in the wrong place.
*/
export function voiceoverPlacements(audioTracks: AxcutAudioTrack[]): TranscriptPlacement[] {
return audioTracks
- .filter((track) => track.kind === "voiceover")
+ .filter((track) => track.kind === "voiceover" && !track.loop)
.slice()
.sort((a, b) => a.startMs - b.startMs || a.id.localeCompare(b.id))
.map((track) => {
@@ -334,16 +346,6 @@ export function lanePlacements(
return lane === "voiceover" ? voiceoverPlacements(audioTracks) : clips;
}
-/** Where the playback head currently is, in source time. */
-export interface CuePosition {
- assetId: string;
- /** Which clip is playing — the primary selector for the cue's section. Source time is
- * per asset, so `assetId` cannot separate two clips over one media; pass this whenever
- * the caller knows it (the transcript pane always does). */
- clipId?: string;
- sourceTimeSec: number;
-}
-
/**
* Find the word in `sections` that the playback head is currently inside, as a
* {@link clipWordId} — NOT a bare `word.id`, which would name the same moment in every
@@ -356,22 +358,39 @@ export interface CuePosition {
* - Silence tokens (id starts with `silence_`) are skipped over so a
* long pause doesn't surface a fake cue word.
*
- * The section is chosen by `cue.clipId` when the caller knows which clip is playing.
- * Matching on `assetId` alone always resolved to the FIRST section of that asset, so with
- * a clip duplicated on the timeline the cue tracked clip 1 while clip 2 played. `assetId`
- * stays as the fallback for callers that have no clip in hand.
+ * Takes a RAW ruler second. It used to take a clip id resolved from the playhead, which
+ * only ever named a video clip — so the voiceover lane never highlighted anything at all.
+ * Raw time is what both lanes have in common, and it also settles the case the clip id was
+ * introduced for: with one clip duplicated on the timeline, the two sections occupy
+ * different raw extents even though their source ranges are identical.
+ *
+ * The section is the one whose raw extent contains the head. An open-ended placement (a
+ * clip whose media has not been probed) has no extent of its own and runs to the next
+ * section's head, then to the end of time.
*/
-export function findCueWordId(sections: ClipSection[], cue: CuePosition | null): string | null {
- if (!cue) return null;
- const withWords = sections.filter((s) => s.words.length > 0);
- // No fallback when `clipId` is given but that clip has no transcript: the playing clip
- // simply has no cue word, and borrowing another clip's would point at the wrong text.
- const match = cue.clipId
- ? withWords.find((s) => s.clip.id === cue.clipId)
- : withWords.find((s) => s.clip.assetId === cue.assetId);
+export function findCueWordId(sections: ClipSection[], rawSec: number | null): string | null {
+ if (rawSec === null || !Number.isFinite(rawSec)) return null;
+ // No fallback to a neighbouring section: a placement with no transcript simply has no
+ // cue word, and borrowing another's would point at the wrong text.
+ const withWords = sections
+ .filter((s) => s.words.length > 0)
+ .sort((a, b) => a.clip.timelineStartSec - b.clip.timelineStartSec);
+
+ let match: ClipSection | null = null;
+ for (const [i, section] of withWords.entries()) {
+ if (rawSec < section.clip.timelineStartSec) break;
+ const extent = placementRawExtent(section.clip);
+ const endSec =
+ extent?.endSec ?? withWords[i + 1]?.clip.timelineStartSec ?? Number.POSITIVE_INFINITY;
+ if (rawSec < endSec) {
+ match = section;
+ break;
+ }
+ }
if (!match) return null;
- const t = cue.sourceTimeSec;
+ // Back to the placement's own source clock, which is what the words are stamped in.
+ const t = match.clip.sourceStartSec + (rawSec - match.clip.timelineStartSec);
let previous: string | null = null;
for (const cw of match.words) {
if (isSilenceWord(cw.word)) continue;
diff --git a/src/lib/ai-edition/timeline/sharedMediaTrim.test.ts b/src/lib/ai-edition/timeline/sharedMediaTrim.test.ts
index 2789dd5e5..5bbe7ac44 100644
--- a/src/lib/ai-edition/timeline/sharedMediaTrim.test.ts
+++ b/src/lib/ai-edition/timeline/sharedMediaTrim.test.ts
@@ -12,6 +12,7 @@ import { applyTimelineOperation } from "@/lib/ai-edition/document/operations";
import { resolvePlaybackSegments } from "@/lib/ai-edition/document/timeline";
import { type AxcutDocument, createEmptyDocument } from "@/lib/ai-edition/schema";
import { buildAggregatedSections } from "@/lib/ai-edition/timeline/aggregated-transcript";
+import { removedRawSpans } from "@/lib/ai-edition/timeline/programme-time";
import { coalescedTrimGroups } from "@/lib/ai-edition/timeline/trim-mapping";
function doc(): AxcutDocument {
@@ -73,7 +74,7 @@ describe("repro: trim on clip 2 of two clips sharing one media", () => {
next.timeline.clips,
next.transcripts,
next.assets,
- next.timeline.trimRanges,
+ removedRawSpans(next.timeline.clips, next.timeline.trimRanges),
);
expect(sections[0].trimRuns).toHaveLength(0);
expect(sections[1].trimRuns).toHaveLength(1);