Skip to content

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

fix(preview): an insertion is media that plays, not a pause

EtienneLescotd2c4740da42f
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 1240d5d8e..fdfcd1110 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -429,8 +429,8 @@ export function NewEditorShell() {
);
const handleTimeChange = useCallback(
- (timeSec: number) => {
- setCurrentTime(timeSec);
+ (timeSec: number, rulerSec?: number) => {
+ setCurrentTime(timeSec, rulerSec);
},
[setCurrentTime],
);
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index e5b80f3dd..7e3ba49b4 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -22,7 +22,11 @@ import type {
} from "@/lib/ai-edition/schema";
import { audioGainScalar } from "@/lib/ai-edition/store/editorSettings";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
-import { holdEnteredBetween, rulerInserts } from "@/lib/ai-edition/timeline/inserted-time";
+import {
+ expandRawSec,
+ 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";
@@ -215,10 +219,12 @@ interface VirtualPreviewProps {
zoomRegions?: AxcutZoomRegion[];
speedRegions?: SpeedRegion[];
trimRanges?: AxcutTrimRange[];
- /** The pauses added words created — they lengthen playback, they do not cut it. */
+ /** The media added words inserted — it lengthens playback, it does not cut it. */
insertRanges?: AxcutInsertRange[];
seekTarget?: { timeSec: number; isSource?: boolean; requestId: number } | null;
- onTimeChange?: (timeSec: number) => void;
+ /** `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;
onLoadedMetadata?: (
durationSec: number,
assetId: string,
@@ -562,30 +568,33 @@ export function VirtualPreview({
trimRangesRef.current = trimRanges;
// What the film no longer contains, recomputed only when the cuts move — the rAF asks
// it once per voiceover per frame, and walking every trim there would be wasteful.
- // The film's pauses, placed on the raw ruler once. The projection needs them or every
- // track after a pause lands D seconds early — the bug this argument exists to close.
- /** The pause the picture is currently sitting on, if any.
+ // The film's insertions, placed on the raw ruler once. The projection needs them or every
+ // track after one lands D seconds early — the bug this argument exists to close.
+ /** The insertion currently playing, if any.
*
- * A word added to a lane buys OUTPUT seconds, and the film has to spend them somewhere.
- * The export spends them holding a frame (`hold_sec`, `walk_composited_timeline`); the
- * ruler spends them by growing (`expandRawSec`); the programme clock spends them by
- * stepping over them (`projectRawTimelineSecToPlayback`). The DOM preview did not spend
- * them at all — the `<video>` ran straight through, because a pause has no frames of its
- * own to decode. So past the first pause the picture was D seconds BEHIND every track
- * positioned on the programme clock, and the preview stopped being the same film as the
- * export (issue #560).
+ * An added word inserts MEDIA inside the clip (issue #560). There is no generator for it
+ * yet, so the stand-in is a fixed frame and silence — but it is a piece of media on the
+ * timeline like any other, and playback runs THROUGH it rather than around it.
*
- * The element is paused and a WALL clock runs the hold out, which is the honest model:
- * the frame is frozen, so media time is exactly what must stop advancing while real time
- * does not. */
- const holdRef = useRef<{
+ * The `<video>` cannot supply those seconds: they are not in the file. So for the
+ * insertion's duration the element is PINNED (`currentTime` held at its source moment,
+ * which is the fixed frame) and MUTED (the inserted audio is silence today). It is
+ * deliberately NOT `pause()`d — the film is playing, and pausing the element told the
+ * whole app otherwise: the store's `playing` flag mirrors the element's `pause` event,
+ * so the transport flipped to stopped the moment an insertion began. */
+ const insertionRef = useRef<{
insertId: string;
rawSec: number;
+ sourceSec: number;
durationSec: number;
startedAtMs: number;
} | null>(null);
- /** Set when the hold interrupted actual playback, so the film resumes on its own. */
- const resumeAfterHoldRef = useRef(false);
+ /** The element's own muted flag, to restore when the insertion ends. */
+ const mutedBeforeInsertionRef = useRef(false);
+ /** How far into the insertion currently playing we are, in ruler seconds. Read by
+ * `updateVirtualTime` so the position it publishes advances ACROSS the insertion while
+ * the raw second it also publishes stands still at the insertion's moment. */
+ const insertionElapsedRef = useRef(0);
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
@@ -689,27 +698,34 @@ export function VirtualPreview({
if (!v || !Number.isFinite(v.currentTime)) {
return;
}
- // Run the pause out FIRST: everything below that is positioned on the programme
- // clock — the imported tracks especially — is still advancing during a hold even
- // though the picture is not, exactly as the render's output stream is.
- let heldElapsedSec = 0;
- const hold = holdRef.current;
- if (hold) {
- heldElapsedSec = Math.min(hold.durationSec, (performance.now() - hold.startedAtMs) / 1000);
- if (heldElapsedSec >= hold.durationSec) {
- holdRef.current = null;
- heldElapsedSec = hold.durationSec;
- if (resumeAfterHoldRef.current) {
- resumeAfterHoldRef.current = false;
- const resumed = v.play();
- if (resumed) void resumed.catch(() => undefined);
+ // Play the insertion FIRST: everything below is positioned against a clock that is
+ // running through it — the imported tracks especially, which sit on the programme
+ // clock exactly as they do in the render's output stream.
+ let insertionElapsedSec = 0;
+ const insertion = insertionRef.current;
+ if (insertion) {
+ insertionElapsedSec = Math.min(
+ insertion.durationSec,
+ (performance.now() - insertion.startedAtMs) / 1000,
+ );
+ if (insertionElapsedSec >= insertion.durationSec) {
+ insertionRef.current = null;
+ insertionElapsedSec = 0;
+ v.muted = mutedBeforeInsertionRef.current;
+ } else {
+ // Re-pinned every frame: the element is still playing, so left alone it
+ // would decode straight past the fixed frame the insertion stands for.
+ if (Math.abs(v.currentTime - insertion.sourceSec) > 0.01) {
+ try {
+ v.currentTime = insertion.sourceSec;
+ } catch {
+ // not seekable this instant; the next frame retries
+ }
}
- } else if (!v.paused) {
- // A `play()` from elsewhere (autoplay, a resume racing the hold) would
- // otherwise let the picture walk out from under the pause.
- v.pause();
+ v.muted = true;
}
}
+ insertionElapsedRef.current = insertionElapsedSec;
for (const audio of [primaryAudioRef.current, supplementalAudioRef.current]) {
if (!audio) continue;
const target = resolveAudioTrackPlayback(v.currentTime, audio.duration);
@@ -746,11 +762,12 @@ export function VirtualPreview({
// was never given a faster `playbackRate`, but seeking it twice as fast
// amounts to the same thing. Dividing raw time by the rate turns that
// back into 1x wall-clock, which is what the render does too.
- // `+ heldElapsedSec`, and only here: the raw playhead is pinned to the held moment
- // for the whole pause, and the projection of that moment is the pause's OPENING
- // (`expandRawSec` and this walk both give the frame about to be held its own
- // instant). Adding the wall-clock elapsed walks the programme through the pause,
- // which is what the mixer downstream is doing over the same seconds.
+ // `+ insertionElapsedSec`, and only here: the RAW playhead stands still at the
+ // insertion's moment for its whole duration — none of those seconds come from the
+ // recording — and the projection of that moment is where the insertion OPENS
+ // (`expandRawSec` and this walk both give the last recorded frame its own instant).
+ // Adding the elapsed walks the programme through the inserted media, which is what
+ // the mixer downstream is doing over the same seconds.
const outputTimeSec =
projectRawTimelineSecToPlayback(
clipsRef.current,
@@ -758,7 +775,7 @@ export function VirtualPreview({
virtualTimeSecRef.current,
filmInsertsRef.current,
speedRegionsRef.current,
- ) + heldElapsedSec;
+ ) + insertionElapsedSec;
for (const track of audioTracksRef.current) {
const el = audioTrackElsRef.current.get(track.id);
if (!el) continue;
@@ -1030,23 +1047,23 @@ export function VirtualPreview({
return;
}
const nextRawTime = clampVirtualTime(clipsRef.current, position.virtualTimeSec);
- // The first pause this frame stepped over — the rule, and why it is half-open,
- // live with the other ruler arithmetic.
- const entering = holdRef.current
+ // The first insertion this frame ran into — the rule, and why it is half-open,
+ // lives with the other ruler arithmetic.
+ const entering = insertionRef.current
? undefined
- : holdEnteredBetween(virtualTimeSecRef.current, nextRawTime, filmInsertsRef.current);
+ : insertionEnteredBetween(virtualTimeSecRef.current, nextRawTime, filmInsertsRef.current);
if (entering) {
- holdRef.current = {
+ mutedBeforeInsertionRef.current = v.muted;
+ insertionRef.current = {
insertId: entering.id,
rawSec: entering.atRawSec,
+ sourceSec: position.sourceTimeSec,
durationSec: entering.durationSec,
startedAtMs: performance.now(),
};
- resumeAfterHoldRef.current = true;
- v.pause();
- // The held moment, not the frame we happened to land on: the transcript cue,
- // the caption lookup and the audio mix all read this, and for the length of
- // the pause the film really is at that one instant.
+ // The insertion's own moment, not the frame we happened to land on: the
+ // transcript cue, the caption lookup and the audio mix all read this, and
+ // through the insertion the RECORDING really is at that one instant.
updateVirtualTime(entering.atRawSec);
return;
}
@@ -1071,7 +1088,14 @@ export function VirtualPreview({
const updateVirtualTime = useCallback(
(nextTimeSec: number) => {
setVirtualTimeSec(nextTimeSec);
- onTimeChange?.(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,
+ );
// 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
@@ -1149,14 +1173,17 @@ export function VirtualPreview({
const seekToVirtualTime = useCallback(
(nextVirtualTimeSec: number, preservePlayback = false, forceResume = false) => {
- // A seek ends any pause the picture was holding: the playhead is somewhere else
- // now, so the frame we were frozen on is not the frame any more. Without this the
- // hold's wall clock would run out under the new position and hand the film back to
- // `play()` — the film starting itself again because the user scrubbed during a
- // pause. The rAF's own seeks (clip advance, trim skip) are gated on `!paused` and
- // so never reach here while a hold is in flight.
- holdRef.current = null;
- resumeAfterHoldRef.current = false;
+ // A seek AWAY ends the insertion that was playing: the playhead is somewhere else
+ // now, so the fixed frame it was pinning is not the frame any more. A seek TO the
+ // insertion's own moment is not "away" — it is the echo of the position this very
+ // tick published, and clearing on it would cut every insertion short the frame it
+ // began.
+ const playingInsertion = insertionRef.current;
+ if (playingInsertion && Math.abs(playingInsertion.rawSec - nextVirtualTimeSec) > 1e-3) {
+ insertionRef.current = null;
+ const el = videoRef.current;
+ if (el) el.muted = mutedBeforeInsertionRef.current;
+ }
const position = locateVirtualPosition(clips, nextVirtualTimeSec);
if (!position) {
videoRef.current?.pause();
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index 1b1d094df..8b202fca8 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -230,14 +230,14 @@ interface RulerTick {
interface PlayheadOverlayProps {
/** Full timeline length in seconds — the denominator for the playhead's percentage. */
totalSec: number;
- /** The pauses added words created. `currentTimeSec` is a STORED second; the ruler it is
- * drawn on counts the pauses, so it has to be placed through them or it drifts from
+ /** 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 a pause, which is zero raw seconds wide. */
+ * that can name a moment INSIDE an insertion, which is zero raw seconds wide. */
overrideRulerSec: number | null;
canvasStyle: React.CSSProperties;
onPointerDown: (e: ReactPointerEvent) => void;
@@ -270,11 +270,27 @@ const PlayheadOverlay = memo(function PlayheadOverlay({
playheadRef,
}: PlayheadOverlayProps) {
const storeTimeSec = useProjectStore((s) => s.currentTimeSec);
- // The scrub hands its RULER position straight through. Expanding the raw one instead
- // would snap the playhead to a pause's left edge the moment the pointer entered it,
- // because every ruler second inside a pause collapses to the same raw moment.
+ 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 ?? expandRawSec(overrideTimeSec ?? storeTimeSec, inserts)) / totalSec) * 100;
+ ((overrideRulerSec ??
+ (overrideTimeSec !== null ? expandRawSec(overrideTimeSec, inserts) : storeSec)) /
+ totalSec) *
+ 100;
return (
<div className={styles.tlPlayheadLayer} aria-hidden>
<div className={styles.tlCanvas} style={canvasStyle}>
@@ -613,7 +629,9 @@ export function V4Timeline({
onAddVoiceover,
}: {
tl: TimelineApi;
- setCurrentTime: (sec: number) => void;
+ /** `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;
variant?: "edit" | "media";
onDropAsset?: (assetId: string) => Promise<void>;
videoSources?: VideoSource[];
@@ -701,11 +719,11 @@ export function V4Timeline({
// clicked instead of looking like it worked. Same question, same helper as the Layout
// pane: is a camera attached anywhere on this timeline?
const hasAnyCamera = useMemo(() => hasAnyClipWithCamera(tl.assets, clips), [tl.assets, clips]);
- // The pauses added words created, placed on the ruler. Everything below measures the
- // EXPANDED ruler — stored clip geometry plus the time those pauses add — because that
+ // The media added words inserted, placed on the ruler. Everything below measures the
+ // EXPANDED ruler — stored clip geometry plus the time those insertions add — because that
// is the film's real length and the one the playhead runs along. Stored geometry is
// never rewritten for this: only what is drawn moves.
- // `?? []` because the key is additive: a document written before it has no pauses.
+ // `?? []` because the key is additive: a document written before it has no insertions.
const inserts = useMemo(
() => rulerInserts(tl.insertRanges ?? [], clips),
[tl.insertRanges, clips],
@@ -841,11 +859,12 @@ export function V4Timeline({
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 a pause — which is
- // zero raw seconds wide, so no raw value can address a moment within it.
+ // 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);
@@ -863,14 +882,15 @@ export function V4Timeline({
// `total` is the EXPANDED ruler, so `pct * total` is a ruler second — and
// `setCurrentTime` is read as a RAW one by every consumer: the preview seek, the
// caption lookup, the transcript cue, the audio mix. Writing the ruler value
- // straight in put the playhead one accumulated pause AHEAD of everything it was
+ // straight in put the playhead one accumulated insertion AHEAD of everything it was
// supposed to be pointing at, which is what showed as the wrong subtitle under a
// correctly-placed playhead (issue #560).
//
- // Collapsing lands on the held moment when the pointer is inside a pause, which
- // is the honest answer: a pause is zero raw seconds, so there is no raw value
- // inside it to seek to. The ruler position is kept separately below so the
- // playhead still follows the pointer across it.
+ // 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);
@@ -883,13 +903,14 @@ export function V4Timeline({
setScrubbingTimeSec(targetTime);
setScrubRulerSec(rulerTime);
pendingSeekTimeRef.current = targetTime;
+ pendingSeekRulerRef.current = rulerTime;
if (isImmediate) {
if (rafSeekRef.current !== 0) {
cancelAnimationFrame(rafSeekRef.current);
rafSeekRef.current = 0;
}
- setCurrentTime(targetTime);
+ setCurrentTime(targetTime, rulerTime);
return;
}
@@ -898,7 +919,7 @@ export function V4Timeline({
rafSeekRef.current = requestAnimationFrame(() => {
rafSeekRef.current = 0;
if (pendingSeekTimeRef.current !== null) {
- setCurrentTime(pendingSeekTimeRef.current);
+ setCurrentTime(pendingSeekTimeRef.current, pendingSeekRulerRef.current ?? undefined);
}
});
}
@@ -1726,8 +1747,8 @@ export function V4Timeline({
}${seg.interactive && isPillSelected(p.id) ? ` ${styles.lanePillSel}` : ""}`}
style={{
left: `${pctAt(seg.segStart)}%`,
- // Measured on the expanded ruler at BOTH ends: a region straddling a pause
- // covers it, so its box has to grow by that pause and not merely slide.
+ // 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))}%`,
transform: seg.shiftPx ? `translateX(${seg.shiftPx}px)` : undefined,
transition: !clipDrag
@@ -2227,7 +2248,7 @@ export function V4Timeline({
assetDurationSec={duration}
// `pctAt`, not `pctOf`: the clip boxes are drawn on the EXPANDED
// ruler and the audio pills were drawn on the stored one, so any
- // pause in the film slid the two lanes apart. The take keeps its
+ // insertion in the film slid the two lanes apart. The take keeps its
// own length — only its head follows the ruler.
leftPct={pctAt(start)}
widthPct={pctOf(widthSec)}
@@ -2291,7 +2312,7 @@ export function V4Timeline({
>
{clips.map((c, i) => {
const dur = c.timelineEndSec - c.timelineStartSec;
- // On the expanded ruler the box also carries whatever pauses fall
+ // 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);
@@ -2373,7 +2394,7 @@ export function V4Timeline({
</span>
</div>
{(insertedWordsByClip.get(c.id) ?? []).map(({ wordId, text, atRawSec }) => {
- // A word whose pause the film holds gets a BAND as wide as the time
+ // A word whose insertion the film plays gets a BAND as wide as the time
// it adds — that width IS the added time, drawn. One that fitted in
// silence already there adds nothing and stays a hairline.
//
@@ -2381,16 +2402,16 @@ export function V4Timeline({
// the expanded ruler and an unpaused one at a fraction of the clip's
// SOURCE span, in the same ternary — two clocks, one of which the
// box is not drawn in.
- const pause = inserts.find((ins) => ins.wordId === wordId);
+ const inserted = inserts.find((ins) => ins.wordId === wordId);
const left = ((expandRawSec(atRawSec, inserts) - boxStart) / boxLen) * 100;
- const width = pause ? (pause.durationSec / boxLen) * 100 : 0;
+ const width = inserted ? (inserted.durationSec / boxLen) * 100 : 0;
return (
<button
key={wordId}
type="button"
data-no-clip-drag
data-inserted-word={wordId}
- data-inserted-sec={pause?.durationSec ?? 0}
+ data-inserted-sec={inserted?.durationSec ?? 0}
className={styles.tlClipInsert}
style={
width > 0
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index c437a3638..d61ce3475 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -13,7 +13,7 @@ import type {
/**
* What `resolvePlaybackSegments` returns: a clip-shaped slice of playable film, plus the
- * one thing a stored clip can never carry — `heldSec`, the pause an added word created.
+ * one thing a stored clip can never carry — `heldSec`, the media an added word inserted.
*
* A held segment's source window is the single frame it shows; its LENGTH is `heldSec`.
* The field lives only on this derived shape, never on `clipSchema`, so nothing can write
@@ -172,8 +172,8 @@ export function resolvePlaybackSegments(
const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);
const result: PlaybackSegment[] = [];
let timelineCursor = 0;
- // The pauses added words need, in the order they will be met. Consumed as the walk
- // passes each one's moment, so a pause inside a span a trim removed is never reached —
+ // The media added words insert, in the order they will be met. Consumed as the walk
+ // passes each one's moment, so an insertion inside a span a trim removed is never reached —
// which is right: the moment it holds is not in the film any more.
const pending = [...insertRanges].sort((a, b) => a.atSec - b.atSec);
const holdAt = (clip: AxcutClip, atSec: number): PlaybackSegment | null => {
@@ -211,10 +211,10 @@ export function resolvePlaybackSegments(
if (!trimAppliesToClip(trim, clip)) continue;
kept = subtractInterval(kept, { startSec: trim.startSec, endSec: trim.endSec });
}
- // A pause sits at the END of the word it follows, which is almost never a boundary a
+ // An insertion sits at the END of the word it follows, which is almost never a boundary a
// trim happened to leave. So each kept span is cut at the moments it holds, and the
// held frame goes between the halves: the stream plays up to that frame, stays on it
- // for the pause, then carries on — which is what makes the film longer.
+ // for the insertion, then carries on — which is what makes the film longer.
const pieces: Array<{ startSec: number; endSec: number; holdAtEnd: boolean }> = [];
for (const iv of kept) {
const moments = pending
@@ -331,9 +331,9 @@ function outputDurationOfRawSpan(
* The raw span that plays for `outSec` OUTPUT seconds starting at `fromRawSec` — the
* inverse of {@link outputDurationOfRawSpan}, and the identity when nothing is sped up.
*
- * A voice-over plays at 1x in the mix, so a pause for a spoken word is D seconds of the
+ * A voice-over plays at 1x in the mix, so an insertion for a spoken word is D seconds of the
* take's own clock. Under a 2x region that is 2 raw seconds, not 1, and getting it wrong
- * puts the resumed narration half a pause out of step with the picture.
+ * puts the resumed narration half an insertion out of step with the picture.
*/
export function rawSpanForOutDuration(
fromRawSec: number,
@@ -372,7 +372,7 @@ export function projectRawTimelineSecToPlayback(
trimRanges: AxcutTrimRange[],
rawSec: number,
/**
- * The recording lane's pauses, already placed on the raw ruler by `rulerInserts`.
+ * The recording lane's insertions, already placed on the raw ruler by `rulerInserts`.
*
* 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
@@ -393,10 +393,10 @@ 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
- // A pause the film holds occupies ZERO raw seconds and D OUTPUT seconds — it is the one
+ // 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 a pause has been landing D seconds early in both the preview
- // and the export. Interleaved here rather than added afterwards, because where the pause
+ // 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;
@@ -408,9 +408,9 @@ export function projectRawTimelineSecToPlayback(
// answers, because a speed region scales it.
for (const seg of keptRawSpans(ordered, trimRanges)) {
let from = seg.startSec;
- // Every pause this segment carries, in order. A pause whose moment a trim removed is
+ // 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 pause.
+ // 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++];
@@ -421,8 +421,8 @@ export function projectRawTimelineSecToPlayback(
}
outCursor += outputDurationOfRawSpan(from, at, speedRegions);
from = at;
- // Strictly after the pause's own moment, matching `expandRawSec`: a track whose
- // head sits exactly there starts WITH the pause, not after it.
+ // 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;
}
diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.ts
index fd47da9cc..69d0cd340 100644
--- a/src/lib/ai-edition/store/projectStore.ts
+++ b/src/lib/ai-edition/store/projectStore.ts
@@ -60,6 +60,20 @@ 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
@@ -146,7 +160,9 @@ export interface ProjectState {
opts: DocumentWriteOptions,
) => Promise<void>;
setSourceDuration: (sec: number) => void;
- setCurrentTime: (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;
setPlaying: (playing: boolean) => void;
markClean: () => void;
/**
@@ -197,6 +213,7 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
error: null,
sourceDurationSec: 0,
currentTimeSec: 0,
+ currentRulerSec: 0,
selectedAudioTrackId: null,
playing: false,
dirty: false,
@@ -549,8 +566,8 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
set({ sourceDurationSec: sec });
},
- setCurrentTime(sec) {
- set({ currentTimeSec: sec });
+ setCurrentTime(sec, rulerSec) {
+ set({ currentTimeSec: sec, currentRulerSec: rulerSec ?? sec });
},
setPlaying(playing) {
@@ -581,6 +598,7 @@ 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 6d4a32ada..bd16a698c 100644
--- a/src/lib/ai-edition/timeline/inserted-time.test.ts
+++ b/src/lib/ai-edition/timeline/inserted-time.test.ts
@@ -10,8 +10,8 @@ import type { AxcutClip, AxcutInsertRange, AxcutWord } from "../schema";
import {
collapseRawSec,
expandRawSec,
- holdEnteredBetween,
insertedWordMarks,
+ insertionEnteredBetween,
type RulerInsert,
rulerInserts,
totalInsertedSec,
@@ -251,8 +251,8 @@ describe("a scrub survives the round trip", () => {
});
it("lands on the held moment for a pointer inside a pause, and says so", () => {
- // Every ruler second inside a pause is the same raw moment: the film is frozen
- // there, so there is nothing else it could mean.
+ // 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");
@@ -266,34 +266,35 @@ describe("a scrub survives the round trip", () => {
});
});
-// ─── Entering a pause ───────────────────────────────────────────────────────
-// The preview holds the picture for a pause the way the export does (`hold_sec`). The
-// half-open rule below is what keeps that from becoming an infinite hold.
+// ─── Running into an insertion ──────────────────────────────────────────────
+// An added word inserts MEDIA inside the clip — a fixed frame and silence, until there is
+// a generator for it. Playback runs THROUGH that media, and the half-open rule below is
+// what keeps it from running through the same insertion forever.
-describe("the pause a frame steps over", () => {
+describe("the insertion a frame runs into", () => {
const marks: RulerInsert[] = [
{ id: "i1", wordId: "w1", atRawSec: 4, durationSec: 2 },
{ id: "i2", wordId: "w2", atRawSec: 9, durationSec: 1 },
];
it("is found when the frame crosses it", () => {
- expect(holdEnteredBetween(3.98, 4.02, marks)?.id).toBe("i1");
- expect(holdEnteredBetween(8.9, 9.1, marks)?.id).toBe("i2");
+ expect(insertionEnteredBetween(3.98, 4.02, marks)?.id).toBe("i1");
+ expect(insertionEnteredBetween(8.9, 9.1, marks)?.id).toBe("i2");
});
- it("is not found again from the moment it holds", () => {
- // The hold pins the playhead to exactly 4. Coming out, the next frames must not
- // re-enter — otherwise the film never gets past the pause.
- expect(holdEnteredBetween(4, 4.02, marks)).toBeUndefined();
- expect(holdEnteredBetween(4, 4.5, marks)).toBeUndefined();
+ it("is not found again from the moment it occupies", () => {
+ // While the insertion plays, the raw playhead stands still at exactly 4. Coming out,
+ // the next frames must not re-enter — otherwise the film never gets past it.
+ expect(insertionEnteredBetween(4, 4.02, marks)).toBeUndefined();
+ expect(insertionEnteredBetween(4, 4.5, marks)).toBeUndefined();
});
it("takes the earliest of several in one frame, and none outside", () => {
- expect(holdEnteredBetween(0, 20, marks)?.id).toBe("i1");
- expect(holdEnteredBetween(5, 8, marks)).toBeUndefined();
+ expect(insertionEnteredBetween(0, 20, marks)?.id).toBe("i1");
+ expect(insertionEnteredBetween(5, 8, marks)).toBeUndefined();
});
- it("holds a pause landing exactly on the frame boundary", () => {
- expect(holdEnteredBetween(3.9, 4, marks)?.id).toBe("i1");
+ it("plays an insertion landing exactly on the frame boundary", () => {
+ expect(insertionEnteredBetween(3.9, 4, marks)?.id).toBe("i1");
});
});
diff --git a/src/lib/ai-edition/timeline/inserted-time.ts b/src/lib/ai-edition/timeline/inserted-time.ts
index 6b6de359d..c6786d25c 100644
--- a/src/lib/ai-edition/timeline/inserted-time.ts
+++ b/src/lib/ai-edition/timeline/inserted-time.ts
@@ -10,23 +10,23 @@
// This module is the arithmetic, and nothing else: pure, no document, no React. It answers
// two questions.
//
-// • Where does a pause land on the RULER? A range is anchored in SOURCE time, so it has
+// • Where does an insertion land on the RULER? A range is anchored in SOURCE time, so it has
// to be projected through whichever clip plays that moment — `rulerInserts`.
-// • What does the ruler look like once the pauses are counted? Stored raw seconds and
+// • What does the ruler look like once the insertions are counted? Stored raw seconds and
// the seconds the user actually scrubs are no longer the same number, and
// `expandRawSec` / `collapseRawSec` are the one place that difference is resolved.
//
-// The two are inverses everywhere except INSIDE a pause, where they cannot be: a stretch
+// The two are inverses everywhere except INSIDE an insertion, where they cannot be: a stretch
// of ruler maps to the single source moment being held. `collapseRawSec` returns that
// moment, which is exactly what a decoder parked on a held frame should be told.
import type { AxcutClip, AxcutInsertRange, AxcutWord } from "../schema";
-/** A pause placed on the raw ruler, ready to be counted. */
+/** An insertion placed on the raw ruler, ready to be counted. */
export interface RulerInsert {
id: string;
wordId: string;
- /** Where the pause begins, in STORED raw seconds — before any pause is counted. */
+ /** Where the insertion begins, in STORED raw seconds — before any insertion is counted. */
atRawSec: number;
durationSec: number;
}
@@ -34,7 +34,7 @@ export interface RulerInsert {
/**
* Project each insert onto the raw ruler through the clip that plays its source moment.
*
- * A range whose moment no clip plays yields nothing: the pause exists for a word that is
+ * A range whose moment no clip plays yields nothing: the insertion exists for a word that is
* not on the timeline, so there is no ruler position for it and nothing to add. Same rule
* the captions follow for a line no clip covers.
*
@@ -49,7 +49,7 @@ export function rulerInserts(
for (const clip of clips) {
if (clip.assetId !== insert.assetId) continue;
const sourceEnd = clip.sourceEndSec ?? Number.POSITIVE_INFINITY;
- // Inclusive at both edges: a pause sits at the END of the word it follows, which
+ // 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;
placed.push({
@@ -64,7 +64,7 @@ export function rulerInserts(
return placed.sort((a, b) => a.atRawSec - b.atRawSec);
}
-/** How much time the pauses add in total — what the ruler grows by. */
+/** 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);
}
@@ -73,8 +73,8 @@ export function totalInsertedSec(inserts: readonly RulerInsert[]): number {
* Stored raw seconds → the ruler the user sees.
*
* Monotone and total: every stored moment has exactly one place on the expanded ruler.
- * A moment sitting exactly ON a pause maps to where the pause BEGINS, so the frame that
- * is about to be held keeps its own instant and the pause opens after it.
+ * 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.
*/
export function expandRawSec(sec: number, inserts: readonly RulerInsert[]): number {
let out = sec;
@@ -87,7 +87,7 @@ export function expandRawSec(sec: number, inserts: readonly RulerInsert[]): numb
/**
* The ruler the user sees → stored raw seconds.
*
- * The inverse of {@link expandRawSec} outside a pause. Inside one it cannot be an inverse
+ * 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.
*/
@@ -108,15 +108,16 @@ export function collapseRawSec(
}
/**
- * The pause a frame of playback stepped over, if it stepped over one.
+ * The insertion a frame of playback ran into, if it ran into one.
*
- * Half-open on the LEFT, and that is the whole point: a player that holds pins its raw
- * playhead to exactly `atRawSec` for the length of the pause, so `>` is what refuses that
- * same moment on the way OUT. With `>=` the pause is re-entered the instant it ends and the
- * film never gets past it. Closed on the right (with the frame epsilon) so a pause landing
- * precisely on a frame boundary is held rather than skipped.
+ * 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.
*/
-export function holdEnteredBetween(
+export function insertionEnteredBetween(
prevRawSec: number,
nextRawSec: number,
inserts: readonly RulerInsert[],
@@ -138,12 +139,12 @@ export interface InsertedWordMark {
/**
* Where each added word's mark belongs, one per word.
*
- * Claimed once, and half-open at a clip's far edge except for the last: a pause sits at the
+ * Claimed once, and half-open at a clip's far edge except for the last: an insertion sits at the
* END of the word it follows, which is routinely a split boundary, and testing both edges
* inclusively painted the same word in BOTH halves (issue #560).
*
* Returns RAW seconds. The caller expands them; it used to mix a raw-then-expanded position
- * for a word with a pause and a fraction of the clip's SOURCE span for one without, in the
+ * for a word with an insertion and a fraction of the clip's SOURCE span for one without, in the
* same ternary — two clocks, and the clip box is not drawn in the second.
*/
export function insertedWordMarks(