diff --git a/src/components/video-editor/audio/useAudioPreviewSync.ts b/src/components/video-editor/audio/useAudioPreviewSync.ts index aa5a32a3af..ef9aa9bc42 100644 --- a/src/components/video-editor/audio/useAudioPreviewSync.ts +++ b/src/components/video-editor/audio/useAudioPreviewSync.ts @@ -356,7 +356,8 @@ export function useAudioPreviewSync({ if (isPlaying && isInRegion) { enablePitchPreservingPlayback(audio); - const audioOffset = (currentTimeMs - startMs) / 1000; + const audioOffset = + (currentTimeMs - startMs + (track.sourceRef.sourceStartMs ?? 0)) / 1000; syncPreviewAudioTime(audio, audioOffset, 0.2); const syncedPlaybackRate = getMediaSyncPlaybackRate({ basePlaybackRate: 1, diff --git a/src/components/video-editor/hooks/useAudioRegionCommands.test.ts b/src/components/video-editor/hooks/useAudioRegionCommands.test.ts new file mode 100644 index 0000000000..3d4b4fc688 --- /dev/null +++ b/src/components/video-editor/hooks/useAudioRegionCommands.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vitest"; +import type { AudioRegion } from "../types"; +import { getAudioSpanUpdate } from "./useAudioRegionCommands"; + +const region: AudioRegion = { + id: "audio-1", + startMs: 1000, + endMs: 6000, + audioPath: "/tmp/music.mp3", + volume: 1, +}; + +describe("getAudioSpanUpdate", () => { + it("skips the trimmed audio when the start edge is trimmed", () => { + expect(getAudioSpanUpdate(region, { start: 3000, end: 6000 })).toEqual({ + startMs: 3000, + endMs: 6000, + sourceStartMs: 2000, + }); + }); + + it("preserves the source mapping when the start edge is dragged past the file start and back", () => { + const trimmed = { ...region, ...getAudioSpanUpdate(region, { start: 3000, end: 6000 }) }; + expect(getAudioSpanUpdate(trimmed, { start: 2500, end: 6000 }).sourceStartMs).toBe(1500); + + const extended = getAudioSpanUpdate(trimmed, { start: 0, end: 6000 }); + expect(extended).toEqual({ startMs: 1000, endMs: 6000, sourceStartMs: 0 }); + expect(getAudioSpanUpdate({ ...trimmed, ...extended }, { start: 3000, end: 6000 })).toEqual( + { + startMs: 3000, + endMs: 6000, + sourceStartMs: 2000, + }, + ); + }); + + it("keeps the source offset when moving or trimming the end", () => { + const trimmed = { ...region, sourceStartMs: 500 }; + expect(getAudioSpanUpdate(trimmed, { start: 2000, end: 7000 }).sourceStartMs).toBe(500); + expect(getAudioSpanUpdate(trimmed, { start: 1000, end: 4000 }).sourceStartMs).toBe(500); + }); +}); diff --git a/src/components/video-editor/hooks/useAudioRegionCommands.ts b/src/components/video-editor/hooks/useAudioRegionCommands.ts index 0d40bbc7c0..aa758cea12 100644 --- a/src/components/video-editor/hooks/useAudioRegionCommands.ts +++ b/src/components/video-editor/hooks/useAudioRegionCommands.ts @@ -1,6 +1,10 @@ import type { Span } from "dnd-timeline"; import { type Dispatch, type MutableRefObject, type SetStateAction, useCallback } from "react"; -import type { AudioRegion, EditorEffectSection } from "../types"; +import { + type AudioRegion, + type EditorEffectSection, + getAudioRegionEarliestStartMs, +} from "../types"; interface UseAudioRegionCommandsParams { setSelectedClipId: Dispatch>; @@ -14,6 +18,25 @@ interface UseAudioRegionCommandsParams { nextAudioIdRef: MutableRefObject; } +/** + * Trimming the start edge keeps the end fixed, so the trimmed amount must be + * skipped in the source audio; moving the region keeps the source offset. + */ +export function getAudioSpanUpdate( + region: AudioRegion, + span: Span, +): Pick { + const requestedStartMs = Math.round(span.start); + const endMs = Math.round(span.end); + const sourceStartMs = region.sourceStartMs ?? 0; + if (endMs !== region.endMs || requestedStartMs === region.startMs) { + return { startMs: requestedStartMs, endMs, sourceStartMs }; + } + + const startMs = Math.max(requestedStartMs, getAudioRegionEarliestStartMs(region)); + return { startMs, endMs, sourceStartMs: sourceStartMs + startMs - region.startMs }; +} + export function useAudioRegionCommands({ setSelectedClipId, setAudioRegions, @@ -89,8 +112,7 @@ export function useAudioRegionCommands({ region.id === id ? { ...region, - startMs: Math.round(span.start), - endMs: Math.round(span.end), + ...getAudioSpanUpdate(region, span), ...(normalizedTrackIndex === undefined ? {} : { trackIndex: normalizedTrackIndex }), diff --git a/src/components/video-editor/projectOverlayRegionsNormalization.ts b/src/components/video-editor/projectOverlayRegionsNormalization.ts index 49518422fe..b96ce62471 100644 --- a/src/components/video-editor/projectOverlayRegionsNormalization.ts +++ b/src/components/video-editor/projectOverlayRegionsNormalization.ts @@ -113,6 +113,9 @@ export function normalizeProjectOverlayRegions(editor: Partial { - const duration = Math.max(0, waveformSpan.end - waveformSpan.start); - return { start: 0, end: duration }; - }, [waveformSpan.end, waveformSpan.start]); + const sourceStart = item.sourceSpan?.start ?? 0; + const waveformDuration = Math.max(0, waveformSpan.end - waveformSpan.start); return ( diff --git a/src/components/video-editor/timeline/core/timelineTypes.ts b/src/components/video-editor/timeline/core/timelineTypes.ts index 1763cee60f..4936362f4f 100644 --- a/src/components/video-editor/timeline/core/timelineTypes.ts +++ b/src/components/video-editor/timeline/core/timelineTypes.ts @@ -12,6 +12,7 @@ export interface TimelineRegionSpan { start: number; end: number; rowId: string; + minResizeStartMs?: number; } export interface TimelineRegion { diff --git a/src/components/video-editor/timeline/dnd/engine.test.ts b/src/components/video-editor/timeline/dnd/engine.test.ts index f9b23ad703..111715ae7c 100644 --- a/src/components/video-editor/timeline/dnd/engine.test.ts +++ b/src/components/video-editor/timeline/dnd/engine.test.ts @@ -296,3 +296,44 @@ describe("timeline dnd engine", () => { expect(result?.rowId).toBe("row-audio-2"); }); }); + +it("keeps the right edge fixed when resizing an audio span", () => { + const config = { + totalMs: 8000, + minItemDurationMs: 500, + allRegionSpans: [ + { id: "audio-1", rowId: "row-audio-0", start: 3000, end: 6000, minResizeStartMs: 1000 }, + ], + hasOverlap: () => false, + }; + + expect(resolveResizeEnd("audio-1", { start: 0, end: 6000 }, config)).toEqual({ + start: 1000, + end: 6000, + }); + expect(resolveResizeEnd("audio-1", { start: 5900, end: 6000 }, config)).toEqual({ + start: 5500, + end: 6000, + }); +}); + +it.each([ + { start: 2200, end: 2800 }, + { start: 2999, end: 3000 }, +])("keeps an audio trim against a preceding region ending at $end", (sibling) => { + const config = { + totalMs: 8000, + minItemDurationMs: 500, + allRegionSpans: [ + { id: "audio-1", rowId: "row-audio-0", start: 3000, end: 6000, minResizeStartMs: 2000 }, + { id: "previous", rowId: "row-audio-0", ...sibling }, + ], + hasOverlap: (span: { start: number; end: number }) => + span.start < sibling.end && sibling.start < span.end, + }; + + expect(resolveResizeEnd("audio-1", { start: 0, end: 6000 }, config)).toEqual({ + start: sibling.end, + end: 6000, + }); +}); diff --git a/src/components/video-editor/timeline/dnd/engine.ts b/src/components/video-editor/timeline/dnd/engine.ts index 76cf762419..0837ad24f9 100644 --- a/src/components/video-editor/timeline/dnd/engine.ts +++ b/src/components/video-editor/timeline/dnd/engine.ts @@ -187,16 +187,17 @@ export function resolveResizeEnd( "totalMs" | "minItemDurationMs" | "allRegionSpans" | "hasOverlap" >, ): Span | null { + if (!Number.isFinite(updatedSpan.start) || !Number.isFinite(updatedSpan.end)) return null; + const { totalMs, minItemDurationMs, allRegionSpans, hasOverlap } = config; const activeItem = allRegionSpans.find((region) => region.id === activeItemId); + const resizedStart = + activeItem && updatedSpan.start !== activeItem.start && updatedSpan.end === activeItem.end; if (activeItem?.rowId === CLIP_ROW_ID) { - if (!Number.isFinite(updatedSpan.start) || !Number.isFinite(updatedSpan.end)) return null; // Source limits are enforced by the clip command. Negative left edges and // extension beyond the old sequence end reveal trimmed source before repacking. const minDuration = Math.max(1, minItemDurationMs); - const resizedLeft = - updatedSpan.start !== activeItem.start && updatedSpan.end === activeItem.end; - return resizedLeft + return resizedStart ? { start: Math.min(updatedSpan.start, updatedSpan.end - minDuration), end: updatedSpan.end, @@ -206,6 +207,31 @@ export function resolveResizeEnd( end: Math.max(updatedSpan.end, updatedSpan.start + minDuration), }; } + if (resizedStart && activeItem?.minResizeStartMs !== undefined) { + // Audio left trims are bounded by the file start and the preceding + // region. Moving the right edge would also change which audio plays. + const earliestStart = getSiblingSpans( + activeItemId, + activeItem.rowId, + allRegionSpans, + ).reduce( + (start, sibling) => + sibling.end <= activeItem.start ? Math.max(start, sibling.end) : start, + activeItem.minResizeStartMs, + ); + const minDuration = Math.min( + Math.max(1, minItemDurationMs), + activeItem.end - activeItem.start, + ); + const latestStart = activeItem.end - minDuration; + if (earliestStart > latestStart || (totalMs > 0 && activeItem.end > totalMs)) return null; + + const span = { + start: Math.max(earliestStart, Math.min(updatedSpan.start, latestStart)), + end: activeItem.end, + }; + return hasOverlap(span, activeItemId) ? null : span; + } let clamped = clampSpanToBounds(updatedSpan, { totalMs, minItemDurationMs }); const effectiveMinDuration = totalMs > 0 ? Math.min(minItemDurationMs, totalMs) : minItemDurationMs; diff --git a/src/components/video-editor/timeline/model/timelineModel.test.ts b/src/components/video-editor/timeline/model/timelineModel.test.ts index 35b536d498..7d01919bf6 100644 --- a/src/components/video-editor/timeline/model/timelineModel.test.ts +++ b/src/components/video-editor/timeline/model/timelineModel.test.ts @@ -74,6 +74,30 @@ describe("timeline model", () => { }); }); + it("maps trimmed audio to its source waveform and earliest left edge", () => { + const input = { + zoomRegions: [], + clipRegions: [], + annotationRegions: [], + audioRegions: [ + { + id: "audio-1", + startMs: 3000, + endMs: 6000, + sourceStartMs: 2000, + audioPath: "/song.wav", + volume: 1, + }, + ], + }; + + expect(buildTimelineItems(input)[0]).toMatchObject({ + span: { start: 3000, end: 6000 }, + sourceSpan: { start: 2000, end: 5000 }, + }); + expect(buildAllRegionSpans(input)[0]).toMatchObject({ minResizeStartMs: 1000 }); + }); + it("keeps a split clip's sourceSpan in source coordinates", () => { const items = buildTimelineItems({ zoomRegions: [], diff --git a/src/components/video-editor/timeline/model/timelineModel.ts b/src/components/video-editor/timeline/model/timelineModel.ts index 87a1fafe62..3d06d8bf72 100644 --- a/src/components/video-editor/timeline/model/timelineModel.ts +++ b/src/components/video-editor/timeline/model/timelineModel.ts @@ -6,7 +6,11 @@ import type { ClipRegion, ZoomRegion, } from "../../types"; -import { getClipSourceEndMs, getClipSourceStartMs } from "../../types"; +import { + getAudioRegionEarliestStartMs, + getClipSourceEndMs, + getClipSourceStartMs, +} from "../../types"; import { CAPTION_ROW_ID, CLIP_ROW_ID, ZOOM_ROW_ID } from "../core/constants"; import { getAnnotationTrackIndex, @@ -88,16 +92,23 @@ export function buildTimelineItems(params: { variant: "annotation", })); - const audios: TimelineRenderItem[] = audioRegions.map((region) => ({ - id: region.id, - rowId: getAudioTrackRowId(region.trackIndex ?? 0), - span: { start: region.startMs, end: region.endMs }, - label: getAudioLabel(region), - audioPath: region.audioPath, - audioGain: region.volume, - audioNormalize: Boolean(region.normalize), - variant: "audio", - })); + const audios: TimelineRenderItem[] = audioRegions.map((region) => { + const sourceStartMs = region.sourceStartMs ?? 0; + return { + id: region.id, + rowId: getAudioTrackRowId(region.trackIndex ?? 0), + span: { start: region.startMs, end: region.endMs }, + sourceSpan: { + start: sourceStartMs, + end: sourceStartMs + region.endMs - region.startMs, + }, + label: getAudioLabel(region), + audioPath: region.audioPath, + audioGain: region.volume, + audioNormalize: Boolean(region.normalize), + variant: "audio", + }; + }); const captions: TimelineRenderItem[] = captionCues.map((cue) => ({ id: cue.id, @@ -135,6 +146,7 @@ export function buildAllRegionSpans(params: { start: r.startMs, end: r.endMs, rowId: getAudioTrackRowId(r.trackIndex ?? 0), + minResizeStartMs: getAudioRegionEarliestStartMs(r), })); return [ ...zooms, diff --git a/src/components/video-editor/types.ts b/src/components/video-editor/types.ts index d0cf8dbec1..fff89e31c0 100644 --- a/src/components/video-editor/types.ts +++ b/src/components/video-editor/types.ts @@ -595,11 +595,19 @@ export interface AudioRegion { startMs: number; endMs: number; audioPath: string; + /** Offset into the audio file where playback begins (set by trimming the region start). */ + sourceStartMs?: number; volume: number; normalize?: boolean; trackIndex?: number; } +export function getAudioRegionEarliestStartMs( + region: Pick, +): number { + return Math.max(0, region.startMs - (region.sourceStartMs ?? 0)); +} + export interface CaptionCue { id: string; startMs: number; diff --git a/src/lib/exporter/audioRoutingEngine.ts b/src/lib/exporter/audioRoutingEngine.ts index 542cd9eb88..86a7c69d03 100644 --- a/src/lib/exporter/audioRoutingEngine.ts +++ b/src/lib/exporter/audioRoutingEngine.ts @@ -12,6 +12,7 @@ export interface ResolvedAudioTrack { sourceRef: { path: string; startDelayMs: number; + sourceStartMs?: number; }; gain: number; timelineBinding: { @@ -72,6 +73,7 @@ export function buildResolvedAudioPlan(input: { sourceRef: { path: region.audioPath, startDelayMs: 0, + sourceStartMs: Math.max(0, region.sourceStartMs ?? 0), }, gain: clampGain(region.volume * (region.normalize ? SOURCE_AUDIO_NORMALIZE_GAIN : 1), 1), timelineBinding: { diff --git a/src/lib/exporter/offlineAudioProcessor.ts b/src/lib/exporter/offlineAudioProcessor.ts index 6a5a227d0a..63b85d599b 100644 --- a/src/lib/exporter/offlineAudioProcessor.ts +++ b/src/lib/exporter/offlineAudioProcessor.ts @@ -421,9 +421,9 @@ export class OfflineAudioProcessor extends AudioMediaProcessor { if (localEndSec <= 0 || localStartSec >= chunkDurationSec) return; // Clip to chunk bounds - let bufferOffsetSec = 0; + let bufferOffsetSec = Math.max(0, region.sourceStartMs ?? 0) / 1000; if (localStartSec < 0) { - bufferOffsetSec = -localStartSec; + bufferOffsetSec += -localStartSec; localStartSec = 0; } if (localEndSec > chunkDurationSec) {