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(document): scope speed regions per clip, keep other assets' trims, and apply trims natively

Etienne Lescot7fb2777299c4
diff --git a/poc-d3d/src/live.rs b/poc-d3d/src/live.rs
index 018d23347..f5e29c487 100644
--- a/poc-d3d/src/live.rs
+++ b/poc-d3d/src/live.rs
@@ -20,6 +20,7 @@
//! `Mutex<Option<(u32, u32, Vec<u8>)>>` pour la traversée de threads vers le napi.
use crate::compositor::{Compositor, LiveParams};
+use crate::regions::speed_at;
use crate::scene::Scene;
use crate::config::{self, Cfg};
use crate::cursor::CursorTrack;
@@ -1008,10 +1009,26 @@ unsafe fn render_thread(
}
acc = 0.0; // resynchronise l'accumulateur de lecture libre après un seek
} else if shared.playing.load(Ordering::Relaxed) {
- acc += dt;
+ // BUG corrigé : la lecture libre décodait toujours exactement 1 frame par tick de
+ // 1/60s réel, quelle que soit la speed region active au temps source courant — ni
+ // l'écran ni la webcam n'accéléraient/ralentissaient jamais en preview live (seul
+ // l'export, via `speed_segments_for_window`/`advance_decoder_to` dans pipeline.rs,
+ // retimait correctement). Mod 3 corrige déjà le fps-mismatch webcam/écran (la webcam
+ // suit le temps source RÉEL de l'écran, pas un pas 1:1) — reprend ici la même idée :
+ // l'accumulateur de temps réel est mis à l'échelle par le multiplicateur de vitesse
+ // actif, donc `step()` (qui resynchronise la webcam sur le temps écran courant,
+ // cf. plus haut) décode plus/moins de frames par seconde réelle selon la région.
+ let speed = full_scene
+ .as_ref()
+ .map(|scene| speed_at(&scene.speed_regions, active_clip_index, player.screen_time_sec()))
+ .unwrap_or(1.0);
+ acc += dt * speed;
let step = 1.0 / 60.0;
let mut n = 0;
- while acc >= step && n < 3 {
+ // Cap proportionnel à la vitesse (borné) : à vitesse élevée, plus de frames doivent
+ // être décodées par tick réel pour ne pas prendre du retard sur l'accumulateur.
+ let max_steps = ((3.0 * speed.max(1.0)).ceil() as i32).min(64);
+ while acc >= step && n < max_steps {
// Timeline = niveau d'abstraction AU-DESSUS des clips : dès que le décodeur
// écran atteint la fin de fenêtre du clip actif, on enchaîne nous-mêmes sur
// le clip suivant (ou on reboucle sur le premier après le dernier) — sans
diff --git a/poc-d3d/src/regions.rs b/poc-d3d/src/regions.rs
index c719d3599..8f5bce8f3 100644
--- a/poc-d3d/src/regions.rs
+++ b/poc-d3d/src/regions.rs
@@ -66,6 +66,33 @@ pub fn speed_segments_for_window(
spans
}
+/// Multiplicateur de vitesse actif au temps source `t` (temps ABSOLU de la source, même
+/// convention que `SceneSpeedRegion.start_sec`/`end_sec` — pas de fenêtre de clip à soustraire).
+/// 1.0 hors de toute région. Utilisé par la preview live (`live.rs`) pour moduler le nombre de
+/// frames décodées par tick réel — contrairement à `speed_segments_for_window` (export), qui a
+/// besoin de pré-découper toute la fenêtre en spans pour connaître le compte de frames total à
+/// l'avance, la lecture live avance tick par tick et n'a besoin que de la vitesse "maintenant".
+///
+/// BUG corrigé : ignorait `region.clip_index`, filtrant seulement par recouvrement temporel sur
+/// la scène BRUTE (non filtrée par clip) — dès qu'un projet a plus d'un clip, deux clips peuvent
+/// tout à fait partager la même fenêtre de temps source (chacun démarrant près de t=0 de son
+/// propre fichier, cas courant), et la région du MAUVAIS clip matchait alors silencieusement (ou
+/// aucune ne matchait quand le clip actif est censé être couvert par une région tournée d'un
+/// autre index). Même garde-fou que `Scene::for_clip_window`'s `belongs` (scene.rs) : accepte la
+/// région seulement si `clip_index` est absent (vieux payload) OU vaut `active_clip_index`.
+pub fn speed_at(regions: &[SceneSpeedRegion], active_clip_index: usize, t: f64) -> f64 {
+ for region in regions {
+ let belongs = region.clip_index.map(|i| i == active_clip_index).unwrap_or(true);
+ if belongs && t >= region.start_sec && t < region.end_sec {
+ if region.speed.is_finite() && region.speed > 0.0 {
+ return region.speed;
+ }
+ return 1.0;
+ }
+ }
+ 1.0
+}
+
fn push_speed_segment(
spans: &mut Vec<SpeedSegment>,
start_sec: f64,
diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsx
index 133e4852d..41542dbc4 100644
--- a/src/components/ai-edition/ExportDialog.tsx
+++ b/src/components/ai-edition/ExportDialog.tsx
@@ -37,7 +37,7 @@ import {
import { exportMultiNative, exportNative } from "@/native";
import { nativeBridgeClient } from "@/native/client";
import type { CompositorClipInput } from "@/native/contracts";
-import { buildSceneDescription } from "@/native/sceneDescription";
+import { buildSceneDescription, resolveVisibleClips } from "@/native/sceneDescription";
import {
type AspectRatio,
getAspectRatioValue,
@@ -58,40 +58,40 @@ function formatHms(totalSeconds: number): string {
return [h, m, sec].map((v) => v.toString().padStart(2, "0")).join(":");
}
-/** Maps the document's timeline to the native multiclip export contract: ordered clips, each
- * with its asset's screen file + camera file (falls back to the screen when a clip has no
- * camera — the no-webcam layout is a later step) and its source trim. */
+/** Maps the document's timeline to the native multiclip export contract: ordered,
+ * trim-narrowed clips (`resolveVisibleClips` — shared with `buildSceneDescription` and
+ * `NativeCompositorOverlay`, so export/preview/scene all see the exact same clip stream),
+ * each with its asset's screen file + camera file (falls back to the screen when a clip has
+ * no camera — the no-webcam layout is a later step) and its source trim. */
function buildNativeClipList(document: AxcutDocument): CompositorClipInput[] {
const assetById = new Map(document.assets.map((a) => [a.id, a]));
- return [...document.timeline.clips]
- .sort((a, b) => a.timelineStartSec - b.timelineStartSec)
- .flatMap((clip) => {
- const asset = assetById.get(clip.assetId);
- if (!asset?.originalPath) {
- return [];
- }
- const cam = asset.cameraTrack;
- // sourceEndSec is optional in the schema (unknown until probed) — fall back through
- // the single canonical precedence used by every consumer (clip.probe → asset.duration
- // → timeline-length guess). See `resolveClipSourceEndSec` for the full order.
- const sourceEndSec = resolveClipSourceEndSec(clip, asset);
- // ponytail: matches the rule in `buildSceneDescription` — screen recordings
- // from this app always carry a decodable audio track (the webcam path
- // never does), so the only clips that reach this branch already have audio.
- // If a per-asset audio-probe flag lands on the schema later, swap to
- // `Boolean(asset.audio)` here too and keep these two derivation paths in
- // lock-step with `buildSceneDescription` in src/native/sceneDescription.ts.
- return [
- {
- screenPath: asset.originalPath,
- webcamPath: cam?.sourcePath ?? asset.originalPath,
- sourceStartSec: clip.sourceStartSec,
- sourceEndSec,
- webcamOffsetSec: cam ? (cam.startMs + cam.offsetMs) / 1000 : 0,
- hasAudio: true,
- },
- ];
- });
+ return resolveVisibleClips(document).flatMap((clip) => {
+ const asset = assetById.get(clip.assetId);
+ if (!asset?.originalPath) {
+ return [];
+ }
+ const cam = asset.cameraTrack;
+ // sourceEndSec is optional in the schema (unknown until probed) — fall back through
+ // the single canonical precedence used by every consumer (clip.probe → asset.duration
+ // → timeline-length guess). See `resolveClipSourceEndSec` for the full order.
+ const sourceEndSec = resolveClipSourceEndSec(clip, asset);
+ // ponytail: matches the rule in `buildSceneDescription` — screen recordings
+ // from this app always carry a decodable audio track (the webcam path
+ // never does), so the only clips that reach this branch already have audio.
+ // If a per-asset audio-probe flag lands on the schema later, swap to
+ // `Boolean(asset.audio)` here too and keep these two derivation paths in
+ // lock-step with `buildSceneDescription` in src/native/sceneDescription.ts.
+ return [
+ {
+ screenPath: asset.originalPath,
+ webcamPath: cam?.sourcePath ?? asset.originalPath,
+ sourceStartSec: clip.sourceStartSec,
+ sourceEndSec,
+ webcamOffsetSec: cam ? (cam.startMs + cam.offsetMs) / 1000 : 0,
+ hasAudio: true,
+ },
+ ];
+ });
}
// Target short side (px) for the two fixed quality tiers -- mirrors the legacy
diff --git a/src/components/ai-edition/NativeCompositorOverlay.tsx b/src/components/ai-edition/NativeCompositorOverlay.tsx
index a33a027ff..caa10a23f 100644
--- a/src/components/ai-edition/NativeCompositorOverlay.tsx
+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx
@@ -52,8 +52,15 @@ export function NativeCompositorOverlay() {
() => 0,
);
- // Match buildSceneDescription's sorted+visible clip stream exactly. The resulting index is
- // sent to Rust because paths/offsets cannot distinguish multiple cuts of one source asset.
+ // BUG corrigé : ceci pointait vers `resolveVisibleClips` (compacté, trim-rétréci) alors que
+ // `currentTimeSec` reste — et doit rester — le temps RAW/document (voir NewEditorShell) :
+ // un trim ne change jamais quel ASSET/fichier est actif (seul un changement de clip source
+ // le fait), donc cette détection de "playhead entré dans un autre clip" (→ setActiveClip,
+ // bascule de la paire écran/webcam) n'a besoin d'aucune connaissance des trims — juste la
+ // liste RAW triée/filtrée, dans le même référentiel que `currentTimeSec`. Le flux
+ // Le flux COMPACTÉ (`resolveVisibleClips`, dans `buildSceneDescription` ci-dessous) reste
+ // utilisé pour la SCÈNE envoyée au natif (`setNativeScene`), qui elle doit bien refléter
+ // les trims.
const nativeClips = useMemo(() => {
if (!document) return [];
const assetById = new Map(document.assets.map((asset) => [asset.id, asset]));
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 32fa364ce..da6fb1076 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -130,6 +130,16 @@ export function NewEditorShell() {
const clips: AxcutClip[] = document?.timeline.clips ?? [];
// Mirror transport/playhead onto the native compositor view (no-op if inactive). The hook
// maps absolute timeline time into the active clip's trimmed source-media clock.
+ //
+ // BUG corrigé : `currentTimeSec` est — et doit rester — la position sur le timeline
+ // RAW/document (celle de la règle, des zoom/speed regions, du marqueur de trim
+ // lui-même). Un instant, `<Preview>` et ce hook recevaient une liste de clips COMPACTÉE
+ // (trim-rétrécie) alors que `currentTimeSec` restait RAW — la tête de lecture visuelle
+ // (règle) et le clock de lecture (natif/scrub) se retrouvaient dans deux référentiels
+ // différents : le marqueur de trim ne représentait plus rien de cohérent, et la tête de
+ // lecture le traversait au lieu de le sauter. Voir `VirtualPreview.tsx` pour où le saut
+ // par-dessus un trim doit réellement se produire (sur l'horloge SOURCE du <video>, pas
+ // sur le timeline virtuel rapporté au parent).
useNativePlaybackSync(playing, currentTimeSec, clips);
const hasProject = Boolean(document);
const hasAsset = projectId !== null && (document?.assets.length ?? 0) > 0;
@@ -568,30 +578,28 @@ export function NewEditorShell() {
// apps/web/src/App.tsx.
const handleAddTrimRange = useCallback(
(assetId: string, startSec: number, endSec: number, reason: string) => {
- // ponytail: read the latest document from the store, not the
- // closure. The closure captures the document at render time; if
- // the user fires two rapid Backspaces before React re-renders,
- // the second call would see the same stale document and add the
- // second skip to a base that already has the first skip's
- // pending-state. Then the two saveDocument calls race and the
- // last one to call set() wins. Reading from getState() always
- // returns the latest committed value.
- const doc = useProjectStore.getState().document ?? document;
- if (!doc) return;
- // ponytail: serialise via saveQueueRef so two rapid trims
- // can't race each other's IPC save and overwrite one another.
+ // BUG corrigé : `doc` était lu de façon SYNCHRONE au moment de l'appel, puis seule la
+ // SAUVEGARDE était sérialisée via `saveQueueRef` — pas la LECTURE. Éditer le clip 1 puis
+ // le clip 2 avant que la chaîne async du premier save (import() + applyTimelineOperation +
+ // saveDocument, qui fait un aller-retour IPC) n'ait commit dans le store faisait lire au
+ // second appel le MÊME doc pré-edit-1 ; son propre saveDocument(next.document) écrasait
+ // alors le store avec un doc qui contient le trim du clip 2 mais PAS celui du clip 1 — les
+ // edits du clip 1 disparaissaient. La lecture doit donc elle aussi être mise dans la
+ // chaîne, après avoir attendu le tour précédent, pour toujours partir du doc déjà commit.
const queued = saveQueueRef.current
.then(() => import("@/lib/ai-edition/document/operations"))
- .then(({ applyTimelineOperation }) =>
- applyTimelineOperation(doc, {
+ .then(({ applyTimelineOperation }) => {
+ const doc = useProjectStore.getState().document ?? document;
+ if (!doc) return null;
+ return applyTimelineOperation(doc, {
type: "add_trim_range",
assetId,
startSec,
endSec,
reason,
- }),
- )
- .then((next) => saveDocument(next.document));
+ });
+ })
+ .then((next) => next && saveDocument(next.document));
saveQueueRef.current = queued.then(
() => undefined,
() => undefined,
@@ -603,18 +611,20 @@ export function NewEditorShell() {
const handleRemoveTrimRange = useCallback(
(trimId: string) => {
- const doc = useProjectStore.getState().document ?? document;
- if (!doc) return;
+ // See handleAddTrimRange above — same fix: the document read must be
+ // inside the queued chain, after awaiting the previous save.
const queued = saveQueueRef.current
.then(() => import("@/lib/ai-edition/document/operations"))
- .then(({ applyTimelineOperation }) =>
- applyTimelineOperation(doc, {
+ .then(({ applyTimelineOperation }) => {
+ const doc = useProjectStore.getState().document ?? document;
+ if (!doc) return null;
+ return applyTimelineOperation(doc, {
type: "remove_trim_range",
trimId,
reason: "Restored from transcript pane.",
- }),
- )
- .then((next) => saveDocument(next.document));
+ });
+ })
+ .then((next) => next && saveDocument(next.document));
saveQueueRef.current = queued.then(
() => undefined,
() => undefined,
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 3207ff48e..6004ea30b 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -499,10 +499,10 @@ export function TranscriptPane({
[clips, transcripts, assets, trimRanges],
);
- // the cue position is the playback head's location in the
- // current clip's source time. `locateVirtualPosition` already accounts
- // for skip ranges and clipped durations — the cue word naturally
- // jumps over gaps the user has trimmed.
+ // the cue position is the playback head's location in the current clip's source time.
+ // `currentTimeSec` is the RAW/document timeline (same referential as the ruler, see
+ // NewEditorShell) — looked up against the raw `clips`, matching that referential.
+ // `findCueWordId` only reads `assetId`/`sourceTimeSec` off the result.
const cue = useMemo(() => {
if (clips.length === 0) return null;
const position = locateVirtualPosition(clips, currentTimeSec);
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index 27425063e..b601d45b1 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -4,6 +4,7 @@ import {
DEFAULT_CROP_REGION,
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";
@@ -40,6 +41,25 @@ 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[];
@@ -151,6 +171,22 @@ export function VirtualPreview({
// mutation.
const clipsRef = useRef(clips);
clipsRef.current = clips;
+ // Trim-narrowed (`resolvePlaybackSegments`) — used ONLY to detect "has the <video>'s own
+ // currentTime drifted into a trim" and where to jump it back out to. Everything ELSE in
+ // this component (`clips`/`clipsRef` above, virtualTimeSec, zoom/speed region lookups,
+ // what gets reported via `onTimeChange`) stays on the RAW/document timeline — the same
+ // coordinate space the ruler, zoom/speed regions, and the trim marker itself use. Keeping
+ // these two lists separate (rather than swapping `clips` itself to the trim-narrowed one)
+ // is what makes the reported playhead jump OVER a trim marker instead of drifting out of
+ // sync with it: `locateSourcePosition` below, fed RAW clips, maps the underlying video's
+ // source time to a RAW virtual time that jumps discontinuously by exactly the trim's
+ // width the moment the video itself jumps — matching the marker's own pixel span.
+ const playbackClips = useMemo(
+ () => resolvePlaybackSegments(clips, trimRanges),
+ [clips, trimRanges],
+ );
+ const playbackClipsRef = useRef(playbackClips);
+ playbackClipsRef.current = playbackClips;
const videoSourcesRef = useRef(videoSources);
videoSourcesRef.current = videoSources;
const sourceIndexRef = useRef(sourceIndex);
@@ -161,8 +197,6 @@ export function VirtualPreview({
virtualDurationSecRef.current = virtualDurationSec;
const speedRegionsRef = useRef(speedRegions);
speedRegionsRef.current = speedRegions;
- const trimRangesRef = useRef(trimRanges);
- trimRangesRef.current = trimRanges;
// biome-ignore lint/correctness/useExhaustiveDependencies: re-create the rAF when the active source swaps.
useEffect(() => {
let raf = 0;
@@ -182,32 +216,32 @@ export function VirtualPreview({
clockRef.current.virtualTimeSec = virtualTimeSecRef.current;
}
const activeSourceId = videoSourcesRef.current[sourceIndexRef.current]?.id;
- // Trim regions only trim ahead during actual playback — mirrors
- // main's videoEventHandlers.ts (findActiveTrimRegion + jump to
- // endMs, gated on `!video.paused`). Scrubbing/paused seeks are
- // intentionally NOT clamped: the user can navigate freely inside
- // a trim while editing; only Play/export treats it as a cut.
+ // 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
+ // this replaces). Jump is on the SOURCE clock only: the RAW virtual-time report
+ // below (locateSourcePosition against `clipsRef.current`, unchanged) naturally
+ // jumps by the trim's exact width the instant `v.currentTime` does, so the ruler's
+ // playhead visually skips the trim marker instead of drifting through it.
if (!v.paused) {
- const activeTrim = trimRangesRef.current.find(
- (trim) =>
- trim.assetId === activeSourceId &&
- v.currentTime >= trim.startSec &&
- v.currentTime < trim.endSec,
+ const inKeptSegment = locateSourcePosition(
+ playbackClipsRef.current,
+ v.currentTime,
+ activeSourceId,
);
- if (activeTrim) {
- if (activeTrim.endSec >= (v.duration || Infinity)) {
- v.pause();
- } else {
- // ponytail: seeking to exactly `endSec` can land the decoder a
- // hair before it (frame/sample quantization), which still
- // satisfies `currentTime < trim.endSec` — the next tick
- // re-seeks to the same spot, forever, so playback never
- // actually progresses past the trim (looked like a hard
- // stop instead of an invisible cut). A small epsilon past
- // the boundary guarantees each re-check reads past it.
- v.currentTime = activeTrim.endSec + 0.05;
+ if (!inKeptSegment) {
+ const jumpTo = nextKeptSourceTime(
+ playbackClipsRef.current,
+ activeSourceId,
+ v.currentTime,
+ );
+ if (jumpTo !== null) {
+ v.currentTime = jumpTo;
+ return;
}
- 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.
}
}
// ponytail: also push setSourceTimeSec every frame (was previously
diff --git a/src/lib/ai-edition/document/operations.test.ts b/src/lib/ai-edition/document/operations.test.ts
index 693521e52..fd646c5e9 100644
--- a/src/lib/ai-edition/document/operations.test.ts
+++ b/src/lib/ai-edition/document/operations.test.ts
@@ -69,6 +69,54 @@ describe("applyTimelineOperation.add_trim_range", () => {
expect(skip?.startSec).toBe(4);
expect(skip?.endSec).toBe(10);
});
+
+ it("preserves an existing trim on a DIFFERENT asset (multi-clip transcript pane repro)", () => {
+ const doc = makeDoc();
+ const otherAsset = {
+ id: "asset_2",
+ kind: "video" as const,
+ label: "Recording 2",
+ originalPath: "C:/videos/rec2.mp4",
+ durationSec: 30,
+ };
+ const docWithTwoAssets: AxcutDocument = {
+ ...doc,
+ assets: [...doc.assets, otherAsset],
+ timeline: {
+ ...doc.timeline,
+ clips: [
+ ...doc.timeline.clips,
+ {
+ id: "clip_2",
+ assetId: otherAsset.id,
+ sourceStartSec: 0,
+ sourceEndSec: 30,
+ timelineStartSec: 60,
+ timelineEndSec: 90,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ],
+ },
+ };
+ // Edit clip 1's word (asset_1) first...
+ const afterFirst = applyTimelineOperation(docWithTwoAssets, {
+ type: "add_trim_range",
+ assetId: "asset_1",
+ startSec: 5,
+ endSec: 8,
+ }).document;
+ // ...then edit clip 2's word (asset_2) — this must NOT wipe asset_1's trim.
+ const afterSecond = applyTimelineOperation(afterFirst, {
+ type: "add_trim_range",
+ assetId: "asset_2",
+ startSec: 2,
+ endSec: 4,
+ }).document;
+ expect(afterSecond.timeline.trimRanges.filter((s) => s.assetId === "asset_1")).toHaveLength(1);
+ expect(afterSecond.timeline.trimRanges.filter((s) => s.assetId === "asset_2")).toHaveLength(1);
+ });
});
describe("applyTimelineOperation.drop_range", () => {
diff --git a/src/lib/ai-edition/document/operations.ts b/src/lib/ai-edition/document/operations.ts
index bbb30c5d1..8758e1462 100644
--- a/src/lib/ai-edition/document/operations.ts
+++ b/src/lib/ai-edition/document/operations.ts
@@ -178,6 +178,14 @@ export function applyTimelineOperation(
if (!assetId) return { document, summary: "no asset to trim" };
const lo = Math.max(0, Math.min(op.startSec, op.endSec));
const hi = Math.max(lo, Math.max(op.startSec, op.endSec));
+ // BUG corrigé : `merged` (calculé UNIQUEMENT à partir des trims de CET assetId)
+ // remplaçait ensuite `document.timeline.trimRanges` EN ENTIER — les trims de tout
+ // autre asset (donc tout autre clip, dès qu'un projet a plus d'un enregistrement)
+ // disparaissaient silencieusement dès qu'on ajoutait un trim sur un asset différent.
+ // C'est exactement le "éditer le clip 2 efface les edits du clip 1" observé : les deux
+ // clips du repro pointent vers deux fichiers distincts. Il faut conserver les trims des
+ // AUTRES assets tels quels et ne remplacer que la tranche de CET asset.
+ const otherAssetsRanges = document.timeline.trimRanges.filter((s) => s.assetId !== assetId);
const existing = document.timeline.trimRanges.filter((s) => s.assetId === assetId);
// ponytail: bound by the trim-range asset's duration, not the
// primary asset's. Recording projects can have a short primary
@@ -194,14 +202,20 @@ export function applyTimelineOperation(
...document,
timeline: {
...document.timeline,
- trimRanges: merged.map((iv, i) => ({
- id: `trim_${i + 1}`,
- assetId,
- startSec: iv.startSec,
- endSec: iv.endSec,
- origin: "user" as const,
- reason: op.reason ?? "",
- })),
+ trimRanges: [
+ ...otherAssetsRanges,
+ ...merged.map((iv, i) => ({
+ // ponytail: id scoped by assetId — plain `trim_${i+1}` collided across
+ // assets (two different assets could each mint "trim_1"), which would
+ // have made remove/update_trim_range act on the wrong asset's range by id.
+ id: `trim_${assetId}_${i + 1}`,
+ assetId,
+ startSec: iv.startSec,
+ endSec: iv.endSec,
+ origin: "user" as const,
+ reason: op.reason ?? "",
+ })),
+ ],
},
preview: { ...document.preview, revision: document.preview.revision + 1 },
};
diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.ts
index 8decce826..7c9d30694 100644
--- a/src/lib/ai-edition/document/timeline.test.ts
+++ b/src/lib/ai-edition/document/timeline.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import type { AxcutClip, AxcutDocument } from "../schema";
+import type { AxcutClip, AxcutDocument, AxcutTrimRange } from "../schema";
import {
buildTimelineFromIntervals,
duplicateClip,
@@ -8,6 +8,7 @@ import {
normalizeIntervals,
primaryAssetDuration,
replaceTimeline,
+ resolvePlaybackSegments,
restoreFullTimeline,
subtractInterval,
timelineIntervals,
@@ -246,6 +247,122 @@ function makeClip(overrides: Partial<AxcutClip> = {}): AxcutClip {
};
}
+function makeTrim(overrides: Partial<AxcutTrimRange> = {}): AxcutTrimRange {
+ return {
+ id: "trim_1",
+ assetId: "asset_1",
+ startSec: 0,
+ endSec: 0,
+ origin: "user",
+ reason: "",
+ ...overrides,
+ };
+}
+
+describe("resolvePlaybackSegments", () => {
+ it("splits a clip around an interior trim into two contiguous segments", () => {
+ const clip = makeClip({
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ });
+ const trim = makeTrim({ startSec: 4, endSec: 6 });
+ const segments = resolvePlaybackSegments([clip], [trim]);
+ expect(segments).toHaveLength(2);
+ expect(segments[0]).toMatchObject({
+ sourceStartSec: 0,
+ sourceEndSec: 4,
+ timelineStartSec: 0,
+ timelineEndSec: 4,
+ });
+ expect(segments[1]).toMatchObject({
+ sourceStartSec: 6,
+ sourceEndSec: 10,
+ timelineStartSec: 4,
+ timelineEndSec: 8,
+ });
+ });
+
+ it("leaves a clip untouched when the trim belongs to a different asset", () => {
+ const clip = makeClip({ assetId: "asset_1", sourceStartSec: 0, sourceEndSec: 10 });
+ const trim = makeTrim({ assetId: "asset_2", startSec: 2, endSec: 4 });
+ const segments = resolvePlaybackSegments([clip], [trim]);
+ expect(segments).toHaveLength(1);
+ expect(segments[0]).toMatchObject({ sourceStartSec: 0, sourceEndSec: 10 });
+ });
+
+ it("drops a clip entirely when a trim fully covers it", () => {
+ const clip = makeClip({ sourceStartSec: 0, sourceEndSec: 10 });
+ const trim = makeTrim({ startSec: 0, endSec: 10 });
+ expect(resolvePlaybackSegments([clip], [trim])).toHaveLength(0);
+ });
+
+ it("narrows both clips when a trim is ventilated across a clip boundary (two DSL rows)", () => {
+ // Mirrors ventilateTimelineSpanToTrims's own output shape: one row per covered clip.
+ const clipA = makeClip({
+ id: "clip_a",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ });
+ const clipB = makeClip({
+ id: "clip_b",
+ assetId: "asset_1",
+ sourceStartSec: 10,
+ sourceEndSec: 20,
+ timelineStartSec: 10,
+ timelineEndSec: 20,
+ });
+ const trims = [
+ makeTrim({ id: "t1", startSec: 8, endSec: 10 }),
+ makeTrim({ id: "t2", startSec: 10, endSec: 12 }),
+ ];
+ const segments = resolvePlaybackSegments([clipA, clipB], trims);
+ expect(segments).toHaveLength(2);
+ expect(segments[0]).toMatchObject({
+ sourceStartSec: 0,
+ sourceEndSec: 8,
+ timelineStartSec: 0,
+ timelineEndSec: 8,
+ });
+ expect(segments[1]).toMatchObject({
+ sourceStartSec: 12,
+ sourceEndSec: 20,
+ timelineStartSec: 8,
+ timelineEndSec: 16,
+ });
+ });
+
+ it("does not let a trim on one clip affect an unrelated same-asset clip elsewhere", () => {
+ // Regression guard for the exact cross-clip bug just fixed in operations.ts:
+ // two clips of the SAME asset, non-adjacent source windows; a trim scoped to
+ // the first must not touch the second.
+ const clipA = makeClip({
+ id: "clip_a",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 0,
+ timelineEndSec: 5,
+ });
+ const clipB = makeClip({
+ id: "clip_b",
+ sourceStartSec: 50,
+ sourceEndSec: 55,
+ timelineStartSec: 5,
+ timelineEndSec: 10,
+ });
+ const trim = makeTrim({ startSec: 1, endSec: 2 });
+ const segments = resolvePlaybackSegments([clipA, clipB], [trim]);
+ expect(segments.find((s) => s.id === "clip_b")).toMatchObject({
+ sourceStartSec: 50,
+ sourceEndSec: 55,
+ });
+ });
+});
+
describe("duplicateClip / moveClip", () => {
it("duplicateClip gives the copy a fresh, collision-free id even when called repeatedly", () => {
// Regression test: this used to id the copy as `clip_${clips.length + 1}_copy`,
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index 4656c267a..a441b30a2 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -3,7 +3,7 @@
// (store, exporter, agent) feeds an AxcutDocument and gets back intervals
// or a new document with updated clips.
-import type { AxcutClip, AxcutDocument, AxcutTranscript } from "../schema";
+import type { AxcutClip, AxcutDocument, AxcutTranscript, AxcutTrimRange } from "../schema";
import { reprojectRegionsForReorder } from "../timeline/region-ventilation";
import { createId } from "./ids";
@@ -127,6 +127,61 @@ export function subtractInterval(intervals: Interval[], cut: Interval): Interval
return output;
}
+/**
+ * Derived, ephemeral clip list for playback/native/export — never written back to
+ * `document.timeline.clips`. Each clip's own `[sourceStartSec, sourceEndSec]` (its media
+ * in/out, edited via the clip's own modal) is untouched as a concept; this only narrows the
+ * WINDOW of it handed to playback for the trimmed stretch(es), via `subtractInterval`
+ * (existing, tested — no new interval math). Trims are stored per-asset in source time
+ * (`AxcutTrimRange`) and may already be ventilated into multiple entries by
+ * `ventilateTimelineSpanToTrims` when the user drags one across a clip boundary — subtracting
+ * by matching `assetId` against every clip naturally narrows however many clips that produces,
+ * no special-casing. Everything else about the clip (id, assetId, webcam pairing/offset via
+ * the asset, origin/reason) carries through unchanged, which is what makes this apply to the
+ * webcam for free: webcam sync is derived from the clip's own asset, not recomputed here.
+ */
+export function resolvePlaybackSegments(
+ clips: AxcutClip[],
+ trimRanges: AxcutTrimRange[],
+): AxcutClip[] {
+ const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);
+ const result: AxcutClip[] = [];
+ let timelineCursor = 0;
+ for (const clip of ordered) {
+ const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;
+ if (sourceEnd <= clip.sourceStartSec) {
+ // Duration not probed yet — pass through as a single segment, unchanged.
+ const dur = clip.timelineEndSec - clip.timelineStartSec;
+ result.push({
+ ...clip,
+ timelineStartSec: timelineCursor,
+ timelineEndSec: timelineCursor + dur,
+ });
+ timelineCursor += dur;
+ continue;
+ }
+ let kept: Interval[] = [{ startSec: clip.sourceStartSec, endSec: sourceEnd }];
+ for (const trim of trimRanges) {
+ if (trim.assetId !== clip.assetId) continue;
+ kept = subtractInterval(kept, { startSec: trim.startSec, endSec: trim.endSec });
+ }
+ kept.forEach((iv, i) => {
+ const dur = iv.endSec - iv.startSec;
+ if (dur <= 0) return;
+ result.push({
+ ...clip,
+ id: kept.length === 1 ? clip.id : `${clip.id}_seg${i + 1}`,
+ sourceStartSec: iv.startSec,
+ sourceEndSec: iv.endSec,
+ timelineStartSec: timelineCursor,
+ timelineEndSec: timelineCursor + dur,
+ });
+ timelineCursor += dur;
+ });
+ }
+ return result;
+}
+
export function invertIntervals(intervals: Interval[], durationSec: number): Interval[] {
const cuts: Interval[] = [];
let cursor = 0;
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index 4037f3309..1f3dbd32e 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -18,7 +18,8 @@
import type { CameraFullscreenRegion, SpeedRegion } from "@/components/video-editor/types";
import { DEFAULT_CROP_REGION } from "@/components/video-editor/types";
import { createId } from "@/lib/ai-edition/document/ids";
-import type { AxcutDocument } from "@/lib/ai-edition/schema";
+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 { projectRegionsToSourceTime } from "@/lib/ai-edition/timeline/region-ventilation";
@@ -281,6 +282,22 @@ function pickOutputDims(
return { width: Math.round(longSide * ratio), height: longSide };
}
+/**
+ * The ONE clip list every native-facing consumer must build from — trim-narrowed
+ * (`resolvePlaybackSegments`, so word-level cuts from the transcript editor actually reach
+ * native instead of only affecting the transcript panel's own strikethrough), sorted, and
+ * filtered to clips whose asset has a resolvable path. Shared by `buildSceneDescription`
+ * below, `ExportDialog.tsx`'s `buildNativeClipList` (native MP4 export), and
+ * `NativeCompositorOverlay.tsx`'s `nativeClips` (live preview) — previously these three each
+ * hand-rolled their own sort+filter, acknowledged as needing to be "kept in lock-step".
+ */
+export function resolveVisibleClips(document: AxcutDocument): AxcutClip[] {
+ const assetById = new Map(document.assets.map((a) => [a.id, a]));
+ return resolvePlaybackSegments(document.timeline.clips, document.timeline.trimRanges)
+ .sort((a, b) => a.timelineStartSec - b.timelineStartSec)
+ .filter((clip) => assetById.get(clip.assetId)?.originalPath);
+}
+
/** Serialize a document into a {@link SceneDescription}. Pure — no per-frame math. */
export function buildSceneDescription(
document: AxcutDocument,
@@ -288,16 +305,8 @@ export function buildSceneDescription(
): SceneDescription {
const settings = getEditorSettings(document);
- // Sort+filter the clips once, in the order they will appear in the scene's
- // `clips[]` stream, so the per-clip `cropByClip[]` schedule stays aligned
- // 1:1 with `clips[]` by index. Mirror of `buildNativeClipList` in
- // src/components/ai-edition/ExportDialog.tsx — keep these two derivation
- // paths in lock-step so the native multiclip export and the in-process
- // preview composer see the same clip stream.
const assetById = new Map(document.assets.map((a) => [a.id, a]));
- const visibleClips = [...document.timeline.clips]
- .sort((a, b) => a.timelineStartSec - b.timelineStartSec)
- .filter((clip) => assetById.get(clip.assetId)?.originalPath);
+ const visibleClips = resolveVisibleClips(document);
const clips: CompositorClipInput[] = visibleClips.flatMap((clip) => {
const asset = assetById.get(clip.assetId);
if (!asset?.originalPath) return [];
diff --git a/vite.config.ts b/vite.config.ts
index b55d15285..0e1985f8d 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -34,6 +34,17 @@ export default defineConfig({
"@": path.resolve(__dirname, "src"),
},
},
+ server: {
+ watch: {
+ // Nested worktrees (`.claude/worktrees/**`) and delegate task checkouts
+ // (`.cc-delegate/**`) each carry their own full copy of the repo, including
+ // their own vite/tsconfig files. Without this, deleting/touching one (e.g.
+ // `git worktree remove`) fires hundreds of change events across the main
+ // dev server, forcing repeated full-reloads unrelated to any real source
+ // change — observed as the running app going unresponsive/stale mid-session.
+ ignored: ["**/.claude/worktrees/**", "**/.cc-delegate/**"],
+ },
+ },
build: {
target: "esnext",
minify: "terser",