Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(insertions): an extension is a clip, because that is the only shape the app maps
EtienneLescot63f16b7183d8
diff --git a/electron/media/extensionClip.test.ts b/electron/media/extensionClip.test.tsindex d7199550a..d2f7df681 100644--- a/electron/media/extensionClip.test.ts+++ b/electron/media/extensionClip.test.ts@@ -5,45 +5,48 @@ import { describe, expect, it } from "vitest";import { extensionClipPath } from "../../src/lib/ai-edition/timeline/clip-parts";import { extensionClipArgs } from "./extensionClip";-const SPEC = {- sourcePath: "C:/rec/take.mp4",- atSec: 5.3,- durationSec: 3.6,- fps: 30,- width: 1920,- height: 1080,-};+const SPEC = { durationSec: 3.6, fps: 30, width: 1920, height: 1080 };describe("extensionClipArgs", () => {const args = extensionClipArgs(SPEC, "C:/out/w1_3600.mp4");- const at = (flag: string) => args[args.indexOf(flag) + 1];+ const filter = (prefix: string) => args.find((a) => a.startsWith(prefix)) ?? "";- it("seeks BEFORE the input, so ffmpeg does not decode up to the moment", () => {- expect(args.indexOf("-ss")).toBeLessThan(args.indexOf("-i"));- expect(at("-ss")).toBe("5.300");+ it("draws a test pattern, so generated media is unmistakable on screen", () => {+ // A held frame from the recording looked exactly like a decoder stuck at the end of+ // a clip — which is the bug it hid for three rounds.+ expect(filter("testsrc2=")).toContain("size=1920x1080");+ expect(filter("testsrc2=")).toContain("rate=30");});- it("holds exactly the frozen frame for the whole duration", () => {- const filter = at("-filter_complex");- expect(filter).toContain("trim=end_frame=1");- expect(filter).toContain("loop=loop=-1:size=1:start=0");- expect(filter).toContain("trim=duration=3.600");+ it("carries an audible noise track rather than silence", () => {+ expect(filter("anoisesrc=")).toContain("a=0.2");+ expect(args).toContain("1:a");});- it("matches the recording's geometry, so the two concatenate downstream", () => {- expect(at("-filter_complex")).toContain("fps=30");- expect(at("-filter_complex")).toContain("scale=1920:1080");+ it("reads the recording not at all — nothing to seek, nothing to decode", () => {+ expect(args.filter((a) => a === "-i")).toHaveLength(2);+ expect(args).not.toContain("-ss");+ expect(args.some((a) => a.endsWith(".mp4") && a !== "C:/out/w1_3600.mp4")).toBe(false);});- it("carries an audio track rather than none — silence reads as a broken file", () => {- expect(args.some((a) => a.startsWith("anoisesrc="))).toBe(true);- expect(args).toContain("1:a");+ it("runs for exactly the duration asked for, on both streams and the output", () => {+ expect(filter("testsrc2=")).toContain("duration=3.600");+ expect(filter("anoisesrc=")).toContain("d=3.600");+ expect(args[args.indexOf("-t") + 1]).toBe("3.600");+ expect(args[args.length - 1]).toBe("C:/out/w1_3600.mp4");});- it("bounds the output, so a looping filter cannot run away", () => {- // `-t` appears twice on purpose: once on the noise input, once on the output.- expect(args.filter((a) => a === "-t")).toHaveLength(2);- expect(args[args.length - 1]).toBe("C:/out/w1_3600.mp4");+ it("uses an encoder the bundled LGPL ffmpeg actually has", () => {+ // `libx264` is GPL and absent: the first real run failed with "Unknown encoder".+ expect(args).toContain("libopenh264");+ expect(args).not.toContain("libx264");+ });++ it("still has a geometry when the asset does not know its own", () => {+ // The live project's asset carries `fps: 0` — the probe never filled it in.+ const blind = extensionClipArgs({ ...SPEC, fps: 0, width: 0, height: 0 }, "out.mp4");+ expect(blind.find((a) => a.startsWith("testsrc2="))).toContain("size=1920x1080");+ expect(blind.find((a) => a.startsWith("testsrc2="))).toContain("rate=30");});});@@ -69,19 +72,3 @@ describe("extensionClipPath", () => {);});});--describe("the two things reality imposed", () => {- it("uses an encoder the bundled LGPL ffmpeg actually has", () => {- // `libx264` is GPL and absent: the first real run failed with "Unknown encoder".- const args = extensionClipArgs(SPEC, "out.mp4");- expect(args).toContain("libopenh264");- expect(args).not.toContain("libx264");- });-- it("still has a frame rate when the asset does not know its own", () => {- // The live project's asset carries `fps: 0` — the probe never filled it in, and a- // loop filter with no rate produces nothing.- const args = extensionClipArgs({ ...SPEC, fps: 0 }, "out.mp4");- expect(args[args.indexOf("-filter_complex") + 1]).toContain("fps=30");- });-});diff --git a/electron/media/extensionClip.ts b/electron/media/extensionClip.tsindex 4b874a66a..5022fc5b7 100644--- a/electron/media/extensionClip.ts+++ b/electron/media/extensionClip.ts@@ -2,9 +2,14 @@* The media an added word is spoken over.** A word typed into the transcript has no recording behind it. Until there is TTS and frame- * generation, the stand-in is the last frame the recording showed, held, over faint noise —- * a real file, with real frames and a real audio track, so everything downstream decodes it- * like any other media instead of special-casing its absence.+ * generation the stand-in is a TEST PATTERN over noise — a real file, with real frames and a+ * real audio track, so everything downstream decodes it like any other media instead of+ * special-casing its absence.+ *+ * ponytail: a mire, on purpose, and not the recording's last frame held. A held frame is+ * indistinguishable on screen from a decoder stuck at the end of a clip, which is exactly+ * the bug it hid. The mire says "this is generated media, and it is playing HERE" at a+ * glance. Swap it for synthesized frames the day there are any.** DERIVED, never authored: the word is the truth, this file is regenerable from it. The name* carries what it was generated from, so a stale one is simply never asked for again, and a@@ -23,63 +28,57 @@ import {import { resolveFfmpeg } from "./audioPeaks";export interface ExtensionClipSpec {- /** The recording the frozen frame is taken from. */- sourcePath: string;- /** Source second to freeze on — the moment the added word follows. */- atSec: number;durationSec: number;/** Matched to the recording so the two concatenate without a re-encode downstream.- * `0` when the asset was imported before the probe filled it in — see `FALLBACK_FPS`. */+ * `0` when the asset was imported before the probe filled it in — see the fallbacks. */fps: number;width: number;height: number;}/** Noise rather than silence: a silent track is indistinguishable from a broken one, and- * this stands in for a voice that will be synthesized later. Quiet enough not to startle. */-const NOISE_AMPLITUDE = 0.02;+ * this stands in for a voice that will be synthesized later. Loud enough to be unmistakable+ * while the generated stretch is the thing being debugged. */+const NOISE_AMPLITUDE = 0.2;const SAMPLE_RATE = 48_000;/** The bundled ffmpeg is LGPL, so `libx264` is not in it — `libopenh264` is the software- * H.264 encoder every LGPL build carries, on every platform. The hardware encoders- * (`h264_nvenc`, `h264_mf`, …) are faster and each needs its own hardware; for a clip of a- * few seconds that trade is not worth a platform branch. */+ * H.264 encoder every LGPL build carries, on every platform. */const VIDEO_ENCODER = "libopenh264";-/** Assets imported before the probe filled `video.fps` carry 0, and the live project has- * one. A loop filter needs a rate, so it gets a common one.- * ponytail: fixed 30, read the real rate off the source when the probe backfills it. */+/** Assets imported before the probe filled `video` carry zeroes, and the live project does.+ * ponytail: fixed, read the real geometry off the source when the probe backfills it. */const FALLBACK_FPS = 30;+const FALLBACK_WIDTH = 1920;+const FALLBACK_HEIGHT = 1080;/*** The ffmpeg arguments, as a pure function so the command can be asserted without running it.*- * One pass, no temp file: seek to the moment, keep the single frame there, loop it for the- * duration, and mux it against a noise source of the same length.+ * Two synthetic inputs and nothing else: the recording is not read at all, which is what+ * makes this fast, independent of what the source codec is, and impossible to confuse with+ * the recording once it is on screen.*/export function extensionClipArgs(spec: ExtensionClipSpec, outPath: string): string[] {const dur = spec.durationSec.toFixed(3);const fps = spec.fps > 0 ? spec.fps : FALLBACK_FPS;+ const width = spec.width > 0 ? spec.width : FALLBACK_WIDTH;+ const height = spec.height > 0 ? spec.height : FALLBACK_HEIGHT;return ["-y","-hide_banner","-loglevel","error",- // Before `-i`, so ffmpeg seeks rather than decoding up to the moment.- "-ss",- spec.atSec.toFixed(3),+ "-f",+ "lavfi","-i",- spec.sourcePath,+ `testsrc2=size=${width}x${height}:rate=${fps}:duration=${dur}`,"-f","lavfi",- "-t",- dur,"-i",- `anoisesrc=c=pink:a=${NOISE_AMPLITUDE}:r=${SAMPLE_RATE}`,- "-filter_complex",- `[0:v]trim=end_frame=1,loop=loop=-1:size=1:start=0,fps=${fps},trim=duration=${dur},setpts=PTS-STARTPTS,scale=${spec.width}:${spec.height}[v]`,+ `anoisesrc=c=pink:a=${NOISE_AMPLITUDE}:r=${SAMPLE_RATE}:d=${dur}`,"-map",- "[v]",+ "0:v","-map","1:a","-c:v",@@ -121,8 +120,6 @@ export async function ensureDocumentExtensions(document: {try {await ensureExtensionClip({- sourcePath: asset.originalPath,- atSec: word.startSec,durationSec,fps: asset.video?.fps ?? 0,width: asset.video?.width ?? 0,diff --git a/src/cli/CliExportRunner.tsx b/src/cli/CliExportRunner.tsxindex 9a7f1b590..6c29b9975 100644--- a/src/cli/CliExportRunner.tsx+++ b/src/cli/CliExportRunner.tsx@@ -24,6 +24,7 @@ import { applyProbedDuration } from "@/lib/ai-edition/document/timeline";import type { AxcutDocument } from "@/lib/ai-edition/schema";import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";import { assetCameraSource } from "@/lib/ai-edition/timeline/camera";+import { withExtensions } from "@/lib/ai-edition/timeline/clip-parts";import { resolveClipSourceEndSec } from "@/lib/ai-edition/timeline/clipDuration";import { DEFAULT_ZOOM_DEPTH, ZOOM_DEPTH_SCALES } from "@/lib/ai-edition/timeline/zoom-scale";import { buildAutoZoomSuggestions } from "@/lib/ai-edition/timeline/zoom-suggestions";@@ -78,7 +79,8 @@ function replaceExtension(filePath: string, newExtension: string): string {/** Mirrors ExportDialog.buildNativeClipList: trim-narrowed visible clips mapped* onto the native multiclip contract. Kept in lock-step with* buildSceneDescription so export and scene agree on the clip stream. */-function buildNativeClipList(axcutDocument: AxcutDocument): CompositorClipInput[] {+function buildNativeClipList(rawDocument: AxcutDocument): CompositorClipInput[] {+ const axcutDocument = withExtensions(rawDocument);const assetById = new Map(axcutDocument.assets.map((asset) => [asset.id, asset]));return resolveVisibleClips(axcutDocument).flatMap((clip) => {const asset = assetById.get(clip.assetId);diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsxindex 5dff50acf..97da5286a 100644--- a/src/components/ai-edition/ExportDialog.tsx+++ b/src/components/ai-edition/ExportDialog.tsx@@ -21,6 +21,7 @@ import {import type { AxcutDocument } from "@/lib/ai-edition/schema";import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";import { assetCameraSource } from "@/lib/ai-edition/timeline/camera";+import { withExtensions } from "@/lib/ai-edition/timeline/clip-parts";import { resolveClipSourceEndSec } from "@/lib/ai-edition/timeline/clipDuration";import {type ExportFormat,@@ -80,7 +81,8 @@ function revealExportedFile(filePath: string): void {* `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[] {+function buildNativeClipList(rawDocument: AxcutDocument): CompositorClipInput[] {+ const document = withExtensions(rawDocument);const assetById = new Map(document.assets.map((a) => [a.id, a]));return resolveVisibleClips(document).flatMap((clip) => {const asset = assetById.get(clip.assetId);diff --git a/src/components/ai-edition/NativeCompositorOverlay.tsx b/src/components/ai-edition/NativeCompositorOverlay.tsxindex e4af64102..5bfa32c50 100644--- a/src/components/ai-edition/NativeCompositorOverlay.tsx+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx@@ -4,6 +4,7 @@ import { noteUiProbeClipSwitch } from "@/lib/ai-edition/perf/uiFrameProbe";import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import { assetCameraSource } from "@/lib/ai-edition/timeline/camera";+import { withExtensions } from "@/lib/ai-edition/timeline/clip-parts";import { resolveNativePosition } from "@/lib/ai-edition/timeline/timelineMap";import {pushAllNativeParams,@@ -69,13 +70,18 @@ export function NativeCompositorOverlay() {// Sans ça (ancien `resolveNativePlaybackPosition(nativeClips, currentTimeSec)`), un playhead// RAW lu contre des clips compactés désignait le mauvais clip après un trim → mauvaise caméra// + décalage écran/cam.+ // The document the NATIVE side plays: an extension is a clip on its own asset, with its+ // own file. Everything below — the compacted segments, the raw layout they are placed+ // against, the asset the decoder is pointed at — has to be read from the same one, or+ // they disagree about what the film contains.+ const playedDocument = useMemo(() => (document ? withExtensions(document) : null), [document]);const nativeClips = useMemo(() => {- if (!document) return [];- return resolveVisibleClips(document);- }, [document]);+ if (!playedDocument) return [];+ return resolveVisibleClips(playedDocument);+ }, [playedDocument]);const activePosition = useMemo(- () => resolveNativePosition(currentTimeSec, nativeClips, document?.timeline.clips ?? []),- [nativeClips, currentTimeSec, document],+ () => resolveNativePosition(currentTimeSec, nativeClips, playedDocument?.timeline.clips ?? []),+ [nativeClips, currentTimeSec, playedDocument],);const activeClip = activePosition?.clip ?? null;@@ -191,7 +197,7 @@ export function NativeCompositorOverlay() {useEffect(() => {if (viewId === null ||- !document ||+ !playedDocument ||!activeClipId ||!activeClip ||activeClipIndex === null ||@@ -202,7 +208,7 @@ export function NativeCompositorOverlay() {if (previousActiveClipIdRef.current === activeClipId) {return;}- const asset = document.assets.find((candidate) => candidate.id === activeClip.assetId);+ const asset = playedDocument?.assets.find((candidate) => candidate.id === activeClip.assetId);if (!asset?.originalPath) {return;}@@ -248,7 +254,15 @@ export function NativeCompositorOverlay() {previousActiveClipIdRef.current = null;}});- }, [viewId, document, activeClipId, activeClip, activeClipIndex, activeSourceTimeSec, playing]);+ }, [+ viewId,+ playedDocument,+ activeClipId,+ activeClip,+ activeClipIndex,+ activeSourceTimeSec,+ playing,+ ]);if (!ready) {return null;diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsxindex 61744066c..5622e9990 100644--- a/src/components/ai-edition/NewEditorShell.tsx+++ b/src/components/ai-edition/NewEditorShell.tsx@@ -32,12 +32,7 @@ import {import { useUndoRedoShortcuts } from "@/lib/ai-edition/store/undo";import { useSequentialTimelineOps } from "@/lib/ai-edition/store/useSequentialTimelineOps";import { useTimeline } from "@/lib/ai-edition/store/useTimeline";-import {- extensionAssetId,- extensionClipPath,- extensionDurationSec,- isAddedWord,-} from "@/lib/ai-edition/timeline/clip-parts";+import { withExtensions } from "@/lib/ai-edition/timeline/clip-parts";import { newRegionDurationSec } from "@/lib/ai-edition/timeline/newRegionDuration";import { firstTimelineBusyView } from "@/lib/ai-edition/transcription/status";import {@@ -236,6 +231,10 @@ export function NewEditorShell() {document?.assets.find((a) => a.id === document.project.primaryAssetId)?.originalPath ?? null;void primaryAssetPath;const clips: AxcutClip[] = document?.timeline.clips ?? [];+ // The document as the PLAYER sees it: an extension is a clip on its own asset. The ruler+ // deliberately keeps `clips` above — a clip does not become three on screen because a+ // word was typed into it.+ const playedDocument = useMemo(() => (document ? withExtensions(document) : null), [document]);const visibleClips = useMemo(() => (document ? resolveVisibleClips(document) : []), [document]);const hasProject = Boolean(document);const hasAsset = projectId !== null && (document?.assets.length ?? 0) > 0;@@ -360,45 +359,24 @@ export function NewEditorShell() {}, [promptUnsaved, saveDocument]);const videoSources = useMemo(() => {- if (!document) return [];- // One source per added word, beside the recordings. The player keys sources by asset- // id and an extension answers to `ext:<wordId>`, so it swaps to the generated file at- // the boundary exactly as it swaps between two recordings — no new case.- //- // A file the save has not written yet simply fails to load, and the player reports it- // the way it reports any unreadable source: the edit stands, the picture catches up.- const extensions = document.transcripts.flatMap((transcript) => {- const asset = document.assets.find((a) => a.id === transcript.assetId);- if (!asset?.originalPath) return [];- return transcript.words.filter(isAddedWord).flatMap((word) => {- const durationSec = extensionDurationSec(word.text);- if (durationSec <= 0) return [];- const filePath = extensionClipPath(asset.originalPath, word.id, durationSec);- return [- {- id: extensionAssetId(word.id),- filePath,- src: toFileUrl(filePath),- label: word.text,- },- ];- });- });- return document.assets- .map((asset) => ({- id: asset.id,- filePath: /^(https?|blob|data):/.test(asset.originalPath) ? undefined : asset.originalPath,- // Real Electron assets are filesystem paths and go through toFileUrl.- // In the browser preview an asset can already point at an http(s)/- // blob/data URL served by Vite; toFileUrl would mangle those into a- // broken file:// URL, so pass web URLs through untouched.- src: /^(https?|blob|data):/.test(asset.originalPath)- ? asset.originalPath- : toFileUrl(asset.originalPath),- label: asset.label,- }))- .concat(extensions);- }, [document]);+ if (!playedDocument) return [];+ // Every asset, extensions included — they are assets by the time they get here, each+ // with a real path. A file the save has not written yet simply fails to load, and the+ // player reports it the way it reports any unreadable source: the edit stands, the+ // picture catches up on the next save.+ return playedDocument.assets.map((asset) => ({+ id: asset.id,+ filePath: /^(https?|blob|data):/.test(asset.originalPath) ? undefined : asset.originalPath,+ // Real Electron assets are filesystem paths and go through toFileUrl.+ // In the browser preview an asset can already point at an http(s)/+ // blob/data URL served by Vite; toFileUrl would mangle those into a+ // broken file:// URL, so pass web URLs through untouched.+ src: /^(https?|blob|data):/.test(asset.originalPath)+ ? asset.originalPath+ : toFileUrl(asset.originalPath),+ label: asset.label,+ }));+ }, [playedDocument]);const handleLoadedMetadata = useCallback((durationSec: number, assetId: string) => {@@ -1539,12 +1517,11 @@ export function NewEditorShell() {// itself keeps playing — that is what the user is narrating to.audioTracks={voiceoverRecording ? NO_AUDIO_TRACKS : tl.audioTracks}audioSources={videoSources}- clips={clips}+ clips={playedDocument?.timeline.clips ?? clips}zoomRegions={tl.zoomRegions}speedRegions={tl.speedRegions}cameraFullscreenRegions={tl.cameraFullscreenRegions}trimRanges={tl.trimRanges}- transcripts={document?.transcripts ?? []}selectedZoomRegionId={tl.selection?.kind === "zoom" ? tl.selection.id : null}onZoomFocusChange={tl.updateZoomFocusLive}onZoomFocusCommit={() => void tl.commitZoomFocus()}diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsxindex 84875bf35..feb174ff8 100644--- a/src/components/ai-edition/VirtualPreview.tsx+++ b/src/components/ai-edition/VirtualPreview.tsx@@ -16,13 +16,11 @@ import {import type {AxcutAudioTrack,AxcutClip,- AxcutTranscript,AxcutTrimRange,AxcutZoomRegion,} from "@/lib/ai-edition/schema";import { audioGainScalar } from "@/lib/ai-edition/store/editorSettings";import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";-import { clipsWithExtensions } from "@/lib/ai-edition/timeline/clip-parts";import type { PlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock";import { removedRawSpans } from "@/lib/ai-edition/timeline/programme-time";import { findActiveSpeedRegion, type SpeedRegion } from "@/lib/ai-edition/timeline/speed";@@ -214,8 +212,6 @@ interface VirtualPreviewProps {zoomRegions?: AxcutZoomRegion[];speedRegions?: SpeedRegion[];trimRanges?: AxcutTrimRange[];- /** So a clip carrying added words plays their extensions — see `clipParts`. */- transcripts?: AxcutTranscript[];seekTarget?: { timeSec: number; isSource?: boolean; requestId: number } | null;onTimeChange?: (timeSec: number) => void;onLoadedMetadata?: (@@ -262,7 +258,6 @@ export function VirtualPreview({zoomRegions = [],speedRegions = [],trimRanges = [],- transcripts = [],seekTarget,onTimeChange,onLoadedMetadata,@@ -552,13 +547,8 @@ export function VirtualPreview({// stuck at 0% and the drag range at `max=1`. The refs let the rAF// always see the latest values without re-creating on every clip// mutation.- // The clips this player sees: each extension spliced in as a clip of its own, so the- // source-swap and the clock it already has apply to it without a new case. Everything- // below reads THIS list — `clips` from the props is the document's, and the difference- // is exactly the media an added word is spoken over.- const playerClips = useMemo(() => clipsWithExtensions(clips, transcripts), [clips, transcripts]);- const clipsRef = useRef(playerClips);- clipsRef.current = playerClips;+ const clipsRef = useRef(clips);+ clipsRef.current = clips;// Same reason as `clipsRef`: the rAF projects the playhead and each imported// audio track's head raw→output every frame (see the audio-track loop), and// must see the live trims, not the set captured when the loop was created.@@ -599,10 +589,8 @@ export function VirtualPreview({// 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(- // `[]` transcripts, not a forgotten argument: `playerClips` has already spliced the- // extensions in, and splicing them twice would play each one twice.- () => resolvePlaybackSegments(playerClips, trimRanges, []),- [playerClips, trimRanges],+ () => resolvePlaybackSegments(clips, trimRanges),+ [clips, trimRanges],);const playbackClipsRef = useRef(playbackClips);playbackClipsRef.current = playbackClips;diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsxindex 81b79d80b..8d87a48b3 100644--- a/src/components/ai-edition/v4/V4Timeline.tsx+++ b/src/components/ai-edition/v4/V4Timeline.tsx@@ -49,6 +49,7 @@ import { useChatPromptBus } from "@/lib/ai-edition/store/useChatPromptBus";import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";import { hasAnyClipWithCamera } from "@/lib/ai-edition/timeline/camera";+import { clipParts } from "@/lib/ai-edition/timeline/clip-parts";import { formatSec } from "@/lib/ai-edition/timeline/format";import {newRegionDurationSec,@@ -712,21 +713,29 @@ export function V4Timeline({// clip because each mark is positioned inside its clip's own box — it then travels with// the clip through a reorder for free, with no ruler arithmetic of its own.const insertedWordsByClip = useMemo(() => {- const byAsset = new Map<string, AxcutWord[]>();- for (const transcript of tl.transcripts) {- const added = transcript.words.filter((word) => word.source === "synth");- if (added.length > 0) byAsset.set(transcript.assetId, added);- }- if (byAsset.size === 0) return new Map<string, Array<{ word: AxcutWord; atPct: number }>>();- const out = new Map<string, Array<{ word: AxcutWord; atPct: number }>>();+ type Mark = { word: AxcutWord; atPct: number; widthPct: number; atSec: number };+ const byAsset = new Map(tl.transcripts.map((t) => [t.assetId, t.words]));+ const out = new Map<string, Mark[]>();for (const clip of clips) {const words = byAsset.get(clip.assetId);- const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;- const span = sourceEnd - clip.sourceStartSec;+ // The clip's TIMELINE span, which is what the box on screen measures. Using the+ // source span put the mark at the wrong percentage AND gave it no width, because+ // the two spans stop being equal the moment a word is added.+ const span = clip.timelineEndSec - clip.timelineStartSec;if (!words || span <= 0) continue;- const marks = words- .filter((word) => word.startSec >= clip.sourceStartSec && word.startSec <= sourceEnd)- .map((word) => ({ word, atPct: ((word.startSec - clip.sourceStartSec) / span) * 100 }));+ const byId = new Map(words.map((w) => [w.id, w]));+ const marks = clipParts(clip, words).flatMap((part): Mark[] => {+ const word = part.kind === "extension" ? byId.get(part.wordId) : undefined;+ if (!word) return [];+ return [+ {+ word,+ atPct: ((part.timelineStartSec - clip.timelineStartSec) / span) * 100,+ widthPct: ((part.timelineEndSec - part.timelineStartSec) / span) * 100,+ atSec: part.timelineStartSec,+ },+ ];+ });if (marks.length > 0) out.set(clip.id, marks);}return out;@@ -2259,33 +2268,35 @@ export function V4Timeline({{tl.assets.find((a) => a.id === c.assetId)?.label ?? c.assetId}</span></div>- {(insertedWordsByClip.get(c.id) ?? []).map(({ word, atPct }) => {- const left = atPct;- const width = 0;- return (- <button- key={word.id}- type="button"- data-no-clip-drag- data-inserted-word={word.id}- className={styles.tlClipInsert}- style={- width > 0- ? { left: `${left}%`, width: `${width}%`, marginLeft: 0 }- : { left: `${left}%` }- }- title={t("toolbar.addedWord", { word: word.text })}- aria-label={t("toolbar.addedWord", { word: word.text })}- onPointerDown={(e) => e.stopPropagation()}- onClick={(e) => {- // Jump to the moment the added text sits on. The clip box- // underneath would otherwise take this as a selection.- e.stopPropagation();- setCurrentTime(c.timelineStartSec + (word.startSec - c.sourceStartSec));- }}- />- );- })}+ {(insertedWordsByClip.get(c.id) ?? []).map(+ ({ word, atPct, widthPct, atSec }) => {+ const left = atPct;+ const width = widthPct;+ return (+ <button+ key={word.id}+ type="button"+ data-no-clip-drag+ data-inserted-word={word.id}+ className={styles.tlClipInsert}+ style={+ width > 0+ ? { left: `${left}%`, width: `${width}%`, marginLeft: 0 }+ : { left: `${left}%` }+ }+ title={t("toolbar.addedWord", { word: word.text })}+ aria-label={t("toolbar.addedWord", { word: word.text })}+ onPointerDown={(e) => e.stopPropagation()}+ onClick={(e) => {+ // Jump to the moment the added text sits on. The clip box+ // underneath would otherwise take this as a selection.+ e.stopPropagation();+ setCurrentTime(atSec);+ }}+ />+ );+ },+ )}{selected ? (<buttontype="button"diff --git a/src/lib/ai-edition/captions/captions.test.ts b/src/lib/ai-edition/captions/captions.test.tsindex b313cd8f7..58a7de304 100644--- a/src/lib/ai-edition/captions/captions.test.ts+++ b/src/lib/ai-edition/captions/captions.test.ts@@ -684,6 +684,15 @@ describe("captions over an inserted word", () => {expect(cues[cues.length - 1].endMs).toBeCloseTo(6000 + (4 / 15) * 1000, 0);});+ it("gives the inserted word a line of its own, over the media it inserted", () => {+ // Grouped with the recorded words beside it, it inherited their span — which is what+ // left the inserted subtitle glued to the line before it.+ const wait = deriveCaptionCues(withInsertion(), ON, {}).find((c) => c.text === "wait");+ expect(wait).toBeDefined();+ expect(wait?.startMs).toBe(2000);+ expect(wait?.endMs).toBeCloseTo(2000 + (4 / 15) * 1000, 0);+ });+it("leaves the cues before it exactly where they were", () => {const before = deriveCaptionCues(doc(), ON, {});const after = deriveCaptionCues(withInsertion(), ON, {});diff --git a/src/lib/ai-edition/captions/cues.ts b/src/lib/ai-edition/captions/cues.tsindex 49d8fa315..a8ac19be4 100644--- a/src/lib/ai-edition/captions/cues.ts+++ b/src/lib/ai-edition/captions/cues.ts@@ -28,6 +28,7 @@ import {placementRawSec,type TranscriptPlacement,} from "../timeline/aggregated-transcript";+import { extensionSpanAtSource, isAddedWord } from "../timeline/clip-parts";import { removedRawSpans } from "../timeline/programme-time";import {type CaptionAnchorV,@@ -50,10 +51,42 @@ export interface CaptionCue {* the subtitle. Well clear of the annotation z-range, which counts up from 1. */export const CAPTION_Z_INDEX_BASE = 100_000;-function toCaptionSegments(transcript: AxcutTranscript): CaptionSegment[] {+/** A caption word that carries whether it was ADDED, which decides where a line breaks. */+type StreamWord = CaptionSegment & { added?: true };++function toCaptionSegments(transcript: AxcutTranscript): StreamWord[] {return transcript.words.filter((word) => word.text.trim().length > 0)- .map((word) => ({ startSec: word.startSec, endSec: word.endSec, text: word.text }));+ .map((word) => ({+ startSec: word.startSec,+ endSec: word.endSec,+ text: word.text,+ ...(isAddedWord(word) ? { added: true as const } : {}),+ }));+}++/**+ * The stream cut into runs, each grouped into lines on its own, with every added word a run+ * of one.+ *+ * An added word is spoken over its OWN media for its own stretch. Grouped with the recorded+ * words beside it, its line inherits their span — which is what glued the inserted subtitle+ * to the line before it and left it on screen at the wrong moment.+ */+function runsAroundAddedWords(stream: StreamWord[]): StreamWord[][] {+ const runs: StreamWord[][] = [];+ let run: StreamWord[] = [];+ for (const word of stream) {+ if (word.added) {+ if (run.length > 0) runs.push(run);+ runs.push([word]);+ run = [];+ continue;+ }+ run.push(word);+ }+ if (run.length > 0) runs.push(run);+ return runs;}function segmentWordsAsCaptionSegments(@@ -119,10 +152,17 @@ export function captionLinesForAsset(: translatedWordStream(transcript, translations, settings.language);if (stream.length === 0) return [];- return polish(groupTimedCaptionWordsIntoLines(stream, minWords, maxWords));+ return runsAroundAddedWords(stream).flatMap((run) =>+ // An added word is already a line, and must stay the POINT in source time that it is:+ // the polish pass gives a line a minimum span, and a span is exactly what this has+ // none of. Its real length comes from the extension it is spoken over, downstream.+ run.length === 1 && run[0].added+ ? [{ startSec: run[0].startSec, endSec: run[0].endSec, text: run[0].text }]+ : polish(groupTimedCaptionWordsIntoLines(run, minWords, maxWords)),+ );}-function originalWordStream(transcript: AxcutTranscript): CaptionSegment[] {+function originalWordStream(transcript: AxcutTranscript): StreamWord[] {const words = toCaptionSegments(transcript);if (words.length > 0) return words;// A transcript with segments but no words (hand-authored / imported) still@@ -174,7 +214,14 @@ export function sourceSpanToTimelineSpans(const clipSourceEnd = clip.sourceEndSec ?? Number.POSITIVE_INFINITY;const s = Math.max(startSec, clip.sourceStartSec);const e = Math.min(endSec, clipSourceEnd);- if (e <= s) continue;+ if (e <= s) {+ // An added word occupies no source time at all — its line is a POINT here. Its+ // moment is the extension inserted there, which is the one thing that knows how+ // long it lasts.+ const span = clip.parts ? extensionSpanAtSource(clip.parts, s) : null;+ if (span) out.push(span);+ continue;+ }// Through `placementRawSec`, never the subtraction it used to write here: a clip// carrying an added word plays its media in pieces, and the seconds after the// insertion sit further along the ruler than their distance from the clip's start.diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.tsindex 9abbbb2c8..06f83943d 100644--- a/src/lib/ai-edition/document/timeline.test.ts+++ b/src/lib/ai-edition/document/timeline.test.ts@@ -1736,84 +1736,3 @@ describe("projectRawTimelineSecToPlayback with speed regions", () => {expect(projectRawTimelineSecToPlayback([clip], [], 4, speed)).toBeCloseTo(4, 6);});});--// ─── The pause an added word bought ──────────────────────────────-// Created time only exists once playback honours it. These pin the one thing the record-// is for: the stream really does stay on the held frame, and the film really is longer.--// ─── Segments across an extension ───────────────────────────────────────────-// The whole point of the layer, seen from the one funnel every consumer goes through: an-// added word becomes a SEGMENT of its own, naming media rather than a behaviour, and the-// recording on either side keeps the source window it always had.--describe("resolvePlaybackSegments across an added word", () => {- const clip = makeClip({- id: "c1",- assetId: "a1",- sourceStartSec: 0,- sourceEndSec: 10,- timelineStartSec: 0,- timelineEndSec: 10,- });- const transcripts = [- {- assetId: "a1",- language: "en",- segments: [],- words: [- { id: "w1", segmentId: "s", startSec: 1, endSec: 2, text: "said" },- {- id: "synth_1",- segmentId: "s",- startSec: 4,- endSec: 4,- text: "really",- source: "synth" as const,- },- ],- },- ];-- it("puts the extension between the halves, as its own segment", () => {- const segs = resolvePlaybackSegments([clip], [], transcripts);- expect(segs.map((s) => s.extensionWordId ?? null)).toEqual([null, "synth_1", null]);- // The recording resumes at the source second it stopped on — nothing moved.- expect(segs[0]).toMatchObject({ sourceStartSec: 0, sourceEndSec: 4 });- expect(segs[2]).toMatchObject({ sourceStartSec: 4, sourceEndSec: 10 });- });-- it("gives the extension its own media window, starting at zero", () => {- const [, ext] = resolvePlaybackSegments([clip], [], transcripts);- expect(ext.sourceStartSec).toBe(0);- expect(ext.sourceEndSec).toBeCloseTo(6 / 15, 6);- expect(ext.timelineEndSec - ext.timelineStartSec).toBeCloseTo(6 / 15, 6);- });-- it("lays the programme out end to end, with no gap and no overlap", () => {- const segs = resolvePlaybackSegments([clip], [], transcripts);- expect(segs[0].timelineStartSec).toBe(0);- for (const [i, seg] of segs.slice(0, -1).entries()) {- expect(seg.timelineEndSec).toBeCloseTo(segs[i + 1].timelineStartSec, 9);- }- });-- it("still cuts the recording, and never the extension", () => {- // A trim is anchored in the RECORDING's seconds; an extension has none, so no trim- // can name it. Cutting source 5..6 shortens the half after the added word only.- const trims = [makeTrim({ id: "t1", clipId: "c1", startSec: 5, endSec: 6 })];- const segs = resolvePlaybackSegments([clip], trims, transcripts);- expect(segs.filter((s) => s.extensionWordId).length).toBe(1);- const recorded = segs.filter((s) => !s.extensionWordId);- expect(recorded.map((s) => [s.sourceStartSec, s.sourceEndSec])).toEqual([- [0, 4],- [4, 5],- [6, 10],- ]);- });-- it("behaves exactly as before when no word was added", () => {- const plain = resolvePlaybackSegments([clip], []);- expect(plain).toHaveLength(1);- expect(plain[0]).toMatchObject({ id: "c1", sourceStartSec: 0, sourceEndSec: 10 });- });-});diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.tsindex 3d724c425..9fa9330f4 100644--- a/src/lib/ai-edition/document/timeline.ts+++ b/src/lib/ai-edition/document/timeline.ts@@ -8,15 +8,11 @@ import type { AxcutClip, AxcutDocument, AxcutTranscript, AxcutTrimRange } from "/*** What `resolvePlaybackSegments` returns: a clip-shaped slice of playable film.*- * `extensionWordId` names the ONE case where the media is not the clip's own asset — the- * extension an added word is spoken over, whose file is derived from the word. It says which- * MEDIA to play, not what behaviour to perform, and that is the whole difference from the- * `heldSec` this replaces: a reader resolves it to a file like any other, rather than- * carrying a special case for a stretch with nothing to decode.- *- * Derived-only, never on `clipSchema`, so nothing can write one to disk.+ * A plain clip, deliberately. An extension is one too by the time it gets here — `withExtensions`+ * resolved it into a clip on its own asset upstream — so nothing below this line carries a+ * notion of inserted media, and the trim arithmetic is the same it was before insertions existed.*/-export type PlaybackSegment = AxcutClip & { extensionWordId?: string };+export type PlaybackSegment = AxcutClip;import { clipParts, partsLengthSec } from "../timeline/clip-parts";import { type Interval, subtractInterval } from "../timeline/intervals";@@ -193,12 +189,8 @@ export function resequenceClips(clips: AxcutClip[]): AxcutClip[] {export function resolvePlaybackSegments(clips: AxcutClip[],trimRanges: AxcutTrimRange[],- /** The transcripts, so a clip carrying added words splits into its parts. Omitted, a- * clip is one recording part and this behaves exactly as it did before extensions. */- transcripts: readonly AxcutTranscript[] = [],): PlaybackSegment[] {const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);- const wordsByAsset = new Map(transcripts.map((t) => [t.assetId, t.words]));const result: PlaybackSegment[] = [];let timelineCursor = 0;for (const clip of ordered) {@@ -214,54 +206,24 @@ export function resolvePlaybackSegments(timelineCursor += dur;continue;}- // The insertion layer, and the only place this function meets it. Below here a part- // is media with a source window, and the trim arithmetic is the same it always was.- const parts = clipParts(clip, wordsByAsset.get(clip.assetId) ?? []);- // Named once the clip's own pieces are known: a clip keeps its id only when it yields- // exactly ONE piece of recording and nothing else. Naming from the PART count instead- // missed the split a trim makes inside a single part.- const clipSegments: PlaybackSegment[] = [];- for (const part of parts) {- if (part.kind === "extension") {- // No trim can name it: a trim is anchored in the RECORDING's seconds, and an- // extension has none. Its own media starts at zero and runs its full length.- clipSegments.push({- ...clip,- id: `${clip.id}__ext_${part.wordId}`,- extensionWordId: part.wordId,- sourceStartSec: 0,- sourceEndSec: part.timelineEndSec - part.timelineStartSec,- timelineStartSec: timelineCursor,- timelineEndSec: timelineCursor + (part.timelineEndSec - part.timelineStartSec),- });- timelineCursor += part.timelineEndSec - part.timelineStartSec;- continue;- }- let kept: Interval[] = [{ startSec: part.sourceStartSec, endSec: part.sourceEndSec }];- for (const trim of trimRanges) {- if (!trimAppliesToClip(trim, clip)) continue;- kept = subtractInterval(kept, { startSec: trim.startSec, endSec: trim.endSec });- }- for (const piece of kept) {- const dur = piece.endSec - piece.startSec;- if (dur <= 0) continue;- clipSegments.push({- ...clip,- sourceStartSec: piece.startSec,- sourceEndSec: piece.endSec,- timelineStartSec: timelineCursor,- timelineEndSec: timelineCursor + dur,- });- timelineCursor += dur;- }- }- const recorded = clipSegments.filter((seg) => seg.extensionWordId === undefined);- let n = 0;- for (const seg of clipSegments) {- if (seg.extensionWordId !== undefined) continue;- seg.id = recorded.length === 1 ? clip.id : `${clip.id}_seg${++n}`;+ let kept: Interval[] = [{ startSec: clip.sourceStartSec, endSec: sourceEnd }];+ for (const trim of trimRanges) {+ if (!trimAppliesToClip(trim, clip)) continue;+ kept = subtractInterval(kept, { startSec: trim.startSec, endSec: trim.endSec });}- result.push(...clipSegments);+ const pieces = kept.filter((piece) => piece.endSec > piece.startSec);+ pieces.forEach((piece, i) => {+ const dur = piece.endSec - piece.startSec;+ result.push({+ ...clip,+ id: pieces.length === 1 ? clip.id : `${clip.id}_seg${i + 1}`,+ sourceStartSec: piece.startSec,+ sourceEndSec: piece.endSec,+ timelineStartSec: timelineCursor,+ timelineEndSec: timelineCursor + dur,+ });+ timelineCursor += dur;+ });}return result;}diff --git a/src/lib/ai-edition/timeline/clip-parts.test.ts b/src/lib/ai-edition/timeline/clip-parts.test.tsindex d26495167..3ac97d4ce 100644--- a/src/lib/ai-edition/timeline/clip-parts.test.ts+++ b/src/lib/ai-edition/timeline/clip-parts.test.ts@@ -2,16 +2,18 @@// start where the clip starts, and no stored source coordinate moved to achieve it.import { describe, expect, it } from "vitest";-import type { AxcutClip, AxcutWord } from "../schema";+import { resolvePlaybackSegments } from "../document/timeline";+import type { AxcutClip, AxcutDocument, AxcutWord } from "../schema";import {+ baseClipId,clipParts,- clipsWithExtensions,- extensionAssetId,extensionAt,+ extensionClipPath,extensionDurationSec,partsLengthSec,partsRawSec,partsSourceSec,+ withExtensions,} from "./clip-parts";const CLIP: AxcutClip = {@@ -115,34 +117,85 @@ describe("extensionDurationSec", () => {});});-// ─── What a player sees ─────────────────────────────────────────────────────-// The DOM preview already plays several clips over several files and swaps at the boundary.-// An extension is exactly that, so it is handed a clip rather than taught a new case.+// ─── What everything that RENDERS sees ──────────────────────────────────────+// Every mapping downstream — the ruler, the native decoder swap, the exporter, the DOM+// player — is built on "a clip is an uninterrupted shift from source to ruler". So the+// interruption is resolved into the shape they already handle, and below this line an+// extension is simply a clip that plays a generated file.-describe("clipsWithExtensions", () => {- const transcripts = [{ assetId: "a1", words: [added("synth_1", 4, "really")] }];+const DOC = (words: AxcutWord[], clips: AxcutClip[] = [CLIP]): AxcutDocument =>+ ({+ assets: [+ {+ id: "a1",+ kind: "video",+ label: "take",+ originalPath: "C:/rec/take.mp4",+ video: { width: 1920, height: 1080, fps: 30 },+ cameraTrack: null,+ },+ ],+ transcripts: [{ assetId: "a1", words }],+ timeline: { clips, trimRanges: [] },+ }) as unknown as AxcutDocument;++describe("withExtensions", () => {+ const doc = DOC([added("synth_1", 4, "really")]);++ it("makes the extension a clip on an asset of its own", () => {+ const out = withExtensions(doc);+ expect(out.timeline.clips.map((c) => c.assetId)).toEqual(["a1", "ext:synth_1", "a1"]);+ expect(out.timeline.clips[1]).toMatchObject({ sourceStartSec: 0 });+ expect(out.timeline.clips[1].sourceEndSec).toBeCloseTo(6 / 15, 6);+ });- it("splices the extension in as a clip of its own, on its own media", () => {- const out = clipsWithExtensions([CLIP], transcripts);- expect(out.map((c) => c.assetId)).toEqual(["a1", "ext:synth_1", "a1"]);- expect(out[1]).toMatchObject({ sourceStartSec: 0 });- expect(out[1].sourceEndSec).toBeCloseTo(6 / 15, 6);+ it("gives that asset the file the generator writes, so the decoder can open it", () => {+ const asset = withExtensions(doc).assets.find((a) => a.id === "ext:synth_1");+ expect(asset?.originalPath).toBe(+ extensionClipPath("C:/rec/take.mp4", "synth_1", extensionDurationSec("really")),+ );+ // The recording's geometry: the generated file was made to match it.+ expect(asset?.video).toMatchObject({ width: 1920, height: 1080 });});- it("lays them end to end, so the player's clock never sees a gap", () => {- const out = clipsWithExtensions([CLIP], transcripts);+ it("lays them end to end, so no mapping downstream sees a gap", () => {+ const out = withExtensions(doc).timeline.clips;expect(out[0].timelineStartSec).toBe(0);for (const [i, clip] of out.slice(0, -1).entries()) {expect(clip.timelineEndSec).toBeCloseTo(out[i + 1].timelineStartSec, 9);}});- it("returns the clips unchanged when no word was added", () => {- expect(clipsWithExtensions([CLIP], [{ assetId: "a1", words: [] }])).toEqual([CLIP]);+ it("is the same document when no word was added", () => {+ const plain = DOC([]);+ expect(withExtensions(plain)).toBe(plain);+ });++ it("is idempotent — deriving twice must not split the halves again", () => {+ const once = withExtensions(doc);+ expect(withExtensions(once)).toBe(once);});- it("gives the extension an id no real asset can collide with", () => {- expect(extensionAssetId("synth_1")).toBe("ext:synth_1");+ it("keeps every piece answering to the name a trim knows the clip by", () => {+ const ids = withExtensions(doc).timeline.clips.map((c) => baseClipId(c.id));+ expect(ids).toEqual(["c1", "c1", "c1"]);+ });++ it("still cuts the recording, and never the extension", () => {+ // A trim is anchored in the RECORDING's seconds; an extension has none. Cutting+ // source 5..6 shortens the half AFTER the added word and nothing else.+ const clips = withExtensions(doc).timeline.clips;+ const trims = [+ { id: "t1", clipId: "c1", assetId: "a1", startSec: 5, endSec: 6 },+ ] as unknown as Parameters<typeof resolvePlaybackSegments>[1];+ const segs = resolvePlaybackSegments(clips, trims);+ const recorded = segs.filter((s) => !s.assetId.startsWith("ext:"));+ expect(recorded.map((s) => [s.sourceStartSec, s.sourceEndSec])).toEqual([+ [0, 4],+ [4, 5],+ [6, 10],+ ]);+ expect(segs.filter((s) => s.assetId.startsWith("ext:"))).toHaveLength(1);});});diff --git a/src/lib/ai-edition/timeline/clip-parts.ts b/src/lib/ai-edition/timeline/clip-parts.tsindex b9aef8375..c7617dad3 100644--- a/src/lib/ai-edition/timeline/clip-parts.ts+++ b/src/lib/ai-edition/timeline/clip-parts.ts@@ -13,7 +13,7 @@// with a source window and a place on the timeline, and the plain arithmetic every reader// used before insertions works again.-import type { AxcutClip, AxcutWord } from "../schema";+import type { AxcutAsset, AxcutClip, AxcutDocument, AxcutWord } from "../schema";/** How fast a synthesized voice will be assumed to speak, in characters per second.*@@ -128,48 +128,111 @@ export function extensionClipPath(assetPath: string, wordId: string, durationSecreturn `${dir}${sep}${EXTENSIONS_DIR}${sep}${wordId}_${Math.round(durationSec * 1000)}.mp4`;}-/** The id an extension's media answers to, so a player that keys sources by asset finds it- * without knowing what an extension is. Prefixed rather than opaque: it can never collide- * with a real asset id, and it says what it is in a log line. */+/** Marks every id this module derives. Never produced by the writers, so `withExtensions`+ * can recognise a document it has already derived — and a log line says what it is. */+export const EXTENSION_ID_PREFIX = "ext:";++/** The id an extension's media answers to. */export function extensionAssetId(wordId: string): string {- return `ext:${wordId}`;+ return `${EXTENSION_ID_PREFIX}${wordId}`;+}++/** Separates a derived piece from the clip it was cut out of. Double, so it cannot collide+ * with the single underscores every generated clip id already carries. */+const PIECE = "__";++/** The stored clip a derived piece came from. A trim names a clip by id, and both halves of+ * a split clip are still that clip — so both must answer to its name. */+export function baseClipId(clipId: string): string {+ const at = clipId.indexOf(PIECE);+ return at < 0 ? clipId : clipId.slice(0, at);}/**- * The clips a PLAYER should see: each extension spliced in as a clip of its own.+ * The document as everything that RENDERS it should see it: an extension is a clip, on an+ * asset, with a file.+ *+ * This is the whole insertion layer, and it exists because of one property every mapping in+ * this codebase is built on — a clip is an UNINTERRUPTED shift between its source seconds+ * and the ruler. `timelineMap`, the native `setActiveClip`, the exporter and the DOM player+ * all assume it. A clip interrupted by generated media breaks that assumption in every one+ * of them at once, which is why teaching them each about extensions never converged: the+ * fix was eight special cases, and it was still one bug.+ *+ * So the interruption is resolved HERE, once, into the shape they already handle. Below this+ * line there are no extensions — only clips, some of which happen to play a generated file.*- * The DOM preview already knows how to play several clips over several files and swap at the- * boundary. An extension is exactly that — a different file, played for a stretch — so it is- * handed one rather than taught a new case. `resolvePlaybackSegments` does the same thing- * one layer down, with the trims applied; this is the untrimmed list the player's own clock- * maps against.+ * Derived, never stored: one direction, nothing to reconcile. The stored clip keeps its own+ * single identity and its own source window, and the words remain the only truth about what+ * was added.*/-export function clipsWithExtensions(- clips: readonly AxcutClip[],- transcripts: ReadonlyArray<{ assetId: string; words: readonly AxcutWord[] }>,-): AxcutClip[] {- const wordsByAsset = new Map(transcripts.map((t) => [t.assetId, t.words]));- return clips.flatMap((clip) =>- clipParts(clip, wordsByAsset.get(clip.assetId) ?? []).map((part) =>- part.kind === "extension"- ? {- ...clip,- id: `${clip.id}__ext_${part.wordId}`,- assetId: extensionAssetId(part.wordId),- sourceStartSec: 0,- sourceEndSec: part.timelineEndSec - part.timelineStartSec,- timelineStartSec: part.timelineStartSec,- timelineEndSec: part.timelineEndSec,- }- : {+export function withExtensions(document: AxcutDocument): AxcutDocument {+ // Already derived — deriving again would split the halves a second time, because the+ // added word sits exactly on the first half's end.+ if (document.assets.some((a) => a.id.startsWith(EXTENSION_ID_PREFIX))) return document;++ const wordsByAsset = new Map(document.transcripts.map((t) => [t.assetId, t.words]));+ const assetById = new Map(document.assets.map((a) => [a.id, a]));+ const assets = [...document.assets];++ const clips = document.timeline.clips.flatMap((clip): AxcutClip[] => {+ const parts = clipParts(clip, wordsByAsset.get(clip.assetId) ?? []);+ if (parts.length < 2) return [clip];+ const source = assetById.get(clip.assetId);+ let piece = 0;+ return parts.flatMap((part): AxcutClip[] => {+ if (part.kind === "recording") {+ piece += 1;+ return [+ {...clip,+ // The first piece keeps the clip's own name so anything holding it still+ // finds something; `baseClipId` is what makes the rest answer to it too.+ id: piece === 1 ? clip.id : `${clip.id}${PIECE}r${piece}`,sourceStartSec: part.sourceStartSec,sourceEndSec: part.sourceEndSec,timelineStartSec: part.timelineStartSec,timelineEndSec: part.timelineEndSec,},- ),- );+ ];+ }+ // Nothing to name the file after, so nothing to play: the clip simply stays short+ // of what the word asked for, rather than pointing at a path that cannot exist.+ if (!source?.originalPath) return [];+ const durationSec = part.timelineEndSec - part.timelineStartSec;+ const id = extensionAssetId(part.wordId);+ if (!assetById.has(id)) {+ const asset: AxcutAsset = {+ id,+ kind: "video",+ label: part.text.trim().slice(0, 40) || part.wordId,+ originalPath: extensionClipPath(source.originalPath, part.wordId, durationSec),+ durationSec,+ // The recording's geometry, because the generated file was made to match it.+ video: source.video,+ cameraTrack: null,+ };+ assetById.set(id, asset);+ assets.push(asset);+ }+ return [+ {+ ...clip,+ id: `${clip.id}${PIECE}ext_${part.wordId}`,+ assetId: id,+ // Authored against the recording's framing, which this is not.+ cropRegion: undefined,+ sourceStartSec: 0,+ sourceEndSec: durationSec,+ timelineStartSec: part.timelineStartSec,+ timelineEndSec: part.timelineEndSec,+ },+ ];+ });+ });++ if (assets.length === document.assets.length) return document;+ return { ...document, assets, timeline: { ...document.timeline, clips } };}/** Hidden, because it is derived: deleting it costs nothing but a regeneration. */@@ -240,3 +303,31 @@ export function extensionAt(parts: readonly ClipPart[], rawSec: number): string}return null;}++/**+ * The ruler span of the extension inserted at this source second, if there is one.+ *+ * The answer to a question source time cannot express: an added word occupies no source+ * seconds, so anything measuring it there measures zero. Its span lives on its part.+ */+export function extensionSpanAtSource(+ parts: readonly ClipPart[],+ sourceSec: number,+): { startSec: number; endSec: number } | null {+ const played = recordings(parts);+ for (const [i, part] of parts.entries()) {+ if (part.kind !== "extension") continue;+ // The recording part that ENDS where this extension begins is the one whose last+ // source second the word was typed after.+ const before =+ parts+ .slice(0, i)+ .filter((p) => p.kind === "recording")+ .at(-1) ?? played[0];+ const at = before ? before.sourceEndSec : sourceSec;+ if (Math.abs(at - sourceSec) < 1e-6) {+ return { startSec: part.timelineStartSec, endSec: part.timelineEndSec };+ }+ }+ return null;+}diff --git a/src/lib/ai-edition/timeline/trim-mapping.ts b/src/lib/ai-edition/timeline/trim-mapping.tsindex 0dee56d7d..62a79b4ce 100644--- a/src/lib/ai-edition/timeline/trim-mapping.ts+++ b/src/lib/ai-edition/timeline/trim-mapping.ts@@ -15,6 +15,7 @@// had no answer and each caller invented its own. See `trimAppliesToClip`.import type { AxcutClip, AxcutTrimRange } from "../schema";+import { baseClipId } from "./clip-parts";import { type CoalescedSpan, ventilateSpanAcrossClips } from "./region-ventilation";import { coalesceByIdentity, regionIdentityKey } from "./timelineMap";@@ -46,7 +47,10 @@ export function trimAppliesToClip(trim: TrimAnchor,clip: Pick<AxcutClip, "id" | "assetId">,): boolean {- if (trim.clipId !== undefined) return trim.clipId === clip.id;+ // `baseClipId`, not the id itself: an insertion splits a clip into pieces that are all+ // still the clip the trim was authored on, and matching the piece would have left the+ // cut applied to the first half only.+ if (trim.clipId !== undefined) return trim.clipId === baseClipId(clip.id);return trim.assetId === clip.assetId;}diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.tsindex 1832851be..ef6743476 100644--- a/src/native/sceneDescription.ts+++ b/src/native/sceneDescription.ts@@ -40,7 +40,7 @@ import {import type { AxcutClip, AxcutDocument } from "@/lib/ai-edition/schema";import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";import { assetCameraSource } from "@/lib/ai-edition/timeline/camera";-import { extensionClipPath } from "@/lib/ai-edition/timeline/clip-parts";+import { withExtensions } from "@/lib/ai-edition/timeline/clip-parts";import { resolveClipSourceEndSec } from "@/lib/ai-edition/timeline/clipDuration";import { removedRawSpans } from "@/lib/ai-edition/timeline/programme-time";import { takeProgramme } from "@/lib/ai-edition/timeline/take-programme";@@ -521,22 +521,24 @@ function clipAssetIsResolvable(* Returns `PlaybackSegment[]`, not `AxcutClip[]`: a held segment carries `heldSec`, and* widening it away here is what kept the pause from ever reaching the compositor. Every*/-export function resolveVisibleClips(document: AxcutDocument): PlaybackSegment[] {+export function resolveVisibleClips(rawDocument: AxcutDocument): PlaybackSegment[] {+ // An extension is a clip on its own asset from here down. Idempotent, so a caller that+ // already derived the document pays nothing.+ const document = withExtensions(rawDocument);const assetById = new Map(document.assets.map((a) => [a.id, a]));- return resolvePlaybackSegments(- document.timeline.clips,- document.timeline.trimRanges,- document.transcripts,- )+ return resolvePlaybackSegments(document.timeline.clips, document.timeline.trimRanges).sort((a, b) => a.timelineStartSec - b.timelineStartSec).filter((clip) => clipAssetIsResolvable(clip, assetById));}/** Serialize a document into a {@link SceneDescription}. Pure — no per-frame math. */export function buildSceneDescription(- document: AxcutDocument,+ rawDocument: AxcutDocument,webcamSourceSize: { width: number; height: number } | null = null,): SceneDescription {+ // Once, at the top: every list below — the assets, the clips, the raw layout the regions+ // are projected through — has to agree about what the film contains.+ const document = withExtensions(rawDocument);const settings = getEditorSettings(document);const assetById = new Map(document.assets.map((a) => [a.id, a]));@@ -703,25 +705,6 @@ export function buildSceneDescription(const clips: CompositorClipInput[] = visibleClips.flatMap((clip) => {const asset = assetById.get(clip.assetId);if (!asset?.originalPath) return [];- // An extension plays GENERATED media, not the recording's. Everything else about the- // entry is the clip's — same webcam pairing, same audio expectation — because that is- // the point of making it a file rather than a behaviour.- if (clip.extensionWordId) {- return [- {- screenPath: extensionClipPath(- asset.originalPath,- clip.extensionWordId,- clip.sourceEndSec ?? 0,- ),- webcamPath: "",- sourceStartSec: 0,- sourceEndSec: clip.sourceEndSec ?? 0,- webcamOffsetSec: 0,- hasAudio: true,- },- ];- }const camera = assetCameraSource(asset);// ponytail: `asset.audio` exists in the schema but the probe pipeline never// populates it, so there is no per-asset "is there a track?" signal to read@@ -809,7 +792,9 @@ export function buildSceneDescription(const captionAspect = outputDims.height > 0 ? outputDims.width / outputDims.height : 16 / 9;const captionSettings = getCaptionSettings(document, captionAspect);const captionRegions = captionCuesToTextRegions(- deriveCaptionCues(document, captionSettings, getCaptionTranslations(document)),+ // `rawDocument`: the caption path resolves the insertion itself, through the clip's+ // parts, and handing it the derived clips would ask the same question twice.+ deriveCaptionCues(rawDocument, captionSettings, getCaptionTranslations(document)),captionSettings,captionAspect,);