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): keep one demuxer seek in flight instead of ~60 a second

EtienneLescotc267418b6b7b
diff --git a/src/components/ai-edition/VirtualPreview.seekStorm.test.tsx b/src/components/ai-edition/VirtualPreview.seekStorm.test.tsx
new file mode 100644
index 000000000..bb0d97cbd
--- /dev/null
+++ b/src/components/ai-edition/VirtualPreview.seekStorm.test.tsx
@@ -0,0 +1,150 @@
+// @vitest-environment jsdom
+import "@testing-library/jest-dom";
+import { act, cleanup, fireEvent, render } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { AxcutClip } from "@/lib/ai-edition/schema";
+import { type VideoSource, VirtualPreview } from "./VirtualPreview";
+
+// The root cause of issue #395, in a test.
+//
+// Dragging the playhead publishes a new time every rAF, the shell mints a
+// seekTarget per publish, and this component used to turn each one into a
+// `currentTime` write — ~60 demuxer seeks a second on a 1080p H.264 file the
+// native compositor is decoding at the same time. Chromium eventually fails
+// one (`PIPELINE_ERROR_READ: FFmpegDemuxer: demuxer seek failed`, observed on a
+// file ffmpeg decodes end to end without a defect), and on main any media error
+// emptied the editor.
+
+afterEach(cleanup);
+
+const SOURCES: VideoSource[] = [{ id: "a1", src: "file:///tmp/a1.mp4", label: "a1" }];
+const CLIPS: AxcutClip[] = [
+ {
+ id: "clip_1",
+ assetId: "a1",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+];
+
+/** A `<video>` that behaves like a real one on the only axis this file tests:
+ * a `currentTime` write starts a seek, and the element stays `seeking` until
+ * the browser says otherwise. */
+function driveVideo(element: HTMLVideoElement) {
+ let currentTime = 0;
+ let seeking = false;
+ const writes: number[] = [];
+ Object.defineProperty(element, "currentTime", {
+ configurable: true,
+ get: () => currentTime,
+ set: (next: number) => {
+ currentTime = next;
+ seeking = true;
+ writes.push(next);
+ },
+ });
+ Object.defineProperty(element, "seeking", { configurable: true, get: () => seeking });
+ Object.defineProperty(element, "paused", { configurable: true, get: () => true });
+ Object.defineProperty(element, "readyState", { configurable: true, get: () => 4 });
+ Object.defineProperty(element, "duration", { configurable: true, get: () => 10 });
+ element.play = vi.fn(() => Promise.resolve());
+ element.pause = vi.fn();
+ return {
+ writes,
+ get currentTime() {
+ return currentTime;
+ },
+ /** What the browser does when the demuxer is done. */
+ finishSeek: () => {
+ seeking = false;
+ act(() => {
+ fireEvent.seeked(element);
+ });
+ },
+ };
+}
+
+function mount() {
+ let requestId = 0;
+ const tree = (seekTarget: { timeSec: number; requestId: number } | null) => (
+ <VirtualPreview videoSources={SOURCES} clips={CLIPS} seekTarget={seekTarget} />
+ );
+ const view = render(tree(null));
+ const element = view.container.querySelector("video");
+ if (!element) throw new Error("no <video> rendered");
+ const video = driveVideo(element as HTMLVideoElement);
+ act(() => {
+ fireEvent.loadedMetadata(element);
+ });
+ video.writes.length = 0;
+ return {
+ video,
+ /** One rAF-throttled scrub publish, the way the shell emits them. */
+ scrubTo: (timeSec: number) =>
+ act(() => {
+ requestId += 1;
+ view.rerender(tree({ timeSec, requestId }));
+ }),
+ };
+}
+
+describe("VirtualPreview keeps one demuxer seek in flight (issue #395 root cause)", () => {
+ it("does not stack a seek onto an element that is still seeking", () => {
+ const { video, scrubTo } = mount();
+
+ scrubTo(2);
+ expect(video.writes).toEqual([2]); // demuxer busy from here
+
+ scrubTo(4);
+ scrubTo(6);
+ scrubTo(8);
+
+ // Three more scrub publishes, no extra seeks: this is the storm that made
+ // the demuxer fail.
+ expect(video.writes).toEqual([2]);
+ });
+
+ it("applies the newest target once the demuxer is free, not the queued ones", () => {
+ const { video, scrubTo } = mount();
+
+ scrubTo(2);
+ scrubTo(4);
+ scrubTo(6);
+ scrubTo(8);
+
+ video.finishSeek();
+
+ // The last position the user asked for — the intermediate ones were never
+ // destinations, and replaying them would be the storm again, delayed.
+ expect(video.writes).toEqual([2, 8]);
+ expect(video.currentTime).toBe(8);
+ });
+
+ it("stops seeking once the playhead settles", () => {
+ const { video, scrubTo } = mount();
+
+ scrubTo(5);
+ video.finishSeek();
+ expect(video.writes).toEqual([5]);
+
+ // The drag ended on the position already reached: nothing more to do.
+ scrubTo(5);
+ video.finishSeek();
+ expect(video.writes).toEqual([5]);
+ });
+
+ it("still serves an ordinary seek immediately when nothing is in flight", () => {
+ const { video, scrubTo } = mount();
+
+ scrubTo(3);
+ video.finishSeek();
+ scrubTo(7);
+
+ expect(video.writes).toEqual([3, 7]);
+ });
+});
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index 68c3e7d3b..a69a336ce 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -137,6 +137,8 @@ export function VirtualPreview({
const videoFrameRef = useRef<HTMLDivElement | null>(null);
const isProgrammaticSeekRef = useRef(false);
+ // The seek that arrived while another was still running (see applySourceTime).
+ const pendingScrubTargetRef = useRef<number | null>(null);
const pendingSeekRef = useRef<{ sourceTimeSec: number; play: boolean } | null>(null);
// Reload bookkeeping for the mounted source (see `reloadActiveSource`).
// `attempts` is spent by failures and re-armed by playing past the point one
@@ -490,6 +492,39 @@ export function VirtualPreview({
frame.style.transform = `translate(${transform.translateXPercent}%, ${transform.translateYPercent}%) scale(${transform.scale})`;
}, [zoomRegions, virtualTimeSec]);
+ /**
+ * Write a source position onto the element with AT MOST ONE demuxer seek in
+ * flight; a target that arrives while one is running replaces the queue and
+ * is applied on `seeked`. Latest wins — an intermediate scrub position is
+ * never a destination the user asked to see.
+ *
+ * This is the root cause of #395, not a mitigation of it. Dragging the
+ * playhead makes V4Timeline publish a new time every rAF (it already
+ * coalesces pointermove to that, "to avoid IPC flooding"), the shell mints a
+ * seekTarget per publish, and this component turned each one into a
+ * `currentTime` write: ~60 demuxer seeks a second on a 1080p H.264 file that
+ * the native compositor is decoding at the same time. Chromium eventually
+ * fails one — `PIPELINE_ERROR_READ: FFmpegDemuxer: demuxer seek failed`,
+ * reproduced on a file ffmpeg decodes end to end without a single defect —
+ * and before this branch, any media error emptied the editor.
+ */
+ const applySourceTime = useCallback((video: HTMLVideoElement, sourceTimeSec: number) => {
+ if (!Number.isFinite(sourceTimeSec)) return;
+ if (Math.abs(video.currentTime - sourceTimeSec) <= 0.01) {
+ pendingScrubTargetRef.current = null;
+ return;
+ }
+ if (video.seeking) {
+ pendingScrubTargetRef.current = sourceTimeSec;
+ return;
+ }
+ pendingScrubTargetRef.current = null;
+ // Flagged at the moment of the ACTUAL write: a deferred target must not
+ // have its flag consumed by a frame on which no seek happened.
+ isProgrammaticSeekRef.current = true;
+ video.currentTime = sourceTimeSec;
+ }, []);
+
const seekToVirtualTime = useCallback(
(nextVirtualTimeSec: number, preservePlayback = false, forceResume = false) => {
const position = locateVirtualPosition(clips, nextVirtualTimeSec);
@@ -549,11 +584,8 @@ export function VirtualPreview({
play: shouldContinuePlayback,
};
}
- isProgrammaticSeekRef.current = true;
updateVirtualTime(position.virtualTimeSec);
- if (Math.abs(video.currentTime - position.sourceTimeSec) > 0.01) {
- video.currentTime = position.sourceTimeSec;
- }
+ applySourceTime(video, position.sourceTimeSec);
if (shouldContinuePlayback) {
// A rejection here means playback never actually started, so the browser
// never fired 'play' — nothing to reconcile, just avoid an unhandled
@@ -563,17 +595,23 @@ export function VirtualPreview({
});
}
},
- [clips, videoSources, sourceIndex, updateVirtualTime],
+ [applySourceTime, clips, videoSources, sourceIndex, updateVirtualTime],
);
- const seekToSourceTime = useCallback((sourceTimeSec: number) => {
- const video = videoRef.current;
- if (!video) return;
- isProgrammaticSeekRef.current = true;
- if (Math.abs(video.currentTime - sourceTimeSec) > 0.01) {
- video.currentTime = sourceTimeSec;
- }
- }, []);
+ const seekToSourceTime = useCallback(
+ (sourceTimeSec: number) => {
+ const video = videoRef.current;
+ if (!video) return;
+ // A load is in flight, so this write would be a no-op that
+ // `onLoadedMetadata` then overwrites — re-aim the queued resume instead.
+ if (pendingSeekRef.current) {
+ pendingSeekRef.current = { sourceTimeSec, play: pendingSeekRef.current.play };
+ return;
+ }
+ applySourceTime(video, sourceTimeSec);
+ },
+ [applySourceTime],
+ );
/**
* Re-run the media load algorithm on the mounted element after a delay, and
@@ -766,6 +804,15 @@ export function VirtualPreview({
seekToVirtualTime(virtualTimeSec);
}
}}
+ onSeeked={(e) => {
+ // The demuxer is free again: apply the newest target that
+ // arrived while it was busy, if the playhead has moved on.
+ const queued = pendingScrubTargetRef.current;
+ if (queued !== null) {
+ pendingScrubTargetRef.current = null;
+ applySourceTime(e.currentTarget, queued);
+ }
+ }}
onWaiting={() => setLoadState("loading")}
onCanPlay={() => {
setLoadState("ready");