Skip to content

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

refactor(timeline): one clock — an insertion is media, so the clip is longer

EtienneLescot156b87b6718c
diff --git a/src/components/ai-edition/NativeCompositorOverlay.tsx b/src/components/ai-edition/NativeCompositorOverlay.tsx
index e4af64102..18b63f72e 100644
--- a/src/components/ai-edition/NativeCompositorOverlay.tsx
+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx
@@ -74,7 +74,13 @@ export function NativeCompositorOverlay() {
return resolveVisibleClips(document);
}, [document]);
const activePosition = useMemo(
- () => resolveNativePosition(currentTimeSec, nativeClips, document?.timeline.clips ?? []),
+ () =>
+ resolveNativePosition(
+ currentTimeSec,
+ nativeClips,
+ document?.timeline.clips ?? [],
+ document?.timeline.insertRanges ?? [],
+ ),
[nativeClips, currentTimeSec, document],
);
const activeClip = activePosition?.clip ?? null;
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index fdfcd1110..93c5c7eb4 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -21,7 +21,12 @@ import {
setDocumentWordText,
} from "@/lib/ai-edition/document/transcript";
import { isModalOpen } from "@/lib/ai-edition/modalGuard";
-import { type AxcutAudioTrack, type AxcutClip, documentSchema } from "@/lib/ai-edition/schema";
+import {
+ type AxcutAudioTrack,
+ type AxcutClip,
+ type AxcutInsertRange,
+ documentSchema,
+} from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import {
useAssetTranscriptions,
@@ -92,15 +97,17 @@ const NO_AUDIO_TRACKS: AxcutAudioTrack[] = [];
function NativePlaybackSync({
visibleClips,
clips,
+ insertRanges,
}: {
visibleClips: AxcutClip[];
clips: AxcutClip[];
+ insertRanges: readonly AxcutInsertRange[];
}) {
const playing = useProjectStore((s) => s.playing);
const currentTimeSec = useProjectStore((s) => s.currentTimeSec);
// visibleClips = trim-compressed native stream; `clips` = RAW layout currentTimeSec
// is measured against. resolveNativePosition needs both (see timelineMap).
- useNativePlaybackSync(playing, currentTimeSec, visibleClips, clips);
+ useNativePlaybackSync(playing, currentTimeSec, visibleClips, clips, insertRanges);
return null;
}
@@ -429,8 +436,8 @@ export function NewEditorShell() {
);
const handleTimeChange = useCallback(
- (timeSec: number, rulerSec?: number) => {
- setCurrentTime(timeSec, rulerSec);
+ (timeSec: number) => {
+ setCurrentTime(timeSec);
},
[setCurrentTime],
);
@@ -1428,7 +1435,11 @@ export function NewEditorShell() {
className={v4.app}
style={{ gridTemplateRows: `58px 1fr ${showTimeline ? timelineRow : "0px"}` }}
>
- <NativePlaybackSync visibleClips={visibleClips} clips={clips} />
+ <NativePlaybackSync
+ visibleClips={visibleClips}
+ clips={clips}
+ insertRanges={document?.timeline.insertRanges ?? []}
+ />
<EditorTopBar
mode={mode}
onModeChange={setMode}
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index 5661f0e64..a68d759d3 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -22,11 +22,7 @@ import type {
} from "@/lib/ai-edition/schema";
import { audioGainScalar } from "@/lib/ai-edition/store/editorSettings";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
-import {
- expandRawSec,
- insertionEnteredBetween,
- rulerInserts,
-} from "@/lib/ai-edition/timeline/inserted-time";
+import { insertionEnteredBetween, rulerInserts } from "@/lib/ai-edition/timeline/inserted-time";
import type { PlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock";
import { removedRawSpans } from "@/lib/ai-edition/timeline/programme-time";
import { findActiveSpeedRegion, type SpeedRegion } from "@/lib/ai-edition/timeline/speed";
@@ -222,9 +218,7 @@ interface VirtualPreviewProps {
/** The media added words inserted — it lengthens playback, it does not cut it. */
insertRanges?: AxcutInsertRange[];
seekTarget?: { timeSec: number; isSource?: boolean; requestId: number } | null;
- /** `rulerSec` is the same moment measured on the ruler the user sees, which differs
- * from `timeSec` as soon as an insertion sits before it, or under it. */
- onTimeChange?: (timeSec: number, rulerSec: number) => void;
+ onTimeChange?: (timeSec: number) => void;
onLoadedMetadata?: (
durationSec: number,
assetId: string,
@@ -591,6 +585,10 @@ export function VirtualPreview({
* `updateVirtualTime` so the RULER position it publishes crosses the insertion while the
* RAW second it publishes alongside stands still at the insertion's own moment. */
const insertionElapsedRef = useRef(0);
+ // The ranges themselves for anything that maps through a clip; their timeline positions
+ // for the one thing that asks "did this frame run into one".
+ const insertRangesRef = useRef(insertRanges);
+ insertRangesRef.current = insertRanges;
const filmInsertsRef = useRef(rulerInserts(insertRanges, clips));
filmInsertsRef.current = useMemo(() => rulerInserts(insertRanges, clips), [insertRanges, clips]);
// One walk per take, recomputed only when the cuts or the insertions move. The rAF asks
@@ -760,7 +758,7 @@ export function VirtualPreview({
clipsRef.current,
trimRangesRef.current,
virtualTimeSecRef.current,
- filmInsertsRef.current,
+ insertRangesRef.current,
speedRegionsRef.current,
) + insertionElapsedRef.current;
for (const track of audioTracksRef.current) {
@@ -770,7 +768,7 @@ export function VirtualPreview({
clipsRef.current,
trimRangesRef.current,
track.startMs / 1000,
- filmInsertsRef.current,
+ insertRangesRef.current,
speedRegionsRef.current,
);
// Length is measured WITHOUT speed, position WITH it. A trim REMOVES
@@ -785,13 +783,13 @@ export function VirtualPreview({
clipsRef.current,
trimRangesRef.current,
track.endMs / 1000,
- filmInsertsRef.current,
+ insertRangesRef.current,
) -
projectRawTimelineSecToPlayback(
clipsRef.current,
trimRangesRef.current,
track.startMs / 1000,
- filmInsertsRef.current,
+ insertRangesRef.current,
),
);
// A voiceover follows the cuts AND its own insertions, through one walk over
@@ -985,6 +983,7 @@ export function VirtualPreview({
activeSourceId,
0.05,
activeClipIdRef.current ?? undefined,
+ insertRangesRef.current,
);
if (pos) {
activeClipIdRef.current = pos.clip.id;
@@ -1055,7 +1054,10 @@ export function VirtualPreview({
updateVirtualTime(entering.atRawSec);
return;
}
- updateVirtualTime(nextRawTime);
+ // While an insertion plays the element is parked, so the position it reports stands
+ // still at where the insertion opens. Its own wall clock is what carries the
+ // playhead across it — nothing else is moving. Zero the rest of the time.
+ updateVirtualTime(nextRawTime + insertionElapsedRef.current);
};
raf = window.requestAnimationFrame(tick);
return () => window.cancelAnimationFrame(raf);
@@ -1076,14 +1078,7 @@ export function VirtualPreview({
const updateVirtualTime = useCallback(
(nextTimeSec: number) => {
setVirtualTimeSec(nextTimeSec);
- // Two coordinates, one publish. The raw second says where the RECORDING is; the
- // ruler second says where on the timeline the playhead is, which is the only one
- // that can move while an insertion plays — the recording is standing still at the
- // insertion's moment for its whole duration.
- onTimeChange?.(
- nextTimeSec,
- expandRawSec(nextTimeSec, filmInsertsRef.current) + insertionElapsedRef.current,
- );
+ onTimeChange?.(nextTimeSec);
// ponytail: mirrors main's per-frame `video.playbackRate = ...`
// (videoEventHandlers.ts) — the browser does the actual time
// warping, so this is the only thing speed regions need. No
@@ -1166,7 +1161,7 @@ export function VirtualPreview({
// advance, trim skip) are gated on `!v.paused` and so never land here mid-insertion.
insertionRef.current = null;
insertionElapsedRef.current = 0;
- const position = locateVirtualPosition(clips, nextVirtualTimeSec);
+ const position = locateVirtualPosition(clips, nextVirtualTimeSec, insertRanges);
if (!position) {
videoRef.current?.pause();
updateVirtualTime(0);
@@ -1273,7 +1268,11 @@ export function VirtualPreview({
// the one that has to come back. An asset switch queued in the
// meantime is newer intent still, so it wins outright.
if (!pendingSeekRef.current) {
- const position = locateVirtualPosition(clipsRef.current, virtualTimeSecRef.current);
+ const position = locateVirtualPosition(
+ clipsRef.current,
+ virtualTimeSecRef.current,
+ insertRangesRef.current,
+ );
// `locateVirtualPosition` answers for whatever clip the playhead
// is on, which after a boundary advance can belong to a DIFFERENT
// asset — its source time would be a meaningless offset into the
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index b97f24ab7..ef487f931 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -51,13 +51,9 @@ import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";
import { hasAnyClipWithCamera } from "@/lib/ai-edition/timeline/camera";
import { formatSec } from "@/lib/ai-edition/timeline/format";
import {
- collapseRawSec,
- expandRawSec,
type InsertedWordMark,
insertedWordMarks,
- type RulerInsert,
rulerInserts,
- totalInsertedSec,
} from "@/lib/ai-edition/timeline/inserted-time";
import {
newRegionDurationSec,
@@ -230,15 +226,8 @@ interface RulerTick {
interface PlayheadOverlayProps {
/** Full timeline length in seconds — the denominator for the playhead's percentage. */
totalSec: number;
- /** The media added words inserted. `currentTimeSec` is a STORED second; the ruler it is
- * drawn on counts the insertions, so it has to be placed through them or it drifts from
- * the clips by the whole added time. */
- inserts: readonly RulerInsert[];
/** Live scrub position in RAW seconds, when a drag is in flight. */
overrideTimeSec: number | null;
- /** The same drag's RULER position. Preferred when present: it is the only coordinate
- * that can name a moment INSIDE an insertion, which is zero raw seconds wide. */
- overrideRulerSec: number | null;
canvasStyle: React.CSSProperties;
onPointerDown: (e: ReactPointerEvent) => void;
playheadRef?: React.MutableRefObject<HTMLDivElement | null>;
@@ -262,35 +251,13 @@ interface PlayheadOverlayProps {
*/
const PlayheadOverlay = memo(function PlayheadOverlay({
totalSec,
- inserts,
overrideTimeSec,
- overrideRulerSec,
canvasStyle,
onPointerDown,
playheadRef,
}: PlayheadOverlayProps) {
const storeTimeSec = useProjectStore((s) => s.currentTimeSec);
- const storeRulerSec = useProjectStore((s) => s.currentRulerSec);
- // The ruler position, from the most trustworthy source that has one.
- //
- // The raw second alone cannot draw this playhead: an insertion occupies ruler seconds
- // and none of the recording, so every ruler second inside one collapses to the same raw
- // moment and expanding it back puts the playhead on the insertion's near edge — where it
- // visibly stalls through playback, and where it snaps back to after a scrub released over
- // one (issue #560).
- //
- // The store's ruler second is trusted only when it still AGREES with the raw one: a
- // caller that predates insertions writes the raw value for both, which is right until an
- // insertion sits before it. Collapsing is the test, and expanding is the fallback.
- const storeSec =
- Math.abs(collapseRawSec(storeRulerSec, inserts).sec - storeTimeSec) < 1e-3
- ? storeRulerSec
- : expandRawSec(storeTimeSec, inserts);
- const pct =
- ((overrideRulerSec ??
- (overrideTimeSec !== null ? expandRawSec(overrideTimeSec, inserts) : storeSec)) /
- totalSec) *
- 100;
+ const pct = (((overrideTimeSec ?? storeTimeSec) / totalSec) * 100) as number;
return (
<div className={styles.tlPlayheadLayer} aria-hidden>
<div className={styles.tlCanvas} style={canvasStyle}>
@@ -629,9 +596,7 @@ export function V4Timeline({
onAddVoiceover,
}: {
tl: TimelineApi;
- /** `rulerSec` is the same moment on the ruler the user sees; it differs from `sec` as
- * soon as an insertion sits before it, or under it. */
- setCurrentTime: (sec: number, rulerSec?: number) => void;
+ setCurrentTime: (sec: number) => void;
variant?: "edit" | "media";
onDropAsset?: (assetId: string) => Promise<void>;
videoSources?: VideoSource[];
@@ -732,13 +697,11 @@ export function V4Timeline({
() =>
Math.max(
1,
- clips.reduce((m, c) => Math.max(m, c.timelineEndSec), 0) + totalInsertedSec(inserts),
+ clips.reduce((m, c) => Math.max(m, c.timelineEndSec), 0),
),
[clips, inserts],
);
const pctOf = useCallback((sec: number) => (sec / total) * 100, [total]);
- /** Stored raw seconds → a percentage of the expanded ruler. */
- const pctAt = useCallback((sec: number) => pctOf(expandRawSec(sec, inserts)), [pctOf, inserts]);
const showLanes = variant === "edit";
// The visible fraction of the timeline, and what one second is worth on screen
@@ -857,14 +820,8 @@ export function V4Timeline({
// pointer for the frame the store hasn't caught up on yet. Handed down as an
// override to the two components that read the playhead from the store.
const [scrubbingTimeSec, setScrubbingTimeSec] = useState<number | null>(null);
- // The pointer's RULER position while scrubbing, kept apart from the raw one above.
- // Two numbers because they mean different things: the timecode reads the raw clock,
- // like the store, and the playhead has to be able to sit INSIDE an insertion — which
- // takes up none of the recording, so no raw value can address a moment within it.
- const [scrubRulerSec, setScrubRulerSec] = useState<number | null>(null);
const rafSeekRef = useRef<number>(0);
const pendingSeekTimeRef = useRef<number | null>(null);
- const pendingSeekRulerRef = useRef<number | null>(null);
// ── interactions ────────────────────────────────────────────────
const playheadElRef = useRef<HTMLDivElement | null>(null);
@@ -886,13 +843,7 @@ export function V4Timeline({
// supposed to be pointing at, which is what showed as the wrong subtitle under a
// correctly-placed playhead (issue #560).
//
- // Collapsing lands on the insertion's own moment when the pointer is inside one,
- // which is the honest answer: an insertion takes up none of the recording, so
- // there is no raw value inside it to seek the media to. The ruler position goes
- // to the store ALONGSIDE it, which is what lets the playhead stay where it was
- // released instead of snapping to the insertion's near edge.
- const rulerTime = pct * total;
- const { sec: targetTime } = collapseRawSec(rulerTime, inserts);
+ const targetTime = pct * total;
// Direct DOM playhead update (0ms latency, zero React re-render overhead)
if (playheadElRef.current) {
@@ -901,16 +852,14 @@ export function V4Timeline({
// Optimistic local UI state update
setScrubbingTimeSec(targetTime);
- setScrubRulerSec(rulerTime);
pendingSeekTimeRef.current = targetTime;
- pendingSeekRulerRef.current = rulerTime;
if (isImmediate) {
if (rafSeekRef.current !== 0) {
cancelAnimationFrame(rafSeekRef.current);
rafSeekRef.current = 0;
}
- setCurrentTime(targetTime, rulerTime);
+ setCurrentTime(targetTime);
return;
}
@@ -919,7 +868,7 @@ export function V4Timeline({
rafSeekRef.current = requestAnimationFrame(() => {
rafSeekRef.current = 0;
if (pendingSeekTimeRef.current !== null) {
- setCurrentTime(pendingSeekTimeRef.current, pendingSeekRulerRef.current ?? undefined);
+ setCurrentTime(pendingSeekTimeRef.current);
}
});
}
@@ -960,15 +909,10 @@ export function V4Timeline({
rafSeekRef.current = 0;
}
if (pendingSeekTimeRef.current !== null) {
- // The RULER second goes with it, or releasing over an insertion drops the
- // only coordinate that could name where the pointer was: the raw second
- // alone lands on the insertion's near edge, which is the snap-back.
- setCurrentTime(pendingSeekTimeRef.current, pendingSeekRulerRef.current ?? undefined);
+ setCurrentTime(pendingSeekTimeRef.current);
pendingSeekTimeRef.current = null;
- pendingSeekRulerRef.current = null;
}
setScrubbingTimeSec(null);
- setScrubRulerSec(null);
};
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
@@ -1750,10 +1694,10 @@ export function V4Timeline({
compact ? ` ${styles.lanePillCompact}` : ""
}${seg.interactive && isPillSelected(p.id) ? ` ${styles.lanePillSel}` : ""}`}
style={{
- left: `${pctAt(seg.segStart)}%`,
+ left: `${pctOf(seg.segStart)}%`,
// Measured on the expanded ruler at BOTH ends: a region straddling an insertion
// covers it, so its box has to grow by that insertion and not merely slide.
- width: `${pctOf(expandRawSec(seg.segEnd, inserts) - expandRawSec(seg.segStart, inserts))}%`,
+ width: `${pctOf(seg.segEnd - seg.segStart)}%`,
transform: seg.shiftPx ? `translateX(${seg.shiftPx}px)` : undefined,
transition: !clipDrag
? undefined
@@ -2164,7 +2108,7 @@ export function V4Timeline({
<div
key={tick.sec}
className={`${styles.tlTick}${tick.major ? ` ${styles.tlTickMajor}` : ""}`}
- style={{ left: `${pctAt(tick.sec)}%` }}
+ style={{ left: `${pctOf(tick.sec)}%` }}
>
{tick.major ? (
<span className={styles.tlTickLabel}>{fmtTick(tick.sec, rulerTicks.step)}</span>
@@ -2254,7 +2198,7 @@ export function V4Timeline({
// ruler and the audio pills were drawn on the stored one, so any
// insertion in the film slid the two lanes apart. The take keeps its
// own length — only its head follows the ruler.
- leftPct={pctAt(start)}
+ leftPct={pctOf(start)}
widthPct={pctOf(widthSec)}
row={audioRows.rowOf.get(track.id) ?? 0}
rowHeight={AUDIO_ROW_HEIGHT_PX + AUDIO_ROW_GAP_PX}
@@ -2319,8 +2263,8 @@ export function V4Timeline({
// On the expanded ruler the box also carries whatever insertions fall
// inside it — the film really does stay on this clip's frame for
// them, so they belong to its box rather than between boxes.
- const boxStart = expandRawSec(c.timelineStartSec, inserts);
- const boxEnd = expandRawSec(c.timelineEndSec, inserts);
+ const boxStart = c.timelineStartSec;
+ const boxEnd = c.timelineEndSec;
const boxLen = boxEnd - boxStart;
const asset = tl.assets.find((a) => a.id === c.assetId);
const clipVideoUrl = videoSources.find((v) => v.id === c.assetId)?.src;
@@ -2407,7 +2351,7 @@ export function V4Timeline({
// SOURCE span, in the same ternary — two clocks, one of which the
// box is not drawn in.
const inserted = inserts.find((ins) => ins.wordId === wordId);
- const left = ((expandRawSec(atRawSec, inserts) - boxStart) / boxLen) * 100;
+ const left = ((atRawSec - boxStart) / boxLen) * 100;
const width = inserted ? (inserted.durationSec / boxLen) * 100 : 0;
return (
<button
@@ -2469,9 +2413,7 @@ export function V4Timeline({
{showLanes ? (
<PlayheadOverlay
totalSec={total}
- inserts={inserts}
overrideTimeSec={scrubbingTimeSec}
- overrideRulerSec={scrubRulerSec}
canvasStyle={canvasStyle}
onPointerDown={startScrub}
playheadRef={playheadElRef}
diff --git a/src/lib/ai-edition/captions/captionLane.test.ts b/src/lib/ai-edition/captions/captionLane.test.ts
index 87d7520f8..776578709 100644
--- a/src/lib/ai-edition/captions/captionLane.test.ts
+++ b/src/lib/ai-edition/captions/captionLane.test.ts
@@ -142,9 +142,11 @@ describe("captionLane", () => {
expect(texts(corrected, "voiceover")).toContain("Kubernetes words");
});
- it("measures a pause against the FILM, on either lane", () => {
- // A pause is a held CLIP frame. Measuring it against the take instead would land
- // every voiceover cue early — so the inserts stay clips-derived on both lanes.
+ it("leaves a take's cues alone when the FILM gains an insertion", () => {
+ // An insertion is media inside the clip that carries it, and it lengthens that clip.
+ // A take laid over the film keeps its own position on the timeline — the picture
+ // slides underneath it — so its cues do not move either. Measured per placement,
+ // through the asset the placement actually plays.
const paused = doc({
timeline: {
...doc().timeline,
@@ -164,11 +166,9 @@ describe("captionLane", () => {
});
const before = deriveCaptionCues(doc(), on("voiceover"), {});
const after = deriveCaptionCues(paused, on("voiceover"), {});
- // The line covers the held moment, so its END is pushed out by the second the film
- // gained and it stays on screen through the pause. That it moves AT ALL is the
- // point: the insert names the recording's asset, so a placement-derived ruler
- // would have found nothing to apply and left the voiceover cue where it was.
- expect(after[0].endMs - before[0].endMs).toBeCloseTo(1000, 0);
+ // The insertion names the RECORDING's asset. The take is a different asset laid at
+ // its own timeline position, so nothing about this cue changes.
expect(after[0].startMs).toBe(before[0].startMs);
+ expect(after[0].endMs).toBe(before[0].endMs);
});
});
diff --git a/src/lib/ai-edition/captions/cues.ts b/src/lib/ai-edition/captions/cues.ts
index 78fd9250f..553f1b856 100644
--- a/src/lib/ai-edition/captions/cues.ts
+++ b/src/lib/ai-edition/captions/cues.ts
@@ -22,10 +22,10 @@ import {
splitMergedCaptionsByWordBounds,
} from "@/lib/captioning/annotationsFromCaptions";
import type { CaptionSegment } from "@/lib/captioning/transcribe";
-import type { AxcutDocument, AxcutTranscript } from "../schema";
+import type { AxcutDocument, AxcutInsertRange, AxcutTranscript } from "../schema";
import { lanePlacements, type TranscriptPlacement } from "../timeline/aggregated-transcript";
import { takeInserts } from "../timeline/insert-mapping";
-import { expandRawSec, type RulerInsert, rulerInserts } from "../timeline/inserted-time";
+import { sourceToTimelineSec } from "../timeline/inserted-time";
import { removedRawSpans } from "../timeline/programme-time";
import {
type CaptionAnchorV,
@@ -165,7 +165,7 @@ export function sourceSpanToTimelineSpans(
* window and the ruler head, which both providers carry (issue #560). `AxcutClip`
* stays structurally assignable, so every existing caller is unaffected. */
clips: TranscriptPlacement[],
- inserts: readonly RulerInsert[] = [],
+ inserts: readonly AxcutInsertRange[] = [],
): Array<{ startSec: number; endSec: number }> {
const out: Array<{ startSec: number; endSec: number }> = [];
for (const clip of clips) {
@@ -174,20 +174,15 @@ export function sourceSpanToTimelineSpans(
const s = Math.max(startSec, clip.sourceStartSec);
const e = Math.min(endSec, clipSourceEnd);
if (e <= s) continue;
+ // `"closes"` on the end: a line running up to an added word covers the media that
+ // word inserted, so it stays on screen through it instead of going dark over the
+ // one moment the word exists for.
out.push({
- startSec: clip.timelineStartSec + (s - clip.sourceStartSec),
- endSec: clip.timelineStartSec + (e - clip.sourceStartSec),
+ startSec: sourceToTimelineSec(clip, s, inserts, "opens"),
+ endSec: sourceToTimelineSec(clip, e, inserts, "closes"),
});
}
- // Onto the ruler the viewer actually sees. Expanding BOTH ends does the whole job:
- // a line after a pause slides along by it, and a line that covers the held moment
- // has only its end pushed out — so it stays on screen through the pause instead of
- // going dark over the one moment an added word exists for.
- if (inserts.length === 0) return out;
- return out.map((span) => ({
- startSec: expandRawSec(span.startSec, inserts),
- endSec: expandRawSec(span.endSec, inserts),
- }));
+ return out;
}
/**
@@ -222,7 +217,6 @@ export function deriveCaptionCues(
// lengthens the ruler under everything, including a voiceover laid over it. Feeding it
// placements would measure the pause against the take instead of the film, and land
// every voiceover cue early.
- const inserts = rulerInserts(document.timeline.insertRanges ?? [], document.timeline.clips);
// A transcript is only projected once per asset even when several clips draw
// from it (line grouping is the expensive part, clipping is cheap).
const linesByAsset = new Map<string, CaptionSegment[]>();
@@ -244,7 +238,7 @@ export function deriveCaptionCues(
line.startSec,
line.endSec,
placements,
- inserts,
+ document.timeline.insertRanges ?? [],
)) {
const startMs = Math.round(span.startSec * 1000);
const endMs = Math.max(Math.round(span.endSec * 1000), startMs + 1);
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index d61ce3475..791389d2b 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -21,7 +21,6 @@ import type {
*/
export type PlaybackSegment = AxcutClip & { heldSec?: number };
-import type { RulerInsert } from "../timeline/inserted-time";
import { type Interval, subtractInterval } from "../timeline/intervals";
import { keptRawSpans } from "../timeline/programme-time";
import {
@@ -136,6 +135,54 @@ function collectWordRefs(
// after any structural change (insert / move / remove / trim) so the timeline
// never has gaps or overlaps between clips. Shared by useTimeline (UI) and
// the agent tool executor (main process) so both enforce the same invariant.
+/** How much media this clip's own insertions add to it, in seconds.
+ *
+ * Half-open at the start and closed at the end, matching where an insertion sits: at the
+ * END of the word it follows, which is a moment the clip plays. */
+export function insertedSecForClip(
+ clip: AxcutClip,
+ insertRanges: readonly AxcutInsertRange[],
+): number {
+ const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;
+ return insertRanges.reduce(
+ (sum, range) =>
+ range.assetId === clip.assetId &&
+ range.atSec > clip.sourceStartSec &&
+ range.atSec <= sourceEnd + 1e-6
+ ? sum + range.durationSec
+ : sum,
+ 0,
+ );
+}
+
+/**
+ * Clip geometry that accounts for the media inserted inside each clip (issue #560).
+ *
+ * An added word inserts media — a fixed frame and silence, until there is a generator for
+ * it — and a clip carrying it is that much longer, exactly as it would be if the media had
+ * come from a file. This is the ONE place that says so; every reader downstream then works
+ * in a single coordinate, which is what makes the playhead, the native decoder and the
+ * export agree without any of them converting between two rulers.
+ *
+ * Absolute rather than incremental, so it is idempotent: a stored clip's length is always
+ * its source length (every writer above builds it that way), and re-running this on an
+ * already-reflowed document changes nothing. That is what lets it also serve as the
+ * migration for documents written before insertions existed.
+ */
+export function reflowClipsForInserts(
+ clips: AxcutClip[],
+ insertRanges: readonly AxcutInsertRange[],
+): AxcutClip[] {
+ return resequenceClips(
+ clips.map((clip) => {
+ const sourceLen = (clip.sourceEndSec ?? clip.sourceStartSec) - clip.sourceStartSec;
+ if (sourceLen <= 0) return clip; // duration not probed yet; leave it to the prober
+ const len = sourceLen + insertedSecForClip(clip, insertRanges);
+ return { ...clip, timelineEndSec: clip.timelineStartSec + len };
+ }),
+ );
+}
+
export function resequenceClips(clips: AxcutClip[]): AxcutClip[] {
let cursor = 0;
return clips.map((c) => {
@@ -372,14 +419,13 @@ export function projectRawTimelineSecToPlayback(
trimRanges: AxcutTrimRange[],
rawSec: number,
/**
- * The recording lane's insertions, already placed on the raw ruler by `rulerInserts`.
+ * The insertions, so the kept spans below can carry them.
*
- * REQUIRED, not optional, and every call site was migrated with it. An optional
- * parameter would silently keep the early-audio bug alive at every site that had not
- * been touched yet — which is the exact failure this argument exists to fix, and the
- * kind that shows up as "the music starts a beat early" months later.
+ * REQUIRED, not optional: an optional parameter would silently keep the early-audio bug
+ * alive at every site not yet touched — the one that shows up as "the music starts a
+ * beat early" months later.
*/
- filmInserts: readonly RulerInsert[],
+ insertRanges: readonly AxcutInsertRange[],
/**
* Speed regions on the raw ruler. Supplied by the AUDIO paths, which overlay
* a 1x track onto the finished programme and so need its real, speed-adjusted
@@ -393,39 +439,17 @@ export function projectRawTimelineSecToPlayback(
let lastRawEnd = 0; // raw end of the last kept segment, for the trailing overhang
let landed: number | null = null; // output(rawSec), once it falls in/before a kept segment
- // An insertion occupies ZERO raw seconds and D OUTPUT seconds — it is the one
- // thing a flat kept-interval list cannot express, which is why it was left out and why
- // every audio track after an insertion has been landing D seconds early in both the preview
- // and the export. Interleaved here rather than added afterwards, because where the insertion
- // sits inside the kept span decides which side of it `rawSec` falls on.
- const holds = [...filmInserts].sort((a, b) => a.atRawSec - b.atRawSec);
- let nextHold = 0;
-
// 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)) {
- let from = seg.startSec;
- // Every insertion this segment carries, in order. One whose moment a trim removed is
- // in no kept span at all and is never reached — the moment it holds is not in the
- // film any more, so neither is the insertion.
- while (nextHold < holds.length && holds[nextHold].atRawSec < seg.startSec) nextHold++;
- while (nextHold < holds.length && holds[nextHold].atRawSec < seg.endSec) {
- const hold = holds[nextHold++];
- const at = Math.max(from, hold.atRawSec);
- if (landed === null && rawSec < at) {
- const within = Math.min(Math.max(rawSec, from), at);
- landed = outCursor + outputDurationOfRawSpan(from, within, speedRegions);
- }
- outCursor += outputDurationOfRawSpan(from, at, speedRegions);
- from = at;
- // Strictly after the insertion's own moment, matching `expandRawSec`: a track whose
- // head sits exactly there starts WITH the insertion, not after it.
- if (landed === null && rawSec <= at) landed = outCursor;
- outCursor += hold.durationSec;
- }
+ // same answer (issue #560). It carries the insertions too: they are timeline seconds like
+ // any other, which is exactly what one clock buys — this walk used to interleave them
+ // itself, and every reader that forgot to had audio landing early.
+ //
+ // Trims only REMOVE, so a kept span's 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, insertRanges)) {
+ const from = seg.startSec;
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).
diff --git a/src/lib/ai-edition/document/transcript.test.ts b/src/lib/ai-edition/document/transcript.test.ts
index 87c6b8213..fdc3909d1 100644
--- a/src/lib/ai-edition/document/transcript.test.ts
+++ b/src/lib/ai-edition/document/transcript.test.ts
@@ -750,11 +750,29 @@ describe("insert ranges", () => {
expect(insertRangesMatchWords(take)).toBe(true);
});
- // The clips are the thing the first attempt broke. Nothing here may touch them.
- it("leaves the clips exactly as they were", () => {
+ // An insertion is MEDIA inside the clip, so the clip carrying it is exactly that much
+ // longer — the one fact every reader downstream depends on, and the reason none of them
+ // needs a second ruler to convert to. Its source window is untouched: no frame of the
+ // recording was added or removed.
+ it("lengthens the clip that carries the insertion, by the insertion", () => {
const before = docWithClip();
const result = insertDocumentWord(before, "asset_1", "word_2", "after", "really");
- expect(result.timeline.clips).toEqual(before.timeline.clips);
+ const [range] = result.timeline.insertRanges;
+ const was = before.timeline.clips[0];
+ const now = result.timeline.clips[0];
+ expect(now.timelineEndSec - now.timelineStartSec).toBeCloseTo(
+ was.timelineEndSec - was.timelineStartSec + range.durationSec,
+ 5,
+ );
+ expect(now.sourceStartSec).toBe(was.sourceStartSec);
+ expect(now.sourceEndSec).toBe(was.sourceEndSec);
+ });
+
+ it("gives the length back when the word goes", () => {
+ const before = docWithClip();
+ const added = insertDocumentWord(before, "asset_1", "word_2", "after", "really");
+ const removed = removeDocumentWords(added, "asset_1", ["synth_1"]);
+ expect(removed.timeline.clips).toEqual(before.timeline.clips);
});
it("stores nothing when the word fits in silence that is already there", () => {
diff --git a/src/lib/ai-edition/document/transcript.ts b/src/lib/ai-edition/document/transcript.ts
index 87d6a5800..8d9c49487 100644
--- a/src/lib/ai-edition/document/transcript.ts
+++ b/src/lib/ai-edition/document/transcript.ts
@@ -1,5 +1,6 @@
import type { AxcutDocument, AxcutInsertRange, AxcutTranscript, AxcutWord } from "../schema";
import { createId } from "./ids";
+import { reflowClipsForInserts } from "./timeline";
const CJK_EDGE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u;
const CLOSING_PUNCTUATION = /^[,.;:!?%。,、;:!?…))\]}>》」』】〕]/u;
@@ -385,7 +386,17 @@ function withInsertRangesForWords(document: AxcutDocument, assetId: string): Axc
if (kept.length === existing.length && kept.every((range, i) => range === existing[i])) {
return document;
}
- return { ...document, timeline: { ...document.timeline, insertRanges: kept } };
+ // The clips grow with them. An insertion is media inside the clip, so the clip is that
+ // much longer — the single fact every downstream reader needs, written once, here, where
+ // the ranges themselves are written.
+ return {
+ ...document,
+ timeline: {
+ ...document.timeline,
+ insertRanges: kept,
+ clips: reflowClipsForInserts(document.timeline.clips, kept),
+ },
+ };
}
/**
diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.ts
index 69d0cd340..fd47da9cc 100644
--- a/src/lib/ai-edition/store/projectStore.ts
+++ b/src/lib/ai-edition/store/projectStore.ts
@@ -60,20 +60,6 @@ export interface ProjectState {
error: string | null;
sourceDurationSec: number;
currentTimeSec: number;
- /** The playhead's position on the RULER — the timeline the user sees and scrubs.
- *
- * `currentTimeSec` is the stored, RAW second: where the recording is. The two are the
- * same number until an insertion exists, and then they permanently are not. An insertion
- * is media added INSIDE a clip (issue #560), so it takes up ruler seconds while taking up
- * none of the recording — every ruler second inside one names the same raw moment.
- *
- * Which means the raw second cannot say WHERE inside an insertion the playhead is, and a
- * playhead that only had that number fell to the insertion's near edge the instant it
- * entered: playback stalled visually there, and releasing a scrub over one snapped back
- * to its start. Consumers that resolve MEDIA (seek, captions, transcript cue, mix) keep
- * reading `currentTimeSec` — through an insertion the recording really is at that one
- * instant. Only what draws or measures the ruler reads this. */
- currentRulerSec: number;
/** The selected imported audio track (issue #350), or null. In the store — not
* `useTimeline`'s local selection — because the media panel (which imports the
* file) and the inspector (which edits it) sit in different component subtrees
@@ -160,9 +146,7 @@ export interface ProjectState {
opts: DocumentWriteOptions,
) => Promise<void>;
setSourceDuration: (sec: number) => void;
- /** `rulerSec` defaults to `sec`, which is right everywhere no insertion is involved
- * and is what every existing caller means. */
- setCurrentTime: (sec: number, rulerSec?: number) => void;
+ setCurrentTime: (sec: number) => void;
setPlaying: (playing: boolean) => void;
markClean: () => void;
/**
@@ -213,7 +197,6 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
error: null,
sourceDurationSec: 0,
currentTimeSec: 0,
- currentRulerSec: 0,
selectedAudioTrackId: null,
playing: false,
dirty: false,
@@ -566,8 +549,8 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
set({ sourceDurationSec: sec });
},
- setCurrentTime(sec, rulerSec) {
- set({ currentTimeSec: sec, currentRulerSec: rulerSec ?? sec });
+ setCurrentTime(sec) {
+ set({ currentTimeSec: sec });
},
setPlaying(playing) {
@@ -598,7 +581,6 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
error: null,
sourceDurationSec: 0,
currentTimeSec: 0,
- currentRulerSec: 0,
selectedAudioTrackId: null,
playing: false,
dirty: false,
diff --git a/src/lib/ai-edition/timeline/inserted-time.test.ts b/src/lib/ai-edition/timeline/inserted-time.test.ts
index bd16a698c..7114afc6d 100644
--- a/src/lib/ai-edition/timeline/inserted-time.test.ts
+++ b/src/lib/ai-edition/timeline/inserted-time.test.ts
@@ -8,16 +8,15 @@
import { describe, expect, it } from "vitest";
import type { AxcutClip, AxcutInsertRange, AxcutWord } from "../schema";
import {
- collapseRawSec,
- expandRawSec,
insertedWordMarks,
insertionEnteredBetween,
type RulerInsert,
rulerInserts,
- totalInsertedSec,
+ sourceToTimelineSec,
+ timelineToSourceSec,
} from "./inserted-time";
-function clip(overrides: Partial<AxcutClip> & Pick<AxcutClip, "id">): AxcutClip {
+function clipFixture(overrides: Partial<AxcutClip> & Pick<AxcutClip, "id">): AxcutClip {
return {
assetId: "a1",
sourceStartSec: 0,
@@ -47,7 +46,9 @@ function insert(overrides: Partial<AxcutInsertRange> = {}): AxcutInsertRange {
describe("rulerInserts", () => {
it("projects a pause through the clip that plays its moment", () => {
// The clip plays source 4–10 starting at ruler 20, so source 6 is ruler 22.
- const clips = [clip({ id: "c1", sourceStartSec: 4, timelineStartSec: 20, timelineEndSec: 26 })];
+ const clips = [
+ clipFixture({ id: "c1", sourceStartSec: 4, timelineStartSec: 20, timelineEndSec: 26 }),
+ ];
expect(rulerInserts([insert({ atSec: 6 })], clips)).toEqual([
{ id: "ins_1", wordId: "synth_1", atRawSec: 22, durationSec: 0.5 },
]);
@@ -56,18 +57,22 @@ describe("rulerInserts", () => {
// The word is not on the timeline, so its pause has no place on the ruler and adds
// nothing — the same rule a caption line follows when no clip covers it.
it("drops a pause no clip plays", () => {
- const clips = [clip({ id: "c1", sourceStartSec: 0, sourceEndSec: 3, timelineEndSec: 3 })];
+ const clips = [
+ clipFixture({ id: "c1", sourceStartSec: 0, sourceEndSec: 3, timelineEndSec: 3 }),
+ ];
expect(rulerInserts([insert({ atSec: 6 })], clips)).toEqual([]);
});
it("counts a pause sitting exactly on a clip's edge", () => {
// A pause sits at the END of the word it follows, which is routinely the boundary.
- const clips = [clip({ id: "c1", sourceStartSec: 0, sourceEndSec: 4, timelineEndSec: 4 })];
+ const clips = [
+ clipFixture({ id: "c1", sourceStartSec: 0, sourceEndSec: 4, timelineEndSec: 4 }),
+ ];
expect(rulerInserts([insert({ atSec: 4 })], clips)).toHaveLength(1);
});
it("returns them in ruler order, whatever order they were stored in", () => {
- const clips = [clip({ id: "c1" })];
+ const clips = [clipFixture({ id: "c1" })];
const placed = rulerInserts(
[insert({ id: "b", atSec: 8 }), insert({ id: "a", atSec: 2 })],
clips,
@@ -77,87 +82,13 @@ describe("rulerInserts", () => {
it("places a pause only once when two clips could play its moment", () => {
const clips = [
- clip({ id: "c1" }),
- clip({ id: "c2", timelineStartSec: 10, timelineEndSec: 20 }),
+ clipFixture({ id: "c1" }),
+ clipFixture({ id: "c2", timelineStartSec: 10, timelineEndSec: 20 }),
];
expect(rulerInserts([insert()], clips)).toHaveLength(1);
});
});
-describe("the expanded ruler", () => {
- const INSERTS: RulerInsert[] = [
- { id: "a", wordId: "w_a", atRawSec: 2, durationSec: 0.5 },
- { id: "b", wordId: "w_b", atRawSec: 6, durationSec: 1 },
- ];
-
- it("leaves everything before the first pause where it was", () => {
- expect(expandRawSec(0, INSERTS)).toBe(0);
- expect(expandRawSec(1.9, INSERTS)).toBe(1.9);
- });
-
- // The frame about to be held keeps its own instant; the pause opens after it.
- it("keeps the held moment itself in place", () => {
- expect(expandRawSec(2, INSERTS)).toBe(2);
- });
-
- it("shifts everything after a pause by what it added", () => {
- expect(expandRawSec(3, INSERTS)).toBe(3.5);
- expect(expandRawSec(6, INSERTS)).toBe(6.5);
- expect(expandRawSec(7, INSERTS)).toBe(8.5);
- });
-
- it("grows the ruler by the pauses' total", () => {
- expect(totalInsertedSec(INSERTS)).toBe(1.5);
- expect(expandRawSec(10, INSERTS)).toBe(10 + totalInsertedSec(INSERTS));
- });
-
- it("round-trips every moment that is not inside a pause", () => {
- for (const sec of [0, 1.9, 3, 5.99, 7, 10]) {
- const back = collapseRawSec(expandRawSec(sec, INSERTS), INSERTS);
- expect(back.sec).toBeCloseTo(sec, 9);
- expect(back.heldBy).toBeNull();
- }
- });
-
- // The held moment is the one place the pair is not a clean inverse, and it is not
- // meant to be: source 2 occupies the WHOLE of ruler [2, 2.5) — it is what the pause
- // shows. Expanding picks the start of that stretch; collapsing it back answers with
- // the same source moment and says it is being held, which is the honest reading of a
- // moment that is on screen for half a second.
- it("says the held moment is held, and still names the right source moment", () => {
- const back = collapseRawSec(expandRawSec(2, INSERTS), INSERTS);
- expect(back.sec).toBe(2);
- expect(back.heldBy?.id).toBe("a");
- });
-
- // Not a gap in the model — this IS the pause. A stretch of ruler stands for one held
- // source moment, and the caller is told which pause is holding it so it parks the
- // decoder instead of seeking through content that belongs after.
- it("collapses a moment inside a pause onto the frame being held", () => {
- for (const sec of [2.01, 2.25, 2.49]) {
- const back = collapseRawSec(sec, INSERTS);
- expect(back.sec).toBe(2);
- expect(back.heldBy?.id).toBe("a");
- }
- });
-
- it("resumes on the far side of a pause", () => {
- const back = collapseRawSec(2.5, INSERTS);
- expect(back.sec).toBe(2);
- expect(back.heldBy).toBeNull();
- });
-
- it("counts every earlier pause when collapsing a later moment", () => {
- // Ruler 8.5 is source 7: 0.5s from the first pause and 1s from the second.
- expect(collapseRawSec(8.5, INSERTS)).toEqual({ sec: 7, heldBy: null });
- });
-
- it("is the identity when there are no pauses", () => {
- expect(expandRawSec(4, [])).toBe(4);
- expect(collapseRawSec(4, [])).toEqual({ sec: 4, heldBy: null });
- });
-});
-
// ─── Where an added word's mark goes ─────────────────────────────────────────
// Issue #560. Two defects lived in one ternary in V4Timeline: a word WITH a pause was
// placed on the expanded ruler and one WITHOUT at a fraction of the clip's SOURCE span —
@@ -232,37 +163,84 @@ describe("insertedWordMarks", () => {
});
});
-// ─── The scrub round-trip ───────────────────────────────────────────────────
-// The timeline measures the pointer against the EXPANDED ruler and writes the result into
-// a store every consumer reads as a RAW second — the preview seek, the caption lookup, the
-// transcript cue, the audio mix. Straight through, the playhead sat one accumulated pause
-// AHEAD of everything it pointed at: the right playhead, the wrong subtitle (issue #560).
-
-describe("a scrub survives the round trip", () => {
- const marks: RulerInsert[] = [
- { id: "i1", wordId: "w1", atRawSec: 4, durationSec: 2 },
- { id: "i2", wordId: "w2", atRawSec: 9, durationSec: 1 },
+// ─── Source ↔ timeline, inside one clip ─────────────────────────────────────
+// The whole consequence of an insertion being MEDIA: the clip is longer than its source
+// window, so a moment past an insertion sits that much further along the timeline. Every
+// place that used to convert between a "raw" and an "expanded" ruler is asking this, of
+// one clip — and getting it wrong put a caption, a playhead or a decoder in the wrong
+// place (issue #560).
+
+describe("source ↔ timeline through a clip that carries insertions", () => {
+ // Ten seconds of recording laid at timeline 0, with 0.5s inserted at source 2 and 1s
+ // at source 6 — so the clip is 11.5s long and its source window is untouched.
+ const clip = clipFixture({
+ id: "c1",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 11.5,
+ });
+ const ranges: AxcutInsertRange[] = [
+ {
+ id: "a",
+ assetId: "a1",
+ atSec: 2,
+ durationSec: 0.5,
+ wordId: "w_a",
+ reason: "",
+ origin: "user",
+ },
+ {
+ id: "b",
+ assetId: "a1",
+ atSec: 6,
+ durationSec: 1,
+ wordId: "w_b",
+ reason: "",
+ origin: "user",
+ },
];
- it("comes back to the raw second it started from, before and after each pause", () => {
- for (const raw of [0, 1.5, 3.9, 6, 8.5, 12, 30]) {
- expect(collapseRawSec(expandRawSec(raw, marks), marks).sec).toBeCloseTo(raw, 6);
+ it("leaves everything before the first insertion where it was", () => {
+ expect(sourceToTimelineSec(clip, 0, ranges)).toBeCloseTo(0, 6);
+ expect(sourceToTimelineSec(clip, 1.9, ranges)).toBeCloseTo(1.9, 6);
+ });
+
+ it("counts every insertion before the moment, and only those", () => {
+ expect(sourceToTimelineSec(clip, 4, ranges)).toBeCloseTo(4.5, 6);
+ expect(sourceToTimelineSec(clip, 10, ranges)).toBeCloseTo(11.5, 6);
+ });
+
+ it("puts the insertion's own moment where it opens, or where it closes", () => {
+ // The choice is real: a position and a span's START go before the inserted media,
+ // a span's END goes after it, so a caption running up to an added word covers it.
+ expect(sourceToTimelineSec(clip, 2, ranges, "opens")).toBeCloseTo(2, 6);
+ expect(sourceToTimelineSec(clip, 2, ranges, "closes")).toBeCloseTo(2.5, 6);
+ });
+
+ it("comes back to the source moment it started from", () => {
+ for (const source of [0, 1.9, 2, 3, 5.5, 6, 9.99]) {
+ const back = timelineToSourceSec(clip, sourceToTimelineSec(clip, source, ranges), ranges);
+ expect(back.sourceSec).toBeCloseTo(source, 6);
}
});
- it("lands on the held moment for a pointer inside a pause, and says so", () => {
- // Every ruler second inside an insertion is the same raw moment: none of those
- // seconds come from the recording, so there is nothing else it could mean.
- const inside = collapseRawSec(5, marks);
- expect(inside.sec).toBeCloseTo(4, 6);
- expect(inside.heldBy?.id).toBe("i1");
- expect(collapseRawSec(5.9, marks).sec).toBeCloseTo(4, 6);
+ it("has no source moment inside an insertion, and says which one", () => {
+ // There is nothing else it could answer: none of those seconds come from the file.
+ const inside = timelineToSourceSec(clip, 2.25, ranges);
+ expect(inside.sourceSec).toBeCloseTo(2, 6);
+ expect(inside.insideInsert?.id).toBe("a");
+ expect(timelineToSourceSec(clip, 2.5, ranges).insideInsert).toBeNull();
+ });
+
+ it("is the plain shift when the clip carries nothing", () => {
+ expect(sourceToTimelineSec(clip, 4, [])).toBeCloseTo(4, 6);
+ expect(timelineToSourceSec(clip, 4, []).sourceSec).toBeCloseTo(4, 6);
});
- it("counts every pause before the pointer, not just the first", () => {
- // Ruler 13 is past both: 13 − 2 − 1 = raw 10.
- expect(collapseRawSec(13, marks).sec).toBeCloseTo(10, 6);
- expect(collapseRawSec(13, marks).heldBy).toBeNull();
+ it("ignores insertions belonging to another recording", () => {
+ const other = [{ ...ranges[0], assetId: "a2" }];
+ expect(sourceToTimelineSec(clip, 4, other)).toBeCloseTo(4, 6);
});
});
diff --git a/src/lib/ai-edition/timeline/inserted-time.ts b/src/lib/ai-edition/timeline/inserted-time.ts
index c6786d25c..c921ce878 100644
--- a/src/lib/ai-edition/timeline/inserted-time.ts
+++ b/src/lib/ai-edition/timeline/inserted-time.ts
@@ -45,86 +45,119 @@ export function rulerInserts(
clips: readonly AxcutClip[],
): RulerInsert[] {
const placed: RulerInsert[] = [];
- for (const insert of inserts) {
- for (const clip of clips) {
- if (clip.assetId !== insert.assetId) continue;
- const sourceEnd = clip.sourceEndSec ?? Number.POSITIVE_INFINITY;
- // Inclusive at both edges: an insertion sits at the END of the word it follows, which
- // is routinely a clip's own boundary.
- if (insert.atSec < clip.sourceStartSec || insert.atSec > sourceEnd) continue;
+ const claimed = new Set<string>();
+ for (const clip of clips) {
+ const sourceEnd = clip.sourceEndSec ?? Number.POSITIVE_INFINITY;
+ const mine = inserts
+ // Inclusive at both edges: an insertion sits at the END of the word it follows,
+ // which is routinely a clip's own boundary. Claimed once, by the first clip that
+ // plays the moment — two clips over the same recording are two places, not two
+ // insertions.
+ .filter(
+ (insert) =>
+ insert.assetId === clip.assetId &&
+ !claimed.has(insert.id) &&
+ insert.atSec >= clip.sourceStartSec &&
+ insert.atSec <= sourceEnd,
+ )
+ .sort((a, b) => a.atSec - b.atSec);
+ // Each insertion opens after the ones before it in the same clip: the clip's length
+ // already carries all of them, so a plain source-shift would stack them all at the
+ // first one's position.
+ let carriedSec = 0;
+ for (const insert of mine) {
+ claimed.add(insert.id);
placed.push({
id: insert.id,
wordId: insert.wordId,
- atRawSec: clip.timelineStartSec + (insert.atSec - clip.sourceStartSec),
+ atRawSec: clip.timelineStartSec + (insert.atSec - clip.sourceStartSec) + carriedSec,
durationSec: insert.durationSec,
});
- break;
+ carriedSec += insert.durationSec;
}
}
return placed.sort((a, b) => a.atRawSec - b.atRawSec);
}
-/** How much time the insertions add in total — what the ruler grows by. */
-export function totalInsertedSec(inserts: readonly RulerInsert[]): number {
- return inserts.reduce((sum, insert) => sum + insert.durationSec, 0);
-}
-
/**
- * Stored raw seconds → the ruler the user sees.
+ * A clip's own source moment → where it lands on the timeline.
+ *
+ * Not a plain shift, and this is the whole consequence of an insertion being MEDIA: the
+ * clip is longer than its source window by everything inserted inside it, so a moment past
+ * an insertion sits that much further along. Every place that used to convert between a
+ * "raw" and an "expanded" ruler is really asking this, of one clip.
*
- * Monotone and total: every stored moment has exactly one place on the expanded ruler.
- * A moment sitting exactly ON an insertion maps to where the insertion BEGINS, so the last recorded
- * frame keeps its own instant and the inserted media opens after it.
+ * `edge` decides what happens AT an insertion's own moment, which is a real choice and not
+ * a rounding detail. `"opens"` puts the moment before the inserted media — right for a
+ * position, and for the START of a span, so the span does not swallow the insertion that
+ * precedes it. `"closes"` puts it after — right for the END of a span, so a stretch running
+ * up to an insertion covers it rather than stopping short and leaving it orphaned.
*/
-export function expandRawSec(sec: number, inserts: readonly RulerInsert[]): number {
- let out = sec;
+export function sourceToTimelineSec(
+ /** Only the three fields that locate a clip — so a voiceover placement, which carries
+ * the same three, maps through this too (issue #560). */
+ clip: Pick<AxcutClip, "assetId" | "sourceStartSec" | "timelineStartSec">,
+ sourceSec: number,
+ inserts: readonly AxcutInsertRange[],
+ edge: "opens" | "closes" = "opens",
+): number {
+ let added = 0;
for (const insert of inserts) {
- if (insert.atRawSec < sec) out += insert.durationSec;
+ if (insert.assetId !== clip.assetId) continue;
+ if (insert.atSec <= clip.sourceStartSec) continue;
+ if (edge === "opens" ? insert.atSec < sourceSec : insert.atSec <= sourceSec + 1e-6) {
+ added += insert.durationSec;
+ }
}
- return out;
+ return clip.timelineStartSec + (sourceSec - clip.sourceStartSec) + added;
}
/**
- * The ruler the user sees → stored raw seconds.
+ * The inverse: a timeline second → the source moment the clip is showing there.
*
- * The inverse of {@link expandRawSec} outside an insertion. Inside one it cannot be an inverse
- * — a whole stretch of ruler stands for a single held moment — and it returns that moment,
- * flagged, so a caller driving a decoder knows to hold rather than to seek.
+ * Inside an insertion there is no source moment — that is what makes it an insertion — so
+ * it answers with the moment the inserted media follows, and names the insertion. A caller
+ * driving a decoder needs both: where to park, and the fact that it should stay parked.
*/
-export function collapseRawSec(
- sec: number,
- inserts: readonly RulerInsert[],
-): { sec: number; heldBy: RulerInsert | null } {
- let offset = 0;
- for (const insert of inserts) {
- const startsAt = insert.atRawSec + offset;
- if (sec < startsAt) break;
- if (sec < startsAt + insert.durationSec) {
- return { sec: insert.atRawSec, heldBy: insert };
+export function timelineToSourceSec(
+ clip: AxcutClip,
+ timelineSec: number,
+ inserts: readonly AxcutInsertRange[],
+): { sourceSec: number; insideInsert: AxcutInsertRange | null } {
+ const mine = inserts
+ .filter((insert) => insert.assetId === clip.assetId && insert.atSec > clip.sourceStartSec)
+ .sort((a, b) => a.atSec - b.atSec);
+ let added = 0;
+ for (const insert of mine) {
+ const opensAt = clip.timelineStartSec + (insert.atSec - clip.sourceStartSec) + added;
+ if (timelineSec < opensAt) break;
+ if (timelineSec < opensAt + insert.durationSec) {
+ return { sourceSec: insert.atSec, insideInsert: insert };
}
- offset += insert.durationSec;
+ added += insert.durationSec;
}
- return { sec: sec - offset, heldBy: null };
+ return {
+ sourceSec: clip.sourceStartSec + (timelineSec - clip.timelineStartSec) - added,
+ insideInsert: null,
+ };
}
/**
* The insertion a frame of playback ran into, if it ran into one.
*
- * Half-open on the LEFT, and that is the whole point: while inserted media is playing, the
- * RAW playhead stands still at exactly `atRawSec` — the recording really is at that one
- * instant, because none of the inserted seconds come from it. `>` is therefore what refuses
- * that same moment on the way out; with `>=` the insertion is re-entered the frame it ends
- * and the film never gets past it. Closed on the right (with the frame epsilon) so an
- * insertion landing precisely on a frame boundary is played rather than skipped.
+ * Half-open on the LEFT, and that is the whole point: a player parks on the insertion's
+ * frame and pins its clock to exactly `atRawSec` for the first frame of it, so `>` is what
+ * refuses that same moment on the way in a second time. Closed on the right (with the frame
+ * epsilon) so an insertion landing precisely on a frame boundary is played, not skipped.
*/
export function insertionEnteredBetween(
- prevRawSec: number,
- nextRawSec: number,
+ prevSec: number,
+ nextSec: number,
inserts: readonly RulerInsert[],
epsilonSec = 1e-6,
): RulerInsert | undefined {
return inserts.find(
- (insert) => insert.atRawSec > prevRawSec && insert.atRawSec <= nextRawSec + epsilonSec,
+ (insert) => insert.atRawSec > prevSec && insert.atRawSec <= nextSec + epsilonSec,
);
}
diff --git a/src/lib/ai-edition/timeline/programme-time.test.ts b/src/lib/ai-edition/timeline/programme-time.test.ts
index 9942fb71d..7b2b35cca 100644
--- a/src/lib/ai-edition/timeline/programme-time.test.ts
+++ b/src/lib/ai-edition/timeline/programme-time.test.ts
@@ -7,7 +7,7 @@
import { describe, expect, it } from "vitest";
import { projectRawTimelineSecToPlayback, resolvePlaybackSegments } from "../document/timeline";
-import type { AxcutClip, AxcutTrimRange } from "../schema";
+import type { AxcutClip, AxcutInsertRange, AxcutTrimRange } from "../schema";
import { keptRawSpans, removalAt, removedRawSpans, subtractRemoved } from "./programme-time";
function clip(over: Partial<AxcutClip> & { id: string }): AxcutClip {
@@ -275,53 +275,71 @@ describe("subtractRemoved", () => {
});
});
-// ─── The pause the projection used to ignore ─────────────────────────────────
-// A pause occupies ZERO raw seconds and D OUTPUT seconds, which a flat kept-interval list
-// cannot express — so it was left out, and every audio track after a pause landed D seconds
-// early in both the preview and the export. `filmInserts` is required precisely so no call
-// site can quietly keep that bug.
+// ─── The insertion the projection has to walk over ──────────────────────────
+// An insertion is media INSIDE a clip, so the clip carrying it is that much longer and the
+// insertion's seconds are timeline seconds like any other. The projection's job is unchanged
+// by that — timeline in, output out — but it has to be TOLD, because it walks each clip's
+// kept SOURCE stretches and those are shorter than the clip.
-describe("projectRawTimelineSecToPlayback with the film's pauses", () => {
- const clips = twoClips();
- const pause = { id: "i1", wordId: "w1", atRawSec: 5, durationSec: 1 };
-
- it("pushes everything after a pause later by exactly what it bought", () => {
- expect(projectRawTimelineSecToPlayback(clips, [], 8, [])).toBeCloseTo(8, 6);
- expect(projectRawTimelineSecToPlayback(clips, [], 8, [pause])).toBeCloseTo(9, 6);
- });
-
- it("leaves everything before it where it was", () => {
- expect(projectRawTimelineSecToPlayback(clips, [], 3, [pause])).toBeCloseTo(3, 6);
- });
+describe("projectRawTimelineSecToPlayback across an insertion", () => {
+ // One second inserted at source 5 of the first clip, so that clip runs 0..11 and the
+ // second one starts at 11.
+ const inserted: AxcutInsertRange[] = [
+ {
+ id: "i1",
+ assetId: "a1",
+ atSec: 5,
+ durationSec: 1,
+ wordId: "w1",
+ reason: "",
+ origin: "user",
+ },
+ ];
+ const clips = [
+ clip({
+ id: "c1",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 11,
+ }),
+ clip({
+ id: "c2",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 11,
+ timelineEndSec: 21,
+ }),
+ ];
- it("starts a track whose head sits exactly on the pause WITH the pause", () => {
- // Strict, matching `expandRawSec`: arriving at the pause's moment is the beginning
- // of the hold, not the end of it.
- expect(projectRawTimelineSecToPlayback(clips, [], 5, [pause])).toBeCloseTo(5, 6);
+ it("is the identity when nothing is cut — the insertion is already in the film", () => {
+ // This is what one clock buys. Under two, the walk had to re-add the insertion here
+ // and every reader that forgot to had its audio landing a second early.
+ expect(projectRawTimelineSecToPlayback(clips, [], 3, inserted)).toBeCloseTo(3, 6);
+ expect(projectRawTimelineSecToPlayback(clips, [], 8, inserted)).toBeCloseTo(8, 6);
+ expect(projectRawTimelineSecToPlayback(clips, [], 15, inserted)).toBeCloseTo(15, 6);
});
- it("counts two pauses, in order", () => {
- const second = { id: "i2", wordId: "w2", atRawSec: 7, durationSec: 0.5 };
- expect(projectRawTimelineSecToPlayback(clips, [], 9, [pause, second])).toBeCloseTo(10.5, 6);
- // Order of the argument must not matter: the walk sorts.
- expect(projectRawTimelineSecToPlayback(clips, [], 9, [second, pause])).toBeCloseTo(10.5, 6);
+ it("keeps the insertion's own seconds when a trim takes the film around it", () => {
+ // Cutting source 0..2 of the first clip removes two seconds of RECORDING. The second
+ // the added word bought is not recording, so it survives.
+ const trims = [trim({ id: "t1", clipId: "c1", startSec: 0, endSec: 2 })];
+ expect(projectRawTimelineSecToPlayback(clips, trims, 8, inserted)).toBeCloseTo(6, 6);
});
- it("never reaches a pause a trim removed", () => {
- // The moment it holds is not in the film any more, so neither is the pause — the
- // same rule `resolvePlaybackSegments` already follows.
+ it("loses an insertion whose own moment a trim removed", () => {
+ // The moment it follows is not in the film any more, so neither is it — the same
+ // rule `resolvePlaybackSegments` follows.
const trims = [trim({ id: "t1", clipId: "c1", startSec: 4, endSec: 6 })];
- expect(projectRawTimelineSecToPlayback(clips, trims, 8, [pause])).toBeCloseTo(
- projectRawTimelineSecToPlayback(clips, trims, 8, []),
- 6,
- );
+ const out = projectRawTimelineSecToPlayback(clips, trims, 11, inserted);
+ // 10s of recording, less the 2s cut, and the insertion gone with it.
+ expect(out).toBeCloseTo(8, 6);
});
- it("compresses the film around a pause but never the pause itself", () => {
- // A voice plays at 1x. A 2x region halves the film either side; the second the pause
- // bought is still a second.
- const speed = [{ startMs: 0, endMs: 20_000, speed: 2 }];
- expect(projectRawTimelineSecToPlayback(clips, [], 8, [], speed)).toBeCloseTo(4, 6);
- expect(projectRawTimelineSecToPlayback(clips, [], 8, [pause], speed)).toBeCloseTo(5, 6);
+ it("compresses the film around an insertion, and the insertion with it", () => {
+ // A 2x region halves whatever timeline it covers. The insertion is timeline, so it
+ // is halved too — the film is one thing, and speed is a property of the film.
+ const speed = [{ startMs: 0, endMs: 21_000, speed: 2 }];
+ expect(projectRawTimelineSecToPlayback(clips, [], 8, inserted, speed)).toBeCloseTo(4, 6);
});
});
diff --git a/src/lib/ai-edition/timeline/programme-time.ts b/src/lib/ai-edition/timeline/programme-time.ts
index 60c23f032..f2b7cb3ec 100644
--- a/src/lib/ai-edition/timeline/programme-time.ts
+++ b/src/lib/ai-edition/timeline/programme-time.ts
@@ -18,7 +18,8 @@
// 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 { AxcutClip, AxcutInsertRange, AxcutTrimRange } from "../schema";
+import { sourceToTimelineSec } from "./inserted-time";
import { type Interval, subtractInterval } from "./intervals";
import { trimAppliesToClip } from "./trim-mapping";
@@ -58,11 +59,20 @@ function clipRawExtent(clip: AxcutClip): RawSpan {
};
}
-/** Source interval → raw, through the clip that carries it. */
-function sourceToRaw(clip: AxcutClip, interval: Interval): RawSpan {
+/** Source interval → timeline, through the clip that carries it.
+ *
+ * `"closes"` on the end is what makes an insertion INSIDE a kept stretch part of it: the
+ * film plays those seconds, so they belong to the span. An insertion at the stretch's own
+ * start belongs to whatever came before — and if a trim took that, it is gone with it,
+ * which is right: the moment it follows is not in the film any more. */
+function sourceToRaw(
+ clip: AxcutClip,
+ interval: Interval,
+ insertRanges: readonly AxcutInsertRange[],
+): RawSpan {
return {
- startSec: clip.timelineStartSec + (interval.startSec - clip.sourceStartSec),
- endSec: clip.timelineStartSec + (interval.endSec - clip.sourceStartSec),
+ startSec: sourceToTimelineSec(clip, interval.startSec, insertRanges, "opens"),
+ endSec: sourceToTimelineSec(clip, interval.endSec, insertRanges, "closes"),
};
}
@@ -89,7 +99,11 @@ function keptSourceIntervals(clip: AxcutClip, trimRanges: AxcutTrimRange[]): Int
*
* Zero-length spans are dropped, so a caller can trust `endSec > startSec`.
*/
-export function keptRawSpans(clips: AxcutClip[], trimRanges: AxcutTrimRange[]): RawSpan[] {
+export function keptRawSpans(
+ clips: AxcutClip[],
+ trimRanges: AxcutTrimRange[],
+ insertRanges: readonly AxcutInsertRange[] = [],
+): RawSpan[] {
const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);
const spans: RawSpan[] = [];
for (const clip of ordered) {
@@ -101,7 +115,7 @@ export function keptRawSpans(clips: AxcutClip[], trimRanges: AxcutTrimRange[]):
continue;
}
for (const iv of keptSourceIntervals(clip, trimRanges)) {
- const span = sourceToRaw(clip, iv);
+ const span = sourceToRaw(clip, iv, insertRanges);
if (span.endSec > span.startSec) spans.push(span);
}
}
@@ -126,6 +140,7 @@ export function keptRawSpans(clips: AxcutClip[], trimRanges: AxcutTrimRange[]):
export function removedRawSpans(
clips: AxcutClip[],
trimRanges: AxcutTrimRange[],
+ insertRanges: readonly AxcutInsertRange[] = [],
): RemovedRawSpan[] {
const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);
if (ordered.length === 0) return [];
@@ -154,12 +169,12 @@ export function removedRawSpans(
.filter((trim) => trimAppliesToClip(trim, clip))
.map((trim) => ({
id: trim.id,
- ...sourceToRaw(clip, { startSec: trim.startSec, endSec: trim.endSec }),
+ ...sourceToRaw(clip, { startSec: trim.startSec, endSec: trim.endSec }, insertRanges),
}));
let holeStart = extent.startSec;
for (const iv of kept) {
- const span = sourceToRaw(clip, iv);
+ const span = sourceToRaw(clip, iv, insertRanges);
if (span.startSec > holeStart) {
removed.push(taggedHole(holeStart, span.startSec, applicable));
}
diff --git a/src/lib/ai-edition/timeline/timelineMap.ts b/src/lib/ai-edition/timeline/timelineMap.ts
index 507126f5c..4440b4be0 100644
--- a/src/lib/ai-edition/timeline/timelineMap.ts
+++ b/src/lib/ai-edition/timeline/timelineMap.ts
@@ -18,7 +18,7 @@
// forward by the trimmed duration.
import type { PlaybackSegment } from "../document/timeline";
-import type { AxcutClip } from "../schema";
+import type { AxcutClip, AxcutInsertRange } from "../schema";
import { ventilateSpanAcrossClips } from "./region-ventilation";
import { findRawClipForSegment, getRawVirtualStartTime } from "./virtual-preview";
@@ -402,8 +402,9 @@ export function anchorRegionsWithDerivedMs<
export function segmentRawSpanSec(
segment: PlaybackSegment,
rawClips: AxcutClip[],
+ insertRanges: readonly AxcutInsertRange[] = [],
): { startSec: number; endSec: number } {
- const startSec = getRawVirtualStartTime(segment, rawClips);
+ const startSec = getRawVirtualStartTime(segment, rawClips, insertRanges);
// A held segment's source window is the single frame it shows, so its source length
// is zero — its RAW span is the pause it carries. Without this the playhead could
// never be inside it and would step straight over the pause.
@@ -682,9 +683,10 @@ export function resolveNativePosition(
rawSec: number,
visibleSegments: PlaybackSegment[],
rawClips: AxcutClip[],
+ insertRanges: readonly AxcutInsertRange[] = [],
): NativePosition | null {
if (!Number.isFinite(rawSec) || visibleSegments.length === 0) return null;
- const spans = visibleSegments.map((seg) => segmentRawSpanSec(seg, rawClips));
+ const spans = visibleSegments.map((seg) => segmentRawSpanSec(seg, rawClips, insertRanges));
// Segment whose RAW extent contains the playhead (last segment's end inclusive).
const index = spans.findIndex((s, i) => {
diff --git a/src/lib/ai-edition/timeline/virtual-preview.ts b/src/lib/ai-edition/timeline/virtual-preview.ts
index 1cdc5d2f6..8448ae99d 100644
--- a/src/lib/ai-edition/timeline/virtual-preview.ts
+++ b/src/lib/ai-edition/timeline/virtual-preview.ts
@@ -1,7 +1,8 @@
// Ported from axcut/apps/web/src/lib/virtual-preview.ts — pure time-mapping
// functions shared by the VirtualPreview component and the timeline math.
-import type { AxcutClip } from "../schema";
+import type { AxcutClip, AxcutInsertRange } from "../schema";
+import { sourceToTimelineSec, timelineToSourceSec } from "./inserted-time";
export type VirtualPosition = {
clip: AxcutClip;
@@ -22,6 +23,7 @@ export function clampVirtualTime(clips: AxcutClip[], value: number): number {
export function locateVirtualPosition(
clips: AxcutClip[],
virtualTimeSec: number,
+ insertRanges: readonly AxcutInsertRange[] = [],
): VirtualPosition | null {
if (clips.length === 0) return null;
const clamped = clampVirtualTime(clips, virtualTimeSec);
@@ -32,7 +34,11 @@ export function locateVirtualPosition(
const resolvedIndex = clipIndex >= 0 ? clipIndex : clips.length - 1;
const clip = clips[resolvedIndex];
const clipDuration = (clip.sourceEndSec ?? 0) - clip.sourceStartSec;
- const clipOffset = Math.max(0, Math.min(clipDuration, clamped - clip.timelineStartSec));
+ // Inside an insertion there is no source moment — none of those seconds came from the
+ // file — so this answers with the one the inserted media follows, which is the frame a
+ // decoder should be parked on.
+ const { sourceSec } = timelineToSourceSec(clip, clamped, insertRanges);
+ const clipOffset = Math.max(0, Math.min(clipDuration, sourceSec - clip.sourceStartSec));
return {
clip,
clipIndex: resolvedIndex,
@@ -72,10 +78,19 @@ export function findRawClipForSegment(
* Maps a kept segment (`AxcutClip` from `resolvePlaybackSegments`) back to its
* exact start position on the raw (untrimmed) document timeline.
*/
-export function getRawVirtualStartTime(segment: AxcutClip, rawClips: AxcutClip[]): number {
+export function getRawVirtualStartTime(
+ segment: AxcutClip,
+ rawClips: AxcutClip[],
+ insertRanges: readonly AxcutInsertRange[] = [],
+): number {
const rawClip = findRawClipForSegment(segment, rawClips);
if (!rawClip) return segment.timelineStartSec;
- return rawClip.timelineStartSec + (segment.sourceStartSec - rawClip.sourceStartSec);
+ // A HELD segment is the inserted media itself, so it starts where the insertion opens.
+ // Every other segment starting at that same source moment is the film RESUMING, so it
+ // starts where the insertion closes. Same source second, two different places on the
+ // timeline — which is the whole reason an insertion is media and not a marker.
+ const edge = (segment as { heldSec?: number }).heldSec !== undefined ? "opens" : "closes";
+ return sourceToTimelineSec(rawClip, segment.sourceStartSec, insertRanges, edge);
}
/**
@@ -126,6 +141,7 @@ function toPositionAt(
clips: AxcutClip[],
clipIndex: number,
sourceTimeSec: number,
+ insertRanges: readonly AxcutInsertRange[] = [],
): VirtualPosition {
const clip = clips[clipIndex];
const sourceOffset = Math.max(
@@ -135,7 +151,9 @@ function toPositionAt(
return {
clip,
clipIndex,
- virtualTimeSec: clip.timelineStartSec + sourceOffset,
+ // Not `timelineStartSec + offset`: a clip carrying insertions is longer than its
+ // source window, so a moment past one sits that much further along (issue #560).
+ virtualTimeSec: sourceToTimelineSec(clip, clip.sourceStartSec + sourceOffset, insertRanges),
sourceTimeSec,
};
}
@@ -181,6 +199,7 @@ export function locateSourcePosition(
// its id here so it's preferred whenever the source time still falls
// inside it, before falling back to the ambiguous asset-wide scan.
preferredClipId?: string,
+ insertRanges: readonly AxcutInsertRange[] = [],
): VirtualPosition | null {
if (preferredClipId) {
const preferredIndex = clips.findIndex((clip) => clip.id === preferredClipId);
@@ -198,7 +217,7 @@ export function locateSourcePosition(
(!assetId || clips[preferredIndex].assetId === assetId) &&
isWithinClipBounds(clips[preferredIndex], sourceTimeSec, epsilon, "inclusive")
) {
- return toPositionAt(clips, preferredIndex, sourceTimeSec);
+ return toPositionAt(clips, preferredIndex, sourceTimeSec, insertRanges);
}
}
const scan = (closingEdge: ClosingEdge) =>
@@ -219,7 +238,7 @@ export function locateSourcePosition(
const strict = scan("exclusive");
const clipIndex = strict >= 0 ? strict : scan("inclusive");
if (clipIndex < 0) return null;
- return toPositionAt(clips, clipIndex, sourceTimeSec);
+ return toPositionAt(clips, clipIndex, sourceTimeSec, insertRanges);
}
/**
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index 887b63d79..7fa4f2f03 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -42,7 +42,6 @@ import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";
import { assetCameraSource } from "@/lib/ai-edition/timeline/camera";
import { resolveClipSourceEndSec } from "@/lib/ai-edition/timeline/clipDuration";
import { takeInserts } from "@/lib/ai-edition/timeline/insert-mapping";
-import { rulerInserts } from "@/lib/ai-edition/timeline/inserted-time";
import { removedRawSpans } from "@/lib/ai-edition/timeline/programme-time";
import { takeProgramme } from "@/lib/ai-edition/timeline/take-programme";
import { projectRegionsToSource } from "@/lib/ai-edition/timeline/timelineMap";
@@ -575,7 +574,7 @@ export function buildSceneDescription(
// question, and it does not depend on the track.
// Placed once: the projection below counts them, so a track after a pause lands where
// the ruler says rather than D seconds early.
- const filmInserts = rulerInserts(document.timeline.insertRanges ?? [], projectedClips);
+ const filmInserts = document.timeline.insertRanges ?? [];
const removed = removedRawSpans(projectedClips, document.timeline.trimRanges);
// The take's pills, keyed by group. A voiceover is walked ONCE per pill and never per
// stored fragment: the document keeps one fragment per clip a take covers, so walking
diff --git a/src/native/useNativePlaybackSync.ts b/src/native/useNativePlaybackSync.ts
index f1ab884ed..f9d23c12c 100644
--- a/src/native/useNativePlaybackSync.ts
+++ b/src/native/useNativePlaybackSync.ts
@@ -18,7 +18,7 @@
* re-aligns them.
*/
import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
-import type { AxcutClip } from "@/lib/ai-edition/schema";
+import type { AxcutClip, AxcutInsertRange } from "@/lib/ai-edition/schema";
import { resolveNativePosition } from "@/lib/ai-edition/timeline/timelineMap";
import {
getCurrentNativeViewId,
@@ -34,10 +34,13 @@ export function useNativePlaybackSync(
visibleSegments: readonly AxcutClip[],
/** RAW clip layout (`document.timeline.clips`) `currentTimeSec` is expressed against. */
rawClips: readonly AxcutClip[],
+ /** The insertions those clips carry — a clip is longer than its source window by them,
+ * so a segment's place on the timeline cannot be found without them (issue #560). */
+ insertRanges: readonly AxcutInsertRange[] = [],
): void {
const activePosition = useMemo(
- () => resolveNativePosition(currentTimeSec, [...visibleSegments], [...rawClips]),
- [visibleSegments, rawClips, currentTimeSec],
+ () => resolveNativePosition(currentTimeSec, [...visibleSegments], [...rawClips], insertRanges),
+ [visibleSegments, rawClips, currentTimeSec, insertRanges],
);
const activeClipId = activePosition?.clip.id ?? null;
const sourceTimeSec = activePosition?.sourceTimeSec ?? null;