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(insertions): an insertion is a clip, stored as one

EtienneLescote2c1147e9b19
diff --git a/electron/media/extensionClip.ts b/electron/media/extensionClip.ts
index 5022fc5b7..d7641c25f 100644
--- a/electron/media/extensionClip.ts
+++ b/electron/media/extensionClip.ts
@@ -19,12 +19,7 @@
import { spawn } from "node:child_process";
import { access, mkdir } from "node:fs/promises";
import path from "node:path";
-import type { AxcutWord } from "../../src/lib/ai-edition/schema";
-import {
- extensionClipPath,
- extensionDurationSec,
- isAddedWord,
-} from "../../src/lib/ai-edition/timeline/clip-parts";
+import { isGeneratedAssetId } from "../../src/lib/ai-edition/document/insertion";
import { resolveFfmpeg } from "./audioPeaks";
export interface ExtensionClipSpec {
@@ -94,42 +89,39 @@ export function extensionClipArgs(spec: ExtensionClipSpec, outPath: string): str
}
/**
- * Every extension the document's words call for, generated if it is not already there.
+ * Every insertion's media, generated if it is not already there.
*
- * Called on SAVE, which is the only moment the main process — the one that can spawn ffmpeg
- * — sees the document. Idempotent by name, so a save that adds nothing costs one `stat` per
- * added word. A failure is logged and swallowed: the edit is not lost because a derived file
- * could not be written, and the segment renders black until the next save regenerates it.
+ * Read off the ASSETS, not the words: an insertion is a clip on an asset that already knows
+ * its own path, its own length and its own geometry. There is nothing to derive here and
+ * nothing to agree with the renderer about beyond the path it stored.
+ *
+ * Called on SAVE, the only moment the main process — the one that can spawn ffmpeg — sees
+ * the document. Idempotent by name, so a save that adds nothing costs one `stat` per
+ * insertion. A failure is logged and swallowed: an edit is not lost because a derived file
+ * could not be written, and the clip renders black until the next save regenerates it.
*/
export async function ensureDocumentExtensions(document: {
assets: ReadonlyArray<{
id: string;
originalPath?: string;
+ durationSec?: number;
video?: { width: number; height: number; fps: number };
}>;
- transcripts: ReadonlyArray<{ assetId: string; words: ReadonlyArray<AxcutWord> }>;
}): Promise<void> {
- for (const transcript of document.transcripts) {
- const asset = document.assets.find((a) => a.id === transcript.assetId);
- if (!asset?.originalPath) continue;
- for (const word of transcript.words) {
- if (!isAddedWord(word)) continue;
- const durationSec = extensionDurationSec(word.text);
- if (durationSec <= 0) continue;
- const outPath = extensionClipPath(asset.originalPath, word.id, durationSec);
- try {
- await ensureExtensionClip(
- {
- durationSec,
- fps: asset.video?.fps ?? 0,
- width: asset.video?.width ?? 0,
- height: asset.video?.height ?? 0,
- },
- outPath,
- );
- } catch (error) {
- console.error(`[extension] ${word.id}: ${(error as Error).message}`);
- }
+ for (const asset of document.assets) {
+ if (!isGeneratedAssetId(asset.id) || !asset.originalPath || !asset.durationSec) continue;
+ try {
+ await ensureExtensionClip(
+ {
+ durationSec: asset.durationSec,
+ fps: asset.video?.fps ?? 0,
+ width: asset.video?.width ?? 0,
+ height: asset.video?.height ?? 0,
+ },
+ asset.originalPath,
+ );
+ } catch (error) {
+ console.error(`[insertion] ${asset.id}: ${(error as Error).message}`);
}
}
}
diff --git a/src/cli/CliExportRunner.tsx b/src/cli/CliExportRunner.tsx
index 6c29b9975..9a7f1b590 100644
--- a/src/cli/CliExportRunner.tsx
+++ b/src/cli/CliExportRunner.tsx
@@ -24,7 +24,6 @@ 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";
@@ -79,8 +78,7 @@ 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(rawDocument: AxcutDocument): CompositorClipInput[] {
- const axcutDocument = withExtensions(rawDocument);
+function buildNativeClipList(axcutDocument: AxcutDocument): CompositorClipInput[] {
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.tsx
index 97da5286a..5dff50acf 100644
--- a/src/components/ai-edition/ExportDialog.tsx
+++ b/src/components/ai-edition/ExportDialog.tsx
@@ -21,7 +21,6 @@ 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,
@@ -81,8 +80,7 @@ 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(rawDocument: AxcutDocument): CompositorClipInput[] {
- const document = withExtensions(rawDocument);
+function buildNativeClipList(document: AxcutDocument): CompositorClipInput[] {
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.tsx
index 5bfa32c50..e4af64102 100644
--- a/src/components/ai-edition/NativeCompositorOverlay.tsx
+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx
@@ -4,7 +4,6 @@ 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,
@@ -70,18 +69,13 @@ 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 (!playedDocument) return [];
- return resolveVisibleClips(playedDocument);
- }, [playedDocument]);
+ if (!document) return [];
+ return resolveVisibleClips(document);
+ }, [document]);
const activePosition = useMemo(
- () => resolveNativePosition(currentTimeSec, nativeClips, playedDocument?.timeline.clips ?? []),
- [nativeClips, currentTimeSec, playedDocument],
+ () => resolveNativePosition(currentTimeSec, nativeClips, document?.timeline.clips ?? []),
+ [nativeClips, currentTimeSec, document],
);
const activeClip = activePosition?.clip ?? null;
@@ -197,7 +191,7 @@ export function NativeCompositorOverlay() {
useEffect(() => {
if (
viewId === null ||
- !playedDocument ||
+ !document ||
!activeClipId ||
!activeClip ||
activeClipIndex === null ||
@@ -208,7 +202,7 @@ export function NativeCompositorOverlay() {
if (previousActiveClipIdRef.current === activeClipId) {
return;
}
- const asset = playedDocument?.assets.find((candidate) => candidate.id === activeClip.assetId);
+ const asset = document.assets.find((candidate) => candidate.id === activeClip.assetId);
if (!asset?.originalPath) {
return;
}
@@ -254,15 +248,7 @@ export function NativeCompositorOverlay() {
previousActiveClipIdRef.current = null;
}
});
- }, [
- viewId,
- playedDocument,
- activeClipId,
- activeClip,
- activeClipIndex,
- activeSourceTimeSec,
- playing,
- ]);
+ }, [viewId, document, activeClipId, activeClip, activeClipIndex, activeSourceTimeSec, playing]);
if (!ready) {
return null;
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 5622e9990..416ea8022 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -32,7 +32,6 @@ 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 { 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 {
@@ -231,10 +230,6 @@ 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;
@@ -359,12 +354,12 @@ export function NewEditorShell() {
}, [promptUnsaved, saveDocument]);
const videoSources = useMemo(() => {
- 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) => ({
+ if (!document) return [];
+ // Every asset, insertions included — an insertion is a clip on an asset 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 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.
@@ -376,7 +371,7 @@ export function NewEditorShell() {
: toFileUrl(asset.originalPath),
label: asset.label,
}));
- }, [playedDocument]);
+ }, [document]);
const handleLoadedMetadata = useCallback(
(durationSec: number, assetId: string) => {
@@ -1517,7 +1512,7 @@ export function NewEditorShell() {
// itself keeps playing — that is what the user is narrating to.
audioTracks={voiceoverRecording ? NO_AUDIO_TRACKS : tl.audioTracks}
audioSources={videoSources}
- clips={playedDocument?.timeline.clips ?? clips}
+ clips={clips}
zoomRegions={tl.zoomRegions}
speedRegions={tl.speedRegions}
cameraFullscreenRegions={tl.cameraFullscreenRegions}
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 7bbbac76a..79f9f2e00 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -72,7 +72,6 @@ import {
isSilenceWord,
placementRawExtent,
placementRawSec,
- recordingPlacements,
type TranscriptLane,
type TrimRun,
voiceoverPlacements,
@@ -897,10 +896,7 @@ export function TranscriptPane({
},
[setCaptionSettings],
);
- // The clips WITH their parts, so a word after an insertion resolves to the moment it is
- // actually spoken rather than to its distance from the clip's start.
- const recording = useMemo(() => recordingPlacements(clips, transcripts), [clips, transcripts]);
- const placements = activeLane === "voiceover" ? voiceover : recording;
+ const placements = activeLane === "voiceover" ? voiceover : clips;
const sections = useMemo(
() => buildAggregatedSections(placements, transcripts, assets, removed),
diff --git a/src/components/ai-edition/v4/EditorShellV4.module.css b/src/components/ai-edition/v4/EditorShellV4.module.css
index 15af76b3e..422ff0b54 100644
--- a/src/components/ai-edition/v4/EditorShellV4.module.css
+++ b/src/components/ai-edition/v4/EditorShellV4.module.css
@@ -1680,6 +1680,13 @@
.tlClipSel {
border-color: var(--accent);
}
+/* A generated clip: the media behind an inserted word, which nobody shot. Amber on the box
+ itself rather than a badge inside it, so it stays legible at the zoom levels where a clip
+ is a few pixels wide and there is no room to draw anything in it. */
+.tlClipGenerated {
+ border-color: var(--warn);
+ background: color-mix(in srgb, var(--warn) 18%, var(--surface-1));
+}
/* The clip being carried during a reorder drag — follows the pointer 1:1
(no transition lag) while its siblings slide out of the way with the
base .tlClip transform transition above. */
@@ -1775,44 +1782,6 @@
over the waveform, at the moment the word sits on, wide enough to hit and no wider
— the clip underneath still has to be draggable everywhere else. Amber is the
colour the transcript pane gives the same word, so the two read as one thing. */
-.tlClipInsert {
- position: absolute;
- top: 0;
- bottom: 0;
- z-index: 2;
- /* A pause of zero still needs somewhere to be clicked; a real one is sized inline. */
- min-width: 9px;
- margin-left: -4px;
- padding: 0;
- border: 0;
- background: transparent;
- cursor: pointer;
-}
-/* The mark fills its button rather than sitting at a fixed 3px inside it. The button has
- carried the pause's real width in its inline style for a while; `width: 3px` here meant a
- word that bought two seconds and one that bought nothing drew the same tick, and the wide
- case was a multi-second invisible column that swallowed clip drags (issue #560).
- `min-width` is the floor that keeps a word which borrowed existing silence — a pause of
- zero, so a zero-width button — visible and clickable. */
-.tlClipInsert::before {
- content: "";
- position: absolute;
- left: 0;
- right: 0;
- top: 4px;
- bottom: 4px;
- min-width: 3px;
- border-radius: 2px;
- background: var(--warn);
- box-shadow: 0 0 0 1px color-mix(in srgb, #080a0d 45%, transparent);
- transition: box-shadow var(--motion-fast) var(--ease);
-}
-.tlClipInsert:hover::before,
-.tlClipInsert:focus-visible::before {
- box-shadow:
- 0 0 0 1px color-mix(in srgb, #080a0d 45%, transparent),
- 0 0 0 4px var(--warn-soft);
-}
.tlDropHint {
position: absolute;
inset: 0;
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index 8d87a48b3..ba08eb74f 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -40,8 +40,9 @@ import {
slipAudioOffsetMs,
} from "@/lib/ai-edition/document/audioTracks";
import { createId } from "@/lib/ai-edition/document/ids";
+import { isGeneratedAssetId } from "@/lib/ai-edition/document/insertion";
import { setUiProbeScrubbing } from "@/lib/ai-edition/perf/uiFrameProbe";
-import type { AxcutAudioTrack, AxcutClip, AxcutWord } from "@/lib/ai-edition/schema";
+import type { AxcutAudioTrack, AxcutClip } from "@/lib/ai-edition/schema";
import { audioGainScalar } from "@/lib/ai-edition/store/editorSettings";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useTimelineTranscriptGate } from "@/lib/ai-edition/store/transcriptionStore";
@@ -49,7 +50,6 @@ 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,
@@ -707,39 +707,6 @@ export function V4Timeline({
label: `${(p.member.customScale ?? ZOOM_DEPTH_SCALES[p.member.depth]).toFixed(2)}×`,
sourceIds: p.ids,
}));
- // Where the user has ADDED words. Derived from the transcript on every render and
- // stored nowhere: the word carries `source: "synth"` and its own source time, so a mark
- // built from it cannot drift from the amber word the transcript pane shows. Grouped by
- // 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(() => {
- 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);
- // 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 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;
- }, [tl.transcripts, clips]);
// trims: content-free (no per-instance text/settings), so touching rows —
// inevitable once a trim is ventilated across a clip boundary — are
@@ -2216,7 +2183,11 @@ export function V4Timeline({
<div
key={c.id}
data-clip-id={c.id}
- className={`${styles.tlClip}${selected ? ` ${styles.tlClipSel}` : ""}${
+ className={`${styles.tlClip}${
+ // Amber, because nobody shot it. Same token the mark it replaces
+ // used, so an insertion still reads as one at a glance.
+ isGeneratedAssetId(c.assetId) ? ` ${styles.tlClipGenerated}` : ""
+ }${selected ? ` ${styles.tlClipSel}` : ""}${
dragging ? ` ${styles.tlClipDragging}` : ""
}`}
style={{
@@ -2268,35 +2239,6 @@ export function V4Timeline({
{tl.assets.find((a) => a.id === c.assetId)?.label ?? c.assetId}
</span>
</div>
- {(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 ? (
<button
type="button"
diff --git a/src/lib/ai-edition/captions/captions.test.ts b/src/lib/ai-edition/captions/captions.test.ts
index 58a7de304..a1321e491 100644
--- a/src/lib/ai-edition/captions/captions.test.ts
+++ b/src/lib/ai-edition/captions/captions.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
+import { insertGeneratedClip } from "../document/insertion";
import type { AxcutDocument, AxcutTranscript } from "../schema";
import { captionCuesToTextRegions, deriveCaptionCues } from "./cues";
import type { CaptionSettings } from "./settings";
@@ -63,7 +64,16 @@ function doc(overrides: Partial<AxcutDocument> = {}): AxcutDocument {
updatedAt: "2026-01-01T00:00:00.000Z",
primaryAssetId: "asset-1",
},
- assets: [],
+ assets: [
+ {
+ id: "asset-1",
+ kind: "video",
+ label: "take",
+ originalPath: "C:/rec/take.mp4",
+ video: { width: 1920, height: 1080, fps: 30 },
+ cameraTrack: null,
+ },
+ ],
transcript: null,
transcripts: [transcript()],
timeline: {
@@ -651,51 +661,28 @@ describe("translated caption layout", () => {
});
});
-// The whole point of the insertion layer, seen from the far end: a word typed into the
-// middle of a take lengthens the film, and every caption after it has to move with the
-// audio it belongs to. This is the check that failed on screen before it failed here.
+// An insertion is a clip on its own media, so the cues it produces come out of the ordinary
+// per-asset path: the recording's own lines shift along the ruler, and the inserted text
+// gets a line of its own over the clip that plays it. Both used to be wrong at once.
describe("captions over an inserted word", () => {
- const withInsertion = () => {
- const t = transcript();
- return doc({
- transcripts: [
- {
- ...t,
- words: [
- ...t.words.slice(0, 3),
- {
- id: "synth_1",
- segmentId: "seg_1",
- startSec: 2,
- endSec: 2,
- text: "wait",
- source: "synth",
- },
- ...t.words.slice(3),
- ],
- },
- ],
- });
- };
+ const inserted = () => insertGeneratedClip(doc(), "asset-1", "w3", "after", "wait");
+ // "wait" is 4 chars at 15/s.
+ const GEN_MS = (4 / 15) * 1000;
- it("moves every cue after the insertion by exactly the extension's length", () => {
- const cues = deriveCaptionCues(withInsertion(), ON, {});
- // "wait" is 4 chars at 15/s.
- expect(cues[cues.length - 1].endMs).toBeCloseTo(6000 + (4 / 15) * 1000, 0);
+ it("moves every cue after the insertion by exactly the clip's length", () => {
+ const cues = deriveCaptionCues(inserted(), ON, {});
+ expect(cues[cues.length - 1].endMs).toBeCloseTo(6000 + GEN_MS, 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();
+ it("gives the inserted word a line of its own, over the clip that plays it", () => {
+ const wait = deriveCaptionCues(inserted(), ON, {}).find((c) => c.text === "wait");
expect(wait?.startMs).toBe(2000);
- expect(wait?.endMs).toBeCloseTo(2000 + (4 / 15) * 1000, 0);
+ expect(wait?.endMs).toBeCloseTo(2000 + GEN_MS, 0);
});
it("leaves the cues before it exactly where they were", () => {
- const before = deriveCaptionCues(doc(), ON, {});
- const after = deriveCaptionCues(withInsertion(), ON, {});
- expect(after[0].startMs).toBe(before[0].startMs);
+ expect(deriveCaptionCues(inserted(), ON, {})[0].startMs).toBe(
+ deriveCaptionCues(doc(), ON, {})[0].startMs,
+ );
});
});
diff --git a/src/lib/ai-edition/captions/cues.ts b/src/lib/ai-edition/captions/cues.ts
index a8ac19be4..ed881ab72 100644
--- a/src/lib/ai-edition/captions/cues.ts
+++ b/src/lib/ai-edition/captions/cues.ts
@@ -28,7 +28,6 @@ import {
placementRawSec,
type TranscriptPlacement,
} from "../timeline/aggregated-transcript";
-import { extensionSpanAtSource, isAddedWord } from "../timeline/clip-parts";
import { removedRawSpans } from "../timeline/programme-time";
import {
type CaptionAnchorV,
@@ -51,42 +50,10 @@ 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;
-/** 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[] {
+function toCaptionSegments(transcript: AxcutTranscript): CaptionSegment[] {
return transcript.words
.filter((word) => word.text.trim().length > 0)
- .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;
+ .map((word) => ({ startSec: word.startSec, endSec: word.endSec, text: word.text }));
}
function segmentWordsAsCaptionSegments(
@@ -152,17 +119,10 @@ export function captionLinesForAsset(
: translatedWordStream(transcript, translations, settings.language);
if (stream.length === 0) return [];
- 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)),
- );
+ return polish(groupTimedCaptionWordsIntoLines(stream, minWords, maxWords));
}
-function originalWordStream(transcript: AxcutTranscript): StreamWord[] {
+function originalWordStream(transcript: AxcutTranscript): CaptionSegment[] {
const words = toCaptionSegments(transcript);
if (words.length > 0) return words;
// A transcript with segments but no words (hand-authored / imported) still
@@ -214,14 +174,7 @@ 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) {
- // 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;
- }
+ if (e <= s) 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.
@@ -253,7 +206,6 @@ export function deriveCaptionCues(
// document written before it — or hand-built, never through the schema — has none.
document.audioTracks ?? [],
removedRawSpans(document.timeline.clips, document.timeline.trimRanges),
- document.transcripts,
);
if (placements.length === 0) return [];
diff --git a/src/lib/ai-edition/document/insertion.test.ts b/src/lib/ai-edition/document/insertion.test.ts
new file mode 100644
index 000000000..8a0aae028
--- /dev/null
+++ b/src/lib/ai-edition/document/insertion.test.ts
@@ -0,0 +1,183 @@
+// An insertion is a clip. These pin what that buys and what it costs.
+//
+// The one genuinely delicate part is the inverse: taking the generated clip away has to put
+// the halves back together, and must NOT do it when the user has since made them two clips
+// he means to keep.
+
+import { describe, expect, it } from "vitest";
+import type { AxcutDocument } from "../schema";
+import { insertGeneratedClip, removeGeneratedClips, retextGeneratedClip } from "./insertion";
+import { resolvePlaybackSegments } from "./timeline";
+
+const doc = (over: Partial<AxcutDocument> = {}): AxcutDocument =>
+ ({
+ schemaVersion: 5,
+ project: { id: "p1", title: "t", createdAt: "", updatedAt: "", primaryAssetId: "a1" },
+ assets: [
+ {
+ id: "a1",
+ kind: "video",
+ label: "take",
+ originalPath: "C:/rec/take.mp4",
+ video: { width: 1920, height: 1080, fps: 30 },
+ cameraTrack: null,
+ },
+ ],
+ transcript: null,
+ transcripts: [
+ {
+ assetId: "a1",
+ language: "en",
+ segments: [
+ { id: "s1", kind: "speech", startSec: 0, endSec: 6, text: "a b", wordIds: ["w1", "w2"] },
+ ],
+ words: [
+ { id: "w1", segmentId: "s1", startSec: 1, endSec: 4, text: "hello" },
+ { id: "w2", segmentId: "s1", startSec: 5, endSec: 6, text: "world" },
+ ],
+ },
+ ],
+ timeline: {
+ clips: [
+ {
+ id: "c1",
+ assetId: "a1",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ],
+ gaps: [],
+ trimRanges: [],
+ muteRanges: [],
+ speedRanges: [],
+ captionRanges: [],
+ },
+ annotations: [],
+ zoomRanges: [],
+ audioTracks: [],
+ legacyEditor: null,
+ ...over,
+ }) as unknown as AxcutDocument;
+
+/** Insert "hi" after `w1`, which ends at source second 4. */
+const withInsertion = (base = doc()) => insertGeneratedClip(base, "a1", "w1", "after", "hi");
+// "hi" is 2 chars at 15/s, under the floor.
+const GEN_SEC = 0.15;
+
+describe("insertGeneratedClip", () => {
+ it("cuts the clip in two and puts the generated clip between the halves", () => {
+ const clips = withInsertion().timeline.clips;
+ expect(clips.map((c) => c.assetId)).toEqual(["a1", "ext:synth_1", "a1"]);
+ expect(clips[1].timelineEndSec - clips[1].timelineStartSec).toBeCloseTo(GEN_SEC, 6);
+ });
+
+ it("leaves both halves on the source seconds they always had", () => {
+ const clips = withInsertion().timeline.clips;
+ expect([clips[0].sourceStartSec, clips[0].sourceEndSec]).toEqual([0, 4]);
+ expect([clips[2].sourceStartSec, clips[2].sourceEndSec]).toEqual([4, 10]);
+ });
+
+ it("lays them end to end, so the film grew by exactly the insertion", () => {
+ const clips = withInsertion().timeline.clips;
+ expect(clips[0].timelineStartSec).toBe(0);
+ for (const [i, clip] of clips.slice(0, -1).entries()) {
+ expect(clip.timelineEndSec).toBeCloseTo(clips[i + 1].timelineStartSec, 9);
+ }
+ expect(clips[2].timelineEndSec).toBeCloseTo(10 + GEN_SEC, 6);
+ });
+
+ it("gives the generated clip its own media, and its own transcript to be read from", () => {
+ const next = withInsertion();
+ const asset = next.assets.find((a) => a.id === "ext:synth_1");
+ expect(asset?.originalPath).toBe("C:/rec/.openscreen-extensions/synth_1_150.mp4");
+ const transcript = next.transcripts.find((t) => t.assetId === "ext:synth_1");
+ expect(transcript?.words).toEqual([
+ {
+ id: "synth_1",
+ segmentId: "seg_1",
+ startSec: 0,
+ endSec: GEN_SEC,
+ text: "hi",
+ source: "synth",
+ },
+ ]);
+ });
+
+ it("keeps a trim authored across the cut cutting on both sides of it", () => {
+ // Anchored to the clip that no longer exists as one. Copied onto both halves, each
+ // subtracting its own overlap — so the film loses the same 3..5 it did before.
+ const base = doc();
+ base.timeline.trimRanges = [
+ { id: "t1", clipId: "c1", assetId: "a1", startSec: 3, endSec: 5 },
+ ] as unknown as AxcutDocument["timeline"]["trimRanges"];
+ const next = withInsertion(base);
+ const kept = resolvePlaybackSegments(next.timeline.clips, next.timeline.trimRanges)
+ .filter((s) => s.assetId === "a1")
+ .map((s) => [s.sourceStartSec, s.sourceEndSec]);
+ expect(kept).toEqual([
+ [0, 3],
+ [5, 10],
+ ]);
+ });
+});
+
+describe("removeGeneratedClips", () => {
+ it("puts the clip back exactly as it was", () => {
+ const back = removeGeneratedClips(withInsertion(), ["synth_1"]);
+ expect(back.timeline.clips).toHaveLength(1);
+ expect(back.timeline.clips[0]).toMatchObject({
+ assetId: "a1",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ });
+ });
+
+ it("takes the media it was the only user of with it", () => {
+ const back = removeGeneratedClips(withInsertion(), ["synth_1"]);
+ expect(back.assets.map((a) => a.id)).toEqual(["a1"]);
+ expect(back.transcripts.map((t) => t.assetId)).toEqual(["a1"]);
+ });
+
+ it("does NOT rejoin halves the user has since made different clips", () => {
+ // A crop on one half is an edit the user made deliberately. Rejoining would throw it
+ // away to make the inverse look tidy, which is the one thing this must never do.
+ const next = withInsertion();
+ const cropped = {
+ ...next,
+ timeline: {
+ ...next.timeline,
+ clips: next.timeline.clips.map((c, i) =>
+ i === 2 ? { ...c, cropRegion: { x: 0.1, y: 0.1, width: 0.5, height: 0.5 } } : c,
+ ),
+ },
+ };
+ const back = removeGeneratedClips(cropped, ["synth_1"]);
+ expect(back.timeline.clips).toHaveLength(2);
+ expect(back.timeline.clips[1].timelineStartSec).toBeCloseTo(4, 6);
+ });
+
+ it("is a no-op for a word that has no clip", () => {
+ const base = doc();
+ expect(removeGeneratedClips(base, ["synth_9"])).toBe(base);
+ });
+});
+
+describe("retextGeneratedClip", () => {
+ it("resizes the clip to the new text and renames the file it plays", () => {
+ const next = retextGeneratedClip(withInsertion(), "synth_1", "a much longer sentence");
+ const seconds = "a much longer sentence".length / 15;
+ const clip = next.timeline.clips.find((c) => c.id === "ext:synth_1");
+ expect(clip?.sourceEndSec).toBeCloseTo(seconds, 6);
+ expect(clip?.timelineEndSec ?? 0 - (clip?.timelineStartSec ?? 0)).toBeGreaterThan(0);
+ expect(next.assets.find((a) => a.id === "ext:synth_1")?.originalPath).toBe(
+ `C:/rec/.openscreen-extensions/synth_1_${Math.round(seconds * 1000)}.mp4`,
+ );
+ });
+});
diff --git a/src/lib/ai-edition/document/insertion.ts b/src/lib/ai-edition/document/insertion.ts
new file mode 100644
index 000000000..8a25c2375
--- /dev/null
+++ b/src/lib/ai-edition/document/insertion.ts
@@ -0,0 +1,292 @@
+// An insertion IS a clip.
+//
+// A word typed into the transcript cuts its clip in two and puts a generated clip between
+// the halves:
+//
+// [ recording 0→5.3 ] [ generated 0→0.4 ] [ recording 5.3→20.9 ]
+//
+// Stored exactly as it reads. Nothing downstream carries a notion of an insertion: every
+// mapping in this codebase rests on "a clip is an uninterrupted shift between its source
+// seconds and the ruler", and three clips satisfy that where one interrupted clip satisfied
+// none of them. The generated clip is then a clip like any other — it can be moved, cropped,
+// edited and deleted from the timeline, with no code of its own for any of it.
+//
+// It owns its word: the asset is `ext:<wordId>`, the file is named by the pair, and the
+// transcript holds that one word at 0→duration. So the pane, the captions, the cue highlight
+// and the exporter all read it through the paths they already had.
+//
+// Deleting is the exact inverse, and it is not spelled out here: `removeClip` is the single
+// mutator for taking a clip away, and it rejoins contiguous survivors. Both delete paths —
+// the transcript pane and the timeline — therefore put the clip back together for free.
+
+import type { AxcutAsset, AxcutClip, AxcutDocument, AxcutTranscript } from "../schema";
+import {
+ EXTENSION_ID_PREFIX,
+ extensionAssetId,
+ extensionClipPath,
+ extensionDurationSec,
+} from "../timeline/clip-parts";
+import { createId } from "./ids";
+import { rederiveRegionMs, removeClip, resequenceClips } from "./timeline";
+
+/** Where a new word goes relative to the word the caret was resting on. */
+export type InsertSide = "before" | "after";
+
+/** True for the asset — and the clip, which shares its id — of a generated insertion. */
+export function isGeneratedAssetId(id: string): boolean {
+ return id.startsWith(EXTENSION_ID_PREFIX);
+}
+
+const EPS = 1e-6;
+
+/**
+ * The moment on the RULER the caret is asking for.
+ *
+ * Ruler seconds, not source seconds, so one path covers both anchors: a recorded word
+ * resolves through its clip's own shift, and a word already inserted resolves to the edge of
+ * the generated clip it lives on. Inserting beside an insertion then needs no case at all —
+ * nothing is cut and the new clip lands between two existing ones.
+ */
+function anchorRulerSec(
+ document: AxcutDocument,
+ assetId: string,
+ anchorWordId: string,
+ side: InsertSide,
+): number | null {
+ const word = document.transcripts
+ .find((t) => t.assetId === assetId)
+ ?.words.find((w) => w.id === anchorWordId);
+ if (!word) return null;
+ const at = side === "after" ? word.endSec : word.startSec;
+ const clip = [...document.timeline.clips]
+ .filter((c) => c.assetId === assetId)
+ .sort((a, b) => a.timelineStartSec - b.timelineStartSec)
+ .find((c) => at >= c.sourceStartSec - EPS && at <= (c.sourceEndSec ?? c.sourceStartSec) + EPS);
+ return clip ? clip.timelineStartSec + (at - clip.sourceStartSec) : null;
+}
+
+/** `synth_N`, numbered past every generated asset the document already carries. */
+function nextGeneratedWordId(document: AxcutDocument): string {
+ let highest = 0;
+ for (const asset of document.assets) {
+ const match = /^ext:synth_(\d+)$/.exec(asset.id);
+ if (match) highest = Math.max(highest, Number(match[1]));
+ }
+ return `synth_${highest + 1}`;
+}
+
+/** The recording the generated files are written beside. One rule, so the renderer and the
+ * main process arrive at the same folder without asking each other. */
+function hostAsset(document: AxcutDocument): AxcutAsset | null {
+ const primary = document.assets.find((a) => a.id === document.project.primaryAssetId);
+ if (primary?.originalPath && !isGeneratedAssetId(primary.id)) return primary;
+ return document.assets.find((a) => a.originalPath && !isGeneratedAssetId(a.id)) ?? null;
+}
+
+function generatedAsset(
+ host: AxcutAsset,
+ wordId: string,
+ durationSec: number,
+ text: string,
+): AxcutAsset {
+ return {
+ id: extensionAssetId(wordId),
+ kind: "video",
+ label: text.slice(0, 40),
+ originalPath: extensionClipPath(host.originalPath, wordId, durationSec),
+ durationSec,
+ // The recording's geometry: the generated file is made to match it.
+ video: host.video,
+ cameraTrack: null,
+ };
+}
+
+function generatedTranscript(
+ wordId: string,
+ durationSec: number,
+ text: string,
+ language: string,
+): AxcutTranscript {
+ return {
+ assetId: extensionAssetId(wordId),
+ language,
+ segments: [
+ { id: "seg_1", kind: "speech", startSec: 0, endSec: durationSec, text, wordIds: [wordId] },
+ ],
+ words: [
+ { id: wordId, segmentId: "seg_1", startSec: 0, endSec: durationSec, text, source: "synth" },
+ ],
+ };
+}
+
+/**
+ * Every row anchored to the clip that was just cut, copied onto BOTH halves.
+ *
+ * Not "decide which half each row belongs to" — that is interval arithmetic this file has no
+ * business owning. One copy per half, and `rederiveRegionMs` clamps each to its own clip's
+ * source window and drops what has nothing left. A row wholly on one side survives once; one
+ * straddling the cut survives on both, which is what a zoom drawn across the moment a word
+ * was typed into actually means.
+ */
+function fanOutAnchors(document: AxcutDocument, from: string, to: string): AxcutDocument {
+ // `?? []` for the reason every other collection walk here has one: these keys are
+ // additive, so a document written before one of them — or hand-built, never through the
+ // schema — simply has none, and the schema defaults it back to an empty array anyway.
+ const both = <T extends { id: string; clipId?: string }>(rows: readonly T[] | undefined): T[] =>
+ (rows ?? []).flatMap((row) =>
+ row.clipId === from ? [row, { ...row, id: createId("frag"), clipId: to }] : [row],
+ );
+ return {
+ ...document,
+ timeline: { ...document.timeline, trimRanges: both(document.timeline.trimRanges) },
+ zoomRanges: both(document.zoomRanges),
+ annotations: both(document.annotations),
+ audioTracks: both(document.audioTracks),
+ };
+}
+
+/**
+ * Insert a word nobody said, as a clip of its own.
+ *
+ * The clip under the caret is cut at that moment and the generated clip goes between the
+ * halves; everything after slides along by its length. Dropped on a clip's edge nothing is
+ * cut — the new clip simply takes its place in the order.
+ */
+export function insertGeneratedClip(
+ document: AxcutDocument,
+ assetId: string,
+ anchorWordId: string,
+ side: InsertSide,
+ text: string,
+): AxcutDocument {
+ const trimmed = text.trim();
+ if (trimmed.length === 0) return document;
+ const host = hostAsset(document);
+ if (!host) {
+ throw new Error("Cannot insert a word: the project has no recording to generate beside");
+ }
+ const atRuler = anchorRulerSec(document, assetId, anchorWordId, side);
+ if (atRuler === null) {
+ throw new Error(`Cannot insert beside word "${anchorWordId}": no clip plays that moment`);
+ }
+
+ const wordId = nextGeneratedWordId(document);
+ const durationSec = extensionDurationSec(trimmed);
+ const asset = generatedAsset(host, wordId, durationSec, trimmed);
+ const generated: AxcutClip = {
+ id: asset.id,
+ assetId: asset.id,
+ sourceStartSec: 0,
+ sourceEndSec: durationSec,
+ timelineStartSec: atRuler,
+ timelineEndSec: atRuler + durationSec,
+ wordRefs: [],
+ origin: "user",
+ reason: "inserted word",
+ };
+
+ const ordered = [...document.timeline.clips].sort(
+ (a, b) => a.timelineStartSec - b.timelineStartSec,
+ );
+ const clips: AxcutClip[] = [];
+ let split: { from: string; to: string } | null = null;
+ let placed = false;
+ for (const clip of ordered) {
+ const cutsHere = atRuler > clip.timelineStartSec + EPS && atRuler < clip.timelineEndSec - EPS;
+ if (!placed && cutsHere) {
+ const cut = clip.sourceStartSec + (atRuler - clip.timelineStartSec);
+ const right = {
+ ...clip,
+ id: createId("clip"),
+ sourceStartSec: cut,
+ timelineStartSec: atRuler,
+ };
+ clips.push({ ...clip, sourceEndSec: cut, timelineEndSec: atRuler }, generated, right);
+ split = { from: clip.id, to: right.id };
+ placed = true;
+ continue;
+ }
+ if (!placed && clip.timelineStartSec >= atRuler - EPS) {
+ clips.push(generated);
+ placed = true;
+ }
+ clips.push(clip);
+ }
+ if (!placed) clips.push(generated);
+
+ const next: AxcutDocument = {
+ ...document,
+ assets: [...document.assets, asset],
+ transcripts: [
+ ...document.transcripts,
+ generatedTranscript(
+ wordId,
+ durationSec,
+ trimmed,
+ document.transcripts.find((t) => t.assetId === assetId)?.language ?? "en",
+ ),
+ ],
+ timeline: { ...document.timeline, clips: resequenceClips(clips) },
+ };
+ const anchored = split ? fanOutAnchors(next, split.from, split.to) : next;
+ return rederiveRegionMs(anchored, anchored.timeline.clips);
+}
+
+/**
+ * Delete inserted words.
+ *
+ * `removeClip` does the whole of it: the gap closes, the halves rejoin when they are still
+ * one continuous piece of media, and the rows anchored to the half that goes away follow.
+ * What is left here is the media the clip was the only user of.
+ */
+export function removeGeneratedClips(
+ document: AxcutDocument,
+ wordIds: readonly string[],
+): AxcutDocument {
+ return wordIds.reduce((next, wordId) => {
+ const id = extensionAssetId(wordId);
+ if (!next.timeline.clips.some((c) => c.id === id)) return next;
+ const after = removeClip(next, id);
+ return {
+ ...after,
+ assets: after.assets.filter((a) => a.id !== id),
+ transcripts: after.transcripts.filter((t) => t.assetId !== id),
+ };
+ }, document);
+}
+
+/**
+ * Rewrite an inserted word's text.
+ *
+ * Its length IS its text, so this resizes the clip and renames the file it plays. The old
+ * file is simply never asked for again; the new one is generated on the next save.
+ */
+export function retextGeneratedClip(
+ document: AxcutDocument,
+ wordId: string,
+ text: string,
+): AxcutDocument {
+ const trimmed = text.trim();
+ const id = extensionAssetId(wordId);
+ const host = hostAsset(document);
+ if (trimmed.length === 0 || !host || !document.assets.some((a) => a.id === id)) return document;
+
+ const durationSec = extensionDurationSec(trimmed);
+ const language = document.transcripts.find((t) => t.assetId === id)?.language ?? "en";
+ const next: AxcutDocument = {
+ ...document,
+ assets: document.assets.map((a) =>
+ a.id === id ? generatedAsset(host, wordId, durationSec, trimmed) : a,
+ ),
+ transcripts: document.transcripts.map((t) =>
+ t.assetId === id ? generatedTranscript(wordId, durationSec, trimmed, language) : t,
+ ),
+ timeline: {
+ ...document.timeline,
+ clips: resequenceClips(
+ document.timeline.clips.map((c) => (c.id === id ? { ...c, sourceEndSec: durationSec } : c)),
+ ),
+ },
+ };
+ return rederiveRegionMs(next, next.timeline.clips);
+}
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index 9fa9330f4..e1ca19a5a 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -14,7 +14,6 @@ import type { AxcutClip, AxcutDocument, AxcutTranscript, AxcutTrimRange } from "
*/
export type PlaybackSegment = AxcutClip;
-import { clipParts, partsLengthSec } from "../timeline/clip-parts";
import { type Interval, subtractInterval } from "../timeline/intervals";
import { keptRawSpans } from "../timeline/programme-time";
import {
@@ -129,34 +128,6 @@ function collectWordRefs(
// after any structural change (insert / move / remove / trim) so the timeline
// never has gaps or overlaps between clips. Shared by useTimeline (UI) and
// the agent tool executor (main process) so both enforce the same invariant.
-/**
- * Clip lengths, recomputed from the parts they now have.
- *
- * `timelineEndSec` is STORED, so something has to keep it true once a word can add media
- * inside a clip — and the ruler reads it, so a clip left short draws a film that ends before
- * the programme does. This is that something, and it is a recompute, not a reconciliation:
- * the parts are derived from the words, so there is no second stored fact to drift from.
- *
- * Idempotent, and a no-op for a document with no added words.
- */
-export function withClipsSizedToParts(document: AxcutDocument): AxcutDocument {
- const wordsByAsset = new Map(document.transcripts.map((t) => [t.assetId, t.words]));
- const clips = document.timeline.clips.map((clip) => {
- const parts = clipParts(clip, wordsByAsset.get(clip.assetId) ?? []);
- // No parts means the duration has not been probed yet; the prober owns the length.
- if (parts.length === 0) return clip;
- return { ...clip, timelineEndSec: clip.timelineStartSec + partsLengthSec(parts) };
- });
- const resequenced = resequenceClips(clips);
- const unchanged = resequenced.every(
- (clip, i) =>
- Math.abs(clip.timelineStartSec - document.timeline.clips[i].timelineStartSec) < 1e-9 &&
- Math.abs(clip.timelineEndSec - document.timeline.clips[i].timelineEndSec) < 1e-9,
- );
- return unchanged
- ? document
- : { ...document, timeline: { ...document.timeline, clips: resequenced } };
-}
export function resequenceClips(clips: AxcutClip[]): AxcutClip[] {
let cursor = 0;
@@ -1084,13 +1055,18 @@ export function removeClip(document: AxcutDocument, clipId: string): AxcutDocume
const oldClips = document.timeline.clips;
const arr = oldClips.filter((c) => c.id !== clipId);
if (arr.length === oldClips.length) return document;
- const newClips = resequenceClips(arr);
+ const { clips: joined, reanchor } = joinContiguous(arr);
+ const newClips = resequenceClips(joined);
const next: AxcutDocument = {
...document,
timeline: {
...document.timeline,
clips: newClips,
- trimRanges: document.timeline.trimRanges.filter((t) => t.clipId !== clipId),
+ trimRanges: document.timeline.trimRanges
+ .filter((t) => t.clipId !== clipId)
+ .map((t) =>
+ t.clipId && reanchor.has(t.clipId) ? { ...t, clipId: reanchor.get(t.clipId) } : t,
+ ),
},
};
// The asymmetry with the trim filter three lines up is deliberate, and the obvious
@@ -1123,7 +1099,66 @@ export function removeClip(document: AxcutDocument, clipId: string): AxcutDocume
regions.filter((region) => !(hasCompleteClipAnchor(region) && region.clipId === clipId)),
);
}
- return rederiveRegionMs(next, newClips);
+ const reanchored =
+ reanchor.size === 0
+ ? next
+ : mapAllRegionCollections(next, (regions) =>
+ regions.map((region) =>
+ hasCompleteClipAnchor(region) && reanchor.has(region.clipId)
+ ? { ...region, clipId: reanchor.get(region.clipId) as string }
+ : region,
+ ),
+ );
+ return rederiveRegionMs(reanchored, newClips);
+}
+
+/**
+ * Two clips that are one continuous piece of media are one clip.
+ *
+ * The inverse of the cut an insertion makes: take the generated clip away and the halves it
+ * separated go back to being what they were. Asked only when a clip is REMOVED, which is
+ * the only moment adjacency can appear — a pass over the whole timeline would join clips
+ * the user meant to keep apart.
+ *
+ * Deliberately blind to WHY the two halves are contiguous: no marker, no parent id, nothing
+ * to keep in sync. Same media, source ranges that meet, same crop — then they play as one
+ * clip already, and drawing them as two is the only difference.
+ *
+ * ponytail: today nothing else can produce two contiguous clips of one media, so this can
+ * only ever undo an insertion. Give the cut a marker the day a razor tool lands and a split
+ * with no gap becomes something the user asked for.
+ */
+function joinContiguous(clips: AxcutClip[]): {
+ clips: AxcutClip[];
+ /** Ids that went away, and the clip that now carries their content. */
+ reanchor: Map<string, string>;
+} {
+ const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);
+ const out: AxcutClip[] = [];
+ const reanchor = new Map<string, string>();
+ for (const clip of ordered) {
+ const previous = out[out.length - 1];
+ if (previous && joinable(previous, clip)) {
+ out[out.length - 1] = {
+ ...previous,
+ sourceEndSec: clip.sourceEndSec,
+ timelineEndSec: previous.timelineEndSec + (clip.timelineEndSec - clip.timelineStartSec),
+ };
+ reanchor.set(clip.id, previous.id);
+ continue;
+ }
+ out.push(clip);
+ }
+ return { clips: out, reanchor };
+}
+
+function joinable(left: AxcutClip, right: AxcutClip): boolean {
+ return (
+ left.assetId === right.assetId &&
+ left.sourceEndSec !== undefined &&
+ Math.abs(left.sourceEndSec - right.sourceStartSec) < 1e-6 &&
+ JSON.stringify(left.cropRegion ?? null) === JSON.stringify(right.cropRegion ?? null)
+ );
}
export function restoreFullTimeline(document: AxcutDocument): AxcutDocument {
diff --git a/src/lib/ai-edition/document/transcript.test.ts b/src/lib/ai-edition/document/transcript.test.ts
index b8c40f301..79e1397aa 100644
--- a/src/lib/ai-edition/document/transcript.test.ts
+++ b/src/lib/ai-edition/document/transcript.test.ts
@@ -1,13 +1,6 @@
import { describe, expect, it } from "vitest";
import { type AxcutDocument, type AxcutTranscript, createEmptyDocument } from "../schema";
-import {
- carryOverWordEdits,
- insertDocumentWord,
- removeDocumentWords,
- setDocumentWordText,
- setWordText,
- withTranscript,
-} from "./transcript";
+import { carryOverWordEdits, setDocumentWordText, setWordText, withTranscript } from "./transcript";
function fixture(language = "en"): AxcutTranscript {
return {
@@ -492,11 +485,11 @@ describe("carryOverWordEdits", () => {
});
// ─── The clip grows with the word ───────────────────────────────────────────
-// `timelineEndSec` is stored and the ruler reads it, so a clip left short draws a film that
-// ends before the programme does — the desync the previous attempt spent its life chasing.
-// Recomputed from the parts, at the one funnel every transcript write goes through.
+// An insertion is a clip, so its arithmetic lives in `insertion.test.ts`. What is left here
+// is the promise the plain transcript writes still make: they touch the words and nothing
+// else on the timeline.
-describe("adding a word sizes the clip it lands in", () => {
+describe("correcting a word leaves the timeline alone", () => {
function docWithClip(): AxcutDocument {
return {
assets: [{ id: "a1", kind: "video" }],
@@ -540,25 +533,6 @@ describe("adding a word sizes the clip it lands in", () => {
} as unknown as AxcutDocument;
}
- it("lengthens the clip by exactly the media the word needs", () => {
- const after = insertDocumentWord(docWithClip(), "a1", "w2", "after", "really");
- const [clip] = after.timeline.clips;
- // "really" is 6 chars at 15/s.
- expect(clip.timelineEndSec - clip.timelineStartSec).toBeCloseTo(10 + 6 / 15, 6);
- // And takes not one frame of the recording with it.
- expect(clip.sourceStartSec).toBe(0);
- expect(clip.sourceEndSec).toBe(10);
- });
-
- it("gives the length back when the word goes", () => {
- const before = docWithClip();
- const added = insertDocumentWord(before, "a1", "w2", "after", "really");
- const gone = removeDocumentWords(added, "a1", [
- added.transcripts[0].words.find((w) => w.source === "synth")?.id ?? "",
- ]);
- expect(gone.timeline.clips).toEqual(before.timeline.clips);
- });
-
it("leaves a document with no added words untouched", () => {
const before = docWithClip();
const after = setDocumentWordText(before, "a1", "w1", "HELLO");
diff --git a/src/lib/ai-edition/document/transcript.ts b/src/lib/ai-edition/document/transcript.ts
index 19b44dd9d..6262803f6 100644
--- a/src/lib/ai-edition/document/transcript.ts
+++ b/src/lib/ai-edition/document/transcript.ts
@@ -1,5 +1,11 @@
import type { AxcutDocument, AxcutTranscript, AxcutWord } from "../schema";
-import { withClipsSizedToParts } from "./timeline";
+import {
+ type InsertSide,
+ insertGeneratedClip,
+ isGeneratedAssetId,
+ removeGeneratedClips,
+ retextGeneratedClip,
+} from "./insertion";
const CJK_EDGE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u;
const CLOSING_PUNCTUATION = /^[,.;:!?%。,、;:!?…))\]}>》」』】〕]/u;
@@ -122,14 +128,12 @@ export function withTranscript(
...document.transcripts.filter((t) => t.assetId !== transcript.assetId),
transcript,
];
- // Sized here, at the ONE funnel every transcript write goes through, so adding or
- // removing a word cannot leave a clip claiming a length its parts no longer have.
- return withClipsSizedToParts({
+ return {
...document,
transcript:
document.project.primaryAssetId === transcript.assetId ? transcript : document.transcript,
transcripts,
- });
+ };
}
/**
@@ -143,6 +147,9 @@ export function setDocumentWordText(
wordId: string,
text: string,
): AxcutDocument {
+ // An inserted word's length IS its text, so rewriting it resizes the clip it plays on
+ // and renames the file. Nothing a plain transcript write can express.
+ if (isGeneratedAssetId(assetId)) return retextGeneratedClip(document, wordId, text);
const transcript = document.transcripts.find((t) => t.assetId === assetId);
if (!transcript) {
throw new Error(`Cannot edit a word of asset "${assetId}": it has no transcript`);
@@ -150,162 +157,10 @@ export function setDocumentWordText(
return withTranscript(document, setWordText(transcript, wordId, text));
}
-/** Where a new word goes relative to the word the caret was resting on. */
-export type InsertSide = "before" | "after";
-
-/**
- * How long an inserted word needs to be readable on screen. Subtitle practice is roughly
- * fifteen characters a second, with a floor so a one-letter word is not a single frame.
- * It is only ever a REQUEST — `insertWord` gives the word whatever silence is actually
- * free, and no more.
- */
-function readingSeconds(text: string): number {
- return Math.max(0.4, text.trim().length / 15);
-}
-
-/** `synth_N`, numbered past every id already in the transcript.
- *
- * The prefix buys uniqueness, not meaning: a transcription run regenerates `word_N` from
- * 1, so a synthesized word holding one of those ids would be overwritten by the next run.
- * What the word IS lives in `source`, which is what every reader checks. */
-function nextSynthWordId(transcript: AxcutTranscript): string {
- let highest = 0;
- for (const word of transcript.words) {
- const match = /^synth_(\d+)$/.exec(word.id);
- if (match) highest = Math.max(highest, Number(match[1]));
- }
- return `synth_${highest + 1}`;
-}
-
-/**
- * Insert a word that no one said.
- *
- * It carries no audio, so it takes the SILENCE it is dropped into and nothing else: from
- * the word it follows up to what its text needs to be read, and never past the word that
- * comes next. Dropped between two words that run straight into each other it has no
- * duration at all and simply rides their caption line — which is where it reads correctly
- * anyway, since there is no pause on screen to fill.
- *
- * That is the whole of what an inserted word can do today: it reaches the captions and
- * stops there. When a voice can be synthesized for it, `source: "synth"` is what marks the
- * words that need speaking, and the span computed here is the slot that audio has to fit.
- */
-export function insertWord(
- transcript: AxcutTranscript,
- anchorWordId: string,
- side: InsertSide,
- text: string,
-): AxcutTranscript {
- const trimmed = text.trim();
- if (trimmed.length === 0) {
- throw new Error("Cannot insert an empty word");
- }
- const anchorIndex = transcript.words.findIndex((word) => word.id === anchorWordId);
- if (anchorIndex < 0) {
- throw new Error(`Cannot insert next to missing transcript word "${anchorWordId}"`);
- }
- const anchor = transcript.words[anchorIndex];
- const segment = transcript.segments.find((seg) => seg.id === anchor.segmentId);
- if (!segment) {
- throw new Error(
- `Transcript word "${anchorWordId}" references missing segment "${anchor.segmentId}"`,
- );
- }
- const anchorSlot = segment.wordIds.indexOf(anchorWordId);
- if (anchorSlot < 0) {
- throw new Error(`Segment "${segment.id}" does not reference anchor word "${anchorWordId}"`);
- }
-
- const wanted = readingSeconds(trimmed);
- let startSec: number;
- let endSec: number;
- if (side === "after") {
- startSec = anchor.endSec;
- // The next word IN TIME, which is not necessarily the next one in the array — the
- // array is insertion order, and only time decides what the new word may overlap.
- const nextStart = transcript.words
- .filter((word) => word.startSec >= startSec && word.id !== anchorWordId)
- .reduce<number | null>(
- (soonest, word) => (soonest === null ? word.startSec : Math.min(soonest, word.startSec)),
- null,
- );
- endSec = nextStart === null ? startSec + wanted : Math.min(startSec + wanted, nextStart);
- } else {
- endSec = anchor.startSec;
- const previousEnd = transcript.words
- .filter((word) => word.endSec <= endSec && word.id !== anchorWordId)
- .reduce<number | null>(
- (latest, word) => (latest === null ? word.endSec : Math.max(latest, word.endSec)),
- null,
- );
- const floor = previousEnd === null ? 0 : previousEnd;
- startSec = Math.max(floor, endSec - wanted);
- }
-
- const inserted: AxcutWord = {
- id: nextSynthWordId(transcript),
- segmentId: segment.id,
- startSec,
- endSec: Math.max(startSec, endSec),
- text: trimmed,
- source: "synth",
- };
+export type { InsertSide } from "./insertion";
- // Position in `words` matters as well as the timings: a zero-length insert shares its
- // start with the word it sits against, and the reading order of that tie is the array
- // order (see `withSilenceGaps`).
- const at = side === "after" ? anchorIndex + 1 : anchorIndex;
- const words = [...transcript.words.slice(0, at), inserted, ...transcript.words.slice(at)];
- const slot = side === "after" ? anchorSlot + 1 : anchorSlot;
- const wordIds = [...segment.wordIds.slice(0, slot), inserted.id, ...segment.wordIds.slice(slot)];
- const byId = new Map(words.map((word) => [word.id, word]));
- const segmentText = joinSegmentText(wordIds.map((id) => byId.get(id)?.text ?? ""));
-
- return {
- ...transcript,
- words,
- segments: transcript.segments.map((seg) =>
- seg.id === segment.id ? { ...seg, wordIds, text: segmentText } : seg,
- ),
- };
-}
-
-/**
- * Delete an inserted word.
- *
- * Only a synthesized one: a transcribed word is the label on a piece of audio, and the
- * operation for making that go away is a trim, which removes the sound with it. Deleting
- * the label alone would leave the film saying a word the transcript denies.
- */
-export function removeWord(transcript: AxcutTranscript, wordId: string): AxcutTranscript {
- const target = transcript.words.find((word) => word.id === wordId);
- if (!target) {
- throw new Error(`Cannot remove missing transcript word "${wordId}"`);
- }
- if (target.source !== "synth") {
- throw new Error(
- `Refusing to remove transcribed word "${wordId}": cut it with a trim, or blank its text`,
- );
- }
- const words = transcript.words.filter((word) => word.id !== wordId);
- const byId = new Map(words.map((word) => [word.id, word]));
- return {
- ...transcript,
- words,
- segments: transcript.segments.map((segment) => {
- if (!segment.wordIds.includes(wordId)) return segment;
- const wordIds = segment.wordIds.filter((id) => id !== wordId);
- return {
- ...segment,
- wordIds,
- text: joinSegmentText(wordIds.map((id) => byId.get(id)?.text ?? "")),
- };
- }),
- };
-}
-
-/** {@link insertWord}, addressed by asset. Goes through `withTranscript` for the same
- * reason {@link setDocumentWordText} does. */
+/** Add a word nobody said. It becomes a CLIP — see `insertion.ts`, which is the whole of
+ * what an insertion is. */
export function insertDocumentWord(
document: AxcutDocument,
assetId: string,
@@ -313,29 +168,20 @@ export function insertDocumentWord(
side: InsertSide,
text: string,
): AxcutDocument {
- const transcript = document.transcripts.find((t) => t.assetId === assetId);
- if (!transcript) {
- throw new Error(`Cannot insert a word into asset "${assetId}": it has no transcript`);
- }
- return withTranscript(document, insertWord(transcript, anchorWordId, side, text));
+ return insertGeneratedClip(document, assetId, anchorWordId, side, text);
}
-/** {@link removeWord}, addressed by asset and taking the whole set at once: a Backspace
- * over several inserted words has to be ONE write, or undoing it takes as many presses as
- * there were words. */
+/** Delete inserted words, taking the whole set at once: a Backspace over several of them
+ * has to be ONE write, or undoing it takes as many presses as there were words.
+ *
+ * `assetId` is not read. Each inserted word names its own clip and its own asset, so the
+ * set can span several of them and the caller does not have to group by section. */
export function removeDocumentWords(
document: AxcutDocument,
- assetId: string,
+ _assetId: string,
wordIds: readonly string[],
): AxcutDocument {
- const transcript = document.transcripts.find((t) => t.assetId === assetId);
- if (!transcript) {
- throw new Error(`Cannot remove a word from asset "${assetId}": it has no transcript`);
- }
- return withTranscript(
- document,
- wordIds.reduce((acc, wordId) => removeWord(acc, wordId), transcript),
- );
+ return removeGeneratedClips(document, wordIds);
}
/** What {@link carryOverWordEdits} managed to save from the previous transcript. */
@@ -367,12 +213,11 @@ export function carryOverWordEdits(
const edits = (previous?.words ?? []).filter(
(word) => word.source === "user" && word.originalText !== undefined,
);
- const inserts = (previous?.words ?? [])
- .filter((word) => word.source === "synth")
- .sort((a, b) => a.startSec - b.startSec);
- if (edits.length === 0 && inserts.length === 0) {
- return { transcript: next, carried: 0, dropped: 0 };
- }
+ // Insertions are not carried, and no longer need to be: each one is a CLIP of its own,
+ // on its own asset, so re-transcribing this recording does not touch it. It stays exactly
+ // where it sits on the ruler — which is more than the time-matching this replaces ever
+ // managed.
+ if (edits.length === 0) return { transcript: next, carried: 0, dropped: 0 };
// Candidates are read from `next` throughout, never from the transcript being
// built up: a word already rewritten by an earlier correction no longer carries
@@ -395,23 +240,5 @@ export function carryOverWordEdits(
carried += 1;
}
- // An inserted word has no original text to recognise, so time is what places it: the
- // audio did not change between runs, only how it was heard. Each one goes back after
- // whatever the new transcript now ends last before it — including a word re-inserted a
- // moment ago, which is what keeps two inserts at the same spot in their old order.
- for (const insert of inserts) {
- const before = transcript.words
- .filter((word) => word.endSec <= insert.startSec)
- .reduce<AxcutWord | null>(
- (latest, word) => (latest === null || word.endSec >= latest.endSec ? word : latest),
- null,
- );
- const head = transcript.words[0];
- const target = before ?? head ?? null;
- if (!target) continue;
- transcript = insertWord(transcript, target.id, before ? "after" : "before", insert.text);
- carried += 1;
- }
-
- return { transcript, carried, dropped: edits.length + inserts.length - carried };
+ return { transcript, carried, dropped: edits.length - carried };
}
diff --git a/src/lib/ai-edition/timeline/aggregated-transcript.ts b/src/lib/ai-edition/timeline/aggregated-transcript.ts
index eeebae973..309e3c6aa 100644
--- a/src/lib/ai-edition/timeline/aggregated-transcript.ts
+++ b/src/lib/ai-edition/timeline/aggregated-transcript.ts
@@ -16,7 +16,6 @@
import { collapseTracksToPills } from "../document/audioTracks";
import type { AxcutAsset, AxcutAudioTrack, AxcutClip, AxcutTranscript, AxcutWord } from "../schema";
-import { type ClipPart, clipParts, extensionAt, partsRawSec, partsSourceSec } from "./clip-parts";
import { type RawSpan, type RemovedRawSpan, removalAt } from "./programme-time";
import { takeProgramme } from "./take-programme";
@@ -44,11 +43,6 @@ export interface TranscriptPlacement {
/** Where the window lands on the RAW ruler. Source time is per asset, so this is
* the only thing that turns a word back into a moment the playhead can seek to. */
timelineStartSec: number;
- /** The placement's parts, when it has any: a clip carrying added words plays its own
- * media in pieces with generated media between them, so a source second no longer sits
- * a fixed distance from the head. Absent, the placement is one uninterrupted stretch
- * and every reader below behaves exactly as it did before extensions existed. */
- parts?: readonly ClipPart[];
}
/** Which lane's speech the transcript tab is reading. */
@@ -62,9 +56,7 @@ export type TranscriptLane = "recording" | "voiceover";
* and not in source time (issue #560).
*/
export function placementRawSec(placement: TranscriptPlacement, sourceSec: number): number {
- return placement.parts
- ? partsRawSec(placement.parts, sourceSec)
- : placement.timelineStartSec + (sourceSec - placement.sourceStartSec);
+ return placement.timelineStartSec + (sourceSec - placement.sourceStartSec);
}
/** The placement's own stretch of raw ruler, or null when it runs open-ended. */
@@ -353,36 +345,14 @@ export function voiceoverPlacements(
);
}
-/**
- * The recording lane's placements: the clips, each carrying its own parts.
- *
- * One placement per clip, not one per part. The pane draws a header per placement, and a
- * clip does not become three clips because the user typed a word into it — the split
- * belongs to the mapping, which is where `parts` puts it.
- */
-export function recordingPlacements(
- clips: AxcutClip[],
- transcripts: readonly AxcutTranscript[],
-): TranscriptPlacement[] {
- const wordsByAsset = new Map(transcripts.map((t) => [t.assetId, t.words]));
- return clips.map((clip) => ({
- ...clip,
- parts: clipParts(clip, wordsByAsset.get(clip.assetId) ?? []),
- }));
-}
-
/** The placements a lane contributes, in timeline order. */
export function lanePlacements(
lane: TranscriptLane,
clips: AxcutClip[],
audioTracks: AxcutAudioTrack[],
removed: readonly RemovedRawSpan[] = [],
- /** Needed only by the recording lane, to know where its clips are interrupted. */
- transcripts: readonly AxcutTranscript[] = [],
): TranscriptPlacement[] {
- return lane === "voiceover"
- ? voiceoverPlacements(audioTracks, removed)
- : recordingPlacements(clips, transcripts);
+ return lane === "voiceover" ? voiceoverPlacements(audioTracks, removed) : clips;
}
/**
@@ -428,17 +398,8 @@ export function findCueWordId(sections: ClipSection[], rawSec: number | null): s
}
if (!match) return null;
- // An added word is spoken over its extension, which occupies ruler time and no source
- // time at all. Asked first, and by id: through source time it is indistinguishable from
- // the recorded word that resumes at the same second — which is why the pane used to skip
- // straight past every inserted word to the one after it.
- const spoken = match.clip.parts ? extensionAt(match.clip.parts, rawSec) : null;
- if (spoken) return clipWordId(match.clip.id, spoken);
-
// Back to the placement's own source clock, which is what the words are stamped in.
- const t = match.clip.parts
- ? partsSourceSec(match.clip.parts, rawSec)
- : match.clip.sourceStartSec + (rawSec - match.clip.timelineStartSec);
+ const t = match.clip.sourceStartSec + (rawSec - match.clip.timelineStartSec);
let previous: string | null = null;
for (const cw of match.words) {
if (isSilenceWord(cw.word)) continue;
diff --git a/src/lib/ai-edition/timeline/clip-parts.test.ts b/src/lib/ai-edition/timeline/clip-parts.test.ts
index 3ac97d4ce..447ac3dec 100644
--- a/src/lib/ai-edition/timeline/clip-parts.test.ts
+++ b/src/lib/ai-edition/timeline/clip-parts.test.ts
@@ -1,114 +1,15 @@
-// The one property everything above this module depends on: the parts are contiguous, they
-// start where the clip starts, and no stored source coordinate moved to achieve it.
+// The rules the writer and the generator both have to agree on. Everything else an
+// insertion needs is in `document/insertion.ts` — it is a clip, and clips are already tested.
import { describe, expect, it } from "vitest";
-import { resolvePlaybackSegments } from "../document/timeline";
-import type { AxcutClip, AxcutDocument, AxcutWord } from "../schema";
-import {
- baseClipId,
- clipParts,
- extensionAt,
- extensionClipPath,
- extensionDurationSec,
- partsLengthSec,
- partsRawSec,
- partsSourceSec,
- withExtensions,
-} from "./clip-parts";
-
-const CLIP: AxcutClip = {
- id: "c1",
- assetId: "a1",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 0,
- timelineEndSec: 10,
- wordRefs: [],
- origin: "user",
- reason: "",
-};
-
-const word = (over: Partial<AxcutWord> & { id: string; startSec: number }): AxcutWord => ({
- segmentId: "s1",
- endSec: over.startSec,
- text: "hello",
- ...over,
-});
-
-const added = (id: string, at: number, text: string): AxcutWord =>
- word({ id, startSec: at, text, source: "synth" });
-
-describe("clipParts", () => {
- it("is one recording part when nothing was added", () => {
- expect(clipParts(CLIP, [word({ id: "w1", startSec: 1 })])).toEqual([
- {
- kind: "recording",
- timelineStartSec: 0,
- timelineEndSec: 10,
- sourceStartSec: 0,
- sourceEndSec: 10,
- },
- ]);
- });
-
- it("splits the recording where the word was added, extension between the halves", () => {
- const parts = clipParts(CLIP, [added("s1", 4, "really")]);
- expect(parts.map((p) => p.kind)).toEqual(["recording", "extension", "recording"]);
- expect(parts[0]).toMatchObject({ sourceStartSec: 0, sourceEndSec: 4, timelineEndSec: 4 });
- // "really" is 6 chars at 15/s.
- expect(parts[1]).toMatchObject({ kind: "extension", wordId: "s1", timelineStartSec: 4 });
- expect(parts[1].timelineEndSec).toBeCloseTo(4.4, 6);
- // The SOURCE window of the second half is untouched — it resumes where it left off.
- expect(parts[2]).toMatchObject({ sourceStartSec: 4, sourceEndSec: 10 });
- expect(parts[2].timelineStartSec).toBeCloseTo(4.4, 6);
- });
-
- it("leaves every stored source coordinate exactly where it was", () => {
- // The whole reason the extension is appended to the LIST and not spliced into the
- // media's axis: adding one cannot move an anchor anyone else stored.
- const parts = clipParts(CLIP, [added("s1", 4, "really"), added("s2", 7, "quite")]);
- const recorded = parts.filter((p) => p.kind === "recording");
- expect(recorded.map((p) => [p.sourceStartSec, p.sourceEndSec])).toEqual([
- [0, 4],
- [4, 7],
- [7, 10],
- ]);
- });
-
- it("is contiguous, and starts where the clip starts", () => {
- const parts = clipParts({ ...CLIP, timelineStartSec: 12, timelineEndSec: 22 }, [
- added("s1", 4, "really"),
- added("s2", 7, "quite"),
- ]);
- expect(parts[0].timelineStartSec).toBe(12);
- for (const [i, part] of parts.slice(0, -1).entries()) {
- expect(part.timelineEndSec).toBeCloseTo(parts[i + 1].timelineStartSec, 9);
- }
- });
-
- it("grows the clip by exactly what was added, and by nothing else", () => {
- const bare = partsLengthSec(clipParts(CLIP, []));
- const grown = partsLengthSec(clipParts(CLIP, [added("s1", 4, "really")]));
- expect(bare).toBeCloseTo(10, 6);
- expect(grown - bare).toBeCloseTo(extensionDurationSec("really"), 6);
- });
-
- it("ignores a word another clip of the same recording plays", () => {
- const late = { ...CLIP, sourceStartSec: 6, sourceEndSec: 10, timelineEndSec: 4 };
- expect(clipParts(late, [added("s1", 4, "really")]).map((p) => p.kind)).toEqual(["recording"]);
- });
-
- it("ignores an empty word, which buys nothing", () => {
- expect(clipParts(CLIP, [added("s1", 4, " ")]).map((p) => p.kind)).toEqual(["recording"]);
- });
-});
+import { extensionAssetId, extensionClipPath, extensionDurationSec } from "./clip-parts";
describe("extensionDurationSec", () => {
it("is the text's own length at the assumed rate", () => {
expect(extensionDurationSec("really")).toBeCloseTo(6 / 15, 6);
});
- it("never returns a span too short to be a part", () => {
+ it("never returns a span too short to be a clip", () => {
expect(extensionDurationSec("a")).toBe(0.15);
});
@@ -117,141 +18,31 @@ describe("extensionDurationSec", () => {
});
});
-// ─── 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.
-
-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;
+/** One backslash, built rather than escaped: the escape is what this test keeps losing. */
+const BS = String.fromCharCode(92);
-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("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")),
+describe("extensionClipPath", () => {
+ it("sits beside the recording it belongs to, in a hidden folder", () => {
+ expect(extensionClipPath("C:/rec/take.mp4", "synth_2", 3.6)).toBe(
+ "C:/rec/.openscreen-extensions/synth_2_3600.mp4",
);
- // 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 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("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("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);
- });
-});
-
-// ─── The one conversion ─────────────────────────────────────────────────────
-// Every reader used to write `timelineStartSec + (sec - sourceStartSec)` for itself. That
-// subtraction is right until a clip carries an extension and wrong for every second after
-// it, which is one bug per reader — so it lives here now, once.
-
-describe("partsRawSec", () => {
- const parts = clipParts(CLIP, [added("s1", 4, "really")]);
- const ext = extensionDurationSec("really");
-
- it("leaves the seconds before the insertion where they were", () => {
- expect(partsRawSec(parts, 2)).toBeCloseTo(2, 6);
- });
-
- it("pushes the seconds after it along by exactly what was inserted", () => {
- expect(partsRawSec(parts, 6)).toBeCloseTo(6 + ext, 6);
- expect(partsRawSec(parts, 10)).toBeCloseTo(10 + ext, 6);
- });
-
- it("puts the split second AFTER the extension, where its media actually plays", () => {
- expect(partsRawSec(parts, 4)).toBeCloseTo(4 + ext, 6);
- });
-
- it("is the plain subtraction when nothing was added", () => {
- const plain = clipParts({ ...CLIP, timelineStartSec: 12, timelineEndSec: 22 }, []);
- expect(partsRawSec(plain, 6)).toBeCloseTo(18, 6);
- });
-});
-
-describe("partsSourceSec", () => {
- const parts = clipParts(CLIP, [added("s1", 4, "really")]);
- const ext = extensionDurationSec("really");
-
- it("undoes partsRawSec for a second the recording actually plays", () => {
- for (const sec of [0, 2, 4, 6, 10]) {
- expect(partsSourceSec(parts, partsRawSec(parts, sec))).toBeCloseTo(sec, 6);
- }
+ it("carries the duration, so a re-typed word asks for a different file", () => {
+ expect(extensionClipPath("C:/rec/take.mp4", "synth_2", 3.8)).not.toBe(
+ extensionClipPath("C:/rec/take.mp4", "synth_2", 3.6),
+ );
});
- it("parks at the split while the extension plays — no recording runs there", () => {
- expect(partsSourceSec(parts, 4 + ext / 2)).toBeCloseTo(4, 6);
+ it("is the same rule on a Windows path, so both processes name one file", () => {
+ expect(extensionClipPath(`C:${BS}rec${BS}take.mp4`, "w1", 1)).toBe(
+ `C:${BS}rec${BS}.openscreen-extensions${BS}w1_1000.mp4`,
+ );
});
});
-describe("extensionAt", () => {
- const parts = clipParts(CLIP, [added("s1", 4, "really")]);
- const ext = extensionDurationSec("really");
-
- it("names the word being spoken over its own media", () => {
- expect(extensionAt(parts, 4 + ext / 2)).toBe("s1");
- });
-
- it("is nothing on either side of it, so the recorded words keep the highlight", () => {
- expect(extensionAt(parts, 3.9)).toBeNull();
- expect(extensionAt(parts, 4 + ext + 0.01)).toBeNull();
+describe("extensionAssetId", () => {
+ it("cannot collide with a real asset id, and says what it is in a log line", () => {
+ expect(extensionAssetId("synth_1")).toBe("ext:synth_1");
});
});
diff --git a/src/lib/ai-edition/timeline/clip-parts.ts b/src/lib/ai-edition/timeline/clip-parts.ts
index c7617dad3..470ede0e3 100644
--- a/src/lib/ai-edition/timeline/clip-parts.ts
+++ b/src/lib/ai-edition/timeline/clip-parts.ts
@@ -1,19 +1,12 @@
-// The insertion layer: media -> parts -> clip.
+// What an insertion is made of: a duration, a name, and a file.
//
-// A clip does not read a file, it reads a LIST of parts:
-//
-// [ recording 0→5.3 ] [ extension 0.4s ] [ recording 5.3→20.9 ]
-//
-// The extension does NOT slide into the media's own axis — it is appended to the clip's
-// list. That is the decision the whole design rests on, and its consequence is the point:
-// no stored source coordinate ever moves. A word, a trim, a zoom keeps the second it was
-// authored at, for ever. Adding or removing an extension cannot corrupt an anchor.
-//
-// This is the ONLY module that knows an extension exists. Above it, a part is just media
-// with a source window and a place on the timeline, and the plain arithmetic every reader
-// used before insertions works again.
+// An insertion IS a clip (see `document/insertion.ts`), so there is nothing here that maps
+// between coordinate systems and nothing downstream that knows an insertion exists. What
+// remains is the handful of rules the writer and the generator both have to agree on — how
+// long an added word takes, what its asset is called, and where its file lives — expressed
+// once so the renderer names the file the main process writes.
-import type { AxcutAsset, AxcutClip, AxcutDocument, AxcutWord } from "../schema";
+import type { AxcutWord } from "../schema";
/** How fast a synthesized voice will be assumed to speak, in characters per second.
*
@@ -22,8 +15,7 @@ import type { AxcutAsset, AxcutClip, AxcutDocument, AxcutWord } from "../schema"
* ponytail: fixed rate, ask the synthesizer for the real duration once there is one. */
const CHARS_PER_SEC = 15;
-/** Below this the extension is not worth a part of its own: the clip would gain a few
- * frames nobody asked for and every reader would carry a degenerate span. */
+/** Below this the clip would be a few frames nobody asked for. */
export const MIN_EXTENSION_SEC = 0.15;
/** How long the media for an added word has to be. */
@@ -38,296 +30,26 @@ export function isAddedWord(word: AxcutWord): boolean {
return word.source === "synth";
}
-export type ClipPart =
- | {
- kind: "recording";
- timelineStartSec: number;
- timelineEndSec: number;
- /** The window of the clip's own asset this part plays. */
- sourceStartSec: number;
- sourceEndSec: number;
- }
- | {
- kind: "extension";
- timelineStartSec: number;
- timelineEndSec: number;
- /** The word this media exists for. Its file is derived from the pair. */
- wordId: string;
- text: string;
- };
-
-/**
- * One clip, as the ordered list of media it actually plays.
- *
- * Added words split the clip's source window where they sit — at the END of the word they
- * follow — and their extension goes between the halves. A word outside the window belongs
- * to another clip of the same recording and is not this clip's business.
- *
- * `words` is the transcript of the clip's OWN asset; passing another's yields the clip
- * unsplit, which is the right answer rather than an error.
- */
-export function clipParts(clip: AxcutClip, words: readonly AxcutWord[]): ClipPart[] {
- const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;
- const parts: ClipPart[] = [];
- let timeline = clip.timelineStartSec;
- let from = clip.sourceStartSec;
-
- const added = words
- .filter(
- (word) =>
- isAddedWord(word) &&
- word.startSec > clip.sourceStartSec &&
- word.startSec <= sourceEnd &&
- extensionDurationSec(word.text) > 0,
- )
- .sort((a, b) => a.startSec - b.startSec);
-
- const pushRecording = (to: number) => {
- if (to - from <= 1e-6) return;
- parts.push({
- kind: "recording",
- timelineStartSec: timeline,
- timelineEndSec: timeline + (to - from),
- sourceStartSec: from,
- sourceEndSec: to,
- });
- timeline += to - from;
- from = to;
- };
-
- for (const word of added) {
- pushRecording(Math.min(word.startSec, sourceEnd));
- const durationSec = extensionDurationSec(word.text);
- parts.push({
- kind: "extension",
- timelineStartSec: timeline,
- timelineEndSec: timeline + durationSec,
- wordId: word.id,
- text: word.text,
- });
- timeline += durationSec;
- }
- pushRecording(sourceEnd);
-
- return parts;
-}
-
-/** Where the generated media for an added word lives.
- *
- * Beside the recording it was cut from, in a hidden sibling folder, and derived by pure
- * string work from the asset path and the word — so the renderer and the main process
- * arrive at the same path without asking each other. That is what keeps the file DERIVED:
- * no one stores it, anyone can name it, and the process that can spawn ffmpeg is the only
- * one that has to create it.
- *
- * The name carries the duration, so a re-typed word asks for a different file and a stale
- * one is simply never named again. */
-export function extensionClipPath(assetPath: string, wordId: string, durationSec: number): string {
- const sep = assetPath.includes("\\") ? "\\" : "/";
- const dir = assetPath.slice(0, Math.max(0, assetPath.lastIndexOf(sep)));
- return `${dir}${sep}${EXTENSIONS_DIR}${sep}${wordId}_${Math.round(durationSec * 1000)}.mp4`;
-}
-
-/** 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. */
+/** Marks every id an insertion owns — its asset and its clip share it. Never produced by
+ * anything else, so a reader can tell generated media from a recording at a glance. */
export const EXTENSION_ID_PREFIX = "ext:";
-/** The id an extension's media answers to. */
+/** The id an insertion's media answers to. */
export function extensionAssetId(wordId: string): string {
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 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.
- *
- * 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 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. */
export const EXTENSIONS_DIR = ".openscreen-extensions";
-/** What the clip's timeline length has to be, given its parts. The stored `timelineEndSec`
- * is this — the writer that adds a word is what keeps them equal. */
-export function partsLengthSec(parts: readonly ClipPart[]): number {
- if (parts.length === 0) return 0;
- return parts[parts.length - 1].timelineEndSec - parts[0].timelineStartSec;
-}
-
-/** The parts that carry source time. An extension has none, which is the whole point. */
-function recordings(parts: readonly ClipPart[]): Array<Extract<ClipPart, { kind: "recording" }>> {
- return parts.filter((p): p is Extract<ClipPart, { kind: "recording" }> => p.kind === "recording");
-}
-
-/**
- * A source second of the clip's media, as a second on the ruler. THE conversion.
- *
- * Every reader that writes `timelineStartSec + (sec - sourceStartSec)` is wrong the moment
- * the clip carries an extension: the seconds after one are pushed along by it, and the
- * reader lands everything early by the total inserted before it. That is one bug with one
- * home, not one per reader.
- *
- * A second sitting exactly where an insertion split maps to the moment AFTER the extension,
- * because that is where the recorded media of that second actually plays. The added word
- * itself never asks this question — it has no source second at all, and `extensionAt`
- * names its moment directly.
- */
-export function partsRawSec(parts: readonly ClipPart[], sourceSec: number): number {
- const played = recordings(parts);
- if (played.length === 0) return parts[0]?.timelineStartSec ?? sourceSec;
- let part = played[0];
- for (const candidate of played) {
- if (candidate.sourceStartSec <= sourceSec) part = candidate;
- }
- return part.timelineStartSec + (sourceSec - part.sourceStartSec);
-}
-
-/**
- * The inverse: a second on the ruler, as a second of the clip's media.
- *
- * Inside an extension the source clock is PARKED at the second the insertion split. That is
- * the honest answer — none of the recording plays there, and the split is the last second
- * that did.
- */
-export function partsSourceSec(parts: readonly ClipPart[], rawSec: number): number {
- const played = recordings(parts);
- if (played.length === 0) return rawSec;
- let part = played[0];
- for (const candidate of played) {
- if (candidate.timelineStartSec <= rawSec) part = candidate;
- }
- return Math.min(part.sourceEndSec, part.sourceStartSec + (rawSec - part.timelineStartSec));
-}
-
-/**
- * The added word being spoken at this moment on the ruler, if any.
- *
- * Asked of the parts directly rather than resolved through source time, where an extension
- * and the media that follows it share one second and nothing could tell them apart.
- */
-export function extensionAt(parts: readonly ClipPart[], rawSec: number): string | null {
- for (const part of parts) {
- if (part.kind !== "extension") continue;
- if (rawSec >= part.timelineStartSec && rawSec < part.timelineEndSec) return part.wordId;
- }
- return null;
-}
-
-/**
- * The ruler span of the extension inserted at this source second, if there is one.
+/** Where the generated media for an added word lives.
*
- * 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;
+ * Beside the recording, in a hidden sibling folder, and derived by pure string work from
+ * the asset path and the word — so the renderer and the main process arrive at the same
+ * path without asking each other. The name carries the duration, so a re-typed word asks
+ * for a different file and a stale one is simply never named again. */
+export function extensionClipPath(assetPath: string, wordId: string, durationSec: number): string {
+ const sep = assetPath.includes("\\") ? "\\" : "/";
+ const dir = assetPath.slice(0, Math.max(0, assetPath.lastIndexOf(sep)));
+ return `${dir}${sep}${EXTENSIONS_DIR}${sep}${wordId}_${Math.round(durationSec * 1000)}.mp4`;
}
diff --git a/src/lib/ai-edition/timeline/trim-mapping.ts b/src/lib/ai-edition/timeline/trim-mapping.ts
index 62a79b4ce..0dee56d7d 100644
--- a/src/lib/ai-edition/timeline/trim-mapping.ts
+++ b/src/lib/ai-edition/timeline/trim-mapping.ts
@@ -15,7 +15,6 @@
// 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";
@@ -47,10 +46,7 @@ export function trimAppliesToClip(
trim: TrimAnchor,
clip: Pick<AxcutClip, "id" | "assetId">,
): boolean {
- // `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);
+ if (trim.clipId !== undefined) return trim.clipId === clip.id;
return trim.assetId === clip.assetId;
}
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index ef6743476..ce22db0ed 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -40,7 +40,6 @@ 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 { 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,10 +520,7 @@ 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(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);
+export function resolveVisibleClips(document: AxcutDocument): PlaybackSegment[] {
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)
@@ -533,12 +529,9 @@ export function resolveVisibleClips(rawDocument: AxcutDocument): PlaybackSegment
/** Serialize a document into a {@link SceneDescription}. Pure — no per-frame math. */
export function buildSceneDescription(
- rawDocument: AxcutDocument,
+ document: 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]));
@@ -792,9 +785,7 @@ export function buildSceneDescription(
const captionAspect = outputDims.height > 0 ? outputDims.width / outputDims.height : 16 / 9;
const captionSettings = getCaptionSettings(document, captionAspect);
const captionRegions = captionCuesToTextRegions(
- // `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)),
+ deriveCaptionCues(document, captionSettings, getCaptionTranslations(document)),
captionSettings,
captionAspect,
);