Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(insertions): an insertion in a voice-over is a track fragment
EtienneLescotc8c8b7c7f0b5
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsxindex 79f9f2e00..b7f9562af 100644--- a/src/components/ai-edition/RightPanes.tsx+++ b/src/components/ai-edition/RightPanes.tsx@@ -1012,7 +1012,6 @@ export function TranscriptPane({{sections.map((section, idx) => (<TranscriptClipBlockkey={section.clip.id}- lane={activeLane}index={idx}section={section}busy={busyAssetIds.includes(section.clip.assetId)}@@ -1260,13 +1259,6 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({// timeline time (the pause gesture) it is a silent freeze frame. Drop this gate// when TTS lands.if (!import.meta.env.DEV) return;- // Not on the voiceover lane. `insertRangeSchema` has no `clipId`, and the pause an- // a voiceover placement has no clip to hold. Refused with a reason rather than- // left to write a record nothing can read.- if (lane === "voiceover") {- toast.error(ts("transcript.insertRecordingOnly"));- return;- }if (busy || !seed.trim()) return;const editor = editorRef.current;const selection = globalThis.getSelection();@@ -1278,7 +1270,7 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({if (!anchor) return;setInsertion({ ...anchor, draft: seed });},- [busy, lane, ts, words],+ [busy, words],);const commitInsertion = useCallback(() => {diff --git a/src/lib/ai-edition/document/audioTracks.ts b/src/lib/ai-edition/document/audioTracks.tsindex 33f25e904..19ca98964 100644--- a/src/lib/ai-edition/document/audioTracks.ts+++ b/src/lib/ai-edition/document/audioTracks.ts@@ -76,11 +76,53 @@ export function reanchorAudioTracks(): AxcutAudioTrack[] {// Coalesce back to one raw span per track FIRST: re-anchoring the stored// fragments individually would re-ventilate each one and multiply them.- return collapseTracksToPills(tracks).flatMap((track) =>+ //+ // Joined at the PILL level, before ventilation, for the same reason: ventilation+ // deliberately produces fragments that meet and whose offsets continue, so joining+ // after it would undo the split it just made.+ return joinContiguousTakes(collapseTracksToPills(tracks)).flatMap((track) =>anchorAudioTrackFragments(track, clips, makeId),);}+/**+ * Two takes that are one continuous stretch of one file are one take.+ *+ * The audio lane's half of the clip list's invariant, and it is what puts a take back+ * together when the insertion that split it is removed. Nothing marks the split: the two+ * halves meet on the ruler and the file continues across the join, which is all the+ * evidence there is and all there needs to be.+ */+function joinContiguousTakes(pills: AxcutAudioTrack[]): AxcutAudioTrack[] {+ const ordered = [...pills].sort((a, b) => a.startMs - b.startMs || a.id.localeCompare(b.id));+ const out: AxcutAudioTrack[] = [];+ for (const pill of ordered) {+ const previous = out[out.length - 1];+ if (previous && takesJoin(previous, pill)) {+ out[out.length - 1] = { ...previous, endMs: pill.endMs, fadeOutMs: pill.fadeOutMs };+ continue;+ }+ out.push(pill);+ }+ return out;+}++/** Same file, meeting on the ruler, and the file's own timecode continuing across the join —+ * plus every payload the two would otherwise have to disagree about. */+function takesJoin(left: AxcutAudioTrack, right: AxcutAudioTrack): boolean {+ const spanMs = left.endMs - left.startMs;+ return (+ left.assetId === right.assetId &&+ left.kind === right.kind &&+ !left.loop &&+ !right.loop &&+ left.gainDb === right.gainDb &&+ left.muted === right.muted &&+ Math.abs(left.endMs - right.startMs) < 1 &&+ Math.abs(left.offsetMs + spanMs - right.offsetMs) < 1+ );+}+/*** The user-visible tracks: fragments folded back into one span per `trackId`,* carrying the FIRST fragment's payload (its `offsetMs` is the track's realdiff --git a/src/lib/ai-edition/document/insertion.ts b/src/lib/ai-edition/document/insertion.tsindex 495869b7f..32a726294 100644--- a/src/lib/ai-edition/document/insertion.ts+++ b/src/lib/ai-edition/document/insertion.ts@@ -63,7 +63,7 @@ function anchorRulerSec(}/** `synth_N`, numbered past every generated asset the document already carries. */-function nextGeneratedWordId(document: AxcutDocument): string {+export function nextGeneratedWordId(document: AxcutDocument): string {let highest = 0;for (const asset of document.assets) {const match = /^ext:synth_(\d+)$/.exec(asset.id);@@ -74,13 +74,13 @@ function nextGeneratedWordId(document: AxcutDocument): string {/** 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 {+export 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(+export function generatedAsset(host: AxcutAsset,wordId: string,durationSec: number,@@ -98,7 +98,7 @@ function generatedAsset(};}-function generatedTranscript(+export function generatedTranscript(wordId: string,durationSec: number,text: string,diff --git a/src/lib/ai-edition/document/insertionTrack.test.ts b/src/lib/ai-edition/document/insertionTrack.test.tsnew file mode 100644index 000000000..cf5695464--- /dev/null+++ b/src/lib/ai-edition/document/insertionTrack.test.ts@@ -0,0 +1,172 @@+// The voice-over half of the insertion model. Same shape as the clips, different+// coordinates — and one rule that is the opposite of the clip lane's, pinned here because it+// was settled deliberately: a take insertion does NOT lengthen the film.++import { describe, expect, it } from "vitest";+import type { AxcutDocument } from "../schema";+import { collapseTracksToPills } from "./audioTracks";+import { insertGeneratedClip } from "./insertion";+import {+ insertGeneratedTrack,+ removeGeneratedTracks,+ retextGeneratedTrack,+} from "./insertionTrack";++const doc = (): 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,+ },+ { id: "vo", kind: "audio", label: "vo", originalPath: "C:/rec/vo.wav", cameraTrack: null },+ ],+ transcript: null,+ transcripts: [+ {+ assetId: "a1",+ language: "en",+ segments: [],+ words: [{ id: "w1", segmentId: "s1", startSec: 1, endSec: 4, text: "hello" }],+ },+ {+ assetId: "vo",+ language: "en",+ segments: [],+ words: [+ { id: "v1", segmentId: "s1", startSec: 1, endSec: 4, text: "spoken" },+ { id: "v2", segmentId: "s1", startSec: 6, endSec: 8, text: "later" },+ ],+ },+ ],+ timeline: {+ clips: [+ {+ id: "c1",+ assetId: "a1",+ sourceStartSec: 0,+ sourceEndSec: 20,+ timelineStartSec: 0,+ timelineEndSec: 20,+ wordRefs: [],+ origin: "user",+ reason: "",+ },+ ],+ gaps: [],+ trimRanges: [],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ annotations: [],+ zoomRanges: [],+ audioTracks: [+ {+ id: "t1",+ startMs: 2000,+ endMs: 12000,+ assetId: "vo",+ kind: "voiceover",+ durationSec: 10,+ offsetMs: 0,+ gainDb: 0,+ loop: false,+ fadeInMs: 200,+ fadeOutMs: 300,+ muted: false,+ label: "vo",+ origin: "user",+ },+ ],+ legacyEditor: null,+ }) as unknown as AxcutDocument;++/** Insert "hi" after `v1`, which ends at file second 4 — ruler second 6. */+const inserted = () => insertGeneratedTrack(doc(), "vo", "v1", "after", "hi");+const GEN_MS = 150;++const takes = (d: AxcutDocument) =>+ [...d.audioTracks]+ .sort((a, b) => a.startMs - b.startMs)+ .map((t) => ({+ assetId: t.assetId,+ startMs: t.startMs,+ endMs: t.endMs,+ offsetMs: t.offsetMs,+ }));++describe("insertGeneratedTrack", () => {+ it("cuts the take in two and puts the generated audio between the halves", () => {+ expect(takes(inserted())).toEqual([+ { assetId: "vo", startMs: 2000, endMs: 6000, offsetMs: 0 },+ { assetId: "ext:synth_1", startMs: 6000, endMs: 6000 + GEN_MS, offsetMs: 0 },+ // The file picks up where it stopped: 4s consumed, so the tail starts at 4s in.+ { assetId: "vo", startMs: 6000 + GEN_MS, endMs: 12000 + GEN_MS, offsetMs: 4000 },+ ]);+ });++ it("does NOT lengthen the film — that is the clips' business, and they did not move", () => {+ expect(inserted().timeline.clips).toEqual(doc().timeline.clips);+ });++ it("fades once at each real edge, not at the seam it just made", () => {+ const ordered = [...inserted().audioTracks].sort((a, b) => a.startMs - b.startMs);+ expect(ordered.map((t) => [t.fadeInMs, t.fadeOutMs])).toEqual([+ [200, 0],+ [0, 0],+ [0, 300],+ ]);+ });++ it("gives the generated audio its own transcript, to be read like any other", () => {+ const t = inserted().transcripts.find((x) => x.assetId === "ext:synth_1");+ expect(t?.words.map((w) => [w.text, w.source])).toEqual([["hi", "synth"]]);+ });+});++describe("removeGeneratedTracks", () => {+ it("puts the take back exactly as it was", () => {+ const back = removeGeneratedTracks(inserted(), ["synth_1"]);+ expect(takes(back)).toEqual([{ assetId: "vo", startMs: 2000, endMs: 12000, offsetMs: 0 }]);+ });++ it("takes the media it was the only user of with it", () => {+ const back = removeGeneratedTracks(inserted(), ["synth_1"]);+ expect(back.assets.some((a) => a.id === "ext:synth_1")).toBe(false);+ expect(back.transcripts.some((t) => t.assetId === "ext:synth_1")).toBe(false);+ });+});++describe("retextGeneratedTrack", () => {+ it("resizes it and pushes only what came after, by the difference", () => {+ const longer = retextGeneratedTrack(inserted(), "synth_1", "a much longer line");+ const spanMs = Math.round((("a much longer line".length / 15) as number) * 1000);+ expect(takes(longer)).toEqual([+ { assetId: "vo", startMs: 2000, endMs: 6000, offsetMs: 0 },+ { assetId: "ext:synth_1", startMs: 6000, endMs: 6000 + spanMs, offsetMs: 0 },+ { assetId: "vo", startMs: 6000 + spanMs, endMs: 12000 + spanMs, offsetMs: 4000 },+ ]);+ });+});++describe("the two lanes stay out of each other's way", () => {+ it("a word added to the FILM leaves the take's own span alone", () => {+ // Settled deliberately: the take has its own audio and keeps talking against a picture+ // that has slid. Its ruler span is re-anchored, never stretched.+ const before = doc();+ const after = insertGeneratedClip(before, "a1", "w1", "after", "hi");+ // The clips it covers became three, so the take is stored as three fragments — that is+ // ventilation, and it is what keeps a take playing continuously across a cut. What must+ // not change is the take itself: one pill, the same length, holding the same audio.+ const vo = collapseTracksToPills(after.audioTracks).filter((t) => t.assetId === "vo");+ expect(vo).toHaveLength(1);+ expect(vo[0].endMs - vo[0].startMs).toBe(10000);+ });+});diff --git a/src/lib/ai-edition/document/insertionTrack.ts b/src/lib/ai-edition/document/insertionTrack.tsnew file mode 100644index 000000000..eb7797124--- /dev/null+++ b/src/lib/ai-edition/document/insertionTrack.ts@@ -0,0 +1,228 @@+// An insertion in a VOICE-OVER is a track fragment.+//+// The same move as the recording lane one file over, in the coordinates a take has:+//+// [ take 0→5.3 ] [ generated 0→0.4 ] [ take 5.3→20.9 ]+//+// The take splits in two and the generated audio goes between the halves. Both halves keep+// the file seconds they always had; the right one's `offsetMs` advances by exactly what the+// left consumed, which is the repair `anchorAudioTrackFragments` already does for a take+// spanning two clips.+//+// Two rules the maintainer settled before this, and this respects both:+//+// - A recording-lane insertion does not touch a take. The take has its own audio and keeps+// talking against a picture that has slid.+// - A take insertion does NOT lengthen the programme. The clips decide the length. It+// pushes the take's later content later inside the SAME timeline, and whatever that+// pushes past the last frame is clamped at export, exactly as it always was.+//+// Undoing it is not spelled out here either: contiguous pills of one take whose file+// timecodes continue are one take, and `reanchorAudioTracks` folds them back.++import type { AxcutAudioTrack, AxcutDocument } from "../schema";++const EPS = 1e-6;++import { extensionAssetId, extensionDurationSec } from "../timeline/clip-parts";+import { removedRawSpans } from "../timeline/programme-time";+import { takeProgramme } from "../timeline/take-programme";+import { collapseTracksToPills, reanchorAudioTracks, trackGroupId } from "./audioTracks";+import { createId } from "./ids";+import {+ generatedAsset,+ generatedTranscript,+ hostAsset,+ type InsertSide,+ nextGeneratedWordId,+} from "./insertion";++/** The take that plays this asset and actually contains that second of its file. */+function takeFor(+ document: AxcutDocument,+ assetId: string,+ fileSec: number,+): { pill: AxcutAudioTrack; rawSec: number } | null {+ const removed = removedRawSpans(document.timeline.clips, document.timeline.trimRanges);+ for (const pill of collapseTracksToPills(document.audioTracks)) {+ if (pill.assetId !== assetId || pill.loop) continue;+ for (const piece of takeProgramme(pill, removed)) {+ if (fileSec < piece.sourceStartSec - EPS || fileSec > piece.sourceEndSec + EPS) continue;+ return { pill, rawSec: piece.rawStartSec + (fileSec - piece.sourceStartSec) };+ }+ }+ return null;+}++/** True when this asset is spoken by a take rather than played by a clip. */+export function isTrackAsset(document: AxcutDocument, assetId: string): boolean {+ return document.audioTracks.some((track) => track.assetId === assetId);+}++/**+ * Insert a word nobody said into a take, as a track of its own.+ *+ * The take is cut at that moment and the generated track goes between the halves. Everything+ * of the take that followed moves later by its length; nothing else on the timeline does.+ */+export function insertGeneratedTrack(+ 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 word = document.transcripts+ .find((t) => t.assetId === assetId)+ ?.words.find((w) => w.id === anchorWordId);+ if (!word) throw new Error(`Cannot insert beside word "${anchorWordId}": it has no transcript`);++ const found = takeFor(document, assetId, side === "after" ? word.endSec : word.startSec);+ if (!found) {+ throw new Error(`Cannot insert beside word "${anchorWordId}": no take speaks that moment`);+ }+ const { pill, rawSec } = found;++ const wordId = nextGeneratedWordId(document);+ const durationSec = extensionDurationSec(trimmed);+ const asset = generatedAsset(host, wordId, durationSec, trimmed);+ const atMs = Math.round(rawSec * 1000);+ const spanMs = Math.round(durationSec * 1000);++ // The take's own head and tail keep their fades; the generated stretch has neither.+ const left: AxcutAudioTrack = {+ ...pill,+ id: createId("take"),+ trackId: undefined,+ endMs: atMs,+ fadeOutMs: 0,+ };+ const generated: AxcutAudioTrack = {+ ...pill,+ id: asset.id,+ trackId: undefined,+ assetId: asset.id,+ label: trimmed.slice(0, 40),+ startMs: atMs,+ endMs: atMs + spanMs,+ offsetMs: 0,+ durationSec,+ fadeInMs: 0,+ fadeOutMs: 0,+ };+ const right: AxcutAudioTrack = {+ ...pill,+ id: createId("take"),+ trackId: undefined,+ startMs: atMs + spanMs,+ // The take is as long as the audio it holds, so its tail moves by the whole insertion.+ endMs: pill.endMs + spanMs,+ offsetMs: pill.offsetMs + (atMs - pill.startMs),+ fadeInMs: 0,+ };++ const kept = document.audioTracks.filter((t) => trackGroupId(t) !== trackGroupId(pill));+ const pieces = [left, generated, right].filter((t) => t.endMs - t.startMs > 0);+ return {+ ...document,+ assets: [...document.assets, asset],+ transcripts: [+ ...document.transcripts,+ generatedTranscript(+ wordId,+ durationSec,+ trimmed,+ document.transcripts.find((t) => t.assetId === assetId)?.language ?? "en",+ ),+ ],+ audioTracks: reanchorAudioTracks([...kept, ...pieces], document.timeline.clips, () =>+ createId("take"),+ ),+ };+}++/**+ * Delete inserted words spoken over a take.+ *+ * The exact inverse of the insertion: the generated track goes, and the half it pushed later+ * comes back by the same amount. The two halves then meet with the file continuing across the+ * join, which is all `reanchorAudioTracks` needs to fold them into one take again.+ *+ * A track lane is not re-laid the way the clip list is — pills hold absolute ruler positions —+ * so nothing closes this gap on its own. Only the pushed half moves: the insertion moved only+ * that, and taking it back has to be as narrow as making it was.+ */+export function removeGeneratedTracks(+ document: AxcutDocument,+ wordIds: readonly string[],+): AxcutDocument {+ return wordIds.reduce((next, wordId) => {+ const id = extensionAssetId(wordId);+ const generated = collapseTracksToPills(next.audioTracks).find((t) => t.assetId === id);+ if (!generated) return next;+ const spanMs = generated.endMs - generated.startMs;+ const pills = collapseTracksToPills(next.audioTracks)+ .filter((pill) => pill.assetId !== id)+ .map((pill) => shiftIfAfter(pill, generated.endMs, -spanMs));+ return {+ ...next,+ assets: next.assets.filter((a) => a.id !== id),+ transcripts: next.transcripts.filter((t) => t.assetId !== id),+ audioTracks: reanchorAudioTracks(pills, next.timeline.clips, () => createId("take")),+ };+ }, document);+}++/** The pill the insertion pushed: the one that starts where the generated stretch ends.+ * Nothing else on the lane moved when it was made, so nothing else moves now. */+function shiftIfAfter(pill: AxcutAudioTrack, atMs: number, deltaMs: number): AxcutAudioTrack {+ if (deltaMs === 0 || Math.abs(pill.startMs - atMs) > 1) return pill;+ return { ...pill, startMs: pill.startMs + deltaMs, endMs: pill.endMs + deltaMs };+}++/**+ * Rewrite the text of a word inserted into a take.+ *+ * Its length is its text, so the track resizes and the file it plays is renamed. Everything+ * of the take after it moves by the difference — the same push the insertion itself made.+ */+export function retextGeneratedTrack(+ document: AxcutDocument,+ wordId: string,+ text: string,+): AxcutDocument {+ const trimmed = text.trim();+ const id = extensionAssetId(wordId);+ const host = hostAsset(document);+ const current = document.audioTracks.find((t) => t.assetId === id);+ if (trimmed.length === 0 || !host || !current) return document;++ const durationSec = extensionDurationSec(trimmed);+ const spanMs = Math.round(durationSec * 1000);+ const deltaMs = spanMs - (current.endMs - current.startMs);+ const language = document.transcripts.find((t) => t.assetId === id)?.language ?? "en";++ const pills = collapseTracksToPills(document.audioTracks).map((pill) =>+ pill.assetId === id+ ? { ...pill, endMs: pill.startMs + spanMs, durationSec, label: trimmed.slice(0, 40) }+ : // Only the half the insertion pushed moves again, and only by the difference.+ shiftIfAfter(pill, current.endMs, deltaMs),+ );++ return {+ ...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,+ ),+ audioTracks: reanchorAudioTracks(pills, document.timeline.clips, () => createId("take")),+ };+}diff --git a/src/lib/ai-edition/document/transcript.ts b/src/lib/ai-edition/document/transcript.tsindex 6262803f6..1bfdb7ccf 100644--- a/src/lib/ai-edition/document/transcript.ts+++ b/src/lib/ai-edition/document/transcript.ts@@ -6,6 +6,12 @@ import {removeGeneratedClips,retextGeneratedClip,} from "./insertion";+import {+ insertGeneratedTrack,+ isTrackAsset,+ removeGeneratedTracks,+ retextGeneratedTrack,+} from "./insertionTrack";const CJK_EDGE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u;const CLOSING_PUNCTUATION = /^[,.;:!?%。,、;:!?…))\]}>》」』】〕]/u;@@ -147,9 +153,13 @@ 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);+ // An inserted word's length IS its text, so rewriting it resizes the clip — or the take+ // fragment — it plays on, and renames the file. Nothing a plain transcript write can say.+ if (isGeneratedAssetId(assetId)) {+ return isTrackAsset(document, assetId)+ ? retextGeneratedTrack(document, wordId, text)+ : 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`);@@ -168,7 +178,11 @@ export function insertDocumentWord(side: InsertSide,text: string,): AxcutDocument {- return insertGeneratedClip(document, assetId, anchorWordId, side, text);+ // Which lane the caret was in decides which shape the insertion takes — a clip in the+ // film, a fragment in the take. It is the only thing that differs between them.+ return isTrackAsset(document, assetId)+ ? insertGeneratedTrack(document, assetId, anchorWordId, side, text)+ : insertGeneratedClip(document, assetId, anchorWordId, side, text);}/** Delete inserted words, taking the whole set at once: a Backspace over several of them@@ -181,7 +195,8 @@ export function removeDocumentWords(_assetId: string,wordIds: readonly string[],): AxcutDocument {- return removeGeneratedClips(document, wordIds);+ // Each is a no-op for a word the other lane owns, so the set can span both.+ return removeGeneratedTracks(removeGeneratedClips(document, wordIds), wordIds);}/** What {@link carryOverWordEdits} managed to save from the previous transcript. */