Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/components/video-editor/audio/useAudioPreviewSync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
42 changes: 42 additions & 0 deletions src/components/video-editor/hooks/useAudioRegionCommands.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
28 changes: 25 additions & 3 deletions src/components/video-editor/hooks/useAudioRegionCommands.ts
Original file line number Diff line number Diff line change
@@ -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<SetStateAction<string | null>>;
Expand All @@ -14,6 +18,25 @@ interface UseAudioRegionCommandsParams {
nextAudioIdRef: MutableRefObject<number>;
}

/**
* 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<AudioRegion, "startMs" | "endMs" | "sourceStartMs"> {
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,
Expand Down Expand Up @@ -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 }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ export function normalizeProjectOverlayRegions(editor: Partial<ProjectEditorStat
startMs,
endMs,
audioPath: typeof region.audioPath === "string" ? region.audioPath : "",
sourceStartMs: isFiniteNumber(region.sourceStartMs)
? Math.max(0, Math.round(region.sourceStartMs))
: 0,
volume: isFiniteNumber(region.volume) ? clamp(region.volume, 0, 1) : 1,
normalize: Boolean(region.normalize),
trackIndex: isFiniteNumber(region.trackIndex)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useMemo } from "react";
import type { TimelineRenderItem } from "../../core/timelineTypes";
import { useTimelineAudioPeaks } from "../../hooks/useTimelineAudioPeaks";
import Item from "../../Item";
Expand All @@ -19,10 +18,8 @@ export function AudioItemWithWaveform({
onSelectAudio,
}: AudioItemWithWaveformProps) {
const { peaks } = useTimelineAudioPeaks(item.audioPath ?? null);
const normalizedWaveformSpan = useMemo(() => {
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 (
<Item
id={item.id}
Expand All @@ -32,7 +29,7 @@ export function AudioItemWithWaveform({
onSelectId={onSelectAudio}
variant="audio"
waveformPeaks={peaks}
waveformSegmentSpan={normalizedWaveformSpan}
waveformSegmentSpan={{ start: sourceStart, end: sourceStart + waveformDuration }}
waveformGain={Math.max(0, Math.min(1, item.audioGain ?? 1))}
waveformNormalize={Boolean(item.audioNormalize)}
>
Expand Down
1 change: 1 addition & 0 deletions src/components/video-editor/timeline/core/timelineTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface TimelineRegionSpan {
start: number;
end: number;
rowId: string;
minResizeStartMs?: number;
}

export interface TimelineRegion {
Expand Down
41 changes: 41 additions & 0 deletions src/components/video-editor/timeline/dnd/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
});
34 changes: 30 additions & 4 deletions src/components/video-editor/timeline/dnd/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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;
Expand Down
24 changes: 24 additions & 0 deletions src/components/video-editor/timeline/model/timelineModel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [],
Expand Down
34 changes: 23 additions & 11 deletions src/components/video-editor/timeline/model/timelineModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -135,6 +146,7 @@ export function buildAllRegionSpans(params: {
start: r.startMs,
end: r.endMs,
rowId: getAudioTrackRowId(r.trackIndex ?? 0),
minResizeStartMs: getAudioRegionEarliestStartMs(r),
}));
return [
...zooms,
Expand Down
8 changes: 8 additions & 0 deletions src/components/video-editor/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<AudioRegion, "startMs" | "sourceStartMs">,
): number {
return Math.max(0, region.startMs - (region.sourceStartMs ?? 0));
}

export interface CaptionCue {
id: string;
startMs: number;
Expand Down
2 changes: 2 additions & 0 deletions src/lib/exporter/audioRoutingEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface ResolvedAudioTrack {
sourceRef: {
path: string;
startDelayMs: number;
sourceStartMs?: number;
};
gain: number;
timelineBinding: {
Expand Down Expand Up @@ -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: {
Expand Down
4 changes: 2 additions & 2 deletions src/lib/exporter/offlineAudioProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading