Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(editor): sync imported audio tracks to trims in the export (issue #350)

Benjamin Freeman3fe15545868f
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index 44bb0fd69..a064821eb 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -83,7 +83,10 @@ export function resolveAudioTrackPlayback(
* This is the RAW/document timeline the ruler, playhead and lane all use — NOT
* the trim-compressed output timeline — because that is where the track was
* placed (`useTimeline.addAudioTrack` seeds `timelineStartSec` from the playhead).
- * The export mixes on the same RAW positions (see audio.rs), so the two agree.
+ * The preview's playhead JUMPS across a trim, so a track at a raw head past a cut
+ * still fires at the right wall-clock moment here. The export mixes onto the
+ * compressed programme, so it projects the raw head through the trims first
+ * (`projectRawTimelineSecToPlayback` in sceneDescription) to land at the same place.
*/
export function resolveTimelineAudioPlayback(virtualTimeSec: number, track: AxcutAudioTrack) {
const trimStart = Math.max(0, track.trimStartSec);
diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.ts
index bb5172178..7a6704fd8 100644
--- a/src/lib/ai-edition/document/timeline.test.ts
+++ b/src/lib/ai-edition/document/timeline.test.ts
@@ -13,6 +13,7 @@ import {
normalizeIntervals,
planTimelineReplacement,
primaryAssetDuration,
+ projectRawTimelineSecToPlayback,
rederiveRegionMs,
removeClip,
removeRegion,
@@ -841,6 +842,60 @@ describe("resolvePlaybackSegments", () => {
});
});
+describe("projectRawTimelineSecToPlayback (issue #350 audio-track/trim sync)", () => {
+ // One 10s clip, an interior trim removing raw 2..4 (2s). Output programme is 8s long.
+ const clip = makeClip({
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ });
+ const trim = makeTrim({ startSec: 2, endSec: 4 });
+
+ it("is the identity when there are no trims", () => {
+ expect(projectRawTimelineSecToPlayback([clip], [], 6)).toBeCloseTo(6, 6);
+ });
+
+ it("pulls a raw position after a cut earlier by the removed duration", () => {
+ // Raw 6 sits 2s past the 2s cut → output 4. This is the exact bug: the track was
+ // landing at 6 (delayed by the trim) instead of 4.
+ expect(projectRawTimelineSecToPlayback([clip], [trim], 6)).toBeCloseTo(4, 6);
+ });
+
+ it("is unaffected for a position before the cut", () => {
+ expect(projectRawTimelineSecToPlayback([clip], [trim], 1)).toBeCloseTo(1, 6);
+ });
+
+ it("collapses a position inside the trimmed gap to the end of the kept content before it", () => {
+ // Raw 3 is inside the removed 2..4 span → the next audible sample is at output 2.
+ expect(projectRawTimelineSecToPlayback([clip], [trim], 3)).toBeCloseTo(2, 6);
+ });
+
+ it("sums cuts across multiple clips", () => {
+ const clipA = makeClip({
+ id: "clip_a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ });
+ const clipB = makeClip({
+ id: "clip_b",
+ sourceStartSec: 10,
+ sourceEndSec: 20,
+ timelineStartSec: 10,
+ timelineEndSec: 20,
+ });
+ // Remove 1s from clip A (raw 5..6) and 2s from clip B (raw 12..14) → 3s total.
+ const trims = [
+ makeTrim({ id: "t1", startSec: 5, endSec: 6 }),
+ makeTrim({ id: "t2", startSec: 12, endSec: 14 }),
+ ];
+ // Raw 18 is past both cuts (3s removed) → output 15.
+ expect(projectRawTimelineSecToPlayback([clipA, clipB], trims, 18)).toBeCloseTo(15, 6);
+ });
+});
+
describe("duplicateClip / moveClip", () => {
it("duplicateClip gives the copy a fresh, collision-free id even when called repeatedly", () => {
// Regression test: this used to id the copy as `clip_${clips.length + 1}_copy`,
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index 232bcb6ee..0cbbeabd4 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -202,6 +202,52 @@ export function resolvePlaybackSegments(
return result;
}
+/**
+ * Project a RAW/document-timeline second (the ruler where trims still occupy their space)
+ * onto the trim-COMPRESSED output programme — the concatenation of the kept segments that
+ * {@link resolvePlaybackSegments} produces and that `audio::mix_external_tracks` overlays on.
+ *
+ * The only thing the programme removes is trimmed content, so the output position of a raw
+ * time `T` is `T` minus however much trimmed span sits before it:
+ * `output(T) = T − Σ overlap(each trim's raw extent, [0, T])`.
+ * A `T` past a cut lands earlier by exactly the removed duration (the whole point); a `T`
+ * INSIDE a trimmed span collapses to the output edge just before it; and a `T` in a region
+ * with no trim — including a project with no clips at all — passes straight through.
+ *
+ * A trim is stored in SOURCE seconds anchored to a clip (`trimAppliesToClip`, same match as
+ * `resolvePlaybackSegments`), so its raw extent is the clip's `timelineStartSec` plus the
+ * offset of the trimmed sub-range into the clip's own source window. EXACT for trims; like the
+ * rest of the audio-track export path it does not model speed regions, which stay an approximation.
+ *
+ * Issue #350: imported audio tracks store their head in RAW seconds (seeded from the playhead),
+ * but the export mixes onto the compressed programme — passing the raw head through verbatim
+ * 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 function projectRawTimelineSecToPlayback(
+ clips: AxcutClip[],
+ trimRanges: AxcutTrimRange[],
+ rawSec: number,
+): number {
+ let removed = 0;
+ for (const clip of clips) {
+ const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;
+ if (sourceEnd <= clip.sourceStartSec) continue; // unprobed: no trims resolved against it
+ for (const trim of trimRanges) {
+ if (!trimAppliesToClip(trim, clip)) continue;
+ // The trimmed sub-range clamped to THIS clip's source window, then placed on the raw
+ // ruler where source `s` sits at `timelineStartSec + (s − sourceStartSec)`.
+ const s0 = Math.max(trim.startSec, clip.sourceStartSec);
+ const s1 = Math.min(trim.endSec, sourceEnd);
+ if (s1 <= s0) continue;
+ const rawStart = clip.timelineStartSec + (s0 - clip.sourceStartSec);
+ const rawLen = s1 - s0;
+ removed += Math.min(Math.max(rawSec - rawStart, 0), rawLen);
+ }
+ }
+ return rawSec - removed;
+}
+
export function invertIntervals(intervals: Interval[], durationSec: number): Interval[] {
const cuts: Interval[] = [];
let cursor = 0;
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index 51d02b712..1f7978cbe 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -2033,6 +2033,34 @@ describe("buildSceneDescription.audioTracks", () => {
expect(buildSceneDescription(doc).audioTracks[0]?.trimEndSec).toBe(30);
});
+ it("projects the head onto the trim-compressed programme (issue #350)", () => {
+ // A 10s screen clip with an interior cut removing raw [2,4] (2s). The audio track's
+ // raw head is 5; on the compressed programme that is 3. Passing 5 through verbatim was
+ // the bug — the track played 2s (the trim) late in the render while the preview, whose
+ // playhead jumps the cut, had it on time.
+ const screen = makeAsset({ id: "scr", originalPath: "/screen.mp4", durationSec: 10 });
+ const doc = makeDoc({
+ assets: [screen, audioAsset],
+ clips: [
+ makeClip({
+ id: "c1",
+ assetId: "scr",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ }),
+ ],
+ timeline: {
+ trimRanges: [
+ { id: "t1", assetId: "scr", startSec: 2, endSec: 4, reason: "", origin: "user" },
+ ],
+ },
+ audioTracks: [track],
+ });
+ expect(buildSceneDescription(doc).audioTracks[0]?.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.ts
index 6f203c392..1a06a356d 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -30,7 +30,10 @@ import {
} from "@/lib/ai-edition/captions";
import { createId } from "@/lib/ai-edition/document/ids";
import { pickOutputDims } from "@/lib/ai-edition/document/outputFormat";
-import { resolvePlaybackSegments } from "@/lib/ai-edition/document/timeline";
+import {
+ projectRawTimelineSecToPlayback,
+ resolvePlaybackSegments,
+} from "@/lib/ai-edition/document/timeline";
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";
@@ -413,10 +416,11 @@ export interface SceneDescription {
};
/**
* Imported audio tracks (issue #350), mixed over the assembled programme by
- * `audio::mix_external_tracks`. `startSec` is the head on the OUTPUT programme;
- * it equals the track's raw timeline position, which is exact when the project
- * has no trims/speed and an accepted approximation otherwise (the preview
- * approximates the same way). `trimEndSec` is always concrete — the compositor
+ * `audio::mix_external_tracks`. `startSec` is the head on the trim-COMPRESSED output
+ * programme: the track's raw timeline head projected through the trims via
+ * `projectRawTimelineSecToPlayback`, so a cut ahead of the track pulls it earlier by the
+ * removed duration (exactly as the preview already plays it). Exact for trims; speed
+ * regions stay an approximation. `trimEndSec` is always concrete — the compositor
* preallocates the decode window from it — so it is resolved to the source
* duration when the track's tail isn't trimmed.
*/
@@ -514,7 +518,14 @@ export function buildSceneDescription(
return [
{
path: asset.originalPath,
- startSec: track.timelineStartSec,
+ // The track's head is stored in RAW timeline seconds, but the programme this
+ // mixes onto is trim-compressed — so project raw→output. Passing the raw head
+ // verbatim delayed the track by the total trim duration ahead of it (issue #350).
+ startSec: projectRawTimelineSecToPlayback(
+ document.timeline.clips,
+ document.timeline.trimRanges,
+ track.timelineStartSec,
+ ),
gainDb: track.gainDb,
trimStartSec: track.trimStartSec,
trimEndSec,