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): fades, loop and mute on timeline audio tracks
Ola Adebayo1ad8edde46aa
diff --git a/crates/compositor/src/audio.rs b/crates/compositor/src/audio.rsindex 89da8cbec..b2674b85d 100644--- a/crates/compositor/src/audio.rs+++ b/crates/compositor/src/audio.rs@@ -1431,8 +1431,17 @@ pub fn mix_external_tracks(mut programme: PlanarPcm, tracks: &[SceneAudioTrack])Ok(Some(pcm)) => pcm,_ => continue,};- let gain = 10.0f32.powf(track.gain_db.clamp(-12.0, 12.0) / 20.0);- overlay_track_pcm(&mut programme, &decoded, offset, gain);+ // The app's own range is -60..+12 dB (the inspector slider); clamping at+ // -12 here floored every quiet bed at a tenth of the attenuation asked for.+ let gain = 10.0f32.powf(track.gain_db.clamp(-60.0, 12.0) / 20.0);+ overlay_track_pcm(+ &mut programme,+ &decoded,+ offset,+ gain,+ track.fade_in_sec.max(0.0),+ track.fade_out_sec.max(0.0),+ );}programme}@@ -1441,12 +1450,24 @@ pub fn mix_external_tracks(mut programme: PlanarPcm, tracks: &[SceneAudioTrack])/// truncated at the programme's end. Split out of `mix_external_tracks` so the/// placement/gain/clamp math is testable without ffmpeg, exactly like/// `mix_aligned_tracks` is split from the decode above.-fn overlay_track_pcm(programme: &mut PlanarPcm, decoded: &PlanarPcm, offset: usize, gain: f32) {+fn overlay_track_pcm(+ programme: &mut PlanarPcm,+ decoded: &PlanarPcm,+ offset: usize,+ gain: f32,+ fade_in_sec: f64,+ fade_out_sec: f64,+) {let programme_len = programme.first().map(Vec::len).unwrap_or(0);if offset >= programme_len {return;}let room = programme_len - offset;+ // The ramps are measured against the DECODED length, not the room left in the+ // programme: a track running past the end is cut off there, and a fade-out+ // timed to the cut would ramp down over audio the export never reaches.+ let decoded_len = decoded.iter().map(Vec::len).max().unwrap_or(0);+ let (fade_in, fade_out) = resolve_fade_samples(decoded_len, fade_in_sec, fade_out_sec);for channel in 0..AUDIO_OUTPUT_CHANNELS {let Some(source) = decoded.get(channel) else {continue;@@ -1454,9 +1475,46 @@ fn overlay_track_pcm(programme: &mut PlanarPcm, decoded: &PlanarPcm, offset: usilet count = source.len().min(room);let dst = &mut programme[channel];for k in 0..count {- dst[offset + k] += source[k] * gain;+ dst[offset + k] += source[k] * gain * fade_envelope(k, decoded_len, fade_in, fade_out);+ }+ }+}++/// Fade lengths in samples, reduced to fit inside `len`.+///+/// Fades that do not fit share the window in proportion rather than being clamped+/// independently: clamping each to the length first would turn an asymmetric pair+/// into a symmetric one, losing the shape asked for. Kept identical to the app's+/// `resolveFadeSecs` so the preview and the render agree.+fn resolve_fade_samples(len: usize, fade_in_sec: f64, fade_out_sec: f64) -> (usize, usize) {+ if len == 0 {+ return (0, 0);+ }+ let rate = AUDIO_OUTPUT_SAMPLE_RATE as f64;+ let mut fade_in = fade_in_sec.max(0.0) * rate;+ let mut fade_out = fade_out_sec.max(0.0) * rate;+ let total = fade_in + fade_out;+ if total > len as f64 && total > 0.0 {+ let scale = len as f64 / total;+ fade_in *= scale;+ fade_out *= scale;+ }+ (fade_in.round() as usize, fade_out.round() as usize)+}++/// Linear ramp factor at sample `k` of a `len`-sample track.+fn fade_envelope(k: usize, len: usize, fade_in: usize, fade_out: usize) -> f32 {+ let mut v = 1.0f32;+ if fade_in > 0 && k < fade_in {+ v = v.min(k as f32 / fade_in as f32);+ }+ if fade_out > 0 && len > k {+ let remaining = len - k;+ if remaining <= fade_out {+ v = v.min(remaining as f32 / fade_out as f32);}}+ v}/// Encodeur AAC attaché au muxer avant son header. Les paquets utilisent le même interleaver@@ -1775,7 +1833,7 @@ mod tests {fn overlay_sums_at_offset_with_gain() {let mut programme = planar(&[0.1, 0.1, 0.1, 0.1]);// ×2 gain, placed at sample offset 1.- overlay_track_pcm(&mut programme, &planar(&[0.2, 0.2]), 1, 2.0);+ overlay_track_pcm(&mut programme, &planar(&[0.2, 0.2]), 1, 2.0, 0.0, 0.0);assert_eq!(programme[0], vec![0.1, 0.5, 0.5, 0.1]);assert_eq!(programme[1], vec![0.1, 0.5, 0.5, 0.1]);}@@ -1784,14 +1842,14 @@ mod tests {fn overlay_truncates_a_track_that_runs_past_the_programme() {let mut programme = planar(&[0.0, 0.0, 0.0]);// A 4-sample track placed at offset 2 has room for only 1 sample.- overlay_track_pcm(&mut programme, &planar(&[1.0, 1.0, 1.0, 1.0]), 2, 1.0);+ overlay_track_pcm(&mut programme, &planar(&[1.0, 1.0, 1.0, 1.0]), 2, 1.0, 0.0, 0.0);assert_eq!(programme[0], vec![0.0, 0.0, 1.0]);}#[test]fn overlay_past_the_end_is_a_no_op() {let mut programme = planar(&[0.3, 0.3]);- overlay_track_pcm(&mut programme, &planar(&[1.0]), 5, 1.0);+ overlay_track_pcm(&mut programme, &planar(&[1.0]), 5, 1.0, 0.0, 0.0);assert_eq!(programme[0], vec![0.3, 0.3]);}@@ -1804,6 +1862,8 @@ mod tests {gain_db: 0.0,trim_start_sec: 2.0,trim_end_sec: Some(1.0), // end <= start: empty window, never decoded+ fade_in_sec: 0.0,+ fade_out_sec: 0.0,}];// The empty window is skipped before any decode, so the programme is// untouched even though the path does not exist.@@ -1823,6 +1883,8 @@ mod tests {gain_db: 0.0,trim_start_sec: 0.0,trim_end_sec: Some(3600.0),+ fade_in_sec: 0.0,+ fade_out_sec: 0.0,}];let out = mix_external_tracks(programme, &tracks);assert_eq!(out[0], vec![0.4, 0.4]);@@ -1920,6 +1982,73 @@ mod tests {assert!((loud[0][0] - ceiling).abs() < 1e-6);}+ #[test]+ fn fades_that_fit_are_left_alone() {+ let rate = AUDIO_OUTPUT_SAMPLE_RATE as f64;+ let (fin, fout) = resolve_fade_samples(rate as usize, 0.1, 0.2);+ assert_eq!(fin, (0.1 * rate).round() as usize);+ assert_eq!(fout, (0.2 * rate).round() as usize);+ }++ #[test]+ fn fades_too_long_for_the_track_share_it_in_proportion() {+ // 6 s + 4 s of fade on a 2 s track → 1.2 s / 0.8 s, not a clamped 1 s / 1 s.+ // Mirrors `resolveFadeSecs` on the app side; the two must agree or the+ // preview and the render shape the same track differently.+ let rate = AUDIO_OUTPUT_SAMPLE_RATE as f64;+ let len = (2.0 * rate) as usize;+ let (fin, fout) = resolve_fade_samples(len, 6.0, 4.0);+ assert_eq!(fin, (1.2 * rate).round() as usize);+ assert_eq!(fout, (0.8 * rate).round() as usize);+ assert!(fin + fout <= len + 1);+ }++ #[test]+ fn a_fade_in_longer_than_the_track_still_reaches_full_volume() {+ // Left unreduced this holds the gain near zero for the whole track — the+ // layer exports silent.+ let (fin, fout) = resolve_fade_samples(100, 10.0, 0.0);+ assert_eq!((fin, fout), (100, 0));+ assert!((fade_envelope(99, 100, fin, fout) - 0.99).abs() < 1e-3);+ }++ #[test]+ fn the_envelope_ramps_at_both_edges_and_holds_between() {+ assert_eq!(fade_envelope(0, 100, 10, 10), 0.0);+ assert!((fade_envelope(5, 100, 10, 10) - 0.5).abs() < 1e-6);+ assert_eq!(fade_envelope(50, 100, 10, 10), 1.0);+ assert!((fade_envelope(95, 100, 10, 10) - 0.5).abs() < 1e-6);+ }++ #[test]+ fn overlay_applies_the_fade_over_the_decoded_length() {+ // The ramps are measured against the DECODED length, not the room left in+ // the programme: a fade-out timed to the programme's end would ramp down+ // over audio the export never reaches.+ let mut programme = planar(&[0.0, 0.0, 0.0, 0.0]);+ let decoded = planar(&[1.0, 1.0, 1.0, 1.0]);+ // A 4-sample fade-in at 48 kHz is far below one sample of real time, so+ // ask for the whole decoded length in seconds.+ let four = 4.0 / AUDIO_OUTPUT_SAMPLE_RATE as f64;+ overlay_track_pcm(&mut programme, &decoded, 0, 1.0, four, 0.0);+ assert_eq!(programme[0][0], 0.0);+ assert!(programme[0][1] > 0.0 && programme[0][1] < 1.0);+ assert!(programme[0][3] > programme[0][1]);+ }++ #[test]+ fn a_track_gain_below_the_output_bound_is_honoured() {+ // The per-track gain range is the inspector's -60..+12, NOT the project+ // output trim's ±12: clamping here at -12 floored every quiet bed at a+ // tenth of the attenuation asked for.+ let mut programme = planar(&[0.0]);+ let decoded = planar(&[1.0]);+ let gain = 10.0f32.powf(-40.0 / 20.0);+ overlay_track_pcm(&mut programme, &decoded, 0, gain, 0.0, 0.0);+ assert!((programme[0][0] - gain).abs() < 1e-9);+ assert!(programme[0][0] < 10.0f32.powf(-12.0 / 20.0));+ }+#[test]fn output_is_clipped_to_full_scale_and_keeps_its_length() {// The trim can push a hot signal past full scale; the timeline must come back thediff --git a/crates/compositor/src/scene.rs b/crates/compositor/src/scene.rsindex 5d79ba1b6..7a4905a2f 100644--- a/crates/compositor/src/scene.rs+++ b/crates/compositor/src/scene.rs@@ -453,6 +453,16 @@ pub struct SceneAudioTrack {pub trim_start_sec: f64,#[serde(default)]pub trim_end_sec: Option<f64>,+ /// Ramp lengths at this entry's own edges, in seconds. The app puts them only+ /// on the pieces that touch the track's real start and end, so a split or+ /// looping track fades once instead of at every cut or repeat.+ ///+ /// `#[serde(default)]` for the usual reason: a payload from a build that+ /// predates the field must degrade to "no fade", not fail the whole scene.+ #[serde(default)]+ pub fade_in_sec: f64,+ #[serde(default)]+ pub fade_out_sec: f64,}#[derive(Debug, Clone, Copy, Deserialize)]diff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.tsindex f80176ccd..0aeb18a28 100644--- a/electron/ai-edition/document-service.test.ts+++ b/electron/ai-edition/document-service.test.ts@@ -435,11 +435,16 @@ describe("DocumentService", () => {{id: "trk_1",assetId: audioId,+ kind: "music",startMs: 0,endMs: 10_000,durationSec: 10,offsetMs: 0,gainDb: 0,+ loop: false,+ fadeInMs: 0,+ fadeOutMs: 0,+ muted: false,label: "music",origin: "user",},diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsxindex df6f49df2..8d55c7eb1 100644--- a/src/components/ai-edition/RightPanes.tsx+++ b/src/components/ai-edition/RightPanes.tsx@@ -2343,6 +2343,11 @@ type TimelineApi = ReturnType<typeof useTimeline>;// with the file name, then the volume (a local live value during the drag,// committed as one undo step on release), then a delete button styled like the// region panes' (position and mute are edited on the lane itself).+// Longest fade the inspector offers. Past a few seconds a fade stops reading as+// a fade and starts reading as a level change, and the track's own span caps it+// anyway (`resolveFadeSecs` reduces one that does not fit).+const FADE_MAX_MS = 5000;+export function AudioTrackPane({ tl }: { tl: TimelineApi }) {const ts = useScopedT("settings");const trackId = tl.selectedAudioTrackId;@@ -2353,14 +2358,18 @@ export function AudioTrackPane({ tl }: { tl: TimelineApi }) {? 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".+ // Live-drag values; null means "show the committed value".const [liveGain, setLiveGain] = useState<number | null>(null);+ const [liveFadeIn, setLiveFadeIn] = useState<number | null>(null);+ const [liveFadeOut, setLiveFadeOut] = useState<number | null>(null);// Drop the live value when the selected track changes: a drag released outside// the input never fires onCommit, so without this an uncommitted -10 dB from// track A would show as track B's gain the moment B is selected.// biome-ignore lint/correctness/useExhaustiveDependencies: trackId is the trigger, not a read — the body only resets the live value.useEffect(() => {setLiveGain(null);+ setLiveFadeIn(null);+ setLiveFadeOut(null);}, [trackId]);if (!track) return null;const fileName = track.label || asset?.label || asset?.originalPath?.split(/[\\/]/).pop() || "";@@ -2416,6 +2425,51 @@ export function AudioTrackPane({ tl }: { tl: TimelineApi }) {setLiveGain(null);}}/>+ <SliderCell+ label={ts("audioTrack.fadeIn")}+ value={liveFadeIn ?? track.fadeInMs}+ min={0}+ max={FADE_MAX_MS}+ step={50}+ decimals={0}+ suffix=" ms"+ onChange={setLiveFadeIn}+ onCommit={() => {+ if (liveFadeIn !== null) void tl.updateAudioTrack(track.id, { fadeInMs: liveFadeIn });+ setLiveFadeIn(null);+ }}+ />+ <SliderCell+ label={ts("audioTrack.fadeOut")}+ value={liveFadeOut ?? track.fadeOutMs}+ min={0}+ max={FADE_MAX_MS}+ step={50}+ decimals={0}+ suffix=" ms"+ onChange={setLiveFadeOut}+ onCommit={() => {+ if (liveFadeOut !== null)+ void tl.updateAudioTrack(track.id, { fadeOutMs: liveFadeOut });+ setLiveFadeOut(null);+ }}+ />+ </div>+ <div className={styles.paneRow}>+ <span className={styles.label}>{ts("audioTrack.mute")}</span>+ <Toggle+ checked={track.muted}+ ariaLabel={ts("audioTrack.mute")}+ onChange={(v) => void tl.updateAudioTrack(track.id, { muted: v })}+ />+ </div>+ <div className={styles.paneRow}>+ <span className={styles.label}>{ts("audioTrack.loop")}</span>+ <Toggle+ checked={track.loop}+ ariaLabel={ts("audioTrack.loop")}+ onChange={(v) => void tl.updateAudioTrack(track.id, { loop: v })}+ /></div><buttontype="button"diff --git a/src/components/ai-edition/VirtualPreview.audio.test.ts b/src/components/ai-edition/VirtualPreview.audio.test.tsindex 7ce27660e..7371f851e 100644--- a/src/components/ai-edition/VirtualPreview.audio.test.ts+++ b/src/components/ai-edition/VirtualPreview.audio.test.ts@@ -6,6 +6,7 @@ import {type PreviewAudioGraph,resolveAudioTrackPlayback,resolveTimelineAudioPlayback,+ timelineAudioFadeAt,} from "./VirtualPreview";/** Minimal stand-in: the function only ever touches `gain.gain.value`. */@@ -89,11 +90,16 @@ describe("resolveTimelineAudioPlayback", () => {const track: AxcutAudioTrack = {id: "t1",assetId: "a1",+ kind: "music",startMs: 10_000,endMs: 16_000,durationSec: 20,offsetMs: 2000,gainDb: 0,+ loop: false,+ fadeInMs: 0,+ fadeOutMs: 0,+ muted: false,label: "",origin: "user",};@@ -135,6 +141,18 @@ describe("resolveTimelineAudioPlayback", () => {expect(resolveTimelineAudioPlayback(16, 10, short, spanSec(short)).shouldPlay).toBe(false);});+ it("folds a looping track back into its window, in phase with the export", () => {+ // 4s of source (offset 0, 4s file) under a 10s span.+ const looped = { ...track, endMs: 20_000, offsetMs: 0, durationSec: 4, loop: true };+ const span = spanSec(looped);+ expect(resolveTimelineAudioPlayback(13, 10, looped, span).targetTimeSec).toBeCloseTo(3, 6);+ // 5s in is 1s into the second repeat — the export's second mix entry agrees.+ expect(resolveTimelineAudioPlayback(15, 10, looped, span).targetTimeSec).toBeCloseTo(1, 6);+ expect(resolveTimelineAudioPlayback(15, 10, looped, span).shouldPlay).toBe(true);+ // Past the span it stops, however much file is left.+ expect(resolveTimelineAudioPlayback(21, 10, looped, span).shouldPlay).toBe(false);+ });+// The regression: an interior trim must NOT skip the track's own content, so the// preview stays byte-for-byte with `audio::mix_external_tracks`, which overlays the// decoded window contiguously. Same scenario as Etienne's review and the projection's@@ -184,3 +202,40 @@ describe("resolveTimelineAudioPlayback", () => {).toBeCloseTo(1, 6);});});++describe("timelineAudioFadeAt", () => {+ const track: AxcutAudioTrack = {+ id: "t1",+ assetId: "a1",+ kind: "music",+ startMs: 0,+ endMs: 10_000,+ durationSec: 20,+ offsetMs: 0,+ gainDb: 0,+ loop: false,+ fadeInMs: 1000,+ fadeOutMs: 2000,+ muted: false,+ label: "",+ origin: "user",+ };++ it("ramps in and out over the track's own edges", () => {+ expect(timelineAudioFadeAt(track, 0, 10)).toBe(0);+ expect(timelineAudioFadeAt(track, 0.5, 10)).toBeCloseTo(0.5, 6);+ expect(timelineAudioFadeAt(track, 5, 10)).toBe(1);+ expect(timelineAudioFadeAt(track, 9, 10)).toBeCloseTo(0.5, 6);+ expect(timelineAudioFadeAt(track, 10, 10)).toBe(0);+ });++ it("is silent when muted", () => {+ expect(timelineAudioFadeAt({ ...track, muted: true }, 5, 10)).toBe(0);+ });++ it("still reaches full volume when a fade is longer than the span", () => {+ // Unreduced, the ramp never completes and the track plays near-silent.+ const long = { ...track, fadeInMs: 20_000, fadeOutMs: 0 };+ expect(timelineAudioFadeAt(long, 2, 2)).toBe(1);+ });+});diff --git a/src/components/ai-edition/VirtualPreview.playback.test.tsx b/src/components/ai-edition/VirtualPreview.playback.test.tsxindex 26f784516..f4ffe88a0 100644--- a/src/components/ai-edition/VirtualPreview.playback.test.tsx+++ b/src/components/ai-edition/VirtualPreview.playback.test.tsx@@ -242,11 +242,16 @@ describe("VirtualPreview imported audio tracks", () => {const track = {id: "trk",assetId: "aud",+ kind: "music" as const,startMs: 2000,endMs: 4000,durationSec: 10,offsetMs: 1000,gainDb: 0,+ loop: false,+ fadeInMs: 0,+ fadeOutMs: 0,+ muted: false,label: "",origin: "user" as const,};@@ -333,11 +338,16 @@ describe("VirtualPreview imported audio track boost", () => {const boosted = {id: "trk",assetId: "aud",+ kind: "music" as const,startMs: 2000,endMs: 4000,durationSec: 10,offsetMs: 1000,gainDb: 6.0206,+ loop: false,+ fadeInMs: 0,+ fadeOutMs: 0,+ muted: false,label: "",origin: "user" as const,};diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsxindex 00737545b..50b500a1b 100644--- a/src/components/ai-edition/VirtualPreview.tsx+++ b/src/components/ai-edition/VirtualPreview.tsx@@ -4,6 +4,7 @@ import {DEFAULT_CROP_REGION,MAX_NATIVE_PLAYBACK_RATE,} from "@/components/video-editor/types";+import { resolveFadeSecs } from "@/lib/ai-edition/document/audioTracks";import {projectRawTimelineSecToPlayback,resolvePlaybackSegments,@@ -109,6 +110,14 @@ export function resolveTimelineAudioPlayback(const windowLen = Math.max(0, sourceEnd - offset);const local = outputTimeSec - outputStartSec;const active = local >= 0 && local < spanSec;+ if (track.loop && windowLen > 0) {+ // Fold into the repeating window, exactly as the export's per-repeat mix+ // entries do, so preview and render stay in phase.+ return {+ targetTimeSec: offset + (local > 0 ? local % windowLen : 0),+ shouldPlay: active,+ };+ }return {targetTimeSec: Math.min(Math.max(offset, offset + local), sourceEnd),// A file shorter than its span goes silent at the end rather than@@ -117,6 +126,25 @@ export function resolveTimelineAudioPlayback(};}+/** Fraction 0..1 of a track's volume `localSec` into its span, applying the+ * ramps. Shares `resolveFadeSecs` with the export so a fade too long for its+ * span is reduced the same way on both sides. */+export function timelineAudioFadeAt(+ track: AxcutAudioTrack,+ localSec: number,+ spanSec: number,+): number {+ if (track.muted) return 0;+ const { fadeInSec, fadeOutSec } = resolveFadeSecs(track.fadeInMs, track.fadeOutMs, spanSec);+ let v = 1;+ if (fadeInSec > 0 && localSec < fadeInSec) v = Math.min(v, Math.max(0, localSec / fadeInSec));+ if (fadeOutSec > 0) {+ const remaining = spanSec - localSec;+ if (remaining < fadeOutSec) v = Math.min(v, Math.max(0, remaining / fadeOutSec));+ }+ return v;+}+export interface PreviewAudioGraph {context: AudioContext;gain: GainNode;@@ -627,6 +655,7 @@ export function VirtualPreview({track,spanSec,);+ const fade = timelineAudioFadeAt(track, outputTimeSec - outputStartSec, spanSec);// 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 a@@ -634,10 +663,10 @@ export function VirtualPreview({if (el.playbackRate !== 1) el.playbackRate = 1;const trackGainNode = audioTrackGainNodesRef.current.get(track.id);if (trackGainNode) {- trackGainNode.gain.value = audioGainScalar(track.gainDb);+ trackGainNode.gain.value = audioGainScalar(track.gainDb) * fade;if (el.volume !== 1) el.volume = 1;} else {- el.volume = Math.min(1, audioGainScalar(track.gainDb) * globalGain);+ el.volume = Math.min(1, audioGainScalar(track.gainDb) * globalGain * fade);}// Only re-seek on a real discontinuity (a scrub, a trim jump, a first// play), NOT on the sub-frame drift of normal playback. The primary audiodiff --git a/src/components/ai-edition/v4/V4Timeline.geometry.test.tsx b/src/components/ai-edition/v4/V4Timeline.geometry.test.tsxindex ca773abba..0dbd1afd5 100644--- a/src/components/ai-edition/v4/V4Timeline.geometry.test.tsx+++ b/src/components/ai-edition/v4/V4Timeline.geometry.test.tsx@@ -353,11 +353,16 @@ describe("V4Timeline audio lane drag", () => {const makeTrack = () => ({id: "trk1",assetId: "aud",+ kind: "music" as const,startMs: 100_000,endMs: 160_000,durationSec: 60,offsetMs: 0,gainDb: 0,+ loop: false,+ fadeInMs: 0,+ fadeOutMs: 0,+ muted: false,label: "vo",origin: "user" as const,});diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.jsonindex 4d673a706..61a989c16 100644--- a/src/i18n/locales/ar/settings.json+++ b/src/i18n/locales/ar/settings.json@@ -331,7 +331,11 @@"add": "إضافة مسار صوتي","importFailed": "تعذّر إضافة الصوت","defaultLabel": "مسار صوتي",- "help": "مستوى صوت هذا المسار الصوتي المستورد. يُمزج فوق التسجيل في المعاينة والتصدير. اسحب المسار على المخطط الزمني لتحريكه أو اقتصاصه.",+ "help": "مستوى الصوت والتلاشي والتكرار لهذا المسار الصوتي. يُمزج فوق التسجيل في المعاينة والتصدير. اسحب المسار على المخطط الزمني لتحريكه أو تغيير حجمه.",+ "fadeIn": "تلاشٍ للداخل",+ "fadeOut": "تلاشٍ للخارج",+ "mute": "كتم",+ "loop": "تكرار","remove": "حذف المسار"}}diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.jsonindex eda95eabb..076a55a3c 100644--- a/src/i18n/locales/en/settings.json+++ b/src/i18n/locales/en/settings.json@@ -83,7 +83,11 @@"add": "Add audio track","importFailed": "Could not add audio","defaultLabel": "Audio track",- "help": "Volume for this imported audio track. It mixes over the recording in the preview and the export. Drag the track on the timeline to move or trim it.",+ "help": "Volume, fades and looping for this audio track. It mixes over the recording in the preview and the export. Drag the track on the timeline to move or resize it.",+ "fadeIn": "Fade in",+ "fadeOut": "Fade out",+ "mute": "Mute",+ "loop": "Loop","remove": "Delete track"},"effects": {diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.jsonindex 06cd91da3..2fdc3eff6 100644--- a/src/i18n/locales/es/settings.json+++ b/src/i18n/locales/es/settings.json@@ -331,7 +331,11 @@"add": "Añadir pista de audio","importFailed": "No se pudo añadir el audio","defaultLabel": "Pista de audio",- "help": "Volumen de esta pista de audio importada. Se mezcla sobre la grabación en la vista previa y en la exportación. Arrastra la pista en la línea de tiempo para moverla o recortarla.",+ "help": "Volumen, fundidos y bucle de esta pista de audio. Se mezcla sobre la grabación en la vista previa y la exportación. Arrastra la pista en la línea de tiempo para moverla o redimensionarla.",+ "fadeIn": "Aparición",+ "fadeOut": "Desvanecido",+ "mute": "Silenciar",+ "loop": "Bucle","remove": "Eliminar pista"}}diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.jsonindex 16f8c8d98..331eceb74 100644--- a/src/i18n/locales/fr/settings.json+++ b/src/i18n/locales/fr/settings.json@@ -331,7 +331,11 @@"add": "Ajouter une piste audio","importFailed": "Impossible d’ajouter l’audio","defaultLabel": "Piste audio",- "help": "Volume de cette piste audio importée. Elle est mixée par-dessus l’enregistrement dans l’aperçu et à l’export. Faites glisser la piste sur la timeline pour la déplacer ou la rogner.",+ "help": "Volume, fondus et boucle de cette piste audio. Elle se mixe par-dessus l'enregistrement dans l'aperçu et à l'export. Faites glisser la piste sur la timeline pour la déplacer ou la redimensionner.",+ "fadeIn": "Fondu d'entrée",+ "fadeOut": "Fondu de sortie",+ "mute": "Muet",+ "loop": "Boucle","remove": "Supprimer la piste"}}diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.jsonindex 730a39397..b4175f2a8 100644--- a/src/i18n/locales/it/settings.json+++ b/src/i18n/locales/it/settings.json@@ -331,7 +331,11 @@"add": "Aggiungi traccia audio","importFailed": "Impossibile aggiungere l’audio","defaultLabel": "Traccia audio",- "help": "Volume di questa traccia audio importata. Viene mixata sopra la registrazione nell’anteprima e nell’esportazione. Trascina la traccia sulla timeline per spostarla o ritagliarla.",+ "help": "Volume, dissolvenze e ripetizione di questa traccia audio. Si mixa sopra la registrazione nell'anteprima e nell'esportazione. Trascina la traccia sulla timeline per spostarla o ridimensionarla.",+ "fadeIn": "Dissolvenza in entrata",+ "fadeOut": "Dissolvenza in uscita",+ "mute": "Muto",+ "loop": "Ripeti","remove": "Elimina traccia"}}diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.jsonindex 75ad59deb..484a2c335 100644--- a/src/i18n/locales/ja-JP/settings.json+++ b/src/i18n/locales/ja-JP/settings.json@@ -331,7 +331,11 @@"add": "オーディオトラックを追加","importFailed": "オーディオを追加できませんでした","defaultLabel": "オーディオトラック",- "help": "このインポートしたオーディオトラックの音量。プレビューとエクスポートで録画に重ねてミックスされます。タイムライン上でドラッグして移動またはトリミングできます。",+ "help": "このオーディオトラックの音量、フェード、ループ。プレビューと書き出しの両方で録画にミックスされます。タイムライン上でドラッグすると移動やサイズ変更ができます。",+ "fadeIn": "フェードイン",+ "fadeOut": "フェードアウト",+ "mute": "ミュート",+ "loop": "ループ","remove": "トラックを削除"}}diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.jsonindex 98dbdcee9..816b56b69 100644--- a/src/i18n/locales/ko-KR/settings.json+++ b/src/i18n/locales/ko-KR/settings.json@@ -331,7 +331,11 @@"add": "오디오 트랙 추가","importFailed": "오디오를 추가할 수 없습니다","defaultLabel": "오디오 트랙",- "help": "가져온 이 오디오 트랙의 볼륨입니다. 미리 보기와 내보내기에서 녹화 위에 믹싱됩니다. 타임라인에서 트랙을 드래그하여 이동하거나 자를 수 있습니다.",+ "help": "이 오디오 트랙의 볼륨, 페이드, 반복입니다. 미리보기와 내보내기에서 녹화 위에 믹스됩니다. 타임라인에서 트랙을 끌어 이동하거나 크기를 조절하세요.",+ "fadeIn": "페이드 인",+ "fadeOut": "페이드 아웃",+ "mute": "음소거",+ "loop": "반복","remove": "트랙 삭제"}}diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.jsonindex fd60b7a7e..968dd6b15 100644--- a/src/i18n/locales/pt-BR/settings.json+++ b/src/i18n/locales/pt-BR/settings.json@@ -331,7 +331,11 @@"add": "Adicionar faixa de áudio","importFailed": "Não foi possível adicionar o áudio","defaultLabel": "Faixa de áudio",- "help": "Volume desta faixa de áudio importada. Ela é mixada sobre a gravação na prévia e na exportação. Arraste a faixa na linha do tempo para movê-la ou cortá-la.",+ "help": "Volume, fades e repetição desta faixa de áudio. Ela é mixada sobre a gravação na prévia e na exportação. Arraste a faixa na linha do tempo para movê-la ou redimensioná-la.",+ "fadeIn": "Fade in",+ "fadeOut": "Fade out",+ "mute": "Silenciar",+ "loop": "Repetir","remove": "Excluir faixa"}}diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.jsonindex 038d5a1f6..3ecc1e549 100644--- a/src/i18n/locales/ru/settings.json+++ b/src/i18n/locales/ru/settings.json@@ -331,7 +331,11 @@"add": "Добавить аудиодорожку","importFailed": "Не удалось добавить аудио","defaultLabel": "Аудиодорожка",- "help": "Громкость импортированной аудиодорожки. Она микшируется поверх записи в предпросмотре и при экспорте. Перетащите дорожку на шкале времени, чтобы переместить или обрезать её.",+ "help": "Громкость, затухания и повтор этой аудиодорожки. Она подмешивается к записи в предпросмотре и при экспорте. Перетащите дорожку на таймлайне, чтобы переместить или изменить её размер.",+ "fadeIn": "Нарастание",+ "fadeOut": "Затухание",+ "mute": "Без звука",+ "loop": "Повтор","remove": "Удалить дорожку"}}diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.jsonindex 31d925c21..50a7f2609 100644--- a/src/i18n/locales/tr/settings.json+++ b/src/i18n/locales/tr/settings.json@@ -331,7 +331,11 @@"add": "Ses parçası ekle","importFailed": "Ses eklenemedi","defaultLabel": "Ses parçası",- "help": "Bu içe aktarılmış ses parçasının ses düzeyi. Önizlemede ve dışa aktarmada kaydın üzerine miksleniyor. Taşımak veya kırpmak için parçayı zaman çizelgesinde sürükleyin.",+ "help": "Bu ses parçasının seviyesi, geçişleri ve döngüsü. Önizlemede ve dışa aktarmada kaydın üzerine miksleniyor. Parçayı zaman çizelgesinde sürükleyerek taşıyın veya yeniden boyutlandırın.",+ "fadeIn": "Açılma",+ "fadeOut": "Kararma",+ "mute": "Sessiz",+ "loop": "Döngü","remove": "Parçayı sil"}}diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.jsonindex 5bc0342b5..7944e442b 100644--- a/src/i18n/locales/vi/settings.json+++ b/src/i18n/locales/vi/settings.json@@ -331,7 +331,11 @@"add": "Thêm bản âm thanh","importFailed": "Không thể thêm âm thanh","defaultLabel": "Bản âm thanh",- "help": "Âm lượng của bản âm thanh đã nhập này. Nó được trộn lên trên bản ghi trong bản xem trước và khi xuất. Kéo bản nhạc trên dòng thời gian để di chuyển hoặc cắt.",+ "help": "Âm lượng, hiệu ứng mờ và lặp cho bản âm thanh này. Nó được trộn lên trên bản ghi ở cả xem trước và xuất. Kéo bản trên dòng thời gian để di chuyển hoặc đổi kích thước.",+ "fadeIn": "Mờ vào",+ "fadeOut": "Mờ ra",+ "mute": "Tắt tiếng",+ "loop": "Lặp","remove": "Xóa bản nhạc"}}diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.jsonindex e4f40ee3c..25093113d 100644--- a/src/i18n/locales/zh-CN/settings.json+++ b/src/i18n/locales/zh-CN/settings.json@@ -331,7 +331,11 @@"add": "添加音频轨道","importFailed": "无法添加音频","defaultLabel": "音频轨道",- "help": "此导入音频轨道的音量。在预览和导出中会叠加混合到录制内容上。在时间轴上拖动轨道即可移动或裁剪。",+ "help": "该音频轨道的音量、淡入淡出和循环。它会在预览和导出时混合到录制内容之上。在时间轴上拖动轨道可移动或调整大小。",+ "fadeIn": "淡入",+ "fadeOut": "淡出",+ "mute": "静音",+ "loop": "循环","remove": "删除轨道"}}diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.jsonindex be23c79c4..1179aa3e2 100644--- a/src/i18n/locales/zh-TW/settings.json+++ b/src/i18n/locales/zh-TW/settings.json@@ -332,7 +332,11 @@"add": "新增音訊軌道","importFailed": "無法新增音訊","defaultLabel": "音訊軌道",- "help": "此匯入音訊軌道的音量。在預覽與匯出時會疊加混音到錄製內容上。在時間軸上拖曳軌道即可移動或裁剪。",+ "help": "該音訊軌道的音量、淡入淡出與循環。它會在預覽與匯出時混合到錄製內容之上。在時間軸上拖曳軌道可移動或調整大小。",+ "fadeIn": "淡入",+ "fadeOut": "淡出",+ "mute": "靜音",+ "loop": "循環","remove": "刪除軌道"}}diff --git a/src/lib/ai-edition/document/audioTracks.test.ts b/src/lib/ai-edition/document/audioTracks.test.tsindex 25f7d4cfd..586e9be4e 100644--- a/src/lib/ai-edition/document/audioTracks.test.ts+++ b/src/lib/ai-edition/document/audioTracks.test.ts@@ -5,6 +5,7 @@ import {collapseTracksToPills,patchAudioTrack,removeAudioTrack,+ resolveFadeSecs,trackGroupId,} from "./audioTracks";@@ -71,6 +72,29 @@ describe("anchorAudioTrackFragments", () => {expect(frags[1].offsetMs).toBe(7000);});+ it("keeps the fades on the outer edges only", () => {+ const frags = anchorAudioTrackFragments(+ track({ startMs: 5000, endMs: 15_000, fadeInMs: 500, fadeOutMs: 800 }),+ twoClips,+ makeId,+ );+ expect(frags.map((f) => [f.fadeInMs, f.fadeOutMs])).toEqual([+ [500, 0],+ [0, 800],+ ]);+ });++ it("does not advance the offset of a looping track", () => {+ // Looping folds within `duration - offset`, which every fragment shares;+ // an advanced offset would shorten the window and drift out of phase.+ const frags = anchorAudioTrackFragments(+ track({ startMs: 5000, endMs: 15_000, offsetMs: 1000, loop: true }),+ twoClips,+ makeId,+ );+ expect(frags.map((f) => f.offsetMs)).toEqual([1000, 1000]);+ });+it("ties every fragment to one group id", () => {const frags = anchorAudioTrackFragments(track({ startMs: 5000, endMs: 15_000 }),@@ -91,7 +115,7 @@ describe("anchorAudioTrackFragments", () => {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 }),+ track({ startMs: 5000, endMs: 15_000, offsetMs: 2000, fadeInMs: 400, fadeOutMs: 600 }),twoClips,makeId,);@@ -101,6 +125,7 @@ describe("collapseTracksToPills", () => {// 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.fadeInMs, pill.fadeOutMs]).toEqual([400, 600]);expect(pill.clipId).toBeUndefined();});@@ -150,8 +175,23 @@ describe("patchAudioTrack", () => {makeId,);const doc = { ...emptyDoc(), audioTracks: frags };- const next = patchAudioTrack(doc, trackGroupId(frags[0]), { gainDb: -6 });+ const next = patchAudioTrack(doc, trackGroupId(frags[0]), { gainDb: -6, muted: true });expect(next.audioTracks.map((t) => t.gainDb)).toEqual([-6, -6]);+ expect(next.audioTracks.every((t) => t.muted)).toBe(true);+ });++ it("keeps fades on the outer edges when they are edited", () => {+ const frags = anchorAudioTrackFragments(+ track({ startMs: 5000, endMs: 15_000 }),+ twoClips,+ makeId,+ );+ const doc = { ...emptyDoc(), audioTracks: frags };+ const next = patchAudioTrack(doc, trackGroupId(frags[0]), { fadeInMs: 300, fadeOutMs: 400 });+ expect(next.audioTracks.map((t) => [t.fadeInMs, t.fadeOutMs])).toEqual([+ [300, 0],+ [0, 400],+ ]);});it("shifts the whole track by the offset delta, preserving each advance", () => {@@ -175,3 +215,20 @@ describe("patchAudioTrack", () => {expect(next.audioTracks[1]?.gainDb).toBe(-6);});});++describe("resolveFadeSecs", () => {+ it("passes fades that fit through untouched", () => {+ expect(resolveFadeSecs(1000, 2000, 10)).toEqual({ fadeInSec: 1, fadeOutSec: 2 });+ });++ it("shrinks a fade-in longer than the span to the span", () => {+ // Unreduced this holds the gain at zero for the whole track.+ expect(resolveFadeSecs(5000, 0, 2)).toEqual({ fadeInSec: 2, fadeOutSec: 0 });+ });++ it("shares the span in proportion when both fades overflow", () => {+ const { fadeInSec, fadeOutSec } = resolveFadeSecs(6000, 4000, 2);+ expect(fadeInSec).toBeCloseTo(1.2);+ expect(fadeOutSec).toBeCloseTo(0.8);+ });+});diff --git a/src/lib/ai-edition/document/audioTracks.ts b/src/lib/ai-edition/document/audioTracks.tsindex 7b91071eb..abcf605ec 100644--- a/src/lib/ai-edition/document/audioTracks.ts+++ b/src/lib/ai-edition/document/audioTracks.ts@@ -11,10 +11,11 @@// 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.+// seconds in, so a bed spanning a cut audibly restarts at the boundary, and+// each fragment would re-run the layer's fades. `anchorAudioTrackFragments`+// fixes the payload up afterwards: every fragment's `offsetMs` is advanced by+// the source time its predecessors consumed, and the fades are kept on the+// outer edges only.import type { AxcutAudioTrack, AxcutClip, AxcutDocument } from "../schema";import { anchorRegionsWithDerivedMs, coalesceRegionsForRuler } from "../timeline/timelineMap";@@ -30,6 +31,8 @@ export function trackGroupId(track: AxcutAudioTrack): string {** - `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.+ * - `fadeInMs` stays on the first fragment and `fadeOutMs` on the last, so a+ * split track fades once at each real edge rather than at every cut.* - `trackId` ties the fragments together for the lane, the inspector and* delete.*@@ -46,12 +49,18 @@ export function anchorAudioTrackFragments(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 last = anchored.length - 1;+ return anchored.map((fragment, index) => {const spanMs = Math.max(0, fragment.endMs - fragment.startMs);const next: AxcutAudioTrack = {...fragment,trackId: groupId,- offsetMs: track.offsetMs + elapsedMs,+ // Looping restarts the window on its own, so an advanced offset would+ // double-count the fold; the mixer and the preview both wrap within+ // `durationSec - offsetMs`, which every fragment shares.+ offsetMs: track.loop ? track.offsetMs : track.offsetMs + elapsedMs,+ fadeInMs: index === 0 ? track.fadeInMs : 0,+ fadeOutMs: index === last ? track.fadeOutMs : 0,};elapsedMs += spanMs;return next;@@ -74,8 +83,8 @@ export function reanchorAudioTracks(/*** 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.+ * carrying the FIRST fragment's payload (its `offsetMs` is the track's real+ * offset — later fragments hold advanced copies) and the outer fades.*/export function collapseTracksToPills(tracks: AxcutAudioTrack[]): AxcutAudioTrack[] {const groups = new Map<string, AxcutAudioTrack[]>();@@ -98,6 +107,8 @@ export function collapseTracksToPills(tracks: AxcutAudioTrack[]): AxcutAudioTracsourceEndSec: undefined,startMs: head.startMs,endMs: tail.endMs,+ fadeInMs: head.fadeInMs,+ fadeOutMs: tail.fadeOutMs,};});}@@ -125,25 +136,35 @@ export function removeAudioTrack(doc: AxcutDocument, trackId: string): AxcutDocureturn { ...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. */+/** Patch the shared payload of every fragment of one track. Payload edits (gain,+ * mute, loop, offset) 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,- patch: Partial<Pick<AxcutAudioTrack, "gainDb">> & { offsetMs?: number },+ patch: Partial<Pick<AxcutAudioTrack, "gainDb" | "muted" | "loop" | "fadeInMs" | "fadeOutMs">> & {+ offsetMs?: number;+ },): AxcutDocument {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;+ const last = ordered[ordered.length - 1].id;return {...doc,audioTracks: doc.audioTracks.map((t) => {if (trackGroupId(t) !== trackId) return t;+ const isFirst = t.id === ordered[0].id;+ const isLast = t.id === last;return {...t,...(patch.gainDb === undefined ? {} : { gainDb: patch.gainDb }),+ ...(patch.muted === undefined ? {} : { muted: patch.muted }),+ ...(patch.loop === undefined ? {} : { loop: patch.loop }),+ // Fades live on the outer edges; an interior fragment keeps none.+ ...(patch.fadeInMs === undefined ? {} : { fadeInMs: isFirst ? patch.fadeInMs : 0 }),+ ...(patch.fadeOutMs === undefined ? {} : { fadeOutMs: isLast ? patch.fadeOutMs : 0 }),// Shift the whole track by the delta so each fragment keeps the// advance that makes it continuous with its predecessor....(patch.offsetMs === undefined@@ -153,3 +174,28 @@ export function patchAudioTrack(}),};}++/**+ * Fade lengths in seconds, reduced to fit inside `spanSec`.+ *+ * Fades that do not fit share the span in proportion rather than being clamped+ * independently: clamping each to the span first would turn an asymmetric pair+ * into a symmetric one, losing the shape the user asked for. An unreduced+ * fade-in longer than the span is worse than cosmetic — it holds the gain at+ * zero for the whole track.+ *+ * Mirrored by `resolve_fade_samples` in `crates/compositor/src/audio.rs`; the+ * preview reads this one, the render reads that one, and they must agree.+ */+export function resolveFadeSecs(+ fadeInMs: number,+ fadeOutMs: number,+ spanSec: number,+): { fadeInSec: number; fadeOutSec: number } {+ const fadeInSec = Math.max(0, fadeInMs / 1000);+ const fadeOutSec = Math.max(0, fadeOutMs / 1000);+ const total = fadeInSec + fadeOutSec;+ if (total <= spanSec) return { fadeInSec, fadeOutSec };+ const scale = Math.max(0, spanSec) / total;+ return { fadeInSec: fadeInSec * scale, fadeOutSec: fadeOutSec * scale };+}diff --git a/src/lib/ai-edition/schema/index.test.ts b/src/lib/ai-edition/schema/index.test.tsindex 90df28d28..c53bfae9f 100644--- a/src/lib/ai-edition/schema/index.test.ts+++ b/src/lib/ai-edition/schema/index.test.ts@@ -975,7 +975,7 @@ describe("v6 -> v7 trim clip-anchor migration", () => {});describe("audio tracks (issue #350)", () => {- it("applies defaults for gain, offset and label", () => {+ it("applies defaults for kind, gain, offset, fades and label", () => {const track = audioTrackSchema.parse({id: "audio_1",assetId: "asset_1",@@ -983,8 +983,13 @@ describe("audio tracks (issue #350)", () => {startMs: 0,endMs: 42_000,});+ expect(track.kind).toBe("music");expect(track.offsetMs).toBe(0);expect(track.gainDb).toBe(0);+ expect(track.loop).toBe(false);+ expect(track.fadeInMs).toBe(0);+ expect(track.fadeOutMs).toBe(0);+ expect(track.muted).toBe(false);expect(track.label).toBe("");// Unanchored until a caller places it — same contract as every other// clip-anchored region kind.@@ -1034,12 +1039,16 @@ describe("audio tracks (issue #350)", () => {});it("createAudioTrack takes a shorter span than the source when asked", () => {+ // A voiceover recorded over a 4s tail of the timeline should not lay a+ // 30s pill down just because its file is 30s long.const track = createAudioTrack({assetId: "asset_1",durationSec: 30,+ kind: "voiceover",timelineStartSec: 2,spanSec: 4,});+ expect(track.kind).toBe("voiceover");expect(track.startMs).toBe(2000);expect(track.endMs).toBe(6000);});diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.tsindex 10a26d749..4f32d52bc 100644--- a/src/lib/ai-edition/schema/index.ts+++ b/src/lib/ai-edition/schema/index.ts@@ -512,8 +512,8 @@ export const zoomRegionSchema = endGteStart(// 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.+// file at the same offset and re-run the fades, so a bed spanning a cut would+// audibly restart at the boundary.export const audioTrackSchema = endGteStart(z.object({id: z.string().min(1),@@ -526,11 +526,16 @@ export const audioTrackSchema = endGteStart(endMs: z.number().nonnegative(),...clipAnchorShape,assetId: z.string().min(1),+ kind: z.enum(["voiceover", "music"]).default("music"),// 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),offsetMs: z.number().int().nonnegative().default(0),gainDb: z.number().min(-60).max(12).default(0),+ loop: z.boolean().default(false),+ fadeInMs: z.number().int().nonnegative().default(0),+ fadeOutMs: z.number().int().nonnegative().default(0),+ muted: z.boolean().default(false),label: z.string().default(""),origin: z.enum(["system", "agent", "user"]).default("user"),}),@@ -1076,6 +1081,7 @@ export function ensureDocument(value: unknown): AxcutDocument {export function createAudioTrack(input: {assetId: string;durationSec: number;+ kind?: "voiceover" | "music";/** 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;@@ -1089,6 +1095,7 @@ export function createAudioTrack(input: {return audioTrackSchema.parse({id: createId("audio"),assetId: input.assetId,+ kind: input.kind ?? "music",durationSec: input.durationSec,startMs,endMs: startMs + spanMs,diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.tsindex 7d1eb3e83..cd2b0e91e 100644--- a/src/lib/ai-edition/store/projectStore.ts+++ b/src/lib/ai-edition/store/projectStore.ts@@ -101,7 +101,9 @@ export interface ProjectState {assetId: string,timelineStartSec?: number,options?: {- /** Real source duration, when the caller measured it. */+ kind?: "voiceover" | "music";+ /** Real source duration, when the caller measured it (a fresh recording+ * knows its own length before the asset is probed). */durationSec?: number;/** Timeline span, when it should differ from the source duration. */spanSec?: number;@@ -420,10 +422,13 @@ export const useProjectStore = create<ProjectState>((set, get) => ({const track = createAudioTrack({assetId,durationSec: options?.durationSec ?? asset.durationSec ?? 0,+ kind: options?.kind,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.+ // matching the timeline hook's placement. A voiceover passes the playhead+ // captured when RECORDING STARTED — by the time the take ends the live+ // playhead has run on by the take's own length.timelineStartSec: timelineStartSec ?? get().currentTimeSec,label: asset.label,});diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.tsindex e13ce4b59..f6c472492 100644--- a/src/lib/ai-edition/store/useTimeline.ts+++ b/src/lib/ai-edition/store/useTimeline.ts@@ -1288,7 +1288,7 @@ export function useTimeline() {async (assetId: string,timelineStartSec?: number,- options?: { durationSec?: number; spanSec?: number },+ options?: { kind?: "voiceover" | "music"; durationSec?: number; spanSec?: number },): Promise<string | null> => {const id = await storeAddAudioTrack(assetId, timelineStartSec ?? playheadSec(), options);if (id) {@@ -1372,9 +1372,14 @@ export function useTimeline() {);// Payload edits hit every fragment of the track — the halves of a split take- // must not disagree about their own level.+ // must not disagree about gain, mute or loop.const updateAudioTrack = useCallback(- async (trackId: string, patch: Partial<Pick<AxcutAudioTrack, "gainDb" | "offsetMs">>) => {+ async (+ trackId: string,+ patch: Partial<+ Pick<AxcutAudioTrack, "gainDb" | "muted" | "loop" | "fadeInMs" | "fadeOutMs" | "offsetMs">+ >,+ ) => {const doc = useProjectStore.getState().document;if (!doc) return;await saveDocument(patchAudioTrack(doc, trackId, patch), { history: true });diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.tsindex 60cb37ebd..3effa84c4 100644--- a/src/native/sceneDescription.test.ts+++ b/src/native/sceneDescription.test.ts@@ -2004,11 +2004,16 @@ describe("buildSceneDescription.audioTracks", () => {const track = {id: "trk1",assetId: "aud",+ kind: "music" as const,startMs: 5000,endMs: 15_000,durationSec: 30,offsetMs: 2000,gainDb: -3,+ loop: false,+ fadeInMs: 0,+ fadeOutMs: 0,+ muted: false,label: "",origin: "user" as const,};@@ -2024,6 +2029,8 @@ describe("buildSceneDescription.audioTracks", () => {// The span is 10s and the file has 28s left after the offset, so the// span is what runs out first.trimEndSec: 12,+ fadeInSec: 0,+ fadeOutSec: 0,},]);});@@ -2037,6 +2044,31 @@ describe("buildSceneDescription.audioTracks", () => {expect(buildSceneDescription(doc).audioTracks[0]?.trimEndSec).toBe(30);});+ it("drops a muted track from the mix list", () => {+ const doc = makeDoc({ assets: [audioAsset], audioTracks: [{ ...track, muted: true }] });+ expect(buildSceneDescription(doc).audioTracks).toEqual([]);+ });++ it("emits one entry per repeat for a looping track", () => {+ const doc = makeDoc({+ assets: [audioAsset],+ // 4s of source (offset 26 into a 30s file) under a 10s span → 3 repeats.+ audioTracks: [{ ...track, offsetMs: 26_000, loop: true, fadeInMs: 500, fadeOutMs: 500 }],+ });+ const entries = buildSceneDescription(doc).audioTracks;+ expect(entries.map((e) => [e.startSec, e.trimStartSec, e.trimEndSec])).toEqual([+ [5, 26, 30],+ [9, 26, 30],+ [13, 26, 28],+ ]);+ // The fades belong to the track's edges, not to every repeat.+ expect(entries.map((e) => [e.fadeInSec, e.fadeOutSec])).toEqual([+ [0.5, 0],+ [0, 0],+ [0, 0.5],+ ]);+ });+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 wasdiff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.tsindex 5b97dbb81..17dd3dd3b 100644--- a/src/native/sceneDescription.ts+++ b/src/native/sceneDescription.ts@@ -417,8 +417,8 @@ export interface SceneDescription {/*** 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.+ * clip boundary contributes one entry per fragment (each picking the source up where+ * the last left off), and a looping track one entry per repeat.** `startSec` is the head on the trim-COMPRESSED output programme: the track's raw* timeline head projected through the trims via `projectRawTimelineSecToPlayback`, so@@ -433,6 +433,11 @@ export interface SceneDescription {gainDb: number;trimStartSec: number;trimEndSec: number;+ /** Ramp lengths at the entry's own edges, in seconds. A split or looping+ * track carries them only on the pieces that touch the track's real+ * start and end, so it fades once rather than at every cut or repeat. */+ fadeInSec: number;+ fadeOutSec: number;}>;/*** Per-clip screen crop (fractions of the frame), or null for the identity@@ -540,36 +545,58 @@ export function buildSceneDescription(clipAssetIsResolvable(clip, assetById),);const audioTracks = document.audioTracks.flatMap((track) => {+ if (track.muted) return [];const asset = assetById.get(track.assetId);if (!asset?.originalPath) return [];const sourceDurationSec = asset.durationSec ?? track.durationSec;const offsetSec = track.offsetMs / 1000;const spanSec = (track.endMs - track.startMs) / 1000;if (spanSec <= 0) return [];+ const startSec = projectRawTimelineSecToPlayback(+ projectedClips,+ document.timeline.trimRanges,+ track.startMs / 1000,+ );+ const base = {+ path: asset.originalPath,+ gainDb: track.gainDb,+ fadeInSec: track.fadeInMs / 1000,+ fadeOutSec: track.fadeOutMs / 1000,+ };// 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.+ // there is nothing to loop over and 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 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.startMs / 1000,- ),- gainDb: track.gainDb,+ if (!track.loop) {+ return [+ {+ ...base,+ startSec,+ 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),+ },+ ];+ }+ // A looping track is one mix entry per repeat: the mixer overlays entries+ // independently, so the repeats are just more of them. The last one is cut+ // short wherever the span ends.+ const entries = [];+ for (let played = 0; played < spanSec && entries.length < 1000; played += windowSec) {+ const thisSec = Math.min(windowSec, spanSec - played);+ entries.push({+ ...base,+ startSec: startSec + played,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),- },- ];+ trimEndSec: offsetSec + thisSec,+ // The fades belong to the track's edges, not to every repeat.+ fadeInSec: played === 0 ? base.fadeInSec : 0,+ fadeOutSec: played + thisSec >= spanSec ? base.fadeOutSec : 0,+ });+ }+ return entries;});const visibleClips = resolveVisibleClips(document);const clips: CompositorClipInput[] = visibleClips.flatMap((clip) => {