Skip to content

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

perf(preview): multi-clip trim jumps, canvas buffers and a decoupled playhead

Etienne Lescot92b0d2fdee5c
diff --git a/src/components/ai-edition/NativeCompositorOverlay.tsx b/src/components/ai-edition/NativeCompositorOverlay.tsx
index caa10a23f..50a9c842c 100644
--- a/src/components/ai-edition/NativeCompositorOverlay.tsx
+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx
@@ -133,17 +133,24 @@ export function NativeCompositorOverlay() {
// arriving after mount never gets pushed to native).
}, [viewId, document, sources, _webcamSizeRevision]);
+ const activeClipId = activeClip?.id ?? null;
+ const activeClipIndex = activePosition?.clipIndex ?? null;
+ const activeSourceTimeSec = activePosition?.sourceTimeSec ?? null;
+ const pendingTargetClipIdRef = useRef<string | null>(null);
+
// Change les décodeurs screen/webcam uniquement quand le playhead entre dans un autre clip.
- // `currentTimeSec` est déjà rafraîchi par la boucle de lecture existante ; aucun timer dédié.
useEffect(() => {
- if (viewId === null || !document) {
+ if (
+ viewId === null ||
+ !document ||
+ !activeClipId ||
+ !activeClip ||
+ activeClipIndex === null ||
+ activeSourceTimeSec === null
+ ) {
return;
}
- if (!activeClip || !activePosition) {
- previousActiveClipIdRef.current = null;
- return;
- }
- if (previousActiveClipIdRef.current === activeClip.id) {
+ if (previousActiveClipIdRef.current === activeClipId) {
return;
}
const asset = document.assets.find((candidate) => candidate.id === activeClip.assetId);
@@ -151,18 +158,30 @@ export function NativeCompositorOverlay() {
return;
}
const cam = asset.cameraTrack;
+ const targetClipId = activeClipId;
+ pendingTargetClipIdRef.current = targetClipId;
+ previousActiveClipIdRef.current = targetClipId;
+
setActiveClip(
viewId,
asset.originalPath,
cam?.sourcePath ?? asset.originalPath,
cam ? (cam.startMs + cam.offsetMs) / 1000 : 0,
- activePosition.clipIndex,
- activePosition.sourceTimeSec,
- ).catch((error: unknown) => {
- console.warn("[compositor-view] setActiveClip failed:", error);
- });
- previousActiveClipIdRef.current = activeClip.id;
- }, [viewId, document, activeClip, activePosition]);
+ activeClipIndex,
+ activeSourceTimeSec,
+ )
+ .then(() => {
+ if (pendingTargetClipIdRef.current !== targetClipId) {
+ return;
+ }
+ })
+ .catch((error: unknown) => {
+ console.warn("[compositor-view] setActiveClip failed:", error);
+ if (previousActiveClipIdRef.current === targetClipId) {
+ previousActiveClipIdRef.current = null;
+ }
+ });
+ }, [viewId, document, activeClipId, activeClip, activeClipIndex, activeSourceTimeSec]);
if (!ready) {
return null;
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index b601d45b1..3515643bc 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -11,6 +11,8 @@ import type { PlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock"
import { findActiveSpeedRegion, type SpeedRegion } from "@/lib/ai-edition/timeline/speed";
import {
clampVirtualTime,
+ findNextKeptSegment,
+ getRawVirtualStartTime,
locateSourcePosition,
locateVirtualPosition,
totalVirtualDuration,
@@ -41,25 +43,6 @@ function findNextClipByTimelineOrder(
.sort((a, b) => a.timelineStartSec - b.timelineStartSec)[0];
}
-/** The next KEPT (non-trimmed) source second on this asset, at or after `afterSourceTimeSec` —
- * where the decode-clock `<video>` should jump to when its own `currentTime` has drifted into
- * a trimmed span. `playbackClips` (see `resolvePlaybackSegments`) already only contains kept
- * sub-windows, so "smallest sourceStartSec still ahead" IS the next un-cut content; no new
- * interval math, just a lookup over the existing trim-narrowed list. */
-function nextKeptSourceTime(
- playbackClips: AxcutClip[],
- assetId: string | undefined,
- afterSourceTimeSec: number,
-): number | null {
- let best: number | null = null;
- for (const clip of playbackClips) {
- if (clip.assetId !== assetId) continue;
- if (clip.sourceStartSec <= afterSourceTimeSec) continue;
- if (best === null || clip.sourceStartSec < best) best = clip.sourceStartSec;
- }
- return best;
-}
-
interface VirtualPreviewProps {
videoSources: VideoSource[];
clips: AxcutClip[];
@@ -230,18 +213,21 @@ export function VirtualPreview({
activeSourceId,
);
if (!inKeptSegment) {
- const jumpTo = nextKeptSourceTime(
+ const nextKeptSegment = findNextKeptSegment(
playbackClipsRef.current,
+ clipsRef.current,
+ virtualTimeSecRef.current,
activeSourceId,
v.currentTime,
);
- if (jumpTo !== null) {
- v.currentTime = jumpTo;
+ if (nextKeptSegment) {
+ const rawTargetTime = getRawVirtualStartTime(nextKeptSegment, clipsRef.current);
+ seekToVirtualTime(rawTargetTime, true);
return;
}
- // No more kept content ahead on this asset — fall through to the existing
- // reachedClipEnd/!position handling below (RAW clips), which already covers
- // end-of-clip/pause correctly.
+ v.pause();
+ updateVirtualTime(virtualDurationSecRef.current);
+ return;
}
}
// ponytail: also push setSourceTimeSec every frame (was previously
diff --git a/src/components/ai-edition/preview-compositor/PreviewCompositor.tsx b/src/components/ai-edition/preview-compositor/PreviewCompositor.tsx
index 23d346980..02c787d23 100644
--- a/src/components/ai-edition/preview-compositor/PreviewCompositor.tsx
+++ b/src/components/ai-edition/preview-compositor/PreviewCompositor.tsx
@@ -24,12 +24,15 @@ import { Application, Container, Graphics, Sprite, Texture, VideoSource } from "
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { fromFileUrl } from "@/components/video-editor/projectPersistence";
import { MAX_NATIVE_PLAYBACK_RATE } from "@/components/video-editor/types";
+import { resolvePlaybackSegments } from "@/lib/ai-edition/document/timeline";
import type { AxcutClip, AxcutTrimRange, AxcutZoomRegion } from "@/lib/ai-edition/schema";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import type { PlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock";
import { findActiveSpeedRegion, type SpeedRegion } from "@/lib/ai-edition/timeline/speed";
import {
clampVirtualTime,
+ findNextKeptSegment,
+ getRawVirtualStartTime,
locateSourcePosition,
locateVirtualPosition,
totalVirtualDuration,
@@ -116,6 +119,12 @@ export function PreviewCompositor({
speedRegionsRef.current = speedRegions;
const trimRangesRef = useRef(trimRanges);
trimRangesRef.current = trimRanges;
+ const playbackClips = useMemo(
+ () => resolvePlaybackSegments(clips, trimRanges),
+ [clips, trimRanges],
+ );
+ const playbackClipsRef = useRef(playbackClips);
+ playbackClipsRef.current = playbackClips;
const updateVirtualTime = useCallback(
(nextTimeSec: number) => {
@@ -158,18 +167,27 @@ export function PreviewCompositor({
}
const activeSourceId = videoSourcesRef.current[sourceIndexRef.current]?.id;
if (!v.paused) {
- const activeTrim = trimRangesRef.current.find(
- (skip) =>
- skip.assetId === activeSourceId &&
- v.currentTime >= skip.startSec &&
- v.currentTime < skip.endSec,
+ const inKeptSegment = locateSourcePosition(
+ playbackClipsRef.current,
+ v.currentTime,
+ activeSourceId,
);
- if (activeTrim) {
- if (activeTrim.endSec >= (v.duration || Infinity)) {
- v.pause();
- } else {
- v.currentTime = activeTrim.endSec + 0.05;
+ if (!inKeptSegment) {
+ const nextKeptSegment = findNextKeptSegment(
+ playbackClipsRef.current,
+ clipsRef.current,
+ virtualTimeSecRef.current,
+ activeSourceId,
+ v.currentTime,
+ );
+ if (nextKeptSegment) {
+ const rawTargetTime = getRawVirtualStartTime(nextKeptSegment, clipsRef.current);
+ seekToVirtualTime(rawTargetTime, true);
+ return;
}
+ v.pause();
+ updateVirtualTime(virtualDurationSecRef.current);
+ setIsPlaying(false);
return;
}
}
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index 9df1cc6ab..c79c41820 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -290,9 +290,14 @@ export function V4Timeline({
return out;
}, [total]);
+ const [scrubbingTimeSec, setScrubbingTimeSec] = useState<number | null>(null);
+ const effectiveTimeSec = scrubbingTimeSec ?? currentTimeSec;
+ const rafSeekRef = useRef<number>(0);
+ const pendingSeekTimeRef = useRef<number | null>(null);
+
// ── interactions ────────────────────────────────────────────────
const seekToClientX = useCallback(
- (clientX: number) => {
+ (clientX: number, isImmediate = false) => {
// Measure the canvas (the zoomed timeline frame): (clientX - left)/width
// is the fraction along the FULL timeline under the cursor, so it stays
// correct under zoom/pan and is unaffected by padding or the scrollbar.
@@ -300,7 +305,30 @@ export function V4Timeline({
if (!el) return;
const r = el.getBoundingClientRect();
const pct = Math.min(1, Math.max(0, (clientX - r.left) / r.width));
- setCurrentTime(pct * total);
+ const targetTime = pct * total;
+
+ // Optimistic local UI update (0ms latency for playhead line & readout)
+ setScrubbingTimeSec(targetTime);
+ pendingSeekTimeRef.current = targetTime;
+
+ if (isImmediate) {
+ if (rafSeekRef.current !== 0) {
+ cancelAnimationFrame(rafSeekRef.current);
+ rafSeekRef.current = 0;
+ }
+ setCurrentTime(targetTime);
+ return;
+ }
+
+ // Throttled store update / D3D seek via rAF to avoid IPC flooding
+ if (rafSeekRef.current === 0) {
+ rafSeekRef.current = requestAnimationFrame(() => {
+ rafSeekRef.current = 0;
+ if (pendingSeekTimeRef.current !== null) {
+ setCurrentTime(pendingSeekTimeRef.current);
+ }
+ });
+ }
},
[setCurrentTime, total],
);
@@ -319,16 +347,25 @@ export function V4Timeline({
const target = e.target as HTMLElement;
if (target.closest("[data-clip-id]") || target.closest(`.${styles.lanePill}`)) return;
tl.clearSelection();
- seekToClientX(e.clientX);
+ seekToClientX(e.clientX, true);
const move = (ev: PointerEvent) => seekToClientX(ev.clientX);
const up = () => {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", up);
+ if (rafSeekRef.current !== 0) {
+ cancelAnimationFrame(rafSeekRef.current);
+ rafSeekRef.current = 0;
+ }
+ if (pendingSeekTimeRef.current !== null) {
+ setCurrentTime(pendingSeekTimeRef.current);
+ pendingSeekTimeRef.current = null;
+ }
+ setScrubbingTimeSec(null);
};
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
},
- [seekToClientX, tl],
+ [seekToClientX, tl, setCurrentTime],
);
// Drag a lane pill to move it (mode "move", keeps duration) or resize one
@@ -974,7 +1011,7 @@ export function V4Timeline({
<TransportBar
playing={playing}
loop={loop}
- currentTimeSec={currentTimeSec}
+ currentTimeSec={effectiveTimeSec}
clips={clips}
onTogglePlay={onTogglePlay}
onPrevClip={onPrevClip}
@@ -1148,7 +1185,7 @@ export function V4Timeline({
continuous from the ruler down through the clips and its head aligns. */}
<div className={styles.tlPlayheadLayer} aria-hidden>
<div className={styles.tlCanvas} style={canvasStyle}>
- <div className={styles.tlPlayhead} style={{ left: `${pctOf(currentTimeSec)}%` }}>
+ <div className={styles.tlPlayhead} style={{ left: `${pctOf(effectiveTimeSec)}%` }}>
<span
className={styles.tlPlayheadDiamond}
style={{ pointerEvents: "auto", cursor: "grab" }}
diff --git a/src/lib/ai-edition/timeline/virtual-preview.test.ts b/src/lib/ai-edition/timeline/virtual-preview.test.ts
index 052ff440f..79a1ef141 100644
--- a/src/lib/ai-edition/timeline/virtual-preview.test.ts
+++ b/src/lib/ai-edition/timeline/virtual-preview.test.ts
@@ -2,7 +2,9 @@ import { describe, expect, it } from "vitest";
import type { AxcutClip } from "../schema";
import {
clampVirtualTime,
+ findNextKeptSegment,
formatSeconds,
+ getRawVirtualStartTime,
keptWordIdSet,
locateSourcePosition,
locateVirtualPosition,
@@ -159,4 +161,109 @@ describe("virtual-preview pure functions", () => {
const outOfRange = locateSourcePosition(duplicateClips, 5, "a1", 0.05, "clip_3");
expect(outOfRange?.clip.id).toBe("clip_1");
});
+
+ it("getRawVirtualStartTime maps a kept segment back to exact raw virtual start time", () => {
+ const rawClips: AxcutClip[] = [
+ {
+ id: "clip_1",
+ assetId: "a1",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ {
+ id: "clip_2",
+ assetId: "a2",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 10,
+ timelineEndSec: 20,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ];
+
+ const segClip1Part2: AxcutClip = {
+ ...rawClips[0],
+ id: "clip_1_seg2",
+ sourceStartSec: 6,
+ sourceEndSec: 10,
+ timelineStartSec: 3,
+ timelineEndSec: 7,
+ };
+
+ const segClip2Part1: AxcutClip = {
+ ...rawClips[1],
+ id: "clip_2",
+ sourceStartSec: 3.2,
+ sourceEndSec: 10,
+ timelineStartSec: 7,
+ timelineEndSec: 13.8,
+ };
+
+ expect(getRawVirtualStartTime(segClip1Part2, rawClips)).toBe(6);
+ expect(getRawVirtualStartTime(segClip2Part1, rawClips)).toBe(13.2);
+ });
+
+ it("findNextKeptSegment finds next kept segment across multi-clip trim boundary", () => {
+ const rawClips: AxcutClip[] = [
+ {
+ id: "clip_1",
+ assetId: "a1",
+ sourceStartSec: 0,
+ sourceEndSec: 7.5,
+ timelineStartSec: 0,
+ timelineEndSec: 7.5,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ {
+ id: "clip_2",
+ assetId: "a2",
+ sourceStartSec: 0,
+ sourceEndSec: 7.5,
+ timelineStartSec: 7.5,
+ timelineEndSec: 15.0,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ];
+
+ // Multi-clip trim cut 2.5..7.5 on clip_1 and 0..3.2 on clip_2.
+ // Kept segments:
+ // seg 0: clip_1, source 0..2.5, timelineStart 0
+ // seg 1: clip_2, source 3.2..7.5, timelineStart 2.5
+ const playbackClips: AxcutClip[] = [
+ {
+ ...rawClips[0],
+ id: "clip_1",
+ sourceStartSec: 0,
+ sourceEndSec: 2.5,
+ timelineStartSec: 0,
+ timelineEndSec: 2.5,
+ },
+ {
+ ...rawClips[1],
+ id: "clip_2",
+ sourceStartSec: 3.2,
+ sourceEndSec: 7.5,
+ timelineStartSec: 2.5,
+ timelineEndSec: 6.8,
+ },
+ ];
+
+ // At current raw virtual time 2.5s (end of seg 0), next kept segment is seg 1 (clip_2)
+ const nextSeg = findNextKeptSegment(playbackClips, rawClips, 2.5, "a1", 2.5);
+ expect(nextSeg).toBeDefined();
+ expect(nextSeg?.id).toBe("clip_2");
+ expect(nextSeg?.assetId).toBe("a2");
+ expect(getRawVirtualStartTime(nextSeg!, rawClips)).toBe(10.7);
+ });
});
diff --git a/src/lib/ai-edition/timeline/virtual-preview.ts b/src/lib/ai-edition/timeline/virtual-preview.ts
index ab2ea1a97..8e6a63632 100644
--- a/src/lib/ai-edition/timeline/virtual-preview.ts
+++ b/src/lib/ai-edition/timeline/virtual-preview.ts
@@ -41,6 +41,52 @@ export function locateVirtualPosition(
};
}
+/**
+ * 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 {
+ const rawClip =
+ rawClips.find((c) => c.id === segment.id || segment.id.startsWith(`${c.id}_seg`)) ??
+ rawClips.find(
+ (c) =>
+ c.assetId === segment.assetId &&
+ segment.sourceStartSec >= c.sourceStartSec - 0.001 &&
+ (c.sourceEndSec == null || segment.sourceStartSec <= c.sourceEndSec + 0.001),
+ );
+
+ if (!rawClip) return segment.timelineStartSec;
+ return rawClip.timelineStartSec + (segment.sourceStartSec - rawClip.sourceStartSec);
+}
+
+/**
+ * Resolves the next kept segment on the virtual timeline at or after the given position.
+ * `playbackClips` (from `resolvePlaybackSegments`) is the SSOT for kept timeline content.
+ */
+export function findNextKeptSegment(
+ playbackClips: AxcutClip[],
+ rawClips: AxcutClip[],
+ currentRawTime: number,
+ activeSourceId?: string,
+ currentSourceTime?: number,
+): AxcutClip | undefined {
+ for (const seg of playbackClips) {
+ const segRawStart = getRawVirtualStartTime(seg, rawClips);
+ if (segRawStart > currentRawTime + 0.001) {
+ return seg;
+ }
+ if (
+ activeSourceId &&
+ currentSourceTime !== undefined &&
+ seg.assetId === activeSourceId &&
+ seg.sourceStartSec > currentSourceTime + 0.001
+ ) {
+ return seg;
+ }
+ }
+ return undefined;
+}
+
function toPositionAt(
clips: AxcutClip[],
clipIndex: number,
diff --git a/src/native/hooks/useNativeCompositorView.ts b/src/native/hooks/useNativeCompositorView.ts
index 9692bea40..0656e742c 100644
--- a/src/native/hooks/useNativeCompositorView.ts
+++ b/src/native/hooks/useNativeCompositorView.ts
@@ -139,12 +139,12 @@ export function useNativeCompositorView(
rectRafHandle = requestAnimationFrame(applyRectNow);
};
+ let reusablePixels: Uint8ClampedArray | null = null;
+ let reusableImageData: ImageData | null = null;
+
/** rAF pull loop: throttle to ~30fps and paint the returned buffer
- * into the canvas via `putImageData`. `putImageData` is the natural
- * fit for a raw RGBA pixel buffer (no scaling, no compositing —
- * the bytes ARE the pixels). If the GPU-readback story ever needs
- * to be faster (e.g. higher refresh rates), switching to
- * `createImageBitmap` + `ctx.drawImage` is a localized swap here. */
+ * into the canvas via createImageBitmap + drawImage (hardware GPU blitting).
+ * Runs decoding off the main thread so UI interactions stay at 60/120fps. */
const pullLoop = () => {
pullRafHandle = requestAnimationFrame(pullLoop);
if (disposed) {
@@ -174,15 +174,25 @@ export function useNativeCompositorView(
if (buffer.byteLength !== expected || canvas.width === 0 || canvas.height === 0) {
return;
}
- // `buffer` is `Uint8ClampedArray<ArrayBufferLike>` (Node's Buffer
- // generic defaults to ArrayBufferLike, which the ImageData ctor
- // rejects — it wants `Uint8ClampedArray<ArrayBuffer>` exactly).
- // Copying into a fresh ArrayBuffer-backed array keeps the type
- // system happy; the memcpy is ~1ms at 1080p RGBA on a modern CPU,
- // well under our 30fps budget.
- const pixels = new Uint8ClampedArray(buffer.byteLength);
- pixels.set(buffer);
- ctx.putImageData(new ImageData(pixels, canvas.width, canvas.height), 0, 0);
+ if (!reusablePixels || reusablePixels.byteLength !== buffer.byteLength) {
+ reusablePixels = new Uint8ClampedArray(buffer.byteLength);
+ reusableImageData = new ImageData(reusablePixels, canvas.width, canvas.height);
+ }
+ reusablePixels.set(buffer);
+ if (reusableImageData) {
+ createImageBitmap(reusableImageData)
+ .then((bitmap) => {
+ if (!disposed && ctx) {
+ ctx.drawImage(bitmap, 0, 0);
+ }
+ bitmap.close();
+ })
+ .catch(() => {
+ if (!disposed && reusableImageData && ctx) {
+ ctx.putImageData(reusableImageData, 0, 0);
+ }
+ });
+ }
})
.catch((error: unknown) => {
console.warn("[compositor-view] readFrame failed:", error);
diff --git a/src/native/useNativePlaybackSync.ts b/src/native/useNativePlaybackSync.ts
index 4c6ba5c9f..6b82cb4f8 100644
--- a/src/native/useNativePlaybackSync.ts
+++ b/src/native/useNativePlaybackSync.ts
@@ -17,7 +17,7 @@
* drift (independent tickers); acceptable for the fixture (~6 s loop). A pause
* re-aligns them.
*/
-import { useEffect, useMemo, useSyncExternalStore } from "react";
+import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import type { AxcutClip } from "@/lib/ai-edition/schema";
import {
getCurrentNativeViewId,
@@ -32,12 +32,13 @@ export function useNativePlaybackSync(
currentTimeSec: number,
clips: readonly AxcutClip[],
): void {
- // `currentTimeSec` is the app's absolute timeline clock. Rust's live player expects the
- // active clip's source-media clock, including its source trim offset.
- const sourceTimeSec = useMemo(
- () => resolveNativePlaybackPosition(clips, currentTimeSec)?.sourceTimeSec ?? null,
+ const activePosition = useMemo(
+ () => resolveNativePlaybackPosition(clips, currentTimeSec),
[clips, currentTimeSec],
);
+ const activeClipId = activePosition?.clip.id ?? null;
+ const sourceTimeSec = activePosition?.sourceTimeSec ?? null;
+
// Reactive "is a native view active?" so activation mid-session re-pushes the
// current transport/playhead (time & playing aren't memoised in the store).
const active = useSyncExternalStore(
@@ -53,11 +54,44 @@ export function useNativePlaybackSync(
setNativePlaying(playing);
}, [active, playing]);
- // Scrub/step while paused → discrete seek (see header for why not during play).
+ // Scrub/step while paused OR periodic resync during playback when drift > 100ms
+ const lastSyncedSourceTimeRef = useRef<number | null>(null);
+ const lastSyncedWallTimeRef = useRef<number>(0);
+ const lastActiveClipIdRef = useRef<string | null>(null);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: ref values
useEffect(() => {
- if (!active || playing || sourceTimeSec === null) {
+ if (!active || sourceTimeSec === null || !activeClipId) {
+ return;
+ }
+ const now = performance.now();
+
+ // When clip changes, let setActiveClip handle the atomic clip-switch-and-seek.
+ if (lastActiveClipIdRef.current !== activeClipId) {
+ lastActiveClipIdRef.current = activeClipId;
+ lastSyncedSourceTimeRef.current = sourceTimeSec;
+ lastSyncedWallTimeRef.current = now;
return;
}
- setNativeTime(sourceTimeSec);
- }, [active, playing, sourceTimeSec]);
+
+ if (!playing) {
+ setNativeTime(sourceTimeSec);
+ lastSyncedSourceTimeRef.current = sourceTimeSec;
+ lastSyncedWallTimeRef.current = now;
+ return;
+ }
+ // While playing: periodically verify master clock alignment to prevent drift
+ if (lastSyncedSourceTimeRef.current === null || lastSyncedWallTimeRef.current === 0) {
+ lastSyncedSourceTimeRef.current = sourceTimeSec;
+ lastSyncedWallTimeRef.current = now;
+ return;
+ }
+ const wallElapsedSec = (now - lastSyncedWallTimeRef.current) / 1000;
+ const expectedSourceTimeSec = lastSyncedSourceTimeRef.current + wallElapsedSec;
+ if (Math.abs(sourceTimeSec - expectedSourceTimeSec) > 0.1) {
+ setNativeTime(sourceTimeSec);
+ lastSyncedSourceTimeRef.current = sourceTimeSec;
+ lastSyncedWallTimeRef.current = now;
+ }
+ }, [active, playing, activeClipId, sourceTimeSec]);
}