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(editor): restart playback from the timeline beginning when ended

Bet44f064c5b12dc
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index d4e52187e..4e1d0ac37 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -49,6 +49,10 @@ import {
trimAppliesToClip,
ventilateTimelineSpanToTrims,
} from "@/lib/ai-edition/timeline/trim-mapping";
+import {
+ locateVirtualPosition,
+ totalVirtualDuration,
+} from "@/lib/ai-edition/timeline/virtual-preview";
import { firstTimelineBusyView } from "@/lib/ai-edition/transcription/status";
import { matchesShortcut } from "@/lib/shortcuts";
import { nativeBridgeClient } from "@/native";
@@ -602,8 +606,8 @@ export function NewEditorShell() {
useEffect(() => {
const el = videoElement;
if (!el) return;
- const onPlay = () => setPlaying(true);
- const onPause = () => setPlaying(false);
+ const onPlay = () => setPlaying(!el.paused);
+ const onPause = () => setPlaying(!el.paused);
// BUG corrigé : ce listener écoutait le même événement DOM natif 'ended' que le
// onEnded interne de VirtualPreview.tsx, sans la moindre logique multi-clip — il
// mettait TOUJOURS `playing` à false, y compris quand VirtualPreview venait
@@ -614,9 +618,12 @@ export function NewEditorShell() {
// suivant ?" que VirtualPreview — seul point de
// vérité pour "y a-t-il encore de la timeline à jouer".
const onEnded = () => {
+ if (!el.paused) return;
const playhead = useProjectStore.getState().currentTimeSec;
+ const duration = totalVirtualDuration(clipsForEndedRef.current);
+ const isAtEnd = duration > 0 && playhead >= duration - 0.1;
const hasNextClip = clipsForEndedRef.current.some((c) => c.timelineStartSec > playhead + 0.1);
- if (!hasNextClip) setPlaying(false);
+ if (isAtEnd && !hasNextClip) setPlaying(false);
};
el.addEventListener("play", onPlay);
el.addEventListener("pause", onPause);
@@ -634,6 +641,20 @@ export function NewEditorShell() {
const togglePlay = useCallback(() => {
if (!videoElement) return;
if (videoElement.paused) {
+ const playhead = useProjectStore.getState().currentTimeSec;
+ const duration = totalVirtualDuration(clipsForEndedRef.current);
+ if (duration > 0 && playhead >= duration - 0.05) {
+ handleSeek(0);
+ const startPos = locateVirtualPosition(clipsForEndedRef.current, 0);
+ const endPos = locateVirtualPosition(clipsForEndedRef.current, duration);
+ if (startPos && startPos.clip.assetId === endPos?.clip.assetId) {
+ try {
+ videoElement.currentTime = startPos.sourceTimeSec;
+ } catch {
+ // media metadata not ready yet
+ }
+ }
+ }
// Same catch as VirtualPreview's: `play()` rejects on the autoplay policy
// or when a new load interrupts it, and the store's `playing` flag is
// driven by the element's own play/pause listeners above — so a rejection
@@ -644,7 +665,7 @@ export function NewEditorShell() {
} else {
videoElement.pause();
}
- }, [videoElement]);
+ }, [videoElement, handleSeek]);
// "Transcribe now" from the transcript pane. The run itself belongs to the
// transcription store (it owns the queue, the toasts and the failure
diff --git a/src/components/ai-edition/VirtualPreview.playback.test.tsx b/src/components/ai-edition/VirtualPreview.playback.test.tsx
index becfb077a..4a8ffc4fb 100644
--- a/src/components/ai-edition/VirtualPreview.playback.test.tsx
+++ b/src/components/ai-edition/VirtualPreview.playback.test.tsx
@@ -757,3 +757,68 @@ describe("VirtualPreview primary audio keeps to the picture", () => {
expect(world.audioEl.playbackRate).toBe(1);
});
});
+
+describe("VirtualPreview replay", () => {
+ it.each([10, 4])("restarts with one play event after a %s-second clip ends", (end) => {
+ const { video, element, onTimeChange } = mount([clip("clip_1", "a1", 2, end, 0)]);
+ video.play();
+ video.seekTo(end - 0.04);
+ tick();
+ tick();
+ expect(element.paused).toBe(true);
+
+ act(() => {
+ video.play();
+ fireEvent.play(element);
+ });
+ tick();
+ expect(video.currentTime).toBe(2);
+ expect(element.paused).toBe(false);
+ expect(reportedTimes(onTimeChange).at(-1)).toBe(0);
+ });
+
+ it("restarts after the browser's ended event", () => {
+ const { video, element, onTimeChange } = mount([clip("clip_1", "a1", 0, 10, 0)]);
+ video.seekTo(10);
+ act(() => fireEvent.ended(element));
+ expect(reportedTimes(onTimeChange).at(-1)).toBe(10);
+ act(() => {
+ video.play();
+ fireEvent.play(element);
+ });
+ tick();
+ expect(video.currentTime).toBe(0);
+ expect(element.paused).toBe(false);
+ });
+
+ it("does not pause or cancel playback while a replay seek is in flight", () => {
+ const { video, element, onTimeChange } = mount([clip("clip_1", "a1", 2, 4, 0)]);
+ video.play();
+ video.seekTo(3.96);
+ tick();
+ tick();
+ expect(element.paused).toBe(true);
+ const initialPauseCalls = video.pauseCalls.length;
+
+ let seeking = true;
+ Object.defineProperty(element, "seeking", { configurable: true, get: () => seeking });
+
+ act(() => {
+ video.play();
+ fireEvent.play(element);
+ });
+ // While seek is in flight across ticks, boundary check must not pause:
+ tick();
+ expect(element.paused).toBe(false);
+ expect(video.pauseCalls.length).toBe(initialPauseCalls);
+
+ // Demuxer finishes seeking to target:
+ seeking = false;
+ act(() => fireEvent.seeked(element));
+ tick();
+ expect(element.paused).toBe(false);
+ expect(video.pauseCalls.length).toBe(initialPauseCalls);
+ expect(video.currentTime).toBe(2);
+ expect(reportedTimes(onTimeChange).at(-1)).toBe(0);
+ });
+});
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index 3481e2368..481b0a690 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -1171,10 +1171,25 @@ export function VirtualPreview({
// position rather than jumping. Note this cannot ride on `v.paused`,
// the gate the rest of the tick uses — an `error` does not fire
// `pause`, so a failure mid-playback leaves `paused` false.
- if (recoveringRef.current) {
+ if (recoveringRef.current || v.seeking) {
return;
}
const activeSourceId = videoSourcesRef.current[sourceIndexRef.current]?.id;
+ if (isProgrammaticSeekRef.current) {
+ isProgrammaticSeekRef.current = false;
+ const pos = locateSourcePosition(
+ clipsRef.current,
+ v.currentTime,
+ activeSourceId,
+ 0.05,
+ activeClipIdRef.current ?? undefined,
+ );
+ if (pos) {
+ activeClipIdRef.current = pos.clip.id;
+ updateVirtualTime(clampVirtualTime(clipsRef.current, pos.virtualTimeSec));
+ }
+ return;
+ }
// Trims only trim ahead during actual playback — scrubbing/paused seeks are
// intentionally NOT clamped, so the user can navigate freely into a trim while
// editing; only Play/export treats it as a cut (mirrors the pre-existing intent
@@ -1290,21 +1305,6 @@ export function VirtualPreview({
updateVirtualTime(v.currentTime);
return;
}
- if (isProgrammaticSeekRef.current) {
- isProgrammaticSeekRef.current = false;
- const pos = locateSourcePosition(
- clipsRef.current,
- v.currentTime,
- activeSourceId,
- 0.05,
- activeClipIdRef.current ?? undefined,
- );
- if (pos) {
- activeClipIdRef.current = pos.clip.id;
- updateVirtualTime(clampVirtualTime(clipsRef.current, pos.virtualTimeSec));
- }
- return;
- }
const position = locateSourcePosition(
clipsRef.current,
v.currentTime,
@@ -1739,6 +1739,7 @@ export function VirtualPreview({
}
}}
onSeeked={(e) => {
+ isProgrammaticSeekRef.current = false;
// 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;
@@ -1818,7 +1819,20 @@ export function VirtualPreview({
el.pause();
onVideoError?.(activeSource.id, detail);
}}
- onEnded={() => {
+ onPlay={() => {
+ // The edited timeline can end before the underlying file. A
+ // plain play() would hit that same boundary and pause again.
+ // Resolve the rewind here so cross-asset restarts also carry
+ // playback intent through the pending metadata load.
+ if (
+ virtualDurationSecRef.current > 0 &&
+ virtualTimeSecRef.current >= virtualDurationSecRef.current - 0.05
+ ) {
+ seekToVirtualTimeRef.current?.(0, true, true);
+ }
+ }}
+ onEnded={(e) => {
+ if (!e.currentTarget.paused) return;
// BUG corrigé : ce handler stoppait TOUJOURS la lecture dès que le
// <video> brut atteignait SA PROPRE fin de fichier — une course
// avec la boucle rAF (reachedClipEnd, plus haut) qui gère
@@ -1833,7 +1847,7 @@ export function VirtualPreview({
// navigateur a déjà mis `.paused = true` avant de déclencher
// 'ended', donc le check `!video.paused` habituel empêcherait
// toujours la reprise de la lecture sur le clip suivant. Si aucun
- // clip suivant n'existe, on ne fait rien de plus ici : le navigateur
+ // clip suivant n'existe, on publie la fin de timeline : le navigateur
// a déjà mis la vidéo en pause, et NewEditorShell (seule source de
// vérité pour l'état de lecture) l'apprend via son propre listener
// 'ended'/'pause' sur ce même élément.
@@ -1845,6 +1859,8 @@ export function VirtualPreview({
: undefined;
if (nextClip) {
seekToVirtualTime(nextClip.timelineStartSec, true, true);
+ } else {
+ updateVirtualTime(virtualDurationSecRef.current);
}
}}
// ponytail: handleTimeUpdate is now driven by the rAF loop
diff --git a/src/lib/ai-edition/timeline/virtual-preview.test.ts b/src/lib/ai-edition/timeline/virtual-preview.test.ts
index f3dd64888..2150e519d 100644
--- a/src/lib/ai-edition/timeline/virtual-preview.test.ts
+++ b/src/lib/ai-edition/timeline/virtual-preview.test.ts
@@ -44,6 +44,10 @@ describe("virtual-preview pure functions", () => {
expect(totalVirtualDuration([])).toBe(0);
});
+ it("totalVirtualDuration returns the maximum timelineEndSec even when clips are out of order", () => {
+ expect(totalVirtualDuration([clips[1], clips[0]])).toBe(20);
+ });
+
it("clampVirtualTime bounds to [0, total]", () => {
expect(clampVirtualTime(clips, -5)).toBe(0);
expect(clampVirtualTime(clips, 999)).toBe(20);
@@ -57,6 +61,29 @@ describe("virtual-preview pure functions", () => {
expect(pos?.sourceTimeSec).toBe(22);
});
+ it("locateVirtualPosition locates the end of the timeline when clips are out of order", () => {
+ const pos = locateVirtualPosition([clips[1], clips[0]], 20);
+ expect(pos?.clip.id).toBe("clip_2");
+ expect(pos?.virtualTimeSec).toBe(20);
+ });
+
+ it("locateVirtualPosition prefers a positive-duration clip ending at the timeline end over a zero-length clip", () => {
+ const zeroLengthClip: AxcutClip = {
+ id: "clip_zero",
+ assetId: "a1",
+ sourceStartSec: 30,
+ sourceEndSec: 30,
+ timelineStartSec: 20,
+ timelineEndSec: 20,
+ wordRefs: [],
+ origin: "system",
+ reason: "",
+ };
+ const pos = locateVirtualPosition([...clips, zeroLengthClip], 20);
+ expect(pos?.clip.id).toBe("clip_2");
+ expect(pos?.virtualTimeSec).toBe(20);
+ });
+
it("locateVirtualPosition returns null for empty clips", () => {
expect(locateVirtualPosition([], 0)).toBeNull();
});
diff --git a/src/lib/ai-edition/timeline/virtual-preview.ts b/src/lib/ai-edition/timeline/virtual-preview.ts
index 1cdc5d2f6..686e1d811 100644
--- a/src/lib/ai-edition/timeline/virtual-preview.ts
+++ b/src/lib/ai-edition/timeline/virtual-preview.ts
@@ -11,7 +11,7 @@ export type VirtualPosition = {
};
export function totalVirtualDuration(clips: AxcutClip[]): number {
- return clips.at(-1)?.timelineEndSec ?? 0;
+ return clips.reduce((end, clip) => Math.max(end, clip.timelineEndSec), 0);
}
export function clampVirtualTime(clips: AxcutClip[], value: number): number {
@@ -25,8 +25,17 @@ export function locateVirtualPosition(
): VirtualPosition | null {
if (clips.length === 0) return null;
const clamped = clampVirtualTime(clips, virtualTimeSec);
+ const duration = totalVirtualDuration(clips);
+ let endpointClipIndex = -1;
+ for (let i = clips.length - 1; i >= 0; i--) {
+ const clip = clips[i];
+ if (clip.timelineEndSec === duration && clip.timelineEndSec > clip.timelineStartSec) {
+ endpointClipIndex = i;
+ break;
+ }
+ }
const clipIndex = clips.findIndex((clip, index) => {
- const isLast = index === clips.length - 1;
+ const isLast = index === endpointClipIndex;
return clamped >= clip.timelineStartSec && (clamped < clip.timelineEndSec || isLast);
});
const resolvedIndex = clipIndex >= 0 ? clipIndex : clips.length - 1;