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(audio): clip-anchor timeline audio tracks
Ola Adebayo657f5d5c82db
diff --git a/.gitignore b/.gitignoreindex a1822ee05..24ad425eb 100644--- a/.gitignore+++ b/.gitignore@@ -132,3 +132,4 @@ workbench/fixtures//aur_ci/aur_ci.pub/aur_known_hosts+tmp_handoff.mddiff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.tsindex 91448d350..f80176ccd 100644--- a/electron/ai-edition/document-service.test.ts+++ b/electron/ai-edition/document-service.test.ts@@ -435,11 +435,13 @@ describe("DocumentService", () => {{id: "trk_1",assetId: audioId,- timelineStartSec: 0,+ startMs: 0,+ endMs: 10_000,durationSec: 10,- trimStartSec: 0,+ offsetMs: 0,gainDb: 0,label: "music",+ origin: "user",},],});diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsxindex 4c8120beb..7360757d8 100644--- a/src/components/ai-edition/NewEditorShell.tsx+++ b/src/components/ai-edition/NewEditorShell.tsx@@ -14,7 +14,7 @@ import {replaceTimeline as replaceTimelineOp,} from "@/lib/ai-edition/document/timeline";import { isModalOpen } from "@/lib/ai-edition/modalGuard";-import { type AxcutClip, documentSchema } from "@/lib/ai-edition/schema";+import { type AxcutAudioTrack, type AxcutClip, documentSchema } from "@/lib/ai-edition/schema";import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import {useAssetTranscriptions,@@ -802,6 +802,21 @@ export function NewEditorShell() {return;}+ // Validate before building anything. The clipboard outlives the project, so+ // a track copied in one project and pasted in another would reference an+ // asset that only exists back where it came from — a pill that plays+ // nothing and exports nothing. Audio is the only kind carrying a reference+ // out of the document today; the next one belongs here too, rather than in+ // its own branch below.+ const referencedAssetId = (snapshot.region as { assetId?: unknown }).assetId;+ if (+ typeof referencedAssetId === "string" &&+ !doc.assets.some((a) => a.id === referencedAssetId)+ ) {+ toast.error(te("regionClipboard.pasteAssetMissing"));+ return;+ }+const { anchorRegionsWithDerivedMs } = await import("@/lib/ai-edition/timeline/timelineMap");const { createId } = await import("@/lib/ai-edition/document/ids");@@ -809,6 +824,30 @@ export function NewEditorShell() {const timeMs = Math.round(useProjectStore.getState().currentTimeSec * 1000);const src = snapshot.region as { startMs: number; endMs: number };const prefix = snapshot.kind === "annotation" ? "ann" : snapshot.kind;++ // Audio re-ventilates through its own anchorer, which advances each+ // fragment's source offset — the generic one would copy the offset into+ // every fragment and restart the file at each cut.+ if (snapshot.kind === "audio") {+ const { anchorAudioTrackFragments } = await import("@/lib/ai-edition/document/audioTracks");+ const track = {+ ...(snapshot.region as unknown as AxcutAudioTrack),+ id: createId("audio"),+ trackId: undefined,+ startMs: timeMs,+ endMs: timeMs + (Number(src.endMs) - Number(src.startMs)),+ };+ const fragments = anchorAudioTrackFragments(track, doc.timeline.clips, () =>+ createId("audio"),+ );+ if (fragments.length === 0) return;+ await saveDocument(+ { ...doc, audioTracks: [...doc.audioTracks, ...fragments] },+ { history: true },+ );+ toast.success("Region pasted");+ return;+ }const pasted = {...snapshot.region,id: createId(prefix),@@ -858,7 +897,7 @@ export function NewEditorShell() {// `tl` belongs here now that the trim branch calls tl.addTrim: useTimeline// returns a fresh object each render, so memoizing on saveDocument alone// would paste through a callback holding a stale document.- }, [saveDocument, tl]);+ }, [saveDocument, tl, te]);// Copy the SELECTED pill. Reads the same arrays the lanes render, so what gets// copied is what the user is looking at — the old version dug into the raw@@ -886,6 +925,22 @@ export function NewEditorShell() {return;}+ // An audio track is stored as one fragment per clip it covers; the user+ // copied the PILL, so collapse it back before it goes on the clipboard.+ if (sel.kind === "audio") {+ const { collapseTracksToPills, trackGroupId } = await import(+ "@/lib/ai-edition/document/audioTracks"+ );+ const [pill] = collapseTracksToPills(+ tl.audioTracks.filter((t) => trackGroupId(t) === sel.id),+ );+ if (!pill) return;+ copyRegion({ kind: "audio", region: pill as unknown as Record<string, unknown> });+ setCopiedClipId(null);+ toast.success("Region copied");+ return;+ }+const source =sel.kind === "zoom"? tl.zoomRegionsdiff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsxindex 92962b8b6..df6f49df2 100644--- a/src/components/ai-edition/RightPanes.tsx+++ b/src/components/ai-edition/RightPanes.tsx@@ -39,6 +39,7 @@ import defaultCursorPreviewUrl from "@/assets/cursors/Cursor=Default.svg";import GradientEditor, { type GradientEditorState } from "@/components/ui/gradient-editor";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { useI18n, useScopedT } from "@/contexts/I18nContext";+import { collapseTracksToPills, trackGroupId } from "@/lib/ai-edition/document/audioTracks";import { collectNativeFormats } from "@/lib/ai-edition/document/outputFormat";import type {AxcutAsset,@@ -2345,7 +2346,12 @@ type TimelineApi = ReturnType<typeof useTimeline>;export function AudioTrackPane({ tl }: { tl: TimelineApi }) {const ts = useScopedT("settings");const trackId = tl.selectedAudioTrackId;- const track = tl.audioTracks.find((t) => t.id === trackId);+ // The document stores one clip-anchored fragment per clip the track covers;+ // the inspector edits the user-visible TRACK, so collapse first. Editing a+ // single fragment would let the halves of a split take disagree.+ const track = trackId+ ? collapseTracksToPills(tl.audioTracks.filter((t) => trackGroupId(t) === trackId))[0]+ : undefined;const asset = track ? tl.assets.find((a) => a.id === track.assetId) : undefined;// Live-drag value for the volume slider; null means "show the committed gain".const [liveGain, setLiveGain] = useState<number | null>(null);diff --git a/src/components/ai-edition/VirtualPreview.audio.test.ts b/src/components/ai-edition/VirtualPreview.audio.test.tsindex 0ac1c1b31..7ce27660e 100644--- a/src/components/ai-edition/VirtualPreview.audio.test.ts+++ b/src/components/ai-edition/VirtualPreview.audio.test.ts@@ -85,53 +85,54 @@ describe("applyPreviewAudioSettings", () => {});describe("resolveTimelineAudioPlayback", () => {- // A track placed 10s into the RAW timeline, source windowed to 2..8 (6s long).+ // A 6s track placed 10s into the RAW timeline, playing the source from 2s in.const track: AxcutAudioTrack = {id: "t1",assetId: "a1",- timelineStartSec: 10,+ startMs: 10_000,+ endMs: 16_000,durationSec: 20,- trimStartSec: 2,- trimEndSec: 8,+ offsetMs: 2000,gainDb: 0,label: "",+ origin: "user",};+ const spanSec = (t: AxcutAudioTrack) => (t.endMs - t.startMs) / 1000;// Second arg is the track head projected to output seconds; with no trims it is- // just `timelineStartSec` (10), so these read the same as before the output-space+ // just the raw head (10), so these read the same as before the output-space// change — the projection is exercised separately below.- it("maps the playhead to a source position offset by the trim in-point", () => {- // 3s into the track's span → 2 (trimStart) + 3 = 5s of source.- expect(resolveTimelineAudioPlayback(13, 10, track)).toEqual({+ it("maps the playhead to a source position offset by the track offset", () => {+ // 3s into the track's span → 2 (offset) + 3 = 5s of source.+ expect(resolveTimelineAudioPlayback(13, 10, track, spanSec(track))).toEqual({targetTimeSec: 5,shouldPlay: true,});});it("does not play before the track starts, parked at the in-point", () => {- expect(resolveTimelineAudioPlayback(9, 10, track)).toEqual({+ expect(resolveTimelineAudioPlayback(9, 10, track, spanSec(track))).toEqual({targetTimeSec: 2,shouldPlay: false,});});- it("does not play past the window end, parked at the out-point", () => {- // Window is 6s (2..8), so output 10..16. At 16 it has just ended.- expect(resolveTimelineAudioPlayback(16, 10, track)).toEqual({+ it("does not play past the end of its span, parked at the out-point", () => {+ expect(resolveTimelineAudioPlayback(16, 10, track, spanSec(track))).toEqual({targetTimeSec: 8,shouldPlay: false,});});- it("uses the asset duration as the out-point when the tail isn't trimmed", () => {- const untrimmed = { ...track, trimStartSec: 0, trimEndSec: undefined, durationSec: 5 };- // Span is 10..15. At 14 → 4s of source, still playing.- expect(resolveTimelineAudioPlayback(14, 10, untrimmed)).toEqual({+ it("goes silent when the file runs out before the span does", () => {+ // A 5s file under a 10s span: at 6s in there is no source left, and the+ // element holds at the end rather than restarting.+ const short = { ...track, endMs: 20_000, offsetMs: 0, durationSec: 5 };+ expect(resolveTimelineAudioPlayback(14, 10, short, spanSec(short))).toEqual({targetTimeSec: 4,shouldPlay: true,});- // At 15 the 5s file is over.- expect(resolveTimelineAudioPlayback(15, 10, untrimmed).shouldPlay).toBe(false);+ expect(resolveTimelineAudioPlayback(16, 10, short, spanSec(short)).shouldPlay).toBe(false);});// The regression: an interior trim must NOT skip the track's own content, so the@@ -159,29 +160,27 @@ describe("resolveTimelineAudioPlayback", () => {reason: "",};const bgm: AxcutAudioTrack = {+ ...track,id: "bgm",assetId: "a2",- timelineStartSec: 0,+ startMs: 0,+ endMs: 10_000,durationSec: 10,- trimStartSec: 0,- trimEndSec: 10,- gainDb: 0,- label: "",+ offsetMs: 0,};const project = (rawSec: number) => projectRawTimelineSecToPlayback([clip], [trim], rawSec);- const outputStart = project(bgm.timelineStartSec); // 0+ const outputStart = project(bgm.startMs / 1000); // 0// Raw playhead 5 sits 1s past the 2s cut → output 3. The track is a contiguous// block, so it must be at source 3 — NOT source 5, which the old raw-space// `local` produced (the 2s desync).- expect(resolveTimelineAudioPlayback(project(5), outputStart, bgm)).toEqual({+ expect(resolveTimelineAudioPlayback(project(5), outputStart, bgm, spanSec(bgm))).toEqual({targetTimeSec: 3,shouldPlay: true,});// Just before the cut is unaffected: raw 1 → output 1 → source 1.- expect(resolveTimelineAudioPlayback(project(1), outputStart, bgm).targetTimeSec).toBeCloseTo(- 1,- 6,- );+ expect(+ resolveTimelineAudioPlayback(project(1), outputStart, bgm, spanSec(bgm)).targetTimeSec,+ ).toBeCloseTo(1, 6);});});diff --git a/src/components/ai-edition/VirtualPreview.playback.test.tsx b/src/components/ai-edition/VirtualPreview.playback.test.tsxindex 13d5121cb..26f784516 100644--- a/src/components/ai-edition/VirtualPreview.playback.test.tsx+++ b/src/components/ai-edition/VirtualPreview.playback.test.tsx@@ -238,16 +238,17 @@ function driveAudioEl(el: HTMLAudioElement) {}describe("VirtualPreview imported audio tracks", () => {- // Windowed to source 1..3 (2s) and placed at timeline 2 → occupies 2..4.+ // A 2s span at raw 2..4, playing the source from 1s in → source 1..3.const track = {id: "trk",assetId: "aud",- timelineStartSec: 2,+ startMs: 2000,+ endMs: 4000,durationSec: 10,- trimStartSec: 1,- trimEndSec: 3,+ offsetMs: 1000,gainDb: 0,label: "",+ origin: "user" as const,};function mountWithAudio() {@@ -332,12 +333,13 @@ describe("VirtualPreview imported audio track boost", () => {const boosted = {id: "trk",assetId: "aud",- timelineStartSec: 2,+ startMs: 2000,+ endMs: 4000,durationSec: 10,- trimStartSec: 1,- trimEndSec: 3,+ offsetMs: 1000,gainDb: 6.0206,label: "",+ origin: "user" as const,};it("drives a per-track gain node past unity instead of capping element.volume", () => {diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsxindex 27cf7c81f..00737545b 100644--- a/src/components/ai-edition/VirtualPreview.tsx+++ b/src/components/ai-edition/VirtualPreview.tsx@@ -98,14 +98,22 @@ export function resolveTimelineAudioPlayback(outputTimeSec: number,outputStartSec: number,track: AxcutAudioTrack,+ /** The fragment's own span in seconds — how long it plays on the timeline,+ * which is independent of how much file is left after the offset. */+ spanSec: number,) {- const trimStart = Math.max(0, track.trimStartSec);- const trimEnd = track.trimEndSec ?? track.durationSec;- const windowLen = Math.max(0, trimEnd - trimStart);+ const offset = Math.max(0, track.offsetMs / 1000);+ const sourceEnd = track.durationSec > 0 ? track.durationSec : offset + spanSec;+ // The window the file has left after the offset; the fragment stops at+ // whichever runs out first, its span or the file.+ const windowLen = Math.max(0, sourceEnd - offset);const local = outputTimeSec - outputStartSec;+ const active = local >= 0 && local < spanSec;return {- targetTimeSec: Math.min(Math.max(trimStart, trimStart + local), trimEnd),- shouldPlay: local >= 0 && local < windowLen,+ targetTimeSec: Math.min(Math.max(offset, offset + local), sourceEnd),+ // A file shorter than its span goes silent at the end rather than+ // restarting: seeking a finished element back would stutter it every frame.+ shouldPlay: active && local < windowLen,};}@@ -610,9 +618,15 @@ export function VirtualPreview({const outputStartSec = projectRawTimelineSecToPlayback(clipsRef.current,trimRangesRef.current,- track.timelineStartSec,+ track.startMs / 1000,+ );+ const spanSec = Math.max(0, (track.endMs - track.startMs) / 1000);+ const trackTarget = resolveTimelineAudioPlayback(+ outputTimeSec,+ outputStartSec,+ track,+ spanSec,);- const trackTarget = resolveTimelineAudioPlayback(outputTimeSec, outputStartSec, track);// Imported audio plays at its natural 1× rate, NOT the video's. The export// sums it into the programme at 1× — speed regions stretch clip PCM only,// never the imported track — so following `v.playbackRate` would pitch adiff --git a/src/components/ai-edition/v4/V4Timeline.geometry.test.tsx b/src/components/ai-edition/v4/V4Timeline.geometry.test.tsxindex 0ece54317..ca773abba 100644--- a/src/components/ai-edition/v4/V4Timeline.geometry.test.tsx+++ b/src/components/ai-edition/v4/V4Timeline.geometry.test.tsx@@ -349,23 +349,22 @@ describe("V4Timeline clip row", () => {// covered by document/audioTracks.test.ts.describe("V4Timeline audio lane drag", () => {const AUDIO_ASSET = { id: "aud", label: "voiceover", originalPath: "/vo.mp3", durationSec: 60 };+ // A 60s track whose head sits at raw 100s.const makeTrack = () => ({id: "trk1",assetId: "aud",- timelineStartSec: 100,+ startMs: 100_000,+ endMs: 160_000,durationSec: 60,- trimStartSec: 0,- trimEndSec: undefined as number | undefined,+ offsetMs: 0,gainDb: 0,label: "vo",+ origin: "user" as const,});function renderAudio() {const placeAudioTrack = vi.fn(- async (- _id: string,- _placement: { timelineStartSec: number; trimStartSec: number; trimEndSec?: number },- ) => {+ async (_id: string, _span: { startMs: number; endMs: number }) => {/* the drag only awaits it */},);@@ -423,9 +422,9 @@ describe("V4Timeline audio lane drag", () => {expect(placeAudioTrack).toHaveBeenCalledTimes(1);const [id, placement] = placeAudioTrack.mock.calls[0];expect(id).toBe("trk1");- expect(placement.timelineStartSec).toBeCloseTo(100 + secForPx(90), 3);- expect(placement.trimStartSec).toBe(0);- expect(placement.trimEndSec).toBeCloseTo(60, 3);+ // The span slides whole: head moves, length is unchanged.+ expect(placement.startMs / 1000).toBeCloseTo(100 + secForPx(90), 3);+ expect((placement.endMs - placement.startMs) / 1000).toBeCloseTo(60, 3);});it("right-handle drag pulls the out-point in, head fixed", () => {@@ -437,10 +436,8 @@ describe("V4Timeline audio lane drag", () => {window.dispatchEvent(new MouseEvent("pointerup", { clientX: -30 }));expect(placeAudioTrack).toHaveBeenCalledTimes(1);const [, placement] = placeAudioTrack.mock.calls[0];- expect(placement.timelineStartSec).toBe(100);- expect(placement.trimStartSec).toBe(0);- // 60s window − 60px worth of seconds (−30px = −60s) → out-point at 0? No:- // −30px = −60s, so trimEnd 60 → 0 clamps to trimStart + MIN. Use a smaller drag.- expect(placement.trimEndSec).toBeLessThan(60);+ // The head is pinned; only the tail comes in, so the span gets shorter.+ expect(placement.startMs).toBe(100_000);+ expect(placement.endMs - placement.startMs).toBeLessThan(60_000);});});diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsxindex 136b241b8..411e27c31 100644--- a/src/components/ai-edition/v4/V4Timeline.tsx+++ b/src/components/ai-edition/v4/V4Timeline.tsx@@ -29,6 +29,7 @@ import { fromFileUrl, toFileUrl } from "@/components/video-editor/projectPersistimport { ZOOM_DEPTH_SCALES } from "@/components/video-editor/types";import { useScopedT } from "@/contexts/I18nContext";import { useAudioPeaks } from "@/hooks/useAudioPeaks";+import { collapseTracksToPills } from "@/lib/ai-edition/document/audioTracks";import { createId } from "@/lib/ai-edition/document/ids";import { setUiProbeScrubbing } from "@/lib/ai-edition/perf/uiFrameProbe";import type { AxcutAudioTrack, AxcutClip } from "@/lib/ai-edition/schema";@@ -351,6 +352,8 @@ const AudioLanePill = memo(function AudioLanePill({assetDurationSec,leftPct,widthPct,+ sourceStartSec,+ sourceEndSec,selected,onStartDrag,onSelect,@@ -362,6 +365,10 @@ const AudioLanePill = memo(function AudioLanePill({assetDurationSec: number | undefined;leftPct: number;widthPct: number;+ /** The slice of the source the pill is showing — the track's offset and its+ * span, or the live window while an edge is being dragged. */+ sourceStartSec: number;+ sourceEndSec: number;selected: boolean;onStartDrag: (e: ReactPointerEvent, track: AxcutAudioTrack, mode: "move" | "l" | "r") => void;onSelect: (id: string) => void;@@ -397,8 +404,8 @@ const AudioLanePill = memo(function AudioLanePill({<ClipWaveformvideoUrl={url}assetDurationSec={duration}- sourceStartSec={track.trimStartSec}- sourceEndSec={track.trimEndSec ?? duration}+ sourceStartSec={sourceStartSec}+ sourceEndSec={sourceEndSec}// Track gain AND the project output gain — `finish_audio` applies both and// clamps, so scaling by the track gain alone under-read a boosted output.gain={audioGainScalar(track.gainDb) * outputGain}@@ -893,10 +900,11 @@ export function V4Timeline({const asset = tl.assets.find((a) => a.id === track.assetId);// The source length caps the out-point; fall back to the current window when// the file hasn't been probed (durationSec 0), so a drag can't extend past it.- const sourceLen = asset?.durationSec || track.durationSec || track.trimEndSec || 0;- const origStart = track.timelineStartSec;- const origTrimStart = track.trimStartSec;- const origTrimEnd = track.trimEndSec ?? sourceLen;+ const spanSec = Math.max(0, (track.endMs - track.startMs) / 1000);+ const sourceLen = asset?.durationSec || track.durationSec || spanSec;+ const origStart = track.startMs / 1000;+ const origTrimStart = track.offsetMs / 1000;+ const origTrimEnd = origTrimStart + spanSec;const maxEnd = sourceLen > 0 ? sourceLen : origTrimEnd;// Snap the moving edge to clip boundaries and the timeline ends, same PILL_SNAP_PX// magnet the region pills use.@@ -965,9 +973,8 @@ export function V4Timeline({if (fin) {void tl.placeAudioTrack(fin.id, {- timelineStartSec: fin.start,- trimStartSec: fin.trimStart,- trimEndSec: fin.trimEnd,+ startMs: Math.round(fin.start * 1000),+ endMs: Math.round((fin.start + Math.max(0, fin.trimEnd - fin.trimStart)) * 1000),}).finally(() => {if (audioDragRef.current === fin) {@@ -1715,16 +1722,23 @@ export function V4Timeline({{t("hints.pressAudio")}</span>) : (- tl.audioTracks.map((track) => {+ // One pill per user-visible track: the document stores one+ // clip-anchored fragment per clip the track covers, and the+ // lane must not show a split take as two pills.+ collapseTracksToPills(tl.audioTracks).map((track) => {const asset = tl.assets.find((a) => a.id === track.assetId);const duration = asset?.durationSec ?? track.durationSec;// While this track is being dragged, lay it out from the live// preview geometry instead of the not-yet-written document.const drag = audioDrag?.id === track.id ? audioDrag : null;- const start = drag ? drag.start : track.timelineStartSec;- const trimStart = drag ? drag.trimStart : track.trimStartSec;- const trimEnd = drag ? drag.trimEnd : (track.trimEndSec ?? duration);- const widthSec = Math.max(0, trimEnd - trimStart);+ const start = drag ? drag.start : track.startMs / 1000;+ // A drag carries its span as the trim window it is dragging+ // the edges of; the pill's width is that window.+ const widthSec = drag+ ? Math.max(0, drag.trimEnd - drag.trimStart)+ : Math.max(0, (track.endMs - track.startMs) / 1000);+ const trimStart = drag ? drag.trimStart : track.offsetMs / 1000;+ const trimEnd = trimStart + widthSec;return (<AudioLanePillkey={track.id}@@ -1733,6 +1747,8 @@ export function V4Timeline({assetDurationSec={duration}leftPct={pctOf(start)}widthPct={pctOf(widthSec)}+ sourceStartSec={trimStart}+ sourceEndSec={trimEnd}selected={tl.selectedAudioTrackId === track.id}onStartDrag={startAudioDrag}onSelect={tl.selectAudioTrack}diff --git a/src/i18n/locales/ar/editor.json b/src/i18n/locales/ar/editor.jsonindex 04bd4eba8..901b41785 100644--- a/src/i18n/locales/ar/editor.json+++ b/src/i18n/locales/ar/editor.json@@ -71,6 +71,7 @@"pasted": "تم لصق سمات {{region}}","nothingToCopy": "حدد منطقة لنسخ سماتها","nothingToPaste": "لم يتم نسخ أي سمات بعد",+ "pasteAssetMissing": "ملف هذا المسار الصوتي غير موجود في هذا المشروع","kinds": {"zoom": "تكبير","speed": "سرعة",diff --git a/src/i18n/locales/en/editor.json b/src/i18n/locales/en/editor.jsonindex e1692652d..8d2ddb64f 100644--- a/src/i18n/locales/en/editor.json+++ b/src/i18n/locales/en/editor.json@@ -71,6 +71,7 @@"pasted": "{{region}} attributes pasted","nothingToCopy": "Select a region to copy its attributes","nothingToPaste": "No attributes copied yet",+ "pasteAssetMissing": "That audio track's file isn't in this project","kinds": {"zoom": "Zoom","speed": "Speed",diff --git a/src/i18n/locales/es/editor.json b/src/i18n/locales/es/editor.jsonindex 46f0d3eaf..5f4a6db8c 100644--- a/src/i18n/locales/es/editor.json+++ b/src/i18n/locales/es/editor.json@@ -71,6 +71,7 @@"pasted": "Atributos de {{region}} pegados","nothingToCopy": "Selecciona una región para copiar sus atributos","nothingToPaste": "Aún no se han copiado atributos",+ "pasteAssetMissing": "El archivo de esa pista de audio no está en este proyecto","kinds": {"zoom": "Zoom","speed": "Velocidad",diff --git a/src/i18n/locales/fr/editor.json b/src/i18n/locales/fr/editor.jsonindex 3eb0dfa4e..6e15b4f41 100644--- a/src/i18n/locales/fr/editor.json+++ b/src/i18n/locales/fr/editor.json@@ -71,6 +71,7 @@"pasted": "Attributs de {{region}} collés","nothingToCopy": "Sélectionnez une région pour copier ses attributs","nothingToPaste": "Aucun attribut copié pour l'instant",+ "pasteAssetMissing": "Le fichier de cette piste audio n'est pas dans ce projet","kinds": {"zoom": "Zoom","speed": "Vitesse",diff --git a/src/i18n/locales/it/editor.json b/src/i18n/locales/it/editor.jsonindex 214b0d10a..5a4a4cf91 100644--- a/src/i18n/locales/it/editor.json+++ b/src/i18n/locales/it/editor.json@@ -71,6 +71,7 @@"pasted": "Attributi di {{region}} incollati","nothingToCopy": "Seleziona una regione per copiarne gli attributi","nothingToPaste": "Nessun attributo copiato",+ "pasteAssetMissing": "Il file di questa traccia audio non è in questo progetto","kinds": {"zoom": "Zoom","speed": "Velocità",diff --git a/src/i18n/locales/ja-JP/editor.json b/src/i18n/locales/ja-JP/editor.jsonindex e12096ed1..d32d5dbc3 100644--- a/src/i18n/locales/ja-JP/editor.json+++ b/src/i18n/locales/ja-JP/editor.json@@ -71,6 +71,7 @@"pasted": "{{region}}の属性を貼り付けました","nothingToCopy": "属性をコピーする領域を選択してください","nothingToPaste": "コピーされた属性がありません",+ "pasteAssetMissing": "このオーディオトラックのファイルはこのプロジェクトにありません","kinds": {"zoom": "ズーム","speed": "速度",diff --git a/src/i18n/locales/ko-KR/editor.json b/src/i18n/locales/ko-KR/editor.jsonindex a1fc34a62..1f0bd14a5 100644--- a/src/i18n/locales/ko-KR/editor.json+++ b/src/i18n/locales/ko-KR/editor.json@@ -71,6 +71,7 @@"pasted": "{{region}} 속성을 붙여넣었습니다","nothingToCopy": "속성을 복사할 영역을 선택하세요","nothingToPaste": "복사된 속성이 없습니다",+ "pasteAssetMissing": "이 오디오 트랙의 파일이 이 프로젝트에 없습니다","kinds": {"zoom": "줌","speed": "속도",diff --git a/src/i18n/locales/pt-BR/editor.json b/src/i18n/locales/pt-BR/editor.jsonindex 799f3be74..5759a5804 100644--- a/src/i18n/locales/pt-BR/editor.json+++ b/src/i18n/locales/pt-BR/editor.json@@ -71,6 +71,7 @@"pasted": "Atributos de {{region}} colados","nothingToCopy": "Selecione uma região para copiar seus atributos","nothingToPaste": "Nenhum atributo copiado ainda",+ "pasteAssetMissing": "O arquivo dessa faixa de áudio não está neste projeto","kinds": {"zoom": "Zoom","speed": "Velocidade",diff --git a/src/i18n/locales/ru/editor.json b/src/i18n/locales/ru/editor.jsonindex db5216291..9e493196f 100644--- a/src/i18n/locales/ru/editor.json+++ b/src/i18n/locales/ru/editor.json@@ -71,6 +71,7 @@"pasted": "Атрибуты «{{region}}» вставлены","nothingToCopy": "Выберите регион, чтобы скопировать его атрибуты","nothingToPaste": "Атрибуты ещё не скопированы",+ "pasteAssetMissing": "Файл этой аудиодорожки отсутствует в проекте","kinds": {"zoom": "Масштаб","speed": "Скорость",diff --git a/src/i18n/locales/tr/editor.json b/src/i18n/locales/tr/editor.jsonindex 5b8e9922b..819a77588 100644--- a/src/i18n/locales/tr/editor.json+++ b/src/i18n/locales/tr/editor.json@@ -71,6 +71,7 @@"pasted": "{{region}} öznitelikleri yapıştırıldı","nothingToCopy": "Özniteliklerini kopyalamak için bir bölge seçin","nothingToPaste": "Henüz öznitelik kopyalanmadı",+ "pasteAssetMissing": "Bu ses parçasının dosyası bu projede yok","kinds": {"zoom": "Yakınlaştırma","speed": "Hız",diff --git a/src/i18n/locales/vi/editor.json b/src/i18n/locales/vi/editor.jsonindex 821875edb..59c6a45d6 100644--- a/src/i18n/locales/vi/editor.json+++ b/src/i18n/locales/vi/editor.json@@ -71,6 +71,7 @@"pasted": "Đã dán thuộc tính {{region}}","nothingToCopy": "Chọn một vùng để sao chép thuộc tính của nó","nothingToPaste": "Chưa sao chép thuộc tính nào",+ "pasteAssetMissing": "Tệp của bản âm thanh này không có trong dự án","kinds": {"zoom": "Thu phóng","speed": "Tốc độ",diff --git a/src/i18n/locales/zh-CN/editor.json b/src/i18n/locales/zh-CN/editor.jsonindex 7723d101d..f0f847e14 100644--- a/src/i18n/locales/zh-CN/editor.json+++ b/src/i18n/locales/zh-CN/editor.json@@ -71,6 +71,7 @@"pasted": "已粘贴{{region}}属性","nothingToCopy": "选择一个区域以复制其属性","nothingToPaste": "尚未复制任何属性",+ "pasteAssetMissing": "该音频轨道的文件不在此项目中","kinds": {"zoom": "缩放","speed": "速度",diff --git a/src/i18n/locales/zh-TW/editor.json b/src/i18n/locales/zh-TW/editor.jsonindex 3edf5f320..f98803e1c 100644--- a/src/i18n/locales/zh-TW/editor.json+++ b/src/i18n/locales/zh-TW/editor.json@@ -71,6 +71,7 @@"pasted": "已貼上{{region}}屬性","nothingToCopy": "選擇一個區域以複製其屬性","nothingToPaste": "尚未複製任何屬性",+ "pasteAssetMissing": "該音訊軌道的檔案不在此專案中","kinds": {"zoom": "縮放","speed": "速度",diff --git a/src/lib/ai-edition/document/audioTracks.test.ts b/src/lib/ai-edition/document/audioTracks.test.tsindex d313eb693..25f7d4cfd 100644--- a/src/lib/ai-edition/document/audioTracks.test.ts+++ b/src/lib/ai-edition/document/audioTracks.test.ts@@ -1,96 +1,176 @@import { describe, expect, it } from "vitest";-import { type AxcutAsset, createAudioTrack, createEmptyDocument } from "../schema";+import { type AxcutAsset, type AxcutClip, createAudioTrack, createEmptyDocument } from "../schema";import {- appendAudioTrack,+ anchorAudioTrackFragments,+ collapseTracksToPills,+ patchAudioTrack,removeAudioTrack,- setAudioTrackGain,- setAudioTrackPlacement,+ trackGroupId,} from "./audioTracks";const emptyDoc = () => createEmptyDocument({ projectId: "p", title: "t" });-const docWithTrack = () => {- const track = createAudioTrack({ assetId: "asset_1", durationSec: 30, timelineStartSec: 5 });- return { doc: appendAudioTrack(emptyDoc(), track), track };+function clip(id: string, timelineStartSec: number, lengthSec: number): AxcutClip {+ return {+ id,+ assetId: "video_1",+ sourceStartSec: 0,+ sourceEndSec: lengthSec,+ timelineStartSec,+ timelineEndSec: timelineStartSec + lengthSec,+ wordRefs: [],+ origin: "user",+ reason: "",+ };+}++// Two 10s clips back to back: a track crossing second 10 is ventilated in two.+const twoClips = [clip("c1", 0, 10), clip("c2", 10, 10)];++let seq = 0;+const makeId = () => `frag_${++seq}`;++const track = (over: Partial<ReturnType<typeof createAudioTrack>> = {}) => ({+ ...createAudioTrack({ assetId: "asset_1", durationSec: 30, timelineStartSec: 5, spanSec: 10 }),+ ...over,+});++const audioAsset: AxcutAsset = {+ id: "asset_1",+ kind: "audio",+ label: "BGM",+ originalPath: "/bgm.mp3",+ cameraTrack: null,};-describe("audioTracks document ops (issue #350)", () => {- it("appendAudioTrack adds the track without mutating the input", () => {- const doc = emptyDoc();- const track = createAudioTrack({ assetId: "asset_1", durationSec: 12 });- const next = appendAudioTrack(doc, track);- expect(next.audioTracks).toEqual([track]);- expect(doc.audioTracks).toEqual([]);+describe("anchorAudioTrackFragments", () => {+ it("leaves a track that fits inside one clip as a single fragment", () => {+ const frags = anchorAudioTrackFragments(+ track({ startMs: 1000, endMs: 6000 }),+ twoClips,+ makeId,+ );+ expect(frags).toHaveLength(1);+ expect(frags[0].clipId).toBe("c1");+ expect(frags[0].offsetMs).toBe(0);});- it("removeAudioTrack drops the matching track and is a no-op for unknown ids", () => {- const { doc, track } = docWithTrack();- expect(removeAudioTrack(doc, track.id).audioTracks).toEqual([]);- expect(removeAudioTrack(doc, "nope").audioTracks).toEqual([track]);+ it("advances each fragment's source offset by the time its predecessors played", () => {+ // 5s..15s spans the c1/c2 boundary at 10s: 5s of source, then the next 5s.+ const frags = anchorAudioTrackFragments(+ track({ startMs: 5000, endMs: 15_000, offsetMs: 2000 }),+ twoClips,+ makeId,+ );+ expect(frags).toHaveLength(2);+ expect(frags.map((f) => f.clipId)).toEqual(["c1", "c2"]);+ // Fragment 1 starts the file at the track's own offset...+ expect(frags[0].offsetMs).toBe(2000);+ // ...and fragment 2 picks up where it left off, rather than restarting+ // there — that restart is what made a bed audibly repeat at every cut.+ expect(frags[1].offsetMs).toBe(7000);});- const audioAsset: AxcutAsset = {- id: "asset_1",- kind: "audio",- label: "BGM",- originalPath: "/bgm.mp3",- cameraTrack: null,- };+ it("ties every fragment to one group id", () => {+ const frags = anchorAudioTrackFragments(+ track({ startMs: 5000, endMs: 15_000 }),+ twoClips,+ makeId,+ );+ const groups = new Set(frags.map(trackGroupId));+ expect(groups.size).toBe(1);+ });- it("removeAudioTrack also drops the track's asset when nothing else references it", () => {- const track = createAudioTrack({ assetId: "asset_1", durationSec: 30 });- const doc = { ...appendAudioTrack(emptyDoc(), track), assets: [audioAsset] };- const next = removeAudioTrack(doc, track.id);+ it("returns the track unanchored when no clip is under it", () => {+ const frags = anchorAudioTrackFragments(track({ startMs: 5000, endMs: 15_000 }), [], makeId);+ expect(frags).toHaveLength(1);+ expect(frags[0].clipId).toBeUndefined();+ });+});++describe("collapseTracksToPills", () => {+ it("folds a ventilated track back into one span with its real offset", () => {+ const frags = anchorAudioTrackFragments(+ track({ startMs: 5000, endMs: 15_000, offsetMs: 2000 }),+ twoClips,+ makeId,+ );+ const [pill] = collapseTracksToPills(frags);+ expect(pill.startMs).toBe(5000);+ expect(pill.endMs).toBe(15_000);+ // The FIRST fragment's offset is the track's own; the later ones hold+ // advanced copies that must not leak back into the pill.+ expect(pill.offsetMs).toBe(2000);+ expect(pill.clipId).toBeUndefined();+ });++ it("round-trips through anchoring unchanged", () => {+ const original = track({ startMs: 5000, endMs: 15_000, offsetMs: 2000 });+ const once = anchorAudioTrackFragments(original, twoClips, makeId);+ const twice = anchorAudioTrackFragments(collapseTracksToPills(once)[0], twoClips, makeId);+ expect(twice.map((f) => [f.startMs, f.endMs, f.offsetMs])).toEqual(+ once.map((f) => [f.startMs, f.endMs, f.offsetMs]),+ );+ });+});++describe("removeAudioTrack", () => {+ it("drops every fragment of the track and is a no-op for unknown ids", () => {+ const frags = anchorAudioTrackFragments(+ track({ startMs: 5000, endMs: 15_000 }),+ twoClips,+ makeId,+ );+ const doc = { ...emptyDoc(), audioTracks: frags };+ expect(removeAudioTrack(doc, trackGroupId(frags[0])).audioTracks).toEqual([]);+ expect(removeAudioTrack(doc, "nope").audioTracks).toEqual(frags);+ });++ it("also drops the track's asset when nothing else references it", () => {+ const t = track();+ const doc = { ...emptyDoc(), audioTracks: [t], assets: [audioAsset] };+ const next = removeAudioTrack(doc, t.id);expect(next.audioTracks).toEqual([]);expect(next.assets).toEqual([]);});- it("removeAudioTrack keeps the asset when another track still references it", () => {- const t1 = createAudioTrack({ assetId: "asset_1", durationSec: 30 });- const t2 = createAudioTrack({ assetId: "asset_1", durationSec: 30 });- const doc = {- ...appendAudioTrack(appendAudioTrack(emptyDoc(), t1), t2),- assets: [audioAsset],- };+ it("keeps the asset when another track still references it", () => {+ const t1 = track();+ const t2 = track({ id: "audio_other" });+ const doc = { ...emptyDoc(), audioTracks: [t1, t2], assets: [audioAsset] };expect(removeAudioTrack(doc, t1.id).assets).toEqual([audioAsset]);});+});- it("setAudioTrackGain stores a finite dB and defaults NaN to 0", () => {- const { doc, track } = docWithTrack();- expect(setAudioTrackGain(doc, track.id, -6).audioTracks[0]?.gainDb).toBe(-6);- expect(setAudioTrackGain(doc, track.id, Number.NaN).audioTracks[0]?.gainDb).toBe(0);+describe("patchAudioTrack", () => {+ it("applies a payload edit to every fragment", () => {+ const frags = anchorAudioTrackFragments(+ track({ startMs: 5000, endMs: 15_000 }),+ twoClips,+ makeId,+ );+ const doc = { ...emptyDoc(), audioTracks: frags };+ const next = patchAudioTrack(doc, trackGroupId(frags[0]), { gainDb: -6 });+ expect(next.audioTracks.map((t) => t.gainDb)).toEqual([-6, -6]);});- it("setAudioTrackPlacement writes position and trim together, staying schema-valid", () => {- const { doc, track } = docWithTrack();- const placed = setAudioTrackPlacement(doc, track.id, {- timelineStartSec: 8,- trimStartSec: 3,- trimEndSec: 12,- });- expect(placed.audioTracks[0]).toMatchObject({- timelineStartSec: 8,- trimStartSec: 3,- trimEndSec: 12,- });- // Same guards as the single-field ops: negatives floor, trimEnd >= trimStart.- const guarded = setAudioTrackPlacement(doc, track.id, {- timelineStartSec: -2,- trimStartSec: 5,- trimEndSec: 1,- });- expect(guarded.audioTracks[0]).toMatchObject({- timelineStartSec: 0,- trimStartSec: 5,- trimEndSec: 5,- });+ it("shifts the whole track by the offset delta, preserving each advance", () => {+ const frags = anchorAudioTrackFragments(+ track({ startMs: 5000, endMs: 15_000, offsetMs: 2000 }),+ twoClips,+ makeId,+ );+ const doc = { ...emptyDoc(), audioTracks: frags };+ // 2000 → 3000 is +1000 everywhere; fragment 2 keeps its 5000ms advance.+ const next = patchAudioTrack(doc, trackGroupId(frags[0]), { offsetMs: 3000 });+ expect(next.audioTracks.map((t) => t.offsetMs)).toEqual([3000, 8000]);});- it("update ops leave other tracks untouched", () => {- const a = createAudioTrack({ assetId: "asset_1", durationSec: 10 });- const b = createAudioTrack({ assetId: "asset_2", durationSec: 20 });- const doc = appendAudioTrack(appendAudioTrack(emptyDoc(), a), b);- const next = setAudioTrackGain(doc, b.id, -6);+ it("leaves other tracks untouched", () => {+ const a = track({ id: "audio_a" });+ const b = track({ id: "audio_b" });+ const doc = { ...emptyDoc(), audioTracks: [a, b] };+ const next = patchAudioTrack(doc, "audio_b", { gainDb: -6 });expect(next.audioTracks[0]).toEqual(a);expect(next.audioTracks[1]?.gainDb).toBe(-6);});diff --git a/src/lib/ai-edition/document/audioTracks.ts b/src/lib/ai-edition/document/audioTracks.tsindex 89c97473d..7b91071eb 100644--- a/src/lib/ai-edition/document/audioTracks.ts+++ b/src/lib/ai-edition/document/audioTracks.ts@@ -1,89 +1,155 @@-// Pure document operations for imported audio tracks (issue #350). No DOM, no-// IPC: each function takes an AxcutDocument and returns a new one with-// `audioTracks` updated. The store (useTimeline) wraps these with saveDocument;-// the schema factory (createAudioTrack) builds the track the append receives.+// Placement and payload edits for timeline audio tracks (issue #350).//-// Audio tracks are NOT clip-anchored — they float over the assembled programme-// in OUTPUT (post-trim/post-speed) timeline seconds — so unlike clip regions-// these ops need no anchoring, just array edits with schema-valid guards.--import type { AxcutAudioTrack, AxcutDocument } from "../schema";+// Audio tracks are CLIP-ANCHORED, so unlike the array-only ops this module used+// to hold, placement goes through the shared pill helpers in+// `timeline/timelineMap.ts` — the same machinery zoom, annotation, speed and+// camera-fullscreen regions already use. One user-visible track is one PILL;+// underneath it is one anchored fragment per clip it covers.+//+// The one thing audio needs that no other region kind does is `offsetMs`+// advancement. `anchorRawRegionsToClips` copies a region's payload verbatim+// into every fragment, which is right for value-per-span effects (both halves+// of a split zoom are still "depth 3") and wrong for continuous media: two+// fragments each carrying `offsetMs: 2000` would both restart the file two+// seconds in, so a bed spanning a cut audibly restarts at the boundary.+// `anchorAudioTrackFragments` fixes the payload up afterwards: every+// fragment's `offsetMs` is advanced by the source time its predecessors+// consumed.-// Timeline values arrive from drag deltas and persisted documents, both of which-// can carry NaN; every op clamps the same way the region ops in useTimeline do.-const finiteNonNeg = (n: number) => (Number.isFinite(n) ? Math.max(0, n) : 0);-const finite = (n: number) => (Number.isFinite(n) ? n : 0);+import type { AxcutAudioTrack, AxcutClip, AxcutDocument } from "../schema";+import { anchorRegionsWithDerivedMs, coalesceRegionsForRuler } from "../timeline/timelineMap";-/** Append a track (built by `createAudioTrack`) to the document. */-export function appendAudioTrack(doc: AxcutDocument, track: AxcutAudioTrack): AxcutDocument {- return { ...doc, audioTracks: [...doc.audioTracks, track] };+/** Every fragment of one user-visible track shares this key. */+export function trackGroupId(track: AxcutAudioTrack): string {+ return track.trackId ?? track.id;}/**- * Drop a track by id. A no-op if the id isn't present.+ * Anchor a track's raw span to the clips it covers, then repair the payload so+ * the fragments play as ONE continuous take:*- * Also drops the track's asset if nothing else references it. An imported audio- * asset is only ever reachable through its track — audio is filtered out of the- * clip lists, so it never becomes a clip — so a deleted track orphans it, and it- * would otherwise linger in the document forever, invisible in every asset list- * (issue #350).+ * - `offsetMs` advances by the elapsed source time, so fragment 2 picks up the+ * file where fragment 1 left off instead of restarting at the track offset.+ * - `trackId` ties the fragments together for the lane, the inspector and+ * delete.+ *+ * A track that overlaps no clip is returned unanchored (one fragment, the input+ * span), matching how `anchorRegionsWithDerivedMs` treats every other kind.*/-export function removeAudioTrack(doc: AxcutDocument, trackId: string): AxcutDocument {- const track = doc.audioTracks.find((t) => t.id === trackId);- const audioTracks = doc.audioTracks.filter((t) => t.id !== trackId);- if (!track) return { ...doc, audioTracks };- const stillReferenced =- audioTracks.some((t) => t.assetId === track.assetId) ||- doc.timeline.clips.some((c) => c.assetId === track.assetId);- const assets = stillReferenced ? doc.assets : doc.assets.filter((a) => a.id !== track.assetId);- return { ...doc, audioTracks, assets };+export function anchorAudioTrackFragments(+ track: AxcutAudioTrack,+ clips: AxcutClip[],+ makeId: () => string,+): AxcutAudioTrack[] {+ const groupId = trackGroupId(track);+ const anchored = anchorRegionsWithDerivedMs([track], clips, makeId) as AxcutAudioTrack[];+ if (anchored.length === 0) return [];+ // Fragments come back in clip order, which is the order they play.+ let elapsedMs = 0;+ return anchored.map((fragment) => {+ const spanMs = Math.max(0, fragment.endMs - fragment.startMs);+ const next: AxcutAudioTrack = {+ ...fragment,+ trackId: groupId,+ offsetMs: track.offsetMs + elapsedMs,+ };+ elapsedMs += spanMs;+ return next;+ });}-// Shared updater — maps the one matching track through `patch`. Keeps every op-// below a single expression and the "not found" case a clean no-op.-function updateAudioTrack(- doc: AxcutDocument,- trackId: string,- patch: (track: AxcutAudioTrack) => AxcutAudioTrack,-): AxcutDocument {- return {- ...doc,- audioTracks: doc.audioTracks.map((t) => (t.id === trackId ? patch(t) : t)),- };+/** Re-anchor every track in the document — used after a structural clip edit+ * reshuffles what each fragment sits over. */+export function reanchorAudioTracks(+ tracks: AxcutAudioTrack[],+ clips: AxcutClip[],+ makeId: () => string,+): 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) =>+ anchorAudioTrackFragments(track, clips, makeId),+ );}/**- * Set position and trim together in one write — what an edge-drag on the lane- * needs: dragging the left edge moves both `timelineStartSec` and `trimStartSec`- * at once, and committing that as two ops would be two undo steps. Floors both at- * 0 and pulls `trimEndSec` up to at least `trimStartSec` so the result always- * satisfies the schema's `trimEndSec >= trimStartSec` rule; `trimEndSec:- * undefined` clears the tail trim (play to the end of the file).+ * The user-visible tracks: fragments folded back into one span per `trackId`,+ * carrying the FIRST fragment's payload — its `offsetMs` is the track's real+ * offset, since later fragments hold advanced copies.*/-export function setAudioTrackPlacement(- doc: AxcutDocument,- trackId: string,- placement: { timelineStartSec: number; trimStartSec: number; trimEndSec?: number },-): AxcutDocument {- const timelineStartSec = finiteNonNeg(placement.timelineStartSec);- const trimStartSec = finiteNonNeg(placement.trimStartSec);- const trimEndSec =- placement.trimEndSec === undefined- ? undefined- : Math.max(trimStartSec, finiteNonNeg(placement.trimEndSec));- return updateAudioTrack(doc, trackId, (t) => ({- ...t,- timelineStartSec,- trimStartSec,- trimEndSec,- }));+export function collapseTracksToPills(tracks: AxcutAudioTrack[]): AxcutAudioTrack[] {+ const groups = new Map<string, AxcutAudioTrack[]>();+ for (const track of tracks) {+ const key = trackGroupId(track);+ const bucket = groups.get(key);+ if (bucket) bucket.push(track);+ else groups.set(key, [track]);+ }+ return [...groups.values()].map((fragments) => {+ const ordered = [...fragments].sort((a, b) => a.startMs - b.startMs);+ const head = ordered[0];+ const tail = ordered[ordered.length - 1];+ return {+ ...head,+ id: trackGroupId(head),+ trackId: undefined,+ clipId: undefined,+ sourceStartSec: undefined,+ sourceEndSec: undefined,+ startMs: head.startMs,+ endMs: tail.endMs,+ };+ });+}++/** Lane pills for the ruler, one per user-visible track. */+export function audioTrackPills(tracks: AxcutAudioTrack[]) {+ return coalesceRegionsForRuler(collapseTracksToPills(tracks));}-/** Set a track's level in dB. Any finite value; the mixer applies the gain. */-export function setAudioTrackGain(+/** Drop every fragment of a track, and its asset when nothing else needs it.+ *+ * An imported audio asset is only ever reachable through its track — audio is+ * filtered out of the clip lists, so it never becomes a clip — so a deleted+ * track orphans it, and it would otherwise linger in the document forever,+ * invisible in every asset list (issue #350). */+export function removeAudioTrack(doc: AxcutDocument, trackId: string): AxcutDocument {+ const doomed = doc.audioTracks.filter((t) => trackGroupId(t) === trackId);+ if (doomed.length === 0) return doc;+ const audioTracks = doc.audioTracks.filter((t) => trackGroupId(t) !== trackId);+ const assetId = doomed[0].assetId;+ const stillReferenced =+ audioTracks.some((t) => t.assetId === assetId) ||+ doc.timeline.clips.some((c) => c.assetId === assetId);+ const assets = stillReferenced ? doc.assets : doc.assets.filter((a) => a.id !== assetId);+ return { ...doc, audioTracks, assets };+}++/** Patch the shared payload of every fragment of one track. A payload edit must+ * hit ALL fragments or the halves of a split track disagree; `offsetMs` keeps+ * its per-fragment advance. */+export function patchAudioTrack(doc: AxcutDocument,trackId: string,- gainDb: number,+ patch: Partial<Pick<AxcutAudioTrack, "gainDb">> & { offsetMs?: number },): AxcutDocument {- return updateAudioTrack(doc, trackId, (t) => ({ ...t, gainDb: finite(gainDb) }));+ const fragments = doc.audioTracks.filter((t) => trackGroupId(t) === trackId);+ if (fragments.length === 0) return doc;+ const ordered = [...fragments].sort((a, b) => a.startMs - b.startMs);+ const baseOffset = ordered[0].offsetMs;+ return {+ ...doc,+ audioTracks: doc.audioTracks.map((t) => {+ if (trackGroupId(t) !== trackId) return t;+ return {+ ...t,+ ...(patch.gainDb === undefined ? {} : { gainDb: patch.gainDb }),+ // Shift the whole track by the delta so each fragment keeps the+ // advance that makes it continuous with its predecessor.+ ...(patch.offsetMs === undefined+ ? {}+ : { offsetMs: Math.max(0, t.offsetMs + (patch.offsetMs - baseOffset)) }),+ };+ }),+ };}diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.tsindex 56ac9c858..3cae3e665 100644--- a/src/lib/ai-edition/document/timeline.ts+++ b/src/lib/ai-edition/document/timeline.ts@@ -11,13 +11,14 @@ import {hasCompleteClipAnchor,} from "../timeline/timelineMap";import { dropTrimPillsByIds, trimAppliesToClip } from "../timeline/trim-mapping";+import { removeAudioTrack } from "./audioTracks";import { createId } from "./ids";/** The region families a delete can target by id. Shared with the store so "which kinds* exist" has exactly one definition. `trim` is a source-time cut; the rest are pill-merged* effects (zoom / speed / annotation / camera-fullscreen). Clips are removed via* {@link removeClip}, not here — deleting a clip reflows the whole timeline. */-export type RegionKind = "zoom" | "trim" | "annotation" | "speed" | "cameraFullscreen";+export type RegionKind = "zoom" | "trim" | "annotation" | "speed" | "cameraFullscreen" | "audio";/** Length a clip is given before its media has been probed. Lives here, in the pure* document layer, because that layer decides which clips are still waiting for a real@@ -333,6 +334,10 @@ function mapAllRegionCollections(document.annotations as unknown as StoredRegion[],"ann",) as unknown as AxcutDocument["annotations"],+ audioTracks: fn(+ document.audioTracks as unknown as StoredRegion[],+ "audio",+ ) as unknown as AxcutDocument["audioTracks"],legacyEditor:legacy && (speedRegions || cameraFullscreenRegions)? {@@ -953,6 +958,11 @@ export function removeRegion(document: AxcutDocument, kind: RegionKind, id: stri};case "annotation":return { ...document, annotations: dropPillById(document.annotations, id) };+ case "audio":+ // Not `dropPillById`: an audio track's fragments are grouped by+ // `trackId`, and deleting the pill has to take the asset with it when+ // nothing else references it.+ return removeAudioTrack(document, id);case "trim":return {...document,diff --git a/src/lib/ai-edition/schema/index.test.ts b/src/lib/ai-edition/schema/index.test.tsindex 2e69c6a42..90df28d28 100644--- a/src/lib/ai-edition/schema/index.test.ts+++ b/src/lib/ai-edition/schema/index.test.ts@@ -975,38 +975,42 @@ describe("v6 -> v7 trim clip-anchor migration", () => {});describe("audio tracks (issue #350)", () => {- it("applies defaults for gain, trim, position, and label", () => {+ it("applies defaults for gain, offset and label", () => {const track = audioTrackSchema.parse({id: "audio_1",assetId: "asset_1",durationSec: 42,+ startMs: 0,+ endMs: 42_000,});- expect(track.timelineStartSec).toBe(0);- expect(track.trimStartSec).toBe(0);- expect(track.trimEndSec).toBeUndefined();+ expect(track.offsetMs).toBe(0);expect(track.gainDb).toBe(0);expect(track.label).toBe("");+ // Unanchored until a caller places it — same contract as every other+ // clip-anchored region kind.+ expect(track.clipId).toBeUndefined();});- it("rejects a trim window whose end precedes its start", () => {+ it("rejects a span whose end precedes its start", () => {expect(() =>audioTrackSchema.parse({id: "audio_1",assetId: "asset_1",durationSec: 10,- trimStartSec: 5,- trimEndSec: 2,+ startMs: 5000,+ endMs: 2000,}),).toThrow();});- it("rejects a negative timelineStartSec", () => {+ it("rejects a negative head", () => {expect(() =>audioTrackSchema.parse({id: "audio_1",assetId: "asset_1",durationSec: 10,- timelineStartSec: -1,+ startMs: -1,+ endMs: 1000,}),).toThrow();});@@ -1021,12 +1025,30 @@ describe("audio tracks (issue #350)", () => {expect(track.id).toMatch(/^audio_/);expect(track.assetId).toBe("asset_1");expect(track.durationSec).toBe(12.5);- expect(track.timelineStartSec).toBe(3);+ // The span runs from the head for the source duration by default.+ expect(track.startMs).toBe(3000);+ expect(track.endMs).toBe(15_500);expect(track.label).toBe("voiceover.mp3");// The factory output must itself round-trip through the schema.expect(() => audioTrackSchema.parse(track)).not.toThrow();});+ it("createAudioTrack takes a shorter span than the source when asked", () => {+ const track = createAudioTrack({+ assetId: "asset_1",+ durationSec: 30,+ timelineStartSec: 2,+ spanSec: 4,+ });+ expect(track.startMs).toBe(2000);+ expect(track.endMs).toBe(6000);+ });++ it("createAudioTrack still gives a grabbable span to a zero-duration source", () => {+ const track = createAudioTrack({ assetId: "asset_1", durationSec: 0 });+ expect(track.endMs).toBeGreaterThan(track.startMs);+ });+it("defaults audioTracks to [] when a stored document omits the key", () => {// A document written before issue #350 has no `audioTracks`; the defaulted// array must fill in so older files load unchanged (no schemaVersion bump).diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.tsindex d7fd4763c..10a26d749 100644--- a/src/lib/ai-edition/schema/index.ts+++ b/src/lib/ai-edition/schema/index.ts@@ -492,25 +492,51 @@ export const zoomRegionSchema = endGteStart(// `assetId` points at an asset with `kind: "audio"`. `timelineStartSec` places// the track's head; `trimStartSec`/`trimEndSec` window the source file (both in// source seconds); `gainDb` sets its level.-export const audioTrackSchema = z- .object({+// An imported or recorded audio track (voiceover / BGM / SFX) placed on the+// timeline (issue #350).+//+// CLIP-ANCHORED, on the same v5 contract as zoom/annotation: `{clipId,+// sourceStartSec, sourceEndSec}` is the source of truth and `startMs`/`endMs`+// is a derived ruler cache, so a track travels with the content it was placed+// over instead of sitting still while a reorder or trim slides the programme+// underneath it. Positions are RAW ruler ms; the export projects them onto the+// trim-compressed programme (`projectRawTimelineSecToPlayback`).+//+// `offsetMs` skips INTO the source file — start the music at its chorus. It+// replaces #502's `trimStartSec`/`trimEndSec` pair: the track's own span+// (`startMs`..`endMs`) is where it plays, so the tail trim is implied by the+// span and does not need storing twice. A file longer than its span is cut off+// at the span unless `loop` is set, in which case it repeats.+//+// The anchor ventilates one user-visible track into one fragment PER CLIP it+// covers. Fragments of the same track share `trackId`, and each carries its own+// `offsetMs` advanced by the source time its predecessors consumed — see+// `anchorAudioTrackFragments`. Without that every fragment would restart the+// file at the same offset, so a bed spanning a cut would audibly restart at+// the boundary.+export const audioTrackSchema = endGteStart(+ z.object({id: z.string().min(1),+ // Shared by every fragment of one user-visible track: what the lane draws+ // as a single pill, what the inspector edits, and what delete removes.+ // Absent on tracks written before ventilation existed — they are their own+ // single fragment, so `trackId ?? id` is always the group key.+ trackId: z.string().min(1).optional(),+ startMs: z.number().nonnegative(),+ endMs: z.number().nonnegative(),+ ...clipAnchorShape,assetId: z.string().min(1),- timelineStartSec: z.number().nonnegative().default(0),// Full source duration of the underlying file, cached here so the timeline// can lay out the pill before the asset is re-probed on load.durationSec: z.number().nonnegative().default(0),- trimStartSec: z.number().nonnegative().default(0),- // Absent means "play to the end of the file". Explicit when the user trims- // the tail so the pill and the export agree on where the track stops.- trimEndSec: z.number().nonnegative().optional(),- gainDb: z.number().default(0),+ offsetMs: z.number().int().nonnegative().default(0),+ gainDb: z.number().min(-60).max(12).default(0),label: z.string().default(""),- })- .refine((data) => data.trimEndSec === undefined || data.trimEndSec >= data.trimStartSec, {- message: "trimEndSec must be greater than or equal to trimStartSec",- path: ["trimEndSec"],- });+ origin: z.enum(["system", "agent", "user"]).default("user"),+ }),+ "endMs",+ "startMs",+);// Legacy OpenScreen appearance / export settings that the v3 schema doesn't// normalize into the timeline / assets model. They are applied at export time@@ -1036,25 +1062,36 @@ export function ensureDocument(value: unknown): AxcutDocument {}/**- * Build a timeline audio track for an imported audio asset (issue #350). The- * head is placed at `timelineStartSec` (RAW/document timeline seconds — the same- * clock the ruler, playhead and clip `timelineStartSec` use, NOT the- * trim-compressed output programme; the export projects it with+ * Build a timeline audio track for an imported or recorded audio asset+ * (issue #350). The head is placed at `timelineStartSec` (RAW/document timeline+ * seconds — the same clock the ruler, playhead and clip `timelineStartSec` use,+ * NOT the trim-compressed output programme; the export projects it with* `projectRawTimelineSecToPlayback`) and the track spans the whole source file- * until the user trims it. Parsed through the schema so every default (gain,- * trim) is applied in one place.+ * unless the caller asks for a shorter `spanSec`. Parsed through the schema so+ * every default (gain, fades, loop) is applied in one place.+ *+ * The result is UNANCHORED — `clipId` is absent. Callers place it through+ * `anchorAudioTrackFragments`, which ventilates it across the clips it covers.*/export function createAudioTrack(input: {assetId: string;durationSec: number;+ /** Raw ruler head. The span runs from here for `durationSec`, or for+ * `spanSec` when the caller wants a shorter placement than the file. */timelineStartSec?: number;+ spanSec?: number;label?: string;}): AxcutAudioTrack {+ const startMs = Math.round(Math.max(0, input.timelineStartSec ?? 0) * 1000);+ // A track with no measurable source still needs a visible span, or the pill+ // is zero-width and cannot be grabbed to fix.+ const spanMs = Math.max(1, Math.round((input.spanSec ?? input.durationSec) * 1000));return audioTrackSchema.parse({id: createId("audio"),assetId: input.assetId,durationSec: input.durationSec,- timelineStartSec: input.timelineStartSec ?? 0,+ startMs,+ endMs: startMs + spanMs,label: input.label ?? "",});}diff --git a/src/lib/ai-edition/store/documentWriteAudit.test.ts b/src/lib/ai-edition/store/documentWriteAudit.test.tsindex 4647d87a4..cb4dc775d 100644--- a/src/lib/ai-edition/store/documentWriteAudit.test.ts+++ b/src/lib/ai-edition/store/documentWriteAudit.test.ts@@ -134,7 +134,8 @@ const DECLARED: WritePath[] = [// "Save" chosen on the way out of Ctrl+N and Ctrl+O.w("src/components/ai-edition/NewEditorShell.tsx", "onKey", "save", "gesture"),w("src/components/ai-edition/NewEditorShell.tsx", "onKey", "save", "gesture"),- // Ctrl+V of a copied region: zoom, annotation, or a legacy span.+ // Ctrl+V of a copied region: an audio track, zoom, annotation, or a legacy span.+ w("src/components/ai-edition/NewEditorShell.tsx", "pasteRegion", "save", "gesture"),w("src/components/ai-edition/NewEditorShell.tsx", "pasteRegion", "save", "gesture"),w("src/components/ai-edition/NewEditorShell.tsx", "pasteRegion", "save", "gesture"),w("src/components/ai-edition/NewEditorShell.tsx", "pasteRegion", "save", "gesture"),@@ -240,11 +241,12 @@ const DECLARED: WritePath[] = [w("src/lib/ai-edition/store/useTimeline.ts", "duplicateClip", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "insertClipAt", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "moveClip", "save", "gesture"),- // Imported audio tracks (issue #350). Each is a direct user edit — drag/trim the- // track (placeAudioTrack), change its level, or delete it — one undo step apiece.+ // Timeline audio tracks (issue #350). Each is a direct user edit — drag or resize+ // the track (placeAudioTrack), change its payload (updateAudioTrack, which+ // setAudioTrackGain routes through), or delete it — one undo step apiece.w("src/lib/ai-edition/store/useTimeline.ts", "placeAudioTrack", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "removeAudioTrack", "save", "gesture"),- w("src/lib/ai-edition/store/useTimeline.ts", "setAudioTrackGain", "save", "gesture"),+ w("src/lib/ai-edition/store/useTimeline.ts", "updateAudioTrack", "save", "gesture"),// The round-2 defect: a background duration probe every freshly imported asset// fires, because `addAsset` never populates `durationSec`.w("src/lib/ai-edition/store/useTimeline.ts", "probeAndCorrectClip", "save", "automatic"),diff --git a/src/lib/ai-edition/store/projectStore.test.ts b/src/lib/ai-edition/store/projectStore.test.tsindex 6039f0a11..2b75f0a04 100644--- a/src/lib/ai-edition/store/projectStore.test.ts+++ b/src/lib/ai-edition/store/projectStore.test.ts@@ -400,7 +400,8 @@ describe("useProjectStore", () => {const tracks = useProjectStore.getState().document?.audioTracks ?? [];expect(tracks).toHaveLength(1);- expect(tracks[0]).toMatchObject({ assetId: "audio_1", timelineStartSec: 5, durationSec: 12 });+ // Head at the playhead (5s), in raw ruler ms.+ expect(tracks[0]).toMatchObject({ assetId: "audio_1", startMs: 5000, durationSec: 12 });expect(id).toBe(tracks[0]?.id);// Placing a track selects it so the inspector opens on its controls.expect(useProjectStore.getState().selectedAudioTrackId).toBe(id);diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.tsindex c878e1d35..7d1eb3e83 100644--- a/src/lib/ai-edition/store/projectStore.ts+++ b/src/lib/ai-edition/store/projectStore.ts@@ -3,7 +3,8 @@ import { create } from "zustand";import { toFileUrl } from "@/components/video-editor/projectPersistence";import { toastText } from "@/i18n/toastText";import { nativeBridgeClient } from "@/native/client";-import { appendAudioTrack } from "../document/audioTracks";+import { anchorAudioTrackFragments } from "../document/audioTracks";+import { createId } from "../document/ids";import { type Interval, replaceTimeline as replaceTimelineOp } from "../document/timeline";import { type AxcutAsset, type AxcutDocument, createAudioTrack, documentSchema } from "../schema";import { probeAudioDuration, probeVideoDimensions } from "../timeline/duration";@@ -96,7 +97,16 @@ export interface ProjectState {importAudioAsset: (path: string, label?: string) => Promise<AxcutAsset | null>;/** Place a track for an already-imported audio asset at `timelineStartSec`* (default: the playhead) and select it. Returns the new track id, or null. */- addAudioTrack: (assetId: string, timelineStartSec?: number) => Promise<string | null>;+ addAudioTrack: (+ assetId: string,+ timelineStartSec?: number,+ options?: {+ /** Real source duration, when the caller measured it. */+ durationSec?: number;+ /** Timeline span, when it should differ from the source duration. */+ spanSec?: number;+ },+ ) => Promise<string | null>;setSelectedAudioTrackId: (id: string | null) => void;removeAsset: (assetId: string) => Promise<void>;/**@@ -402,23 +412,29 @@ export const useProjectStore = create<ProjectState>((set, get) => ({set({ selectedAudioTrackId: id });},- async addAudioTrack(assetId, timelineStartSec) {+ async addAudioTrack(assetId, timelineStartSec, options) {const document = get().document;if (!document) return null;const asset = document.assets.find((a) => a.id === assetId);if (!asset || asset.kind !== "audio") return null;const track = createAudioTrack({assetId,- durationSec: asset.durationSec ?? 0,+ durationSec: options?.durationSec ?? asset.durationSec ?? 0,+ spanSec: options?.spanSec,// Default to the playhead (RAW/document timeline seconds — the clock the// ruler and playhead use, NOT the trim-compressed output programme),// matching the timeline hook's placement.timelineStartSec: timelineStartSec ?? get().currentTimeSec,label: asset.label,});- if (!(await get().saveDocument(appendAudioTrack(document, track), { history: true }))) {- return null;- }+ // Anchor before saving: the track becomes one fragment per clip it covers,+ // each picking the source up where the previous one left off.+ const fragments = anchorAudioTrackFragments(track, document.timeline.clips, () =>+ createId("audio"),+ );+ if (fragments.length === 0) return null;+ const next = { ...document, audioTracks: [...document.audioTracks, ...fragments] };+ if (!(await get().saveDocument(next, { history: true }))) return null;set({ selectedAudioTrackId: track.id });return track.id;},diff --git a/src/lib/ai-edition/store/regionClipboard.ts b/src/lib/ai-edition/store/regionClipboard.tsindex ef1116ff8..f0d6d7d10 100644--- a/src/lib/ai-edition/store/regionClipboard.ts+++ b/src/lib/ai-edition/store/regionClipboard.ts@@ -11,6 +11,10 @@ export type RegionSnapshot =| { kind: "annotation"; region: Record<string, unknown> }| { kind: "speed"; region: Record<string, unknown> }| { kind: "cameraFullscreen"; region: Record<string, unknown> }+ // An audio track copies its whole payload (asset, gain, fades, loop) so a+ // paste is a second placement of the same audio, like every other kind. The+ // snapshot is the COLLAPSED pill, never a stored fragment.+ | { kind: "audio"; region: Record<string, unknown> }// A trim carries no user-visible properties, so all there is to copy is how// LONG it was — `{ durationSec }`. That is not a special case so much as the// general one made obvious: every paste keeps the copied properties and takesdiff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.tsindex 0e301c6b2..66b95f8b2 100644--- a/src/lib/ai-edition/store/useTimeline.test.ts+++ b/src/lib/ai-edition/store/useTimeline.test.ts@@ -1344,7 +1344,8 @@ describe("useTimeline audio tracks", () => {expect(tracks[0]).toMatchObject({assetId: "audio_1",durationSec: 30,- timelineStartSec: 4,+ // Head at the playhead (4s), span the source's own length.+ startMs: 4000,label: "voiceover.mp3",});});@@ -1368,13 +1369,9 @@ describe("useTimeline audio tracks", () => {await act(async () => {id = (await result.current.addAudioTrack("audio_1", 2)) ?? "";});- // A lane drag commits position and trim together (see placeAudioTrack).+ // A lane drag commits the whole span in one write and re-ventilates it.await act(async () => {- await result.current.placeAudioTrack(id, {- timelineStartSec: 9,- trimStartSec: 1,- trimEndSec: 8,- });+ await result.current.placeAudioTrack(id, { startMs: 3000, endMs: 8000 });});await act(async () => {await result.current.setAudioTrackGain(id, -6);@@ -1382,9 +1379,8 @@ describe("useTimeline audio tracks", () => {const track = useProjectStore.getState().document?.audioTracks[0];expect(track).toMatchObject({- timelineStartSec: 9,- trimStartSec: 1,- trimEndSec: 8,+ startMs: 3000,+ endMs: 8000,gainDb: -6,});@@ -1395,6 +1391,23 @@ describe("useTimeline audio tracks", () => {expect(useProjectStore.getState().document?.audioTracks[0]?.gainDb).toBe(0);});+ it("clamps a track to the content under it, like every other anchored region", async () => {+ // The sample timeline is one 0..10s clip. A track dragged past the end has+ // nothing to anchor to out there — and the exported programme stops at the+ // last clip regardless — so the span is cut at the content, not stored+ // hanging off the end where it could never play.+ const { result } = renderTimeline();+ let id = "";+ await act(async () => {+ id = (await result.current.addAudioTrack("audio_1", 2)) ?? "";+ });+ await act(async () => {+ await result.current.placeAudioTrack(id, { startMs: 9000, endMs: 16_000 });+ });+ const track = useProjectStore.getState().document?.audioTracks[0];+ expect(track).toMatchObject({ startMs: 9000, endMs: 10_000 });+ });+it("removeAudioTrack deletes the track", async () => {const { result } = renderTimeline();let id = "";@@ -1506,11 +1519,13 @@ describe("useTimeline audio tracks", () => {{id: "trk_2",assetId: "audio_2",- timelineStartSec: 0,+ startMs: 0,+ endMs: 1,durationSec: 0,- trimStartSec: 0,+ offsetMs: 0,gainDb: 0,label: "bgm.mp3",+ origin: "user" as const,},],},diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.tsindex f96b50faa..e13ce4b59 100644--- a/src/lib/ai-edition/store/useTimeline.ts+++ b/src/lib/ai-edition/store/useTimeline.ts@@ -9,9 +9,11 @@ import { toFileUrl } from "@/components/video-editor/projectPersistence";import type { AnnotationRegion, AnnotationType } from "@/components/video-editor/types";import { useScopedT } from "@/contexts/I18nContext";import {+ anchorAudioTrackFragments,+ collapseTracksToPills,+ patchAudioTrack,removeAudioTrack as removeAudioTrackInDocument,- setAudioTrackGain as setAudioTrackGainInDocument,- setAudioTrackPlacement as setAudioTrackPlacementInDocument,+ trackGroupId,} from "../document/audioTracks";import { createId } from "../document/ids";import {@@ -25,7 +27,7 @@ import {resequenceClips,setClipSourceRange,} from "../document/timeline";-import type { AxcutClipCropRegion, AxcutDocument } from "../schema";+import type { AxcutAudioTrack, AxcutClipCropRegion, AxcutDocument } from "../schema";import { hasAnyClipWithCamera } from "../timeline/camera";import { probeAudioDuration, probeVideoDimensions, probeVideoDuration } from "../timeline/duration";import {@@ -150,7 +152,7 @@ export function useTimeline() {// inspector stays open on an empty AudioTrackPane, recoverable only by clicking a facet.useEffect(() => {if (selectedAudioTrackId === null) return;- if (!document?.audioTracks.some((t) => t.id === selectedAudioTrackId)) {+ if (!document?.audioTracks.some((t) => trackGroupId(t) === selectedAudioTrackId)) {setSelectedAudioTrackId(null);}}, [document, selectedAudioTrackId, setSelectedAudioTrackId]);@@ -1270,9 +1272,10 @@ export function useTimeline() {}>) ?? []): [];- // --- Imported audio tracks (issue #350) -------------------------------------- // Timeline-global overlays, so unlike the region ops above these need no clip- // anchoring — each just writes `document.audioTracks` through the pure ops.+ // --- Timeline audio tracks (issue #350) -------------------------------------+ // CLIP-ANCHORED like every region above: one user-visible track is one pill+ // over one-or-more stored fragments, so these ops go through the shared pill+ // helpers and address a track by its group id, never a fragment id.// Place a new track for an imported audio asset, its head at the playhead (in// RAW/document timeline seconds — the clock the ruler and playhead use, NOT the@@ -1282,8 +1285,12 @@ export function useTimeline() {// selection so the new audio-track selection isn't held CONCURRENTLY with a// stale region/clip one.const addAudioTrack = useCallback(- async (assetId: string, timelineStartSec?: number): Promise<string | null> => {- const id = await storeAddAudioTrack(assetId, timelineStartSec ?? playheadSec());+ async (+ assetId: string,+ timelineStartSec?: number,+ options?: { durationSec?: number; spanSec?: number },+ ): Promise<string | null> => {+ const id = await storeAddAudioTrack(assetId, timelineStartSec ?? playheadSec(), options);if (id) {setSelection(null);setMultiSelection([]);@@ -1336,28 +1343,50 @@ export function useTimeline() {[document, saveDocument, selectedAudioTrackId, setSelectedAudioTrackId],);- // The commit for a lane drag: position and trim in one write (one undo step).- // A left-edge drag moves both timelineStartSec and trimStartSec, which two- // separate ops could not do atomically. See setAudioTrackPlacement.+ // The commit for a lane drag or edge-resize: move the pill's whole span and+ // re-ventilate it, so a track dragged across a cut becomes the right set of+ // fragments in one write (one undo step). `offsetMs` is preserved as the+ // track's own — `anchorAudioTrackFragments` re-derives each fragment's+ // advance from the new geometry.const placeAudioTrack = useCallback(- async (- trackId: string,- placement: { timelineStartSec: number; trimStartSec: number; trimEndSec?: number },- ) => {- if (!document) return;- await saveDocument(setAudioTrackPlacementInDocument(document, trackId, placement), {- history: true,- });+ async (trackId: string, span: { startMs: number; endMs: number }) => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ const others = doc.audioTracks.filter((t) => trackGroupId(t) !== trackId);+ const [pill] = collapseTracksToPills(+ doc.audioTracks.filter((t) => trackGroupId(t) === trackId),+ );+ if (!pill) return;+ const moved = {+ ...pill,+ startMs: Math.max(0, Math.round(span.startMs)),+ endMs: Math.max(Math.round(span.startMs) + 1, Math.round(span.endMs)),+ };+ const fragments = anchorAudioTrackFragments(moved, doc.timeline.clips, () =>+ createId("audio"),+ );+ if (fragments.length === 0) return;+ await saveDocument({ ...doc, audioTracks: [...others, ...fragments] }, { history: true });},- [document, saveDocument],+ [saveDocument],+ );++ // Payload edits hit every fragment of the track — the halves of a split take+ // must not disagree about their own level.+ const updateAudioTrack = useCallback(+ async (trackId: string, patch: Partial<Pick<AxcutAudioTrack, "gainDb" | "offsetMs">>) => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ await saveDocument(patchAudioTrack(doc, trackId, patch), { history: true });+ },+ [saveDocument],);const setAudioTrackGain = useCallback(async (trackId: string, gainDb: number) => {- if (!document) return;- await saveDocument(setAudioTrackGainInDocument(document, trackId, gainDb), { history: true });+ await updateAudioTrack(trackId, { gainDb });},- [document, saveDocument],+ [updateAudioTrack],);return {@@ -1384,6 +1413,7 @@ export function useTimeline() {addAudioTrack,addAudio,removeAudioTrack,+ updateAudioTrack,placeAudioTrack,setAudioTrackGain,selectedAudioTrackId,diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.tsindex 1f7978cbe..60cb37ebd 100644--- a/src/native/sceneDescription.test.ts+++ b/src/native/sceneDescription.test.ts@@ -2000,15 +2000,17 @@ describe("buildSceneDescription.audioTracks", () => {originalPath: "/music.mp3",durationSec: 30,});+ // A 10s span starting at raw 5s, playing the source from 2s in.const track = {id: "trk1",assetId: "aud",- timelineStartSec: 5,+ startMs: 5000,+ endMs: 15_000,durationSec: 30,- trimStartSec: 2,- trimEndSec: 12 as number | undefined,+ offsetMs: 2000,gainDb: -3,label: "",+ origin: "user" as const,};it("maps a track to the mix list with its resolved path and window", () => {@@ -2019,17 +2021,19 @@ describe("buildSceneDescription.audioTracks", () => {startSec: 5,gainDb: -3,trimStartSec: 2,+ // The span is 10s and the file has 28s left after the offset, so the+ // span is what runs out first.trimEndSec: 12,},]);});- it("resolves the trim-out to the source duration when the tail isn't trimmed", () => {+ it("caps the trim-out at the end of the file when the span outlasts it", () => {const doc = makeDoc({assets: [audioAsset],- audioTracks: [{ ...track, trimEndSec: undefined }],+ // A 40s span over a 30s file, offset 2s: only 28s of source exist.+ audioTracks: [{ ...track, endMs: 45_000 }],});- // trimEndSec must be concrete for the compositor; falls back to durationSec.expect(buildSceneDescription(doc).audioTracks[0]?.trimEndSec).toBe(30);});diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.tsindex 64ea56eff..5b97dbb81 100644--- a/src/native/sceneDescription.ts+++ b/src/native/sceneDescription.ts@@ -415,14 +415,17 @@ export interface SceneDescription {gainDb: number;};/**- * Imported audio tracks (issue #350), mixed over the assembled programme by- * `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.+ * Timeline audio tracks (issue #350), mixed over the assembled programme by+ * `audio::mix_external_tracks`. One entry per contiguous stretch: a track split by a+ * clip boundary contributes one entry per fragment, each picking the source up where+ * the last left off.+ *+ * `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 from the span and the source duration.*/audioTracks: Array<{path: string;@@ -492,11 +495,22 @@ function parseWallpaper(wallpaper: string) {* `NativeCompositorOverlay.tsx`'s `nativeClips` (live preview) — previously these three each* hand-rolled their own sort+filter, acknowledged as needing to be "kept in lock-step".*/+/** Whether a clip's media can actually be read — the one rule that decides+ * which clips make it into the programme. Shared with the audio-track+ * projection, which must count exactly the clips the programme is built from+ * or every track after a relinked-away clip lands late. */+function clipAssetIsResolvable(+ clip: { assetId: string },+ assetById: Map<string, { originalPath?: string }>,+): boolean {+ return Boolean(assetById.get(clip.assetId)?.originalPath);+}+export function resolveVisibleClips(document: AxcutDocument): AxcutClip[] {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)- .filter((clip) => assetById.get(clip.assetId)?.originalPath);+ .filter((clip) => clipAssetIsResolvable(clip, assetById));}/** Serialize a document into a {@link SceneDescription}. Pure — no per-frame math. */@@ -507,35 +521,53 @@ export function buildSceneDescription(const settings = getEditorSettings(document);const assetById = new Map(document.assets.map((a) => [a.id, a]));- // Imported audio tracks (issue #350) → the compositor's mix list. Resolve the- // asset's file path and a concrete trim-out (the source duration when the tail- // isn't trimmed — the compositor preallocates its decode window from it). A- // track whose asset or path is missing is dropped rather than sent path-less.- // Project onto the SAME clips the programme is assembled from. `resolveVisibleClips`- // (below) drops clips whose asset has no resolvable `originalPath`; if the projection- // walked the full `document.timeline.clips` it would count a relinked-away clip the- // programme does not, landing every following track past the real programme end.- const projectedClips = document.timeline.clips.filter(- (clip) => assetById.get(clip.assetId)?.originalPath,+ // Timeline audio tracks (issue #350) → the compositor's mix list.+ //+ // Each STORED track is one clip-anchored fragment, already carrying its own+ // advanced `offsetMs`, so a fragment maps to one contiguous decode window and+ // the pieces of a split take play as one continuous take. Project each head+ // onto the trim-compressed programme the mixer overlays on: the head is+ // stored in RAW ruler seconds, and passing it verbatim delayed every track by+ // the total trim duration ahead of it (issue #350).+ //+ // Projected onto the same clips the programme is assembled from —+ // `resolveVisibleClips` drops clips whose asset has no resolvable+ // `originalPath`, and a projection that counted a relinked-away clip the+ // programme does not would land every following track past the real end.+ // `projectRawTimelineSecToPlayback` subtracts the trims itself, so it needs+ // the RAW clips behind that filter, not the already-compressed segments.+ const projectedClips = document.timeline.clips.filter((clip) =>+ clipAssetIsResolvable(clip, assetById),);const audioTracks = document.audioTracks.flatMap((track) => {const asset = assetById.get(track.assetId);if (!asset?.originalPath) return [];- const trimEndSec = track.trimEndSec ?? asset.durationSec ?? track.durationSec;+ const sourceDurationSec = asset.durationSec ?? track.durationSec;+ const offsetSec = track.offsetMs / 1000;+ const spanSec = (track.endMs - track.startMs) / 1000;+ if (spanSec <= 0) return [];+ // The window the file has left after the offset. Without a probed duration+ // there is nothing to cap the tail with, so the span itself is the window —+ // the mixer stops at the real end of the file.+ const windowSec = sourceDurationSec > 0 ? Math.max(0, sourceDurationSec - offsetSec) : spanSec;+ if (windowSec <= 0) return [];return [{path: asset.originalPath,- // 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).+ // The 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(projectedClips,document.timeline.trimRanges,- track.timelineStartSec,+ track.startMs / 1000,),gainDb: track.gainDb,- trimStartSec: track.trimStartSec,- trimEndSec,+ trimStartSec: offsetSec,+ // Always concrete: the compositor preallocates its decode window+ // from it. Whichever runs out first — the span or the file.+ trimEndSec: offsetSec + Math.min(windowSec, spanSec),},];});