Skip to content

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

feat(preview): the voice parks with the walk, and every take plays once

EtienneLescot6f45416b8bb6
diff --git a/src/components/ai-edition/VirtualPreview.audio.test.ts b/src/components/ai-edition/VirtualPreview.audio.test.ts
index 9429ac708..624272848 100644
--- a/src/components/ai-edition/VirtualPreview.audio.test.ts
+++ b/src/components/ai-edition/VirtualPreview.audio.test.ts
@@ -1,13 +1,11 @@
import { describe, expect, it } from "vitest";
import { projectRawTimelineSecToPlayback } from "@/lib/ai-edition/document/timeline";
import type { AxcutAudioTrack, AxcutClip, AxcutTrimRange } from "@/lib/ai-edition/schema";
-import { removedRawSpans } from "@/lib/ai-edition/timeline/programme-time";
import {
applyPreviewAudioSettings,
type PreviewAudioGraph,
resolveAudioTrackPlayback,
resolveTimelineAudioPlayback,
- resolveVoiceoverPlayback,
timelineAudioFadeAt,
} from "./VirtualPreview";
@@ -310,98 +308,3 @@ describe("timelineAudioFadeAt", () => {
expect(timelineAudioFadeAt(long, 2, 2)).toBe(1);
});
});
-
-// ─── A cut under a voiceover ──────────────────────────────────────────────────
-// Issue #560. The preview and the export have to agree about this, or a word the
-// transcript pane shows struck through is still audible in one of them.
-
-describe("resolveVoiceoverPlayback", () => {
- const CLIPS = [
- {
- id: "c1",
- assetId: "scr",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 0,
- timelineEndSec: 10,
- wordRefs: [],
- origin: "user" as const,
- reason: "",
- },
- ];
- /** Raw 4..6 is out of the film. */
- const TRIMS = [
- {
- id: "t1",
- assetId: "scr",
- clipId: "c1",
- startSec: 4,
- endSec: 6,
- reason: "",
- origin: "user" as const,
- },
- ];
- const removed = removedRawSpans(CLIPS, TRIMS);
-
- const voice = {
- id: "vo",
- assetId: "aud",
- kind: "voiceover" as const,
- startMs: 0,
- endMs: 10_000,
- durationSec: 30,
- offsetMs: 0,
- gainDb: 0,
- loop: false,
- fadeInMs: 0,
- fadeOutMs: 0,
- muted: false,
- label: "",
- origin: "user" as const,
- } as unknown as AxcutAudioTrack;
-
- it("goes silent exactly where the film lost its moment", () => {
- expect(resolveVoiceoverPlayback(voice, 3.9, removed).shouldPlay).toBe(true);
- expect(resolveVoiceoverPlayback(voice, 4.5, removed).shouldPlay).toBe(false);
- expect(resolveVoiceoverPlayback(voice, 6.1, removed).shouldPlay).toBe(true);
- });
-
- it("keeps the take's own clock running through the cut", () => {
- // It does NOT rewind or skip: raw 7 is second 7 of the take either way, which is
- // what makes the words after the cut still line up with the ones on screen.
- expect(resolveVoiceoverPlayback(voice, 7, removed).targetTimeSec).toBeCloseTo(7, 6);
- expect(
- resolveVoiceoverPlayback({ ...voice, offsetMs: 2000 }, 7, removed).targetTimeSec,
- ).toBeCloseTo(9, 6);
- });
-
- it("stays silent outside its own span, and past the end of its file", () => {
- expect(resolveVoiceoverPlayback({ ...voice, startMs: 2000 }, 1, removed).shouldPlay).toBe(
- false,
- );
- expect(resolveVoiceoverPlayback(voice, 11, removed).shouldPlay).toBe(false);
- // A 3s file under a 10s span: silent after its own end rather than seeking past it.
- const short = { ...voice, durationSec: 3 } as AxcutAudioTrack;
- expect(resolveVoiceoverPlayback(short, 2.5, removed).shouldPlay).toBe(true);
- expect(resolveVoiceoverPlayback(short, 3.5, removed).shouldPlay).toBe(false);
- });
-
- it("schedules the same source seconds the export writes into the mix", () => {
- // Walk the take frame by frame and collect the contiguous runs of source time the
- // preview would play; they must be the export's entries, piece for piece.
- const runs: Array<{ from: number; to: number }> = [];
- for (let raw = 0; raw < 10; raw += 0.05) {
- const at = resolveVoiceoverPlayback(voice, raw, removed);
- if (!at.shouldPlay) continue;
- const last = runs.at(-1);
- if (last && Math.abs(at.targetTimeSec - last.to) < 0.06) last.to = at.targetTimeSec;
- else runs.push({ from: at.targetTimeSec, to: at.targetTimeSec });
- }
- expect(runs).toHaveLength(2);
- expect(runs[0].from).toBeCloseTo(0, 1);
- expect(runs[0].to).toBeCloseTo(4, 1);
- // The second run resumes at source 6 — the two seconds the cut took are never heard.
- expect(runs[1].from).toBeCloseTo(6, 1);
- expect(runs[1].to).toBeCloseTo(10, 1);
- });
-});
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index c00574136..60918a86c 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -4,7 +4,11 @@ import {
DEFAULT_CROP_REGION,
MAX_NATIVE_PLAYBACK_RATE,
} from "@/components/video-editor/types";
-import { resolveFadeSecs } from "@/lib/ai-edition/document/audioTracks";
+import {
+ collapseTracksToPills,
+ resolveFadeSecs,
+ trackGroupId,
+} from "@/lib/ai-edition/document/audioTracks";
import {
projectRawTimelineSecToPlayback,
resolvePlaybackSegments,
@@ -20,12 +24,15 @@ import { audioGainScalar } from "@/lib/ai-edition/store/editorSettings";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import { rulerInserts } from "@/lib/ai-edition/timeline/inserted-time";
import type { PlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock";
-import {
- type RemovedRawSpan,
- removalAt,
- removedRawSpans,
-} from "@/lib/ai-edition/timeline/programme-time";
+import { removedRawSpans } from "@/lib/ai-edition/timeline/programme-time";
import { findActiveSpeedRegion, type SpeedRegion } from "@/lib/ai-edition/timeline/speed";
+import {
+ consumedSourceSec,
+ type TakeInsert,
+ type TakePiece,
+ takePlaybackAt,
+ takeProgramme,
+} from "@/lib/ai-edition/timeline/take-programme";
import {
clampVirtualTime,
findNextKeptSegment,
@@ -133,42 +140,6 @@ export function resolveTimelineAudioPlayback(
};
}
-/**
- * Where a VOICEOVER should be, asked in RAW ruler seconds (issue #560).
- *
- * A cut under a voiceover removes the words that were said there, not the tail of the
- * take: the transcript pane has already struck those words through, so a mix that went on
- * playing them — shifted earlier, as a contiguous block does — would make the red a lie.
- *
- * Raw is the simpler question and the exact one. `resolveTimelineAudioPlayback` works in
- * output seconds because a bed is one contiguous block laid on the finished programme, and
- * getting there means projecting the playhead through the trims. A sliced take needs no
- * projection at all: its source position is its own offset plus however far raw time has
- * carried it, and it falls silent wherever the film did. That is the same question
- * `removedRawSpans` answers for the words themselves, so the two cannot drift.
- *
- * Music does NOT come through here. A bed plays through a cut and ends early, on purpose.
- */
-export function resolveVoiceoverPlayback(
- track: AxcutAudioTrack,
- rawSec: number,
- removed: RemovedRawSpan[],
-) {
- const startSec = track.startMs / 1000;
- const offset = Math.max(0, track.offsetMs / 1000);
- const sourceEnd = track.durationSec > 0 ? track.durationSec : Number.POSITIVE_INFINITY;
- const local = rawSec - startSec;
- const targetTimeSec = Math.min(Math.max(offset, offset + local), sourceEnd);
- return {
- targetTimeSec,
- shouldPlay:
- rawSec >= startSec &&
- rawSec < track.endMs / 1000 &&
- offset + local < sourceEnd &&
- removalAt(removed, rawSec) === null,
- };
-}
-
/** Fraction 0..1 of a track's volume `localSec` into its span, applying the
* ramps. Shares `resolveFadeSecs` with the export so a fade too long for its
* span is reduced the same way on both sides. */
@@ -595,8 +566,46 @@ export function VirtualPreview({
// track after a pause lands D seconds early — the bug this argument exists to close.
const filmInsertsRef = useRef(rulerInserts(insertRanges, clips));
filmInsertsRef.current = useMemo(() => rulerInserts(insertRanges, clips), [insertRanges, clips]);
+ // One walk per take, recomputed only when the cuts or the insertions move. The rAF asks
+ // it every frame per track, and walking on each would be wasteful.
+ // The take's own insertions, resolved from the ranges this component already receives.
+ // `resolveInsertPlacement` needs assets to tell the lanes apart, and the preview has
+ // none — but a range naming an AUDIO asset is exactly one whose asset is not a clip's,
+ // which is the same test, available here.
+ const clipAssetIds = useMemo(() => new Set(clips.map((c) => c.assetId)), [clips]);
+ const takeInsertsByGroup = useCallback(
+ (groupId: string): TakeInsert[] => {
+ const pill = collapseTracksToPills(audioTracks).find((t) => trackGroupId(t) === groupId);
+ if (!pill) return [];
+ return insertRanges
+ .filter((range) => range.assetId === pill.assetId && !clipAssetIds.has(range.assetId))
+ .map((range) => ({
+ id: range.id,
+ wordId: range.wordId,
+ atSourceSec: range.atSec,
+ durationSec: range.durationSec,
+ }));
+ },
+ [audioTracks, insertRanges, clipAssetIds],
+ );
+ const takePiecesRef = useRef<Map<string, TakePiece[]>>(new Map());
+ const takeHeadsRef = useRef<Map<string, string>>(new Map());
const removedRef = useRef(removedRawSpans(clips, trimRanges));
removedRef.current = useMemo(() => removedRawSpans(clips, trimRanges), [clips, trimRanges]);
+ const takeWalks = useMemo(() => {
+ const pieces = new Map<string, TakePiece[]>();
+ const heads = new Map<string, string>();
+ const removed = removedRawSpans(clips, trimRanges);
+ for (const pill of collapseTracksToPills(audioTracks)) {
+ if (pill.kind !== "voiceover" || pill.loop) continue;
+ const groupId = trackGroupId(pill);
+ heads.set(groupId, pill.id);
+ pieces.set(groupId, takeProgramme(pill, removed, takeInsertsByGroup(groupId)));
+ }
+ return { pieces, heads };
+ }, [audioTracks, clips, trimRanges, takeInsertsByGroup]);
+ takePiecesRef.current = takeWalks.pieces;
+ takeHeadsRef.current = takeWalks.heads;
// 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,
@@ -732,14 +741,37 @@ export function VirtualPreview({
filmInsertsRef.current,
),
);
- // A voiceover follows the cuts; a bed plays through them. Step 6 of #560
- // refuses `loop` on a voiceover outright, so until then a looping one keeps
- // the bed's treatment rather than getting semantics invented for it.
- const trackTarget =
+ // A voiceover follows the cuts AND its own insertions, through one walk over
+ // its PILL. Every fragment but the head is silenced: the document keeps one
+ // per clip the take covers, and letting each play its own slice would put the
+ // take on top of itself, exactly as it would in the export.
+ //
+ // A bed plays through a cut and ends early, on purpose. A looping voiceover
+ // keeps the bed's treatment — step 6 of #560 refuses that combination, and
+ // inventing semantics for it would be the worse answer.
+ const takeGroupId = trackGroupId(track);
+ const takePieces =
track.kind === "voiceover" && !track.loop
- ? resolveVoiceoverPlayback(track, virtualTimeSecRef.current, removedRef.current)
- : resolveTimelineAudioPlayback(outputTimeSec, outputStartSec, track, spanSec);
- const fade = timelineAudioFadeAt(track, outputTimeSec - outputStartSec, spanSec);
+ ? takePiecesRef.current.get(takeGroupId)
+ : undefined;
+ if (takePieces && takeHeadsRef.current.get(takeGroupId) !== track.id) {
+ if (!el.paused) el.pause();
+ continue;
+ }
+ const trackTarget = takePieces
+ ? (takePlaybackAt(takePieces, virtualTimeSecRef.current) ?? {
+ targetTimeSec: track.offsetMs / 1000,
+ shouldPlay: false,
+ })
+ : resolveTimelineAudioPlayback(outputTimeSec, outputStartSec, track, spanSec);
+ // Fades measure against the SOURCE the walk consumes, never the take's ruler
+ // extent: an insertion grows the extent without adding a second of file, and
+ // a fade-out measured on it would start early here and nowhere else.
+ const fadeSpanSec = takePieces ? consumedSourceSec(takePieces) : spanSec;
+ const fadeLocalSec = takePieces
+ ? Math.max(0, trackTarget.targetTimeSec - track.offsetMs / 1000)
+ : outputTimeSec - outputStartSec;
+ const fade = timelineAudioFadeAt(track, fadeLocalSec, fadeSpanSec);
// Imported audio plays at its natural 1× rate, NOT the video's. The export
// sums it into the programme at 1× — speed regions stretch clip PCM only,
// never the imported track — so following `v.playbackRate` would pitch a
diff --git a/src/lib/ai-edition/timeline/take-programme.test.ts b/src/lib/ai-edition/timeline/take-programme.test.ts
index cd93690bb..4e157d18b 100644
--- a/src/lib/ai-edition/timeline/take-programme.test.ts
+++ b/src/lib/ai-edition/timeline/take-programme.test.ts
@@ -182,3 +182,57 @@ describe("takePlaybackAt", () => {
expect(takePlaybackAt(pieces, 12)).toBeNull();
});
});
+
+// ─── The preview and the export, held to each other ─────────────────────────
+// They read the same walk now, but "the same walk" is a claim about wiring. This walks the
+// take frame by frame the way the rAF does and asserts the runs of source time it would
+// play are the entries the export emits, piece for piece.
+
+describe("preview and export agree over a take with a cut and a pause", () => {
+ const removed = removedRawSpans(CLIPS, [trim(7, 8)]);
+ const pieces = takeProgramme(TAKE, removed, [ins(4, 1)]);
+
+ it("plays exactly the play pieces, and nothing between them", () => {
+ const runs: Array<{ from: number; to: number }> = [];
+ // A run breaks on SILENCE, not on a jump in source time. Across a pause the source
+ // is deliberately continuous — the voice resumes on the word it stopped on — so a
+ // detector watching only the source would merge the two halves and see one run.
+ let wasPlaying = false;
+ for (let raw = 0; raw < 10; raw += 0.05) {
+ const at = takePlaybackAt(pieces, raw);
+ if (!at?.shouldPlay) {
+ wasPlaying = false;
+ continue;
+ }
+ const last = runs.at(-1);
+ if (wasPlaying && last && Math.abs(at.targetTimeSec - last.to) < 0.06) {
+ last.to = at.targetTimeSec;
+ } else {
+ runs.push({ from: at.targetTimeSec, to: at.targetTimeSec });
+ }
+ wasPlaying = true;
+ }
+ const entries = pieces
+ .filter((p) => p.kind === "play")
+ .map((p) => [p.sourceStartSec, p.sourceEndSec]);
+ expect(runs).toHaveLength(entries.length);
+ runs.forEach((run, i) => {
+ expect(run.from).toBeCloseTo(entries[i][0], 1);
+ expect(run.to).toBeCloseTo(entries[i][1], 1);
+ });
+ });
+
+ it("never re-seeks while the voice is parked", () => {
+ // One value for the whole pause: a target that drifted would re-seek a paused
+ // element every frame, and resuming would restart on the wrong word.
+ const inside = [4.1, 4.3, 4.5, 4.7, 4.9].map((raw) => takePlaybackAt(pieces, raw));
+ expect(inside.every((at) => at?.shouldPlay === false)).toBe(true);
+ expect(new Set(inside.map((at) => at?.targetTimeSec)).size).toBe(1);
+ });
+
+ it("resumes on the second it stopped on", () => {
+ const parked = takePlaybackAt(pieces, 4.5)?.targetTimeSec;
+ const resumed = takePlaybackAt(pieces, 5.01)?.targetTimeSec;
+ expect(resumed).toBeCloseTo(parked ?? -1, 1);
+ });
+});