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(timeline): one walk over a take, losing time to a cut and gaining it to a word
EtienneLescot889751bb5113
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.tsindex ab05856bb..463eb16fc 100644--- a/src/lib/ai-edition/document/timeline.ts+++ b/src/lib/ai-edition/document/timeline.ts@@ -326,6 +326,46 @@ function outputDurationOfRawSpan(return out;}+/**+ * The raw span that plays for `outSec` OUTPUT seconds starting at `fromRawSec` — the+ * inverse of {@link outputDurationOfRawSpan}, and the identity when nothing is sped up.+ *+ * A voice-over plays at 1x in the mix, so a pause for a spoken word is D seconds of the+ * take's own clock. Under a 2x region that is 2 raw seconds, not 1, and getting it wrong+ * puts the resumed narration half a pause out of step with the picture.+ */+export function rawSpanForOutDuration(+ fromRawSec: number,+ outSec: number,+ speedRegions: PlaybackSpeedRegion[] = [],+): number {+ if (!(outSec > 0)) return 0;+ if (speedRegions.length === 0) return outSec;+ // Walk the regions from the head, spending output budget piecewise.+ const edges = [+ ...new Set(+ speedRegions+ .flatMap((r) => [r.startMs / 1000, r.endMs / 1000])+ .filter((edge) => edge > fromRawSec),+ ),+ ].sort((a, b) => a - b);+ let raw = fromRawSec;+ let left = outSec;+ for (const edge of [...edges, Number.POSITIVE_INFINITY]) {+ const mid = raw + Math.min(1e-6, (edge - raw) / 2);+ const region = speedRegions.find(+ (r) => mid >= r.startMs / 1000 && mid < r.endMs / 1000 && r.speed > 0,+ );+ const speed = region?.speed ?? 1;+ const rawAvailable = edge - raw;+ const outAvailable = rawAvailable / speed;+ if (outAvailable >= left) return raw + left * speed - fromRawSec;+ raw = edge;+ left -= outAvailable;+ }+ return raw - fromRawSec;+}+export function projectRawTimelineSecToPlayback(clips: AxcutClip[],trimRanges: AxcutTrimRange[],diff --git a/src/lib/ai-edition/timeline/take-programme.test.ts b/src/lib/ai-edition/timeline/take-programme.test.tsnew file mode 100644index 000000000..cd93690bb--- /dev/null+++ b/src/lib/ai-edition/timeline/take-programme.test.ts@@ -0,0 +1,184 @@+// Issue #560. A take loses time to a cut and gains it to an insertion, and the two must be+// one walk: resolved in two passes, an insertion's raw moment would be computed without the+// holds before it and land in the wrong place.+//+// The load-bearing property is the demotion: with no insertions this must agree with+// `subtractRemoved` exactly, because that is what the export and the preview already do and+// their answers must not move.++import { describe, expect, it } from "vitest";+import { rawSpanForOutDuration } from "../document/timeline";+import type { AxcutAudioTrack, AxcutClip, AxcutTrimRange } from "../schema";+import { removedRawSpans, subtractRemoved } from "./programme-time";+import { consumedSourceSec, takePlaybackAt, takeProgramme } from "./take-programme";++const CLIPS: AxcutClip[] = [+ {+ id: "c1",+ assetId: "rec",+ sourceStartSec: 0,+ sourceEndSec: 20,+ timelineStartSec: 0,+ timelineEndSec: 20,+ wordRefs: [],+ origin: "user",+ reason: "",+ },+];++const trim = (startSec: number, endSec: number, id = "t1"): AxcutTrimRange =>+ ({+ id,+ assetId: "rec",+ clipId: "c1",+ startSec,+ endSec,+ origin: "user",+ reason: "",+ }) as AxcutTrimRange;++/** A take from raw 0 to raw 10, reading its file from the head. */+const TAKE = { startMs: 0, endMs: 10_000, offsetMs: 0 } as Pick<+ AxcutAudioTrack,+ "startMs" | "endMs" | "offsetMs"+>;++const ins = (atSourceSec: number, durationSec: number, id = "i1") => ({+ id,+ wordId: `w_${id}`,+ atSourceSec,+ durationSec,+});++const shape = (pieces: ReturnType<typeof takeProgramme>) =>+ pieces.map((p) => [p.kind, p.rawStartSec, p.rawEndSec, p.sourceStartSec, p.sourceEndSec]);++describe("takeProgramme", () => {+ it("is exactly subtractRemoved when nothing is inserted", () => {+ // The demotion. Every fixture the export and the preview already agree on has to+ // keep its current answer.+ for (const cuts of [+ [] as AxcutTrimRange[],+ [trim(3, 5)],+ [trim(0, 2)],+ [trim(8, 12)],+ [trim(2, 3), trim(6, 7, "t2")],+ ]) {+ const removed = removedRawSpans(CLIPS, cuts);+ const played = takeProgramme(TAKE, removed, [])+ .filter((p) => p.kind === "play")+ .map((p) => [p.rawStartSec, p.rawEndSec]);+ const expected = subtractRemoved(0, 10, removed).map((s) => [s.startSec, s.endSec]);+ expect(played).toEqual(expected);+ }+ });++ it("parks the voice for an insertion and resumes on the same word", () => {+ const pieces = takeProgramme(TAKE, [], [ins(4, 1)]);+ expect(shape(pieces)).toEqual([+ ["play", 0, 4, 0, 4],+ ["hold", 4, 5, 4, 4],+ ["play", 5, 10, 4, 9],+ ]);+ // The take consumed 9 seconds of its file, not 10: the second the pause took is+ // pushed off the end and lost, which is the accepted cost of the clips deciding+ // the length.+ expect(consumedSourceSec(pieces)).toBeCloseTo(9, 6);+ });++ it("resolves the second insertion AFTER the first one's hold, not before it", () => {+ // The case a two-pass design gets wrong: mapped up front, source 6 would be raw 6,+ // which is inside the first hold.+ const pieces = takeProgramme(TAKE, [], [ins(4, 1, "a"), ins(6, 1, "b")]);+ expect(shape(pieces)).toEqual([+ ["play", 0, 4, 0, 4],+ ["hold", 4, 5, 4, 4],+ ["play", 5, 7, 4, 6],+ ["hold", 7, 8, 6, 6],+ ["play", 8, 10, 6, 8],+ ]);+ });++ it("makes two insertions at one moment two adjacent holds, with no empty play between", () => {+ const pieces = takeProgramme(TAKE, [], [ins(4, 1, "a"), ins(4, 0.5, "b")]);+ expect(pieces.map((p) => p.kind)).toEqual(["play", "hold", "hold", "play"]);+ expect(pieces.filter((p) => p.kind === "hold").map((p) => p.holdId)).toEqual(["a", "b"]);+ expect(pieces.some((p) => p.rawEndSec === p.rawStartSec)).toBe(false);+ });++ it("gives nothing to an insertion a cut swallowed", () => {+ const removed = removedRawSpans(CLIPS, [trim(3, 6)]);+ const withIt = takeProgramme(TAKE, removed, [ins(4, 1)]);+ const without = takeProgramme(TAKE, removed, []);+ // The moment it holds is not in the film any more, so it buys no time.+ expect(withIt.some((p) => p.kind === "hold")).toBe(false);+ expect(shape(withIt)).toEqual(shape(without));+ });++ it("keeps an insertion on a cut's far edge, which is what follows the cut", () => {+ const removed = removedRawSpans(CLIPS, [trim(3, 6)]);+ const pieces = takeProgramme(TAKE, removed, [ins(6, 1)]);+ expect(pieces.map((p) => p.kind)).toEqual(["play", "removed", "hold", "play"]);+ });++ it("drops an insertion at or past the take's last moment", () => {+ expect(takeProgramme(TAKE, [], [ins(10, 1)]).some((p) => p.kind === "hold")).toBe(false);+ expect(takeProgramme(TAKE, [], [ins(30, 1)]).some((p) => p.kind === "hold")).toBe(false);+ });++ it("ignores an insertion of no duration", () => {+ expect(takeProgramme(TAKE, [], [ins(4, 0)]).map((p) => p.kind)).toEqual(["play"]);+ });++ it("spends a pause on the take's own clock under a speed region", () => {+ // A voice plays at 1x in the mix. Under a 2x region a one-second pause has to eat+ // TWO raw seconds to last one second of programme.+ const speed = [{ startMs: 0, endMs: 20_000, speed: 2 }];+ const pieces = takeProgramme(TAKE, [], [ins(4, 1)], speed);+ const hold = pieces.find((p) => p.kind === "hold");+ expect(hold && hold.rawEndSec - hold.rawStartSec).toBeCloseTo(2, 6);+ });+});++describe("rawSpanForOutDuration", () => {+ it("is the identity with no regions", () => {+ expect(rawSpanForOutDuration(3, 2)).toBe(2);+ });++ it("inverts outputDurationOfRawSpan across a boundary", () => {+ const speed = [{ startMs: 4000, endMs: 8000, speed: 2 }];+ // From raw 3: one output second buys 1 raw second before the region, then the rest+ // at 2x. Two output seconds = 1 + 2 = 3 raw seconds.+ expect(rawSpanForOutDuration(3, 2, speed)).toBeCloseTo(3, 6);+ });++ it("returns zero for a non-positive duration", () => {+ expect(rawSpanForOutDuration(0, 0)).toBe(0);+ expect(rawSpanForOutDuration(0, -1)).toBe(0);+ });+});++describe("takePlaybackAt", () => {+ const pieces = takeProgramme(TAKE, removedRawSpans(CLIPS, [trim(7, 8)]), [ins(4, 1)]);++ it("plays the file where the file plays", () => {+ expect(takePlaybackAt(pieces, 2)).toMatchObject({ targetTimeSec: 2, shouldPlay: true });+ });++ it("parks on one moment inside the pause rather than tracking a moving target", () => {+ expect(takePlaybackAt(pieces, 4.5)).toMatchObject({+ targetTimeSec: 4,+ shouldPlay: false,+ heldBy: "i1",+ });+ });++ it("keeps the clock running through a cut, silently", () => {+ // Raw 7.5 is one second past the pause, so the file is at 6.5 — and muted.+ expect(takePlaybackAt(pieces, 7.5)).toMatchObject({ targetTimeSec: 6.5, shouldPlay: false });+ });++ it("has nothing to say outside the take", () => {+ expect(takePlaybackAt(pieces, 12)).toBeNull();+ });+});diff --git a/src/lib/ai-edition/timeline/take-programme.ts b/src/lib/ai-edition/timeline/take-programme.tsnew file mode 100644index 000000000..828055f03--- /dev/null+++ b/src/lib/ai-edition/timeline/take-programme.ts@@ -0,0 +1,217 @@+// One walk over a voice-over take (issue #560).+//+// A take is subject to two opposite forces at once and they must not be two passes. A CUT+// under it takes time away — step 3 already slices the mix by `removedRawSpans`. An+// INSERTION inside it adds time: a word added to the take's transcript needs somewhere to+// be spoken, so the voice stops and resumes on the same word.+//+// What this walk deliberately does NOT do:+//+// - It does not react to an insertion in the RECORDING lane. A word added to the film+// freezes the picture; the take has its own audio and keeps talking, finishing that+// much earlier against a picture that has slid. The maintainer settled this: "the+// voice-over is not impacted by the insertion in the recording track". A take is as+// long as the audio it holds, and nothing under it changes that.+// - It does not lengthen the programme. The clips decide the length, full stop. A take+// insertion pushes the take's later content later inside the SAME timeline, and+// whatever that pushes past the last frame is lost at export — `mix_external_tracks`+// clamps every track to the programme. Placing content inside the useful span of the+// timeline is the user's job.+//+// It runs on the PILL, never on a stored fragment. The document stores one fragment per+// clip a take covers; growing one fragment leaves its successor's head where it was, and+// the mixer sums with `+=` at an absolute offset — so a fragment-wise walk ships a take+// playing on top of itself. `anchorAudioTrackFragments` is untouched and stays correct for+// the music and loop paths that still read it.++import type { PlaybackSpeedRegion } from "../document/timeline";+import { rawSpanForOutDuration } from "../document/timeline";+import type { AxcutAudioTrack } from "../schema";+import type { RemovedRawSpan } from "./programme-time";++/** One stretch of a take, in playback order. */+export interface TakePiece {+ /**+ * `play` — the file is heard. `hold` — the voice is parked on one source moment while+ * the timeline runs on (an insertion). `removed` — the film lost this stretch, so the+ * take is silent through it, its own clock still running underneath.+ */+ kind: "play" | "hold" | "removed";+ /** Stored RAW ruler seconds. Insertions occupy raw time here because they consume it+ * from the take's own span — they do not create programme time. */+ rawStartSec: number;+ rawEndSec: number;+ /** The take's own file. Equal on a `hold`: the moment the voice is parked on. */+ sourceStartSec: number;+ sourceEndSec: number;+ /** The insertion that produced a `hold`. */+ holdId?: string;+ /** The word that insertion exists for. */+ wordId?: string;+}++/** An insertion inside one take, in the take's own source seconds. */+export interface TakeInsert {+ id: string;+ wordId: string;+ atSourceSec: number;+ /** OUTPUT seconds. A voice plays at 1x in the mix, so a pause for a spoken word is+ * measured on the take's own clock, not on a raw ruler a speed region compresses. */+ durationSec: number;+}++const EPSILON_SEC = 1e-9;++/**+ * The take, stretch by stretch, in playback order.+ *+ * Both cursors advance together except inside a `hold`, where the source parks. A `removed`+ * stretch advances BOTH — the cut mutes the take without rewinding it, which is what keeps+ * the words after a cut landing on the picture they belong to (the behaviour step 3 shipped+ * and its tests pin).+ *+ * With no insertions this reduces exactly to `subtractRemoved` over the take's span, which+ * is the property that lets the export and the preview keep their current answers.+ */+export function takeProgramme(+ pill: Pick<AxcutAudioTrack, "startMs" | "endMs" | "offsetMs">,+ removed: readonly RemovedRawSpan[],+ inserts: readonly TakeInsert[],+ speedRegions: PlaybackSpeedRegion[] = [],+): TakePiece[] {+ const rawStart = pill.startMs / 1000;+ const rawEnd = Math.max(rawStart, pill.endMs / 1000);+ const sourceStart = Math.max(0, pill.offsetMs / 1000);++ // Every boundary the walk has to stop at, on the RAW ruler, resolved sequentially:+ // an insertion's raw moment depends on the holds before it, so it cannot be mapped in+ // one pass up front.+ const pending = [...inserts]+ .filter((ins) => ins.durationSec > 0)+ .sort((a, b) => a.atSourceSec - b.atSourceSec || a.id.localeCompare(b.id));++ const cuts = [...removed]+ .filter((span) => span.endSec > rawStart && span.startSec < rawEnd)+ .sort((a, b) => a.startSec - b.startSec);++ const pieces: TakePiece[] = [];+ let raw = rawStart;+ let source = sourceStart;+ let nextInsert = 0;+ let nextCut = 0;++ const push = (kind: TakePiece["kind"], rawTo: number, sourceTo: number, ins?: TakeInsert) => {+ if (rawTo - raw <= EPSILON_SEC) return;+ pieces.push({+ kind,+ rawStartSec: raw,+ rawEndSec: rawTo,+ sourceStartSec: source,+ sourceEndSec: sourceTo,+ ...(ins ? { holdId: ins.id, wordId: ins.wordId } : {}),+ });+ raw = rawTo;+ source = sourceTo;+ };++ // A hang is the worst failure a renderer can have. This loop terminates because every+ // pass either advances `raw` or consumes a boundary, so the passes are bounded by the+ // boundary count — but that is an argument, and an argument is not a guarantee. A+ // mutation of the boundary arithmetic span it forever rather than failing an assertion,+ // so the bound is enforced. Counting passes rather than watching `raw` on purpose: a+ // pass that consumes a zero-length insertion makes real progress without moving `raw`,+ // and a no-progress test would cut the walk short on a legitimate document.+ const maxPasses = 4 * (removed.length + inserts.length + 2);+ let passes = 0;+ while (raw < rawEnd - EPSILON_SEC) {+ if (passes++ > maxPasses) break;+ // Skip cuts and insertions the walk has already passed.+ while (nextCut < cuts.length && cuts[nextCut].endSec <= raw + EPSILON_SEC) nextCut++;+ while (nextInsert < pending.length && pending[nextInsert].atSourceSec <= source - EPSILON_SEC) {+ // Its moment is behind the source cursor: a cut swallowed it, or two inserts+ // share a moment and the first already consumed it. Either way it buys nothing.+ nextInsert++;+ }++ const cut = cuts[nextCut];+ const insert = pending[nextInsert];++ // Sitting exactly on an insertion's moment: hold before anything else, so two+ // inserts at one moment become two adjacent holds rather than one merged stretch.+ if (insert && insert.atSourceSec <= source + EPSILON_SEC) {+ const held = Math.min(+ rawSpanForOutDuration(raw, insert.durationSec, speedRegions),+ rawEnd - raw,+ );+ nextInsert++;+ if (held > EPSILON_SEC) {+ pieces.push({+ kind: "hold",+ rawStartSec: raw,+ rawEndSec: raw + held,+ sourceStartSec: source,+ sourceEndSec: source,+ holdId: insert.id,+ wordId: insert.wordId,+ });+ raw += held;+ }+ continue;+ }++ // Inside a cut: silent to the cut's end, both cursors running.+ if (cut && cut.startSec <= raw + EPSILON_SEC) {+ const to = Math.min(cut.endSec, rawEnd);+ push("removed", to, source + (to - raw));+ continue;+ }++ // Otherwise play up to whichever boundary comes first.+ let to = rawEnd;+ if (cut) to = Math.min(to, cut.startSec);+ if (insert) to = Math.min(to, raw + (insert.atSourceSec - source));+ push("play", Math.max(raw, to), source + (Math.max(raw, to) - raw));+ }++ return pieces;+}++/** The take's stretch of raw ruler, or null when it has none. */+export function takeRulerExtent(pieces: readonly TakePiece[]): {+ startSec: number;+ endSec: number;+} | null {+ if (pieces.length === 0) return null;+ return { startSec: pieces[0].rawStartSec, endSec: pieces[pieces.length - 1].rawEndSec };+}++/**+ * Seconds of the take's FILE the walk consumes.+ *+ * Deliberately not called `spanSec`: that name already means the trim-projected OUTPUT span+ * at the preview's call site, and the fades are measured against the consumed source — feed+ * them a span grown by a hold and the fade-out starts early in the preview only.+ */+export function consumedSourceSec(pieces: readonly TakePiece[]): number {+ return pieces.reduce((sum, piece) => sum + (piece.sourceEndSec - piece.sourceStartSec), 0);+}++/** Where the voice is, and whether it is heard, at a raw moment. */+export function takePlaybackAt(+ pieces: readonly TakePiece[],+ rawSec: number,+): { targetTimeSec: number; shouldPlay: boolean; heldBy?: string } | null {+ for (const piece of pieces) {+ if (rawSec < piece.rawStartSec) break;+ if (rawSec >= piece.rawEndSec) continue;+ if (piece.kind === "hold") {+ // Parked on ONE source moment, not clamped to a moving target: resuming from the+ // post-insert source would restart the narration on the wrong word, and a target+ // that drifts every frame would re-seek a paused element every frame.+ return { targetTimeSec: piece.sourceStartSec, shouldPlay: false, heldBy: piece.holdId };+ }+ const target = piece.sourceStartSec + (rawSec - piece.rawStartSec);+ return { targetTimeSec: target, shouldPlay: piece.kind === "play" };+ }+ return null;+}