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 a mid-transition pause, and resolve regions from the clip anchor

Etienne Lescotf95e1087a74a
diff --git a/src/components/ai-edition/NativeCompositorOverlay.tsx b/src/components/ai-edition/NativeCompositorOverlay.tsx
index 4c20609c5..445abf0f2 100644
--- a/src/components/ai-edition/NativeCompositorOverlay.tsx
+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx
@@ -166,8 +166,9 @@ export function NativeCompositorOverlay() {
pendingTargetClipIdRef.current = targetClipId;
previousActiveClipIdRef.current = targetClipId;
- const isPlaying = playing;
- if (isPlaying) {
+ // Pause native across the decoder swap. Deliberately NOT kept in a variable to
+ // resume from later — see the `.then` below, which re-reads the live transport.
+ if (playing) {
setNativePlaying(false);
}
@@ -183,7 +184,13 @@ export function NativeCompositorOverlay() {
if (pendingTargetClipIdRef.current !== targetClipId) {
return;
}
- if (isPlaying) {
+ // Re-read the transport NOW rather than trusting `isPlaying`, captured
+ // before the await. Otherwise pausing *during* a clip transition is
+ // silently undone: the in-flight `.then` resumes native playback on top
+ // of the user's pause, and the preview plays on by itself. The store is
+ // the single source of truth for "is the transport playing", so ask it
+ // at the moment we'd act on it.
+ if (useProjectStore.getState().playing) {
setNativePlaying(true);
}
})
diff --git a/src/lib/ai-edition/timeline/timelineMap.test.ts b/src/lib/ai-edition/timeline/timelineMap.test.ts
index 80d783fd6..04b4ad9d1 100644
--- a/src/lib/ai-edition/timeline/timelineMap.test.ts
+++ b/src/lib/ai-edition/timeline/timelineMap.test.ts
@@ -12,7 +12,7 @@ import {
clampSpanAgainstNeighbours,
coalesceByIdentity,
coalesceRegionsForRuler,
- projectRawRegionsToSource,
+ projectRegionsToSource,
regionIdentityKey,
replacePillSpan,
resolveNativePosition,
@@ -46,9 +46,9 @@ const region = (id: string, startSec: number, endSec: number, payload?: string):
...(payload ? { payload } : {}),
});
-describe("projectRawRegionsToSource", () => {
+describe("projectRegionsToSource", () => {
it("passes a region through unchanged (no clipIndex) when there are no segments", () => {
- const out = projectRawRegionsToSource([region("r", 1.5, 4.25)], [], [], () => "x");
+ const out = projectRegionsToSource([region("r", 1.5, 4.25)], [], [], () => "x");
expect(out).toEqual([{ id: "r", startMs: 1500, endMs: 4250 }]);
});
@@ -60,7 +60,7 @@ describe("projectRawRegionsToSource", () => {
sourceEndSec: 10,
timelineEndSec: 10,
});
- const out = projectRawRegionsToSource([region("r", 3, 5)], [c], [c], () => "x");
+ const out = projectRegionsToSource([region("r", 3, 5)], [c], [c], () => "x");
expect(out).toEqual([{ id: "r", startMs: 3000, endMs: 5000, clipIndex: 0 }]);
});
@@ -75,7 +75,7 @@ describe("projectRawRegionsToSource", () => {
timelineEndSec: 10,
});
const segments = resolvePlaybackSegments([c], [trim("a", 2, 4)]);
- const out = projectRawRegionsToSource([region("r", 6, 8)], segments, [c], () => "x");
+ const out = projectRegionsToSource([region("r", 6, 8)], segments, [c], () => "x");
expect(out).toEqual([{ id: "r", startMs: 6000, endMs: 8000, clipIndex: 1 }]);
});
@@ -96,12 +96,7 @@ describe("projectRawRegionsToSource", () => {
timelineStartSec: 5,
timelineEndSec: 10,
});
- const out = projectRawRegionsToSource(
- [region("r", 3, 7, "keep")],
- [c1, c2],
- [c1, c2],
- () => "r2",
- );
+ const out = projectRegionsToSource([region("r", 3, 7, "keep")], [c1, c2], [c1, c2], () => "r2");
expect(out).toEqual([
{ id: "r", startMs: 103000, endMs: 105000, clipIndex: 0, payload: "keep" },
{ id: "r2", startMs: 200000, endMs: 202000, clipIndex: 1, payload: "keep" },
@@ -119,12 +114,102 @@ describe("projectRawRegionsToSource", () => {
timelineEndSec: 10,
});
const segments = resolvePlaybackSegments([c], [trim("a", 4, 6)]);
- const out = projectRawRegionsToSource([region("r", 3, 8)], segments, [c], () => "r2");
+ const out = projectRegionsToSource([region("r", 3, 8)], segments, [c], () => "r2");
expect(out).toEqual([
{ id: "r", startMs: 3000, endMs: 4000, clipIndex: 0 },
{ id: "r2", startMs: 6000, endMs: 8000, clipIndex: 1 },
]);
});
+
+ // --- anchored path: the anchor is the SSOT, `startMs`/`endMs` are not consulted ---
+
+ it("places an anchored region from its anchor, ignoring a stale startMs/endMs", () => {
+ // THE property phase 1 buys: the derived ms cache is deliberately WRONG here
+ // (raw[0,1] — nowhere near the truth). A region that reads the anchor lands on
+ // source [6,8]; one that still trusted the cache would land on [0,1].
+ const c = clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineEndSec: 10,
+ });
+ const stale = {
+ ...region("r", 0, 1),
+ clipId: "c1",
+ sourceStartSec: 6,
+ sourceEndSec: 8,
+ };
+ const out = projectRegionsToSource([stale], [c], [c], () => "x");
+ expect(out).toEqual([{ ...stale, startMs: 6000, endMs: 8000, clipIndex: 0 }]);
+ });
+
+ it("splits an anchored region across the kept segments of its own clip", () => {
+ // Same trim geometry as the unanchored split above, driven purely by the anchor.
+ const c = clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineEndSec: 10,
+ });
+ const segments = resolvePlaybackSegments([c], [trim("a", 4, 6)]);
+ const anchored = {
+ ...region("r", 3, 8),
+ clipId: "c1",
+ sourceStartSec: 3,
+ sourceEndSec: 8,
+ };
+ const out = projectRegionsToSource([anchored], segments, [c], () => "r2");
+ expect(out).toEqual([
+ { ...anchored, id: "r", startMs: 3000, endMs: 4000, clipIndex: 0 },
+ { ...anchored, id: "r2", startMs: 6000, endMs: 8000, clipIndex: 1 },
+ ]);
+ });
+
+ it("never places an anchored region on a different clip that shares the asset", () => {
+ // Two clips, same asset, overlapping source windows. The anchor names c2, so the
+ // region must appear ONCE, on c2 — the camera/record mix-up this model prevents.
+ const c1 = clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 0,
+ timelineEndSec: 5,
+ });
+ const c2 = clip({
+ id: "c2",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 5,
+ timelineEndSec: 10,
+ });
+ const anchored = {
+ ...region("r", 1, 2),
+ clipId: "c2",
+ sourceStartSec: 1,
+ sourceEndSec: 2,
+ };
+ const out = projectRegionsToSource([anchored], [c1, c2], [c1, c2], () => "x");
+ expect(out).toEqual([{ ...anchored, startMs: 1000, endMs: 2000, clipIndex: 1 }]);
+ });
+
+ it("falls back to the raw mapping when the anchor is incomplete", () => {
+ // Migration keeps un-anchorable regions (never drops them), so a partial anchor
+ // must still resolve via the legacy raw path rather than vanishing.
+ const c = clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineEndSec: 10,
+ });
+ const partial = { ...region("r", 3, 5), clipId: "c1" }; // no source span
+ const out = projectRegionsToSource([partial], [c], [c], () => "x");
+ expect(out).toEqual([{ ...partial, startMs: 3000, endMs: 5000, clipIndex: 0 }]);
+ });
});
describe("resolveNativePosition", () => {
diff --git a/src/lib/ai-edition/timeline/timelineMap.ts b/src/lib/ai-edition/timeline/timelineMap.ts
index 8cca4c3ca..001210011 100644
--- a/src/lib/ai-edition/timeline/timelineMap.ts
+++ b/src/lib/ai-edition/timeline/timelineMap.ts
@@ -19,7 +19,7 @@
import type { AxcutClip } from "../schema";
import { ventilateSpanAcrossClips } from "./region-ventilation";
-import { getRawVirtualStartTime } from "./virtual-preview";
+import { findRawClipForSegment, getRawVirtualStartTime } from "./virtual-preview";
/** A modifier fragment anchored to one clip in that clip's own source time — the
* Stage B storage shape (see docs/architecture/timeline-coordinate-refactor.md).
@@ -382,49 +382,108 @@ export function segmentRawSpanSec(
return { startSec, endSec: startSec + lenSec };
}
+/** The clip anchor a region may carry: WHERE IN THE SOURCE MEDIA it lives. Optional
+ * by design — migration keeps a region it cannot anchor rather than dropping it. */
+interface RegionClipAnchor {
+ clipId?: string;
+ sourceStartSec?: number;
+ sourceEndSec?: number;
+}
+
+/** True when the anchor is usable on its own (all three parts present), i.e. the
+ * region can be placed without consulting raw-virtual time at all. */
+function hasCompleteClipAnchor<T extends RegionClipAnchor>(
+ region: T,
+): region is T & Required<RegionClipAnchor> {
+ return (
+ typeof region.clipId === "string" &&
+ typeof region.sourceStartSec === "number" &&
+ typeof region.sourceEndSec === "number"
+ );
+}
+
/**
- * Project RAW-virtual-ms regions (zoom / speed / camera-fullscreen, as authored
- * on the ruler) onto the SOURCE-ms ranges the native compositor matches against.
- * The raw→source map goes through each visible segment's OWN raw extent, and the
- * trim-compressed order supplies `clipIndex`. A region whose source range a trim
- * splits across two kept segments yields one entry per segment (fresh id for the
- * extra copies, original id on the first — matching the previous contract). A
- * region overlapping no visible segment passes through unchanged with no
- * `clipIndex` (native falls back to time-overlap), same as before.
+ * Resolve regions (zoom / annotation / speed / camera-fullscreen) onto the SOURCE-ms
+ * ranges the native compositor matches against, plus the `clipIndex` into the
+ * trim-compressed stream.
+ *
+ * Two paths, chosen per region:
+ * - **anchored** (`{clipId, sourceStartSec, sourceEndSec}` present): the source span
+ * is read straight off the anchor and intersected with the kept segments of that
+ * clip. This is the SSOT path — it never consults `startMs`/`endMs` nor raw-virtual
+ * time, so a stale derived cache or a shifted ruler layout cannot move the region.
+ * - **unanchored**: the legacy raw→source mapping through each segment's own raw
+ * extent, kept because migration deliberately preserves un-anchorable regions.
*
- * `visibleSegments` MUST be the same array (same order) serialized to
- * `Scene.clips` so the emitted `clipIndex` lines up with the native stream;
- * `rawClips` is `document.timeline.clips` (the un-compressed layout the regions
- * were authored against).
+ * In both paths a region split across two kept segments by a trim yields one entry per
+ * segment (fresh id for the extra copies, original id on the first), and a region
+ * overlapping no visible segment passes through unchanged with no `clipIndex` (native
+ * falls back to time-overlap) — the contract callers already relied on.
+ *
+ * `visibleSegments` MUST be the same array (same order) serialized to `Scene.clips` so
+ * the emitted `clipIndex` lines up with the native stream; `rawClips` is
+ * `document.timeline.clips`.
*/
-export function projectRawRegionsToSource<T extends { id: string; startMs: number; endMs: number }>(
+export function projectRegionsToSource<
+ T extends { id: string; startMs: number; endMs: number } & RegionClipAnchor,
+>(
regions: T[],
visibleSegments: AxcutClip[],
rawClips: AxcutClip[],
makeId: () => string,
): (T & { clipIndex?: number })[] {
+ // RAW extents + owning raw clip per visible segment. Both are only consulted by the
+ // path that needs them (raw fallback / anchor match), but resolving them once keeps
+ // the per-region loop free of repeated lookups.
const spans = visibleSegments.map((seg) => segmentRawSpanSec(seg, rawClips));
+ const segmentRawClipIds = visibleSegments.map((seg) => findRawClipForSegment(seg, rawClips)?.id);
const out: (T & { clipIndex?: number })[] = [];
for (const region of regions) {
- const lo = Math.min(region.startMs, region.endMs) / 1000;
- const hi = Math.max(region.startMs, region.endMs) / 1000;
let emitted = 0;
- visibleSegments.forEach((seg, clipIndex) => {
- const { startSec: segRawStart, endSec: segRawEnd } = spans[clipIndex];
- const s = Math.max(lo, segRawStart);
- const e = Math.min(hi, segRawEnd);
- if (e <= s) return;
- const srcStart = seg.sourceStartSec + (s - segRawStart);
- const srcEnd = seg.sourceStartSec + (e - segRawStart);
+ const emit = (clipIndex: number, srcStartSec: number, srcEndSec: number) => {
out.push({
...region,
id: emitted === 0 ? region.id : makeId(),
- startMs: Math.round(srcStart * 1000),
- endMs: Math.round(srcEnd * 1000),
+ startMs: Math.round(srcStartSec * 1000),
+ endMs: Math.round(srcEndSec * 1000),
clipIndex,
});
emitted += 1;
- });
+ };
+
+ if (hasCompleteClipAnchor(region)) {
+ // ANCHORED — the region already states where it lives in the source media, so
+ // there is nothing to project: intersect its source span with each kept segment
+ // of its OWN clip. No detour through raw-virtual time means no dependency on the
+ // ruler layout (or on `startMs`/`endMs` being freshly re-derived), which is the
+ // entire class of drift this model exists to remove.
+ const lo = Math.min(region.sourceStartSec, region.sourceEndSec);
+ const hi = Math.max(region.sourceStartSec, region.sourceEndSec);
+ visibleSegments.forEach((seg, clipIndex) => {
+ if (segmentRawClipIds[clipIndex] !== region.clipId) return;
+ const s = Math.max(lo, seg.sourceStartSec);
+ const e = Math.min(hi, seg.sourceEndSec ?? seg.sourceStartSec);
+ if (e <= s) return;
+ emit(clipIndex, s, e);
+ });
+ } else {
+ // UNANCHORED — migration kept this region rather than dropping it (see
+ // `anchorRegionsWithDerivedMs`), so it only has its RAW span. Map that through
+ // each segment's own raw extent, exactly as before the anchor existed.
+ const lo = Math.min(region.startMs, region.endMs) / 1000;
+ const hi = Math.max(region.startMs, region.endMs) / 1000;
+ visibleSegments.forEach((seg, clipIndex) => {
+ const { startSec: segRawStart, endSec: segRawEnd } = spans[clipIndex];
+ const s = Math.max(lo, segRawStart);
+ const e = Math.min(hi, segRawEnd);
+ if (e <= s) return;
+ emit(
+ clipIndex,
+ seg.sourceStartSec + (s - segRawStart),
+ seg.sourceStartSec + (e - segRawStart),
+ );
+ });
+ }
if (emitted === 0) out.push(region);
}
return out;
diff --git a/src/lib/ai-edition/timeline/virtual-preview.ts b/src/lib/ai-edition/timeline/virtual-preview.ts
index 8e6a63632..84616f899 100644
--- a/src/lib/ai-edition/timeline/virtual-preview.ts
+++ b/src/lib/ai-edition/timeline/virtual-preview.ts
@@ -42,19 +42,38 @@ export function locateVirtualPosition(
}
/**
- * Maps a kept segment (`AxcutClip` from `resolvePlaybackSegments`) back to its
- * exact start position on the raw (untrimmed) document timeline.
+ * Maps a kept segment (`AxcutClip` from `resolvePlaybackSegments`) back to the RAW
+ * clip it was cut from — the ONE place that knows the segment-id convention
+ * `resolvePlaybackSegments` produces (`clip.id` when a clip survives whole,
+ * `${clip.id}_segN` when trims split it into several kept pieces). Anything that
+ * needs "which document clip is this segment part of?" — raw positioning, matching a
+ * clip-anchored region's `clipId` — must go through here rather than re-deriving the
+ * convention, so producer and consumers can never drift apart.
+ *
+ * Falls back to an asset+source-window match for segments whose id doesn't follow the
+ * convention (hand-built segments, older data). `undefined` when nothing matches.
*/
-export function getRawVirtualStartTime(segment: AxcutClip, rawClips: AxcutClip[]): number {
- const rawClip =
+export function findRawClipForSegment(
+ segment: AxcutClip,
+ rawClips: AxcutClip[],
+): AxcutClip | undefined {
+ return (
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),
- );
+ )
+ );
+}
+/**
+ * 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 = findRawClipForSegment(segment, rawClips);
if (!rawClip) return segment.timelineStartSec;
return rawClip.timelineStartSec + (segment.sourceStartSec - rawClip.sourceStartSec);
}
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index 586a029e0..621d8d70c 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -22,7 +22,7 @@ import { resolvePlaybackSegments } from "@/lib/ai-edition/document/timeline";
import type { AxcutClip, AxcutDocument } from "@/lib/ai-edition/schema";
import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";
import { resolveClipSourceEndSec } from "@/lib/ai-edition/timeline/clipDuration";
-import { projectRawRegionsToSource } from "@/lib/ai-edition/timeline/timelineMap";
+import { projectRegionsToSource } from "@/lib/ai-edition/timeline/timelineMap";
import { computeCompositeLayout, webcamSizeToFraction } from "@/lib/compositeLayout";
import type { AspectRatio } from "@/utils/aspectRatioUtils";
import { getAspectRatioValue, getNativeAspectRatioValue } from "@/utils/aspectRatioUtils";
@@ -355,7 +355,7 @@ export function buildSceneDescription(
// Zoom + Full Camera + speed regions are authored in RAW virtual (timeline) ms
// in the document — the ruler where trims still occupy their space — but the
- // compositor matches them against each frame's SOURCE time. `projectRawRegionsToSource`
+ // compositor matches them against each frame's SOURCE time. `projectRegionsToSource`
// bridges the two through `timelineMap`: it resolves each region's RAW coordinate
// against every visible segment's OWN raw extent (via `document.timeline.clips`,
// the un-compressed layout) and maps the overlap to that segment's source range,
@@ -369,13 +369,13 @@ export function buildSceneDescription(
// dépassait la position compressée de Δ → la région se déclenchait Δ trop tôt (offset
// visible en preview ET au rendu). On passe désormais le layout RAW pour le mapping
// raw→source et on ne garde `visibleClips` que pour l'ordre/`clipIndex`.
- const projectedZoomRegions = projectRawRegionsToSource(
+ const projectedZoomRegions = projectRegionsToSource(
document.zoomRanges ?? [],
visibleClips,
document.timeline.clips,
() => createId("zoom"),
);
- const projectedCameraFullscreenRegions = projectRawRegionsToSource(
+ const projectedCameraFullscreenRegions = projectRegionsToSource(
((document.legacyEditor as Record<string, unknown> | null)?.cameraFullscreenRegions as
| CameraFullscreenRegion[]
| undefined) ?? [],
@@ -386,10 +386,10 @@ export function buildSceneDescription(
// Speed regions carry an extra `speed` field the standard `rangeSchema` does not, so we
// can't read from `document.timeline.speedRanges` today (see SceneDescription.speedRegions
// comment). The legacy web exporter reads from `legacyEditor.speedRegions`; we mirror it.
- // `projectRawRegionsToSource` accepts any `T extends { id; startMs; endMs }` and copies
+ // `projectRegionsToSource` accepts any `T extends { id; startMs; endMs }` and copies
// every other field verbatim via `{...region}` — so the `speed` field passes through,
// and the splitting-across-clips semantics match zoomRegions / cameraFullscreenRegions.
- const projectedSpeedRegions = projectRawRegionsToSource(
+ const projectedSpeedRegions = projectRegionsToSource(
((document.legacyEditor as Record<string, unknown> | null)?.speedRegions as
| SpeedRegion[]
| undefined) ?? [],