Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(audio): keep tracks at 1x and in place under speed regions
Ola Adebayo13562443ef4c
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsxindex 3994c8f29..326bbd642 100644--- a/src/components/ai-edition/VirtualPreview.tsx+++ b/src/components/ai-edition/VirtualPreview.tsx@@ -635,10 +635,16 @@ export function VirtualPreview({// applies the global gain on top, matching the export); the `.volume` path is// the fallback for when the graph is unavailable — there a boost caps at 0 dB.const globalGain = audioGainScalar(audioGainDbRef.current);+ // Speed-aware: under a 2x region the raw playhead races, and a projection+ // blind to speed raced the audio's target position with it — the track+ // was never given a faster `playbackRate`, but seeking it twice as fast+ // amounts to the same thing. Dividing raw time by the rate turns that+ // back into 1x wall-clock, which is what the render does too.const outputTimeSec = projectRawTimelineSecToPlayback(clipsRef.current,trimRangesRef.current,virtualTimeSecRef.current,+ speedRegionsRef.current,);for (const track of audioTracksRef.current) {const el = audioTrackElsRef.current.get(track.id);@@ -647,19 +653,26 @@ export function VirtualPreview({clipsRef.current,trimRangesRef.current,track.startMs / 1000,+ speedRegionsRef.current,);- // The span on the OUTPUT programme, not the raw ruler: both ends go- // through the same projection the head does. A track buried inside a- // trimmed stretch collapses to zero length and stays silent, instead- // of playing its full raw length parked at the cut — audible with- // nothing on screen to explain it.+ // Length is measured WITHOUT speed, position WITH it. A trim REMOVES+ // timeline — a track buried in one has zero length and stays silent,+ // rather than playing its full raw length parked at the cut. A speed+ // region only COMPRESSES: the track still holds all its audio and+ // still plays at 1x, so it must not be cut short because the video+ // under it was sped up.const spanSec = Math.max(0,projectRawTimelineSecToPlayback(clipsRef.current,trimRangesRef.current,track.endMs / 1000,- ) - outputStartSec,+ ) -+ projectRawTimelineSecToPlayback(+ clipsRef.current,+ trimRangesRef.current,+ track.startMs / 1000,+ ),);const trackTarget = resolveTimelineAudioPlayback(outputTimeSec,diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.tsindex af6e056ce..06f83943d 100644--- a/src/lib/ai-edition/document/timeline.test.ts+++ b/src/lib/ai-edition/document/timeline.test.ts@@ -1683,3 +1683,56 @@ describe("a malformed legacyEditor envelope", () => {expect(next.legacyEditor).toEqual({ speedRegions: null, cameraFullscreenRegions: 42 });});});++describe("projectRawTimelineSecToPlayback with speed regions", () => {+ const clip: AxcutClip = {+ id: "c1",+ assetId: "a1",+ sourceStartSec: 0,+ sourceEndSec: 20,+ timelineStartSec: 0,+ timelineEndSec: 20,+ wordRefs: [],+ origin: "user",+ reason: "",+ };++ it("is the identity when nothing is sped up", () => {+ expect(projectRawTimelineSecToPlayback([clip], [], 8, [])).toBeCloseTo(8, 6);+ });++ it("halves the time a 2x stretch takes to play", () => {+ // Raw 4..8 at 2x plays in 2s, so raw 8 lands at output 6.+ const speed = [{ startMs: 4000, endMs: 8000, speed: 2 }];+ expect(projectRawTimelineSecToPlayback([clip], [], 4, speed)).toBeCloseTo(4, 6);+ expect(projectRawTimelineSecToPlayback([clip], [], 6, speed)).toBeCloseTo(5, 6);+ expect(projectRawTimelineSecToPlayback([clip], [], 8, speed)).toBeCloseTo(6, 6);+ // Everything after carries the compression with it.+ expect(projectRawTimelineSecToPlayback([clip], [], 12, speed)).toBeCloseTo(10, 6);+ });++ it("stretches a slow-motion region instead", () => {+ const speed = [{ startMs: 0, endMs: 4000, speed: 0.5 }];+ expect(projectRawTimelineSecToPlayback([clip], [], 4, speed)).toBeCloseTo(8, 6);+ });++ it("composes with trims", () => {+ // Raw 2..4 cut, then raw 6..10 at 2x. Raw 12 = 2 kept + 2 kept + 2 (4s at 2x)+ // + 2 = output 8.+ const trim: AxcutTrimRange = {+ id: "t1",+ assetId: "a1",+ startSec: 2,+ endSec: 4,+ origin: "user",+ reason: "",+ };+ const speed = [{ startMs: 6000, endMs: 10_000, speed: 2 }];+ expect(projectRawTimelineSecToPlayback([clip], [trim], 12, speed)).toBeCloseTo(8, 6);+ });++ it("ignores a nonsense rate rather than dividing by it", () => {+ const speed = [{ startMs: 0, endMs: 4000, speed: 0 }];+ expect(projectRawTimelineSecToPlayback([clip], [], 4, speed)).toBeCloseTo(4, 6);+ });+});diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.tsindex 3cae3e665..987e91dc2 100644--- a/src/lib/ai-edition/document/timeline.ts+++ b/src/lib/ai-edition/document/timeline.ts@@ -225,18 +225,69 @@ export function resolvePlaybackSegments(* delayed every track by the total trim duration ahead of it. The preview already lands them* correctly because its playhead jumps across trims; this makes the render agree.*/+export interface PlaybackSpeedRegion {+ startMs: number;+ endMs: number;+ speed: number;+}++/**+ * Output seconds a raw interval `[fromSec, toSec)` occupies once the speed+ * regions covering it are applied: a 2x stretch of raw time takes half as long+ * to play, so it contributes half its raw length to the programme.+ *+ * Subdivides at every speed boundary the interval crosses and integrates+ * `1 / speed` piecewise. Regions are matched on the raw ruler, the same+ * coordinate their pills are drawn in.+ */+function outputDurationOfRawSpan(+ fromSec: number,+ toSec: number,+ speedRegions: PlaybackSpeedRegion[],+): number {+ if (toSec <= fromSec) return 0;+ if (speedRegions.length === 0) return toSec - fromSec;+ // Every boundary inside the span, so each piece has one constant speed.+ const cuts = new Set<number>([fromSec, toSec]);+ for (const region of speedRegions) {+ for (const edge of [region.startMs / 1000, region.endMs / 1000]) {+ if (edge > fromSec && edge < toSec) cuts.add(edge);+ }+ }+ const edges = [...cuts].sort((a, b) => a - b);+ let out = 0;+ for (let i = 0; i < edges.length - 1; i++) {+ const start = edges[i];+ const end = edges[i + 1];+ const mid = (start + end) / 2;+ const region = speedRegions.find(+ (r) => mid >= r.startMs / 1000 && mid < r.endMs / 1000 && r.speed > 0,+ );+ out += (end - start) / (region?.speed ?? 1);+ }+ return out;+}+export function projectRawTimelineSecToPlayback(clips: AxcutClip[],trimRanges: AxcutTrimRange[],rawSec: number,+ /**+ * Speed regions on the raw ruler. Supplied by the AUDIO paths, which overlay+ * a 1x track onto the finished programme and so need its real, speed-adjusted+ * clock; omitted by callers that only care about trims. Left out, the+ * projection behaves exactly as it did before speed was modelled.+ */+ speedRegions: PlaybackSpeedRegion[] = [],): number {const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);let outCursor = 0; // output length of the kept content walked so farlet lastRawEnd = 0; // raw end of the last kept segment, for the trailing overhanglet landed: number | null = null; // output(rawSec), once it falls in/before a kept segment- // Each kept segment as a raw extent `{ rawStart, dur }`; its output duration equals `dur`- // (trims only remove, they don't scale — speed is the separate approximation noted above).+ // Each kept segment as a raw extent `{ rawStart, dur }`. Trims only REMOVE, so a kept+ // segment's raw length survives here; how long it takes to PLAY is a separate question+ // that `outputDurationOfRawSpan` answers, because a speed region scales it.const keptSegments = (clip: AxcutClip): Array<{ rawStart: number; dur: number }> => {const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;if (sourceEnd <= clip.sourceStartSec) {@@ -264,11 +315,11 @@ export function projectRawTimelineSecToPlayback(const rawEnd = seg.rawStart + seg.dur;if (landed === null && rawSec < rawEnd) {// `rawSec` is inside this segment, or before it in a trimmed/gap region (then- // `within` clamps to 0 → the output edge just before the gap).- const within = Math.min(Math.max(rawSec - seg.rawStart, 0), seg.dur);- landed = outCursor + within;+ // the span clamps to nothing → the output edge just before the gap).+ const within = Math.min(Math.max(rawSec, seg.rawStart), rawEnd);+ landed = outCursor + outputDurationOfRawSpan(seg.rawStart, within, speedRegions);}- outCursor += seg.dur;+ outCursor += outputDurationOfRawSpan(seg.rawStart, rawEnd, speedRegions);lastRawEnd = rawEnd;}}diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.tsindex 0f7eb9dfe..01c656967 100644--- a/src/native/sceneDescription.test.ts+++ b/src/native/sceneDescription.test.ts@@ -2152,6 +2152,62 @@ describe("buildSceneDescription.audioTracks", () => {expect(entry.trimEndSec - entry.trimStartSec).toBeCloseTo(6, 6);});+ it("places a track after a speed region on the compressed clock", () => {+ // The programme is time-stretched before the tracks are mixed onto it+ // (`stretch_clip_pcm_by_speed` then `mix_external_tracks`), so raw 12 with+ // raw 4..8 at 2x is output 10. Blind to speed the track landed at 12 —+ // two seconds late, and later still the more the video is sped up.+ const screen = makeAsset({ id: "scr", originalPath: "/screen.mp4", durationSec: 20 });+ const doc = makeDoc({+ assets: [screen, audioAsset],+ clips: [+ makeClip({+ id: "c1",+ assetId: "scr",+ sourceStartSec: 0,+ sourceEndSec: 20,+ timelineStartSec: 0,+ timelineEndSec: 20,+ }),+ ],+ legacyEditor: { speedRegions: [{ id: "s1", startMs: 4000, endMs: 8000, speed: 2 }] },+ audioTracks: [{ ...track, startMs: 12_000, endMs: 16_000, offsetMs: 0 }],+ });+ const [entry] = buildSceneDescription(doc).audioTracks;+ expect(entry.startSec).toBeCloseTo(10, 6);+ // ...and the track itself is NOT stretched: 4 raw seconds of audio stay 4+ // seconds of source, whatever the video under it is doing.+ expect(entry.trimEndSec - entry.trimStartSec).toBeCloseTo(4, 6);+ });++ it("does not shorten a track just because the video under it is sped up", () => {+ // A speed region compresses the programme; it does not delete anything. The+ // track still holds all its audio and still plays at 1x, so a 4s voiceover+ // under a 2x region is still 4s of narration — measuring its length on the+ // compressed clock silently cut it in half.+ const screen = makeAsset({ id: "scr", originalPath: "/screen.mp4", durationSec: 20 });+ const doc = makeDoc({+ assets: [screen, audioAsset],+ clips: [+ makeClip({+ id: "c1",+ assetId: "scr",+ sourceStartSec: 0,+ sourceEndSec: 20,+ timelineStartSec: 0,+ timelineEndSec: 20,+ }),+ ],+ legacyEditor: { speedRegions: [{ id: "s1", startMs: 2000, endMs: 10_000, speed: 2 }] },+ audioTracks: [{ ...track, startMs: 4000, endMs: 8000, offsetMs: 0 }],+ });+ const [entry] = buildSceneDescription(doc).audioTracks;+ expect(entry.trimEndSec - entry.trimStartSec).toBeCloseTo(4, 6);+ // Its head still moves onto the compressed clock: raw 4 is 1s into a 2x+ // stretch that began at raw 2, so output 3.+ expect(entry.startSec).toBeCloseTo(3, 6);+ });+it("drops a track whose asset has no resolvable path", () => {const doc = makeDoc({ assets: [], audioTracks: [track] });expect(buildSceneDescription(doc).audioTracks).toEqual([]);diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.tsindex 641ce86ce..0d214831b 100644--- a/src/native/sceneDescription.ts+++ b/src/native/sceneDescription.ts@@ -31,6 +31,7 @@ import {import { createId } from "@/lib/ai-edition/document/ids";import { pickOutputDims } from "@/lib/ai-edition/document/outputFormat";import {+ type PlaybackSpeedRegion,projectRawTimelineSecToPlayback,resolvePlaybackSegments,} from "@/lib/ai-edition/document/timeline";@@ -544,6 +545,17 @@ export function buildSceneDescription(const projectedClips = document.timeline.clips.filter((clip) =>clipAssetIsResolvable(clip, assetById),);+ // Speed regions on the RAW ruler. The programme these tracks mix onto has+ // already been time-stretched by them (`stretch_clip_pcm_by_speed` runs before+ // `mix_external_tracks`), so a projection blind to speed lands every track+ // after a speed region at the wrong second. The tracks themselves are never+ // stretched — a voiceover should not chipmunk because the video under it was+ // sped up.+ const rawSpeedRegions = (+ ((document.legacyEditor as Record<string, unknown> | null)?.speedRegions as+ | PlaybackSpeedRegion[]+ | undefined) ?? []+ ).filter((r) => Number.isFinite(r.speed) && r.speed > 0);const audioTracks = document.audioTracks.flatMap((track) => {if (track.muted) return [];const asset = assetById.get(track.assetId);@@ -554,18 +566,29 @@ export function buildSceneDescription(projectedClips,document.timeline.trimRanges,track.startMs / 1000,+ rawSpeedRegions,);- // Measure the span on the OUTPUT programme, not the raw ruler. A track- // sitting inside a trimmed stretch projects BOTH its ends onto the same- // boundary, so its output span is zero and it is dropped — where the raw- // span kept it alive and played it, in full, at the cut. A track that- // merely crosses a trim shortens by what the cut removed.- const endSec = projectRawTimelineSecToPlayback(- projectedClips,- document.timeline.trimRanges,- track.endMs / 1000,- );- const spanSec = endSec - startSec;+ // Length is measured WITHOUT speed, position WITH it — the two do different+ // things to a track and must not be conflated.+ //+ // A trim REMOVES timeline: a track inside removed time has nowhere left to+ // be (zero length, dropped), and one crossing a cut loses what the cut took.+ // A speed region only COMPRESSES: the track still holds all its audio and+ // still plays at 1x, so speeding the video up must not quietly cut the+ // narration short. It changes where the track STARTS, because the programme+ // ahead of it got shorter, and nothing else.+ const trimmedSpanSec =+ projectRawTimelineSecToPlayback(+ projectedClips,+ document.timeline.trimRanges,+ track.endMs / 1000,+ ) -+ projectRawTimelineSecToPlayback(+ projectedClips,+ document.timeline.trimRanges,+ track.startMs / 1000,+ );+ const spanSec = trimmedSpanSec;if (spanSec <= 0) return [];const base = {path: asset.originalPath,