Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat(audio): Implement spectral noise reduction and enhance audio effects

Augustus Otub04b2b2ced02
diff --git a/apps/web/src/bridges/audio-bridge-effects.ts b/apps/web/src/bridges/audio-bridge-effects.ts
index b39cf4f3..e4fb631e 100644
--- a/apps/web/src/bridges/audio-bridge-effects.ts
+++ b/apps/web/src/bridges/audio-bridge-effects.ts
@@ -47,12 +47,16 @@ export interface DelayConfig {
export interface SerializedNoiseProfile {
frequencyBins: number[];
magnitudes: number[];
+ standardDeviations?: number[];
sampleRate: number;
+ fftSize?: number;
}
export const NOISE_REDUCTION_FOCUS_OPTIONS = [
"balanced",
"speech",
+ "whiteNoise",
+ "music",
"heavy",
"wind",
"hum",
@@ -80,7 +84,9 @@ export interface NoiseProfileData {
id: string;
frequencyBins: Float32Array;
magnitudes: Float32Array;
+ standardDeviations?: Float32Array;
sampleRate: number;
+ fftSize?: number;
createdAt: number;
}
@@ -154,9 +160,16 @@ const isSerializedNoiseProfile = (
}
const candidate = profile as Record<string, unknown>;
+ const isValidFftSize = (value: unknown, binCount: number): value is number =>
+ typeof value === "number" &&
+ Number.isInteger(value) &&
+ value > 0 &&
+ (value & (value - 1)) === 0 &&
+ value / 2 === binCount;
return (
Array.isArray(candidate.frequencyBins) &&
+ candidate.frequencyBins.length > 0 &&
candidate.frequencyBins.every(
(value) => typeof value === "number" && Number.isFinite(value),
) &&
@@ -165,8 +178,16 @@ const isSerializedNoiseProfile = (
(value) => typeof value === "number" && Number.isFinite(value),
) &&
candidate.frequencyBins.length === candidate.magnitudes.length &&
+ (candidate.standardDeviations === undefined ||
+ (Array.isArray(candidate.standardDeviations) &&
+ candidate.standardDeviations.length === candidate.magnitudes.length &&
+ candidate.standardDeviations.every(
+ (value) => typeof value === "number" && Number.isFinite(value),
+ ))) &&
typeof candidate.sampleRate === "number" &&
- Number.isFinite(candidate.sampleRate)
+ Number.isFinite(candidate.sampleRate) &&
+ (candidate.fftSize === undefined ||
+ isValidFftSize(candidate.fftSize, candidate.magnitudes.length))
);
};
@@ -273,7 +294,11 @@ export function validateNoiseReduction(
? {
frequencyBins: [...config.profile.frequencyBins],
magnitudes: [...config.profile.magnitudes],
+ standardDeviations: config.profile.standardDeviations
+ ? [...config.profile.standardDeviations]
+ : undefined,
sampleRate: config.profile.sampleRate,
+ fftSize: config.profile.fftSize,
}
: undefined;
@@ -761,7 +786,9 @@ export class AudioBridgeEffects {
id,
frequencyBins: profile.frequencyBins,
magnitudes: profile.magnitudes,
+ standardDeviations: profile.standardDeviations,
sampleRate: profile.sampleRate,
+ fftSize: profile.fftSize,
createdAt: Date.now(),
};
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index 4737c096..18b59e69 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -33,8 +33,14 @@ import {
getSpeedEngine,
getMasterClock,
getRealtimeAudioGraph,
+ initializeAudioEffectsEngine,
+ getPreviewAudioEffects,
+ splitProfileAwareNoiseReductionEffects,
+ resolveClipAudioEffects as resolveTimelineClipAudioEffects,
+ resolveClipVolumeAutomation,
getParticleEngine,
type Effect,
+ type AudioEffectParams,
type AudioClipSchedule,
type TextClip,
type ShapeClip,
@@ -86,6 +92,8 @@ interface PreparedPreviewFrame {
cleanup: () => void;
}
+type PreviewClip = Track["clips"][number];
+
const clipNeedsFrameProcessing = (clipId: string): boolean => {
const bgEngine = getBackgroundRemovalEngine();
if (bgEngine?.isInitialized() && bgEngine.getSettings(clipId).enabled) {
@@ -393,6 +401,7 @@ export const Preview: React.FC = () => {
null,
);
const audioBufferCacheRef = useRef<Map<string, AudioBuffer>>(new Map());
+ const processedAudioBufferCacheRef = useRef<Map<string, AudioBuffer>>(new Map());
const getAudioBufferCacheKey = (mediaId: string, audioTrackIndex?: number): string =>
`${mediaId}:${audioTrackIndex ?? 0}`;
@@ -423,6 +432,74 @@ export const Preview: React.FC = () => {
return null;
};
+ const getAudioEffectSignature = useCallback((effects: Effect[]): string =>
+ JSON.stringify(
+ effects.map((effect) => ({
+ id: effect.id,
+ type: effect.type,
+ enabled: effect.enabled,
+ params: effect.params,
+ metadata: effect.metadata,
+ })),
+ ), []);
+
+ const getPreviewAudioBufferForEffects = useCallback(
+ async (
+ audioBuffer: AudioBuffer,
+ baseCacheKey: string,
+ effects: Effect[],
+ ): Promise<{ audioBuffer: AudioBuffer; effects: Effect[] }> => {
+ const previewEffects = getPreviewAudioEffects(
+ effects.filter((effect) => effect.enabled),
+ );
+ const { profileAwareNoiseEffects, realtimeEffects } =
+ splitProfileAwareNoiseReductionEffects(previewEffects);
+
+ if (profileAwareNoiseEffects.length === 0) {
+ return { audioBuffer, effects: realtimeEffects };
+ }
+
+ const processedCacheKey = `${baseCacheKey}:profile-denoise:${getAudioEffectSignature(profileAwareNoiseEffects)}`;
+ const cached = processedAudioBufferCacheRef.current.get(processedCacheKey);
+ if (cached) {
+ return { audioBuffer: cached, effects: realtimeEffects };
+ }
+
+ const effectsEngine = await initializeAudioEffectsEngine();
+ let processedBuffer = audioBuffer;
+
+ for (const effect of profileAwareNoiseEffects) {
+ const params = effect.params as AudioEffectParams["noiseReduction"];
+ if (!params.profile) {
+ continue;
+ }
+
+ processedBuffer = await effectsEngine.applyNoiseReductionWithProfileData(
+ processedBuffer,
+ params.profile,
+ params.reduction ?? 0.5,
+ params.focus ?? "balanced",
+ params.threshold ?? -40,
+ );
+ }
+
+ processedAudioBufferCacheRef.current.set(processedCacheKey, processedBuffer);
+ return { audioBuffer: processedBuffer, effects: realtimeEffects };
+ },
+ [getAudioEffectSignature],
+ );
+
+ const getResolvedClipAudioEffects = useCallback((clip: PreviewClip): Effect[] => {
+ return resolveTimelineClipAudioEffects(clip, {
+ tracks: timelineTracksRef.current,
+ });
+ }, []);
+
+ const getResolvedClipVolumeAutomation = useCallback((clip: PreviewClip) =>
+ resolveClipVolumeAutomation(clip, {
+ tracks: timelineTracksRef.current,
+ }), []);
+
const rendererRef = useRef<Renderer | null>(null);
const rendererInitializedRef = useRef<boolean>(false);
@@ -1131,9 +1208,6 @@ export const Preview: React.FC = () => {
async (timelinePosition: number): Promise<void> => {
const tracks = timelineTracksRef.current;
const audioTracks = tracks.filter((t) => t.type === "audio" && !t.hidden);
- const videoTracks = tracks.filter(
- (t) => (t.type === "video" || t.type === "image") && !t.hidden,
- );
if (!audioGraphRef.current) {
audioGraphRef.current = getRealtimeAudioGraph();
@@ -1141,7 +1215,6 @@ export const Preview: React.FC = () => {
const audioGraph = audioGraphRef.current;
audioGraph.setPreviewMuted(isMuted);
- const projectStore = useProjectStore.getState();
const speedEngine = getSpeedEngine();
const scheduledClips: AudioClipSchedule[] = [];
@@ -1171,9 +1244,11 @@ export const Preview: React.FC = () => {
continue;
}
- let audioBuffer = audioBufferCacheRef.current.get(
- getAudioBufferCacheKey(audioClip.mediaId, audioClip.audioTrackIndex),
+ const audioCacheKey = getAudioBufferCacheKey(
+ audioClip.mediaId,
+ audioClip.audioTrackIndex,
);
+ let audioBuffer = audioBufferCacheRef.current.get(audioCacheKey);
if (!audioBuffer) {
try {
const audioContext = audioGraph.getAudioContext();
@@ -1186,10 +1261,7 @@ export const Preview: React.FC = () => {
continue;
}
audioBuffer = loaded;
- audioBufferCacheRef.current.set(
- getAudioBufferCacheKey(audioClip.mediaId, audioClip.audioTrackIndex),
- audioBuffer,
- );
+ audioBufferCacheRef.current.set(audioCacheKey, audioBuffer);
} catch (error) {
console.warn(
`[Preview] Failed to decode audio for clip ${audioClip.id}:`,
@@ -1199,33 +1271,18 @@ export const Preview: React.FC = () => {
}
}
- const audioClipData = projectStore.getClip(audioClip.id);
- let audioEffects = audioClipData?.audioEffects || [];
-
- if (audioEffects.length === 0) {
- for (const videoTrack of videoTracks) {
- for (const videoClip of videoTrack.clips) {
- if (
- videoClip.mediaId === audioClip.mediaId &&
- Math.abs(videoClip.startTime - audioClip.startTime) < 0.01
- ) {
- const videoClipData = projectStore.getClip(videoClip.id);
- const linkedEffects = videoClipData?.audioEffects || [];
- if (linkedEffects.length > 0) {
- audioEffects = linkedEffects;
- break;
- }
- }
- }
- if (audioEffects.length > 0) break;
- }
- }
+ const audioEffects = getResolvedClipAudioEffects(audioClip);
const enabledEffects = audioEffects.filter(
(e: Effect) => e.enabled,
);
+ const previewAudio = await getPreviewAudioBufferForEffects(
+ audioBuffer,
+ audioCacheKey,
+ enabledEffects,
+ );
- audioGraph.updateTrackEffects(audioTrack.id, enabledEffects);
+ audioGraph.updateTrackEffects(audioTrack.id, previewAudio.effects);
const clipLocalTime = timelinePosition - audioClip.startTime;
const isReverse = speedEngine.isReverse(audioClip.id);
@@ -1239,14 +1296,14 @@ export const Preview: React.FC = () => {
scheduledClips.push({
clipId: audioClip.id,
trackId: audioTrack.id,
- audioBuffer,
+ audioBuffer: previewAudio.audioBuffer,
startTime: audioClip.startTime,
endTime: clipEnd,
mediaOffset,
volume: audioClip.volume ?? 1,
- volumeAutomation: audioClip.automation?.volume ?? [],
+ volumeAutomation: getResolvedClipVolumeAutomation(audioClip),
pan: 0,
- effects: enabledEffects,
+ effects: previewAudio.effects,
speed: audioClip.speed ?? 1,
});
}
@@ -1258,7 +1315,13 @@ export const Preview: React.FC = () => {
audioGraph.scheduleClips(scheduledClips);
}
},
- [getMediaItem, isMuted],
+ [
+ getMediaItem,
+ getPreviewAudioBufferForEffects,
+ getResolvedClipAudioEffects,
+ getResolvedClipVolumeAutomation,
+ isMuted,
+ ],
);
const preDecodeAllAudioBuffers = useCallback(async (): Promise<void> => {
@@ -1279,29 +1342,47 @@ export const Preview: React.FC = () => {
for (const track of allTracks) {
for (const clip of track.clips) {
const cacheKey = getAudioBufferCacheKey(clip.mediaId, clip.audioTrackIndex);
- if (audioBufferCacheRef.current.has(cacheKey)) {
- continue;
- }
+ let audioBuffer: AudioBuffer | null | undefined =
+ audioBufferCacheRef.current.get(cacheKey);
- const mediaItem = getMediaItem(clip.mediaId);
- if (!mediaItem?.blob) {
- continue;
+ if (!audioBuffer) {
+ const mediaItem = getMediaItem(clip.mediaId);
+ if (!mediaItem?.blob) {
+ continue;
+ }
+
+ try {
+ audioBuffer = await loadAudioBuffer(
+ audioContext,
+ mediaItem.blob,
+ clip.audioTrackIndex ?? 0,
+ );
+ if (audioBuffer) {
+ audioBufferCacheRef.current.set(cacheKey, audioBuffer);
+ }
+ } catch {
+ audioBuffer = null;
+ }
}
- try {
- const audioBuffer = await loadAudioBuffer(
- audioContext,
- mediaItem.blob,
- clip.audioTrackIndex ?? 0,
+ if (audioBuffer) {
+ const audioEffects = getResolvedClipAudioEffects(clip).filter(
+ (effect: Effect) => effect.enabled,
);
- if (audioBuffer) {
- audioBufferCacheRef.current.set(cacheKey, audioBuffer);
+ if (audioEffects.length > 0) {
+ try {
+ await getPreviewAudioBufferForEffects(audioBuffer, cacheKey, audioEffects);
+ } catch (error) {
+ console.warn(
+ `[Preview] Failed to pre-process audio effects for clip ${clip.id}:`,
+ error,
+ );
+ }
}
- } catch {
}
}
}
- }, [getMediaItem]);
+ }, [getMediaItem, getPreviewAudioBufferForEffects, getResolvedClipAudioEffects]);
const getAudioClipsForScheduler = useCallback(
(time: number): AudioClipSchedule[] => {
@@ -1310,7 +1391,6 @@ export const Preview: React.FC = () => {
(t) => (t.type === "audio" || t.type === "video") && !t.hidden && !t.muted,
);
const schedules: AudioClipSchedule[] = [];
- const projectStore = useProjectStore.getState();
for (const track of tracksWithAudio) {
for (const clip of track.clips) {
@@ -1326,22 +1406,40 @@ export const Preview: React.FC = () => {
continue;
}
- const clipData = projectStore.getClip(clip.id);
- const audioEffects = (clipData?.audioEffects || []).filter(
+ const audioEffects = getResolvedClipAudioEffects(clip).filter(
(e: Effect) => e.enabled,
);
+ const previewEffects = getPreviewAudioEffects(audioEffects);
+ const { profileAwareNoiseEffects, realtimeEffects } =
+ splitProfileAwareNoiseReductionEffects(previewEffects);
+ let scheduleAudioBuffer = audioBuffer;
+ let scheduleEffects = previewEffects;
+
+ if (profileAwareNoiseEffects.length > 0) {
+ const processedCacheKey = `${getAudioBufferCacheKey(
+ clip.mediaId,
+ clip.audioTrackIndex,
+ )}:profile-denoise:${getAudioEffectSignature(profileAwareNoiseEffects)}`;
+ const processedAudioBuffer =
+ processedAudioBufferCacheRef.current.get(processedCacheKey);
+
+ if (processedAudioBuffer) {
+ scheduleAudioBuffer = processedAudioBuffer;
+ scheduleEffects = realtimeEffects;
+ }
+ }
schedules.push({
clipId: clip.id,
trackId: track.id,
- audioBuffer,
+ audioBuffer: scheduleAudioBuffer,
startTime: clip.startTime,
endTime: clipEnd,
mediaOffset: clip.inPoint || 0,
volume: clip.volume ?? 1,
- volumeAutomation: clip.automation?.volume ?? [],
+ volumeAutomation: getResolvedClipVolumeAutomation(clip),
pan: 0,
- effects: audioEffects,
+ effects: scheduleEffects,
speed: clip.speed ?? 1,
});
}
@@ -1349,7 +1447,11 @@ export const Preview: React.FC = () => {
return schedules;
},
- [],
+ [
+ getAudioEffectSignature,
+ getResolvedClipAudioEffects,
+ getResolvedClipVolumeAutomation,
+ ],
);
/**
@@ -2296,6 +2398,27 @@ export const Preview: React.FC = () => {
}
}
+ const hasActiveAudioEffects = tracks.some(
+ (track) =>
+ (track.type === "audio" || track.type === "video") &&
+ !track.hidden &&
+ track.clips.some((clip) => {
+ if (clip.startTime + clip.duration <= startPosition) {
+ return false;
+ }
+
+ return getPreviewAudioEffects(
+ getResolvedClipAudioEffects(clip),
+ ).some(
+ (effect) => effect.enabled,
+ );
+ }),
+ );
+
+ if (hasActiveAudioEffects) {
+ return { canUse: false, clips: [] };
+ }
+
if (allVideoClips.length === 0) return { canUse: false, clips: [] };
allVideoClips.sort((a, b) => a.clip.startTime - b.clip.startTime);
@@ -2328,7 +2451,7 @@ export const Preview: React.FC = () => {
return { canUse: true, clips: allVideoClips, imageClips };
},
- [timelineTracks, getMediaItem, allTextClips, allShapeClips],
+ [timelineTracks, getMediaItem, allTextClips, allShapeClips, getResolvedClipAudioEffects],
);
// Start native video playback using hardware-accelerated video elements (handles multiple clips)
@@ -2372,9 +2495,11 @@ export const Preview: React.FC = () => {
}
}
- preDecodeAllAudioBuffers().catch((error) => {
+ try {
+ await preDecodeAllAudioBuffers();
+ } catch (error) {
console.warn("[Preview] Audio warmup failed:", error);
- });
+ }
const videoCache = new Map<
string,
@@ -2479,43 +2604,7 @@ export const Preview: React.FC = () => {
await audioGraph.resume();
audioGraph.seekTo(startPosition);
await masterClock.play();
- audioGraph.startScheduler(() => {
- const tracksWithAudio = timelineTracks.filter(
- (t) => (t.type === "audio" || t.type === "video") && !t.hidden,
- );
- const schedules: AudioClipSchedule[] = [];
- for (const track of tracksWithAudio) {
- for (const audioClip of track.clips) {
- const mediaItem = getMediaItem(audioClip.mediaId);
- const hasAudio =
- mediaItem?.type === "audio" ||
- (mediaItem?.type === "video" &&
- mediaItem?.metadata?.channels &&
- mediaItem.metadata.channels > 0);
- if (!hasAudio) continue;
-
- const audioBuffer = audioBufferCacheRef.current.get(
- getAudioBufferCacheKey(audioClip.mediaId, audioClip.audioTrackIndex),
- );
- if (audioBuffer) {
- schedules.push({
- clipId: audioClip.id,
- trackId: track.id,
- audioBuffer,
- startTime: audioClip.startTime,
- endTime: audioClip.startTime + audioClip.duration,
- mediaOffset: audioClip.inPoint || 0,
- volume: audioClip.volume ?? 1,
- volumeAutomation: audioClip.automation?.volume ?? [],
- pan: 0,
- effects: [],
- speed: audioClip.speed ?? 1,
- });
- }
- }
- }
- return schedules;
- });
+ audioGraph.startScheduler(getAudioClipsForScheduler);
let isActive = true;
let rafId: number | null = null;
@@ -2874,6 +2963,7 @@ export const Preview: React.FC = () => {
actualEndTime,
allSubtitles,
getMediaItem,
+ getAudioClipsForScheduler,
isMuted,
preDecodeAllAudioBuffers,
releaseVideoElement,
@@ -3426,9 +3516,11 @@ export const Preview: React.FC = () => {
return;
}
- preDecodeAllAudioBuffers().catch((error) => {
+ try {
+ await preDecodeAllAudioBuffers();
+ } catch (error) {
console.warn("[Preview] Audio warmup failed:", error);
- });
+ }
if (!audioGraphRef.current) {
audioGraphRef.current = getRealtimeAudioGraph();
@@ -4282,7 +4374,13 @@ export const Preview: React.FC = () => {
const [previewInvalidateCounter, setPreviewInvalidateCounter] = useState(0);
useEffect(() => {
- const handler = () => setPreviewInvalidateCounter((c) => c + 1);
+ const handler = () => {
+ processedAudioBufferCacheRef.current.clear();
+ if (audioGraphRef.current) {
+ audioGraphRef.current.seekTo(getMasterClock().currentTime);
+ }
+ setPreviewInvalidateCounter((c) => c + 1);
+ };
window.addEventListener("openreel:preview-invalidate", handler);
return () => window.removeEventListener("openreel:preview-invalidate", handler);
}, []);
diff --git a/apps/web/src/components/editor/inspector/AudioDuckingSection.tsx b/apps/web/src/components/editor/inspector/AudioDuckingSection.tsx
index 6a2012bf..cf0bc6c7 100644
--- a/apps/web/src/components/editor/inspector/AudioDuckingSection.tsx
+++ b/apps/web/src/components/editor/inspector/AudioDuckingSection.tsx
@@ -10,7 +10,13 @@ import {
RefreshCw,
AlertCircle,
} from "lucide-react";
-import { AudioDucker, type Clip, type Project, type Track } from "@openreel/core";
+import {
+ AudioDucker,
+ resolveAudibleAudioTarget,
+ type Clip,
+ type Project,
+ type Track,
+} from "@openreel/core";
import { Slider } from "@openreel/ui";
import { useProjectStore } from "../../../stores/project-store";
import type { AudioDuckingSettings } from "../../../stores/project";
@@ -203,34 +209,45 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const selectedClip = useMemo(() => findClipById(project, clipId), [project, clipId]);
+ const audioTargetClip = useMemo(
+ () =>
+ selectedClip
+ ? resolveAudibleAudioTarget(selectedClip, project.timeline)
+ : null,
+ [project.timeline, selectedClip],
+ );
const availableSourceTracks = useMemo(() => {
+ const excludedClipIds = new Set(
+ [clipId, audioTargetClip?.id].filter(Boolean) as string[],
+ );
+
return project.timeline.tracks.filter(
(track): track is Track =>
(track.type === "audio" || track.type === "video") &&
- !track.clips.every((clip) => clip.id === clipId),
+ !track.clips.every((clip) => excludedClipIds.has(clip.id)),
);
- }, [clipId, project.timeline.tracks]);
+ }, [audioTargetClip?.id, clipId, project.timeline.tracks]);
const currentTrack = useMemo(() => {
for (const track of project.timeline.tracks) {
for (const clip of track.clips) {
- if (clip.id === clipId) {
+ if (clip.id === (audioTargetClip?.id ?? clipId)) {
return track;
}
}
}
return null;
- }, [project.timeline.tracks, clipId]);
+ }, [audioTargetClip?.id, project.timeline.tracks, clipId]);
const persistedSettings = useMemo(() => {
- const candidate = selectedClip?.metadata?.audioDucking;
+ const candidate = audioTargetClip?.metadata?.audioDucking;
return isAudioDuckingSettings(candidate) ? candidate : null;
- }, [selectedClip]);
+ }, [audioTargetClip]);
const hasAppliedDucking = Boolean(
persistedSettings?.enabled &&
- (selectedClip?.automation?.volume?.length ?? 0) > 0,
+ (audioTargetClip?.automation?.volume?.length ?? 0) > 0,
);
const showControls = settings.enabled || hasAppliedDucking;
@@ -264,7 +281,7 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({
}, []);
const handleApplyDucking = useCallback(async () => {
- if (!selectedClip || !settings.sourceTrackId) {
+ if (!audioTargetClip || !settings.sourceTrackId) {
return;
}
@@ -283,14 +300,14 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({
try {
const triggerBuffer = await buildTriggerTrackBuffer(
project,
- selectedClip,
+ audioTargetClip,
sourceTrack,
);
const ducker = new AudioDucker();
const keyframes = ducker.generateDuckingKeyframes(
triggerBuffer,
settings,
- selectedClip.volume,
+ audioTargetClip.volume > 0 ? audioTargetClip.volume : 1,
);
if (keyframes.length === 0) {
@@ -300,11 +317,13 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({
}
const persisted = { ...settings, enabled: true };
- const applied = setClipAudioDucking(selectedClip.id, persisted, keyframes);
+ const applied = setClipAudioDucking(audioTargetClip.id, persisted, keyframes);
if (!applied) {
throw new Error("Failed to persist ducking on this clip.");
}
+
+ window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"));
} catch (error) {
setErrorMessage(
error instanceof Error ? error.message : "Failed to apply ducking.",
@@ -312,10 +331,10 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({
} finally {
setIsApplying(false);
}
- }, [project, selectedClip, setClipAudioDucking, settings]);
+ }, [audioTargetClip, project, setClipAudioDucking, settings]);
const handleRemoveDucking = useCallback(() => {
- const cleared = clearClipAudioDucking(clipId);
+ const cleared = clearClipAudioDucking(audioTargetClip?.id ?? clipId);
if (!cleared) {
setErrorMessage("Failed to remove ducking from this clip.");
@@ -324,7 +343,8 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({
setSettings(DEFAULT_SETTINGS);
setErrorMessage(null);
- }, [clearClipAudioDucking, clipId]);
+ window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"));
+ }, [audioTargetClip?.id, clearClipAudioDucking, clipId]);
return (
<div className="space-y-3">
diff --git a/apps/web/src/components/editor/inspector/NoiseReductionSection.persistence.test.tsx b/apps/web/src/components/editor/inspector/NoiseReductionSection.persistence.test.tsx
index 623ae5a1..5d71fafd 100644
--- a/apps/web/src/components/editor/inspector/NoiseReductionSection.persistence.test.tsx
+++ b/apps/web/src/components/editor/inspector/NoiseReductionSection.persistence.test.tsx
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { cleanup, render, screen, waitFor } from "@testing-library/react";
-import type { Project } from "@openreel/core";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { autoLearnNoiseProfile, type Project } from "@openreel/core";
import { createEmptyProject } from "../../../stores/project/project-helpers";
import { useProjectStore } from "../../../stores/project-store";
import {
@@ -10,9 +10,37 @@ import {
import * as audioBridgeEffects from "../../../bridges/audio-bridge-effects";
import { NoiseReductionSection } from "./NoiseReductionSection";
+vi.mock("@openreel/core", async () => {
+ const actual = await vi.importActual<typeof import("@openreel/core")>("@openreel/core");
+ return {
+ ...actual,
+ autoLearnNoiseProfile: vi.fn(),
+ };
+});
+
const clipId = "clip-noise";
const trackId = "track-audio";
+const createValidAnalyzedProfile = () => {
+ const frequencyBins = new Float32Array(1024);
+ const magnitudes = new Float32Array(1024);
+ const standardDeviations = new Float32Array(1024);
+
+ for (let index = 0; index < 1024; index += 1) {
+ frequencyBins[index] = index * (48000 / 2048);
+ magnitudes[index] = 0.78 + ((index % 7) * 0.005);
+ standardDeviations[index] = 0.03;
+ }
+
+ return {
+ frequencyBins,
+ magnitudes,
+ standardDeviations,
+ sampleRate: 48000,
+ fftSize: 2048,
+ };
+};
+
const createProjectWithNoiseReduction = (): Project => {
const project = createEmptyProject("Noise Reduction Persistence");
const noiseReductionEffect = createNoiseReductionEffect({
@@ -72,8 +100,84 @@ const createProjectWithNoiseReduction = (): Project => {
};
};
+const createProjectForAnalysis = (): Project => {
+ const project = createEmptyProject("Noise Recommendation");
+
+ return {
+ ...project,
+ mediaLibrary: {
+ items: [
+ {
+ id: "media-1",
+ name: "noisy-video.mp4",
+ type: "video",
+ fileHandle: null,
+ blob: {
+ arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
+ } as unknown as Blob,
+ metadata: {
+ duration: 6,
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ codec: "h264",
+ sampleRate: 48000,
+ channels: 2,
+ fileSize: 5,
+ },
+ thumbnailUrl: null,
+ waveformData: null,
+ },
+ ],
+ },
+ timeline: {
+ ...project.timeline,
+ duration: 6,
+ tracks: [
+ {
+ id: trackId,
+ type: "video",
+ name: "Primary",
+ clips: [
+ {
+ id: clipId,
+ mediaId: "media-1",
+ trackId,
+ startTime: 0,
+ duration: 6,
+ inPoint: 0,
+ outPoint: 6,
+ effects: [],
+ audioEffects: [],
+ transform: {
+ position: { x: 0, y: 0 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+ },
+ volume: 1,
+ keyframes: [],
+ },
+ ],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ },
+ ],
+ },
+ };
+};
+
describe("NoiseReductionSection persistence", () => {
beforeEach(() => {
+ Object.defineProperty(globalThis, "AudioContext", {
+ writable: true,
+ value: window.AudioContext,
+ });
+ vi.mocked(autoLearnNoiseProfile).mockReset();
vi.spyOn(audioBridgeEffects, "initializeAudioBridgeEffects").mockResolvedValue(
audioBridgeEffects.getAudioBridgeEffects(),
);
@@ -106,4 +210,67 @@ describe("NoiseReductionSection persistence", () => {
expect(screen.getByText(/Current mode:/)).toHaveTextContent("Speech Focus");
});
});
+
+ it("shows an explicit apply action before saving analyzed recommendations", async () => {
+ vi.mocked(autoLearnNoiseProfile).mockResolvedValue(createValidAnalyzedProfile());
+ vi.spyOn(
+ audioBridgeEffects.getAudioBridgeEffects(),
+ "learnNoiseProfile",
+ ).mockResolvedValue({
+ id: `profile-${clipId}`,
+ frequencyBins: createValidAnalyzedProfile().frequencyBins,
+ magnitudes: createValidAnalyzedProfile().magnitudes,
+ standardDeviations: createValidAnalyzedProfile().standardDeviations,
+ fftSize: 2048,
+ sampleRate: 48000,
+ createdAt: Date.now(),
+ });
+ useProjectStore.setState({ project: createProjectForAnalysis() });
+
+ render(<NoiseReductionSection clipId={clipId} />);
+
+ fireEvent.click(screen.getByRole("button", { name: /Analyze & Recommend/i }));
+
+ await waitFor(() => {
+ expect(autoLearnNoiseProfile).toHaveBeenCalled();
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("Recommendation ready")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Apply Recommended Cleanup" })).toBeInTheDocument();
+ });
+
+ expect(useProjectStore.getState().getAudioEffects(clipId)).toHaveLength(0);
+
+ fireEvent.click(screen.getByRole("button", { name: "Apply Recommended Cleanup" }));
+
+ await waitFor(() => {
+ const effect = useProjectStore.getState().getAudioEffects(clipId)[0];
+ expect(effect?.type).toBe("noiseReduction");
+ expect(effect?.params).toMatchObject({ focus: "whiteNoise" });
+ expect((effect?.params as { profile?: unknown }).profile).toBeTruthy();
+ expect(screen.getByText(/White Noise applied to this clip/)).toBeInTheDocument();
+ });
+ });
+
+ it("auto-learns a profile when a preset is clicked directly", async () => {
+ vi.mocked(autoLearnNoiseProfile).mockResolvedValue(createValidAnalyzedProfile());
+ useProjectStore.setState({ project: createProjectForAnalysis() });
+
+ render(<NoiseReductionSection clipId={clipId} />);
+
+ fireEvent.click(screen.getByRole("button", { name: /White Noise/i }));
+
+ await waitFor(() => {
+ expect(autoLearnNoiseProfile).toHaveBeenCalled();
+ });
+
+ await waitFor(() => {
+ const effect = useProjectStore.getState().getAudioEffects(clipId)[0];
+ expect(effect?.type).toBe("noiseReduction");
+ expect(effect?.params).toMatchObject({ focus: "whiteNoise" });
+ expect((effect?.params as { profile?: unknown }).profile).toBeTruthy();
+ expect(screen.getByText(/White Noise learned and applied to this clip/)).toBeInTheDocument();
+ });
+ });
});
\ No newline at end of file
diff --git a/apps/web/src/components/editor/inspector/NoiseReductionSection.test.ts b/apps/web/src/components/editor/inspector/NoiseReductionSection.test.ts
index 586af204..890a95a2 100644
--- a/apps/web/src/components/editor/inspector/NoiseReductionSection.test.ts
+++ b/apps/web/src/components/editor/inspector/NoiseReductionSection.test.ts
@@ -17,7 +17,7 @@ const createProfile = (
});
describe("noise reduction presets", () => {
- it("recommends heavy cleanup for broadband high-energy noise", () => {
+ it("recommends white-noise cleanup for broadband hiss", () => {
const preset = suggestNoiseReductionPreset(
createProfile(
[80, 250, 1000, 4000, 8000, 12000],
@@ -25,7 +25,32 @@ describe("noise reduction presets", () => {
),
);
- expect(preset).toBe("heavy");
+ expect(preset).toBe("whiteNoise");
+ });
+
+ it("recommends music-bed cleanup for tonal midrange background music", () => {
+ const config = suggestNoiseReductionConfig(
+ createProfile(
+ [80, 220, 440, 880, 1760, 3520, 8000],
+ [0.08, 1.8, 1.1, 0.85, 0.68, 0.42, 0.12],
+ ),
+ );
+
+ expect(config.focus).toBe("music");
+ expect(config.reduction).toBeGreaterThan(0.8);
+ });
+
+ it("pushes broadband white-noise recommendations into aggressive settings", () => {
+ const config = suggestNoiseReductionConfig(
+ createProfile(
+ [80, 250, 1000, 4000, 8000, 12000],
+ [0.78, 0.82, 0.8, 0.79, 0.81, 0.8],
+ ),
+ );
+
+ expect(config.focus).toBe("whiteNoise");
+ expect(config.reduction).toBeGreaterThanOrEqual(0.9);
+ expect(config.threshold).toBeLessThanOrEqual(-50);
});
it("detects low-end tonal noise as hum or HVAC", () => {
diff --git a/apps/web/src/components/editor/inspector/NoiseReductionSection.tsx b/apps/web/src/components/editor/inspector/NoiseReductionSection.tsx
index b8a6c262..7852d188 100644
--- a/apps/web/src/components/editor/inspector/NoiseReductionSection.tsx
+++ b/apps/web/src/components/editor/inspector/NoiseReductionSection.tsx
@@ -1,11 +1,18 @@
import React, { useCallback, useEffect, useState } from "react";
import { ChevronDown, Volume2, Wand2, AlertCircle, Check } from "lucide-react";
-import { autoLearnNoiseProfile } from "@openreel/core";
+import {
+ autoLearnNoiseProfile,
+ extractAudioSegment,
+ resolveAudibleAudioTarget,
+ type Clip,
+ type Project,
+} from "@openreel/core";
import {
getAudioBridgeEffects,
initializeAudioBridgeEffects,
type NoiseReductionConfig,
type NoiseReductionFocus,
+ type NoiseProfileData,
type SerializedNoiseProfile,
DEFAULT_NOISE_REDUCTION,
} from "../../../bridges/audio-bridge-effects";
@@ -17,6 +24,7 @@ import {
suggestNoiseReductionConfig,
suggestNoiseReductionPreset,
} from "./noise-reduction-presets";
+import { loadAudioBuffer } from "../../../utils/load-audio-buffer";
/**
* NoiseReductionSection Props
@@ -36,7 +44,29 @@ const DEFAULT_NOISE_REDUCTION_STATE: NoiseReductionConfig = {
/**
* Learning state for noise profile
*/
-type LearningState = "idle" | "learning" | "success" | "error";
+type LearningState = "idle" | "learning" | "ready" | "applying" | "success" | "error";
+
+interface NoiseRecommendation {
+ presetId: NoiseReductionFocus;
+ config: NoiseReductionConfig;
+ profile: SerializedNoiseProfile;
+}
+
+interface LearnedNoiseProfileResult {
+ profile: NoiseProfileData;
+ serializedProfile: SerializedNoiseProfile;
+}
+
+const findClipById = (project: Project, clipId: string): Clip | null => {
+ for (const track of project.timeline.tracks) {
+ const clip = track.clips.find((candidate) => candidate.id === clipId);
+ if (clip) {
+ return clip;
+ }
+ }
+
+ return null;
+};
/**
* NoiseReductionSection Component
@@ -49,7 +79,15 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
clipId,
}) => {
const defaultFocus = DEFAULT_NOISE_REDUCTION.focus ?? "balanced";
- const audioEffects = useProjectStore((state) => state.getAudioEffects(clipId));
+ const project = useProjectStore((state) => state.project);
+ const audioTargetClip = React.useMemo(() => {
+ const clip = findClipById(project, clipId);
+ return clip ? resolveAudibleAudioTarget(clip, project.timeline) : null;
+ }, [clipId, project]);
+ const audioTargetClipId = audioTargetClip?.id ?? clipId;
+ const audioEffects = useProjectStore((state) =>
+ state.getAudioEffects(audioTargetClipId),
+ );
const setAudioEffectPreviewBypass = useProjectStore(
(state) => state.setAudioEffectPreviewBypass,
);
@@ -65,6 +103,9 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
const [activePresetId, setActivePresetId] =
useState<NoiseReductionFocus>(defaultFocus);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
+ const [recommendation, setRecommendation] =
+ useState<NoiseRecommendation | null>(null);
+ const [appliedMessage, setAppliedMessage] = useState<string | null>(null);
const [isOpen, setIsOpen] = useState(true);
@@ -78,6 +119,13 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
});
}, []);
+ useEffect(() => {
+ setRecommendation(null);
+ setLearningState("idle");
+ setErrorMessage(null);
+ setAppliedMessage(null);
+ }, [audioTargetClipId, clipId]);
+
useEffect(() => {
const noiseEffect = audioEffects.find((effect) => effect.type === "noiseReduction");
@@ -90,8 +138,6 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
...params,
});
setActivePresetId((params.focus ?? defaultFocus) as NoiseReductionFocus);
- setLearningState("idle");
- setErrorMessage(null);
return;
}
@@ -99,18 +145,16 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
setEffectId(null);
setConfig(DEFAULT_NOISE_REDUCTION_STATE);
setActivePresetId(defaultFocus);
- setLearningState("idle");
- setErrorMessage(null);
}, [audioEffects, clipId, defaultFocus]);
const applyNoiseReductionConfig = useCallback(
- (nextConfig: NoiseReductionConfig) => {
+ (nextConfig: NoiseReductionConfig, existingEffectId = effectId) => {
const bridge = getAudioBridgeEffects();
- if (effectId) {
+ if (existingEffectId) {
const updateResult = bridge.updateNoiseReduction(
- clipId,
- effectId,
+ audioTargetClipId,
+ existingEffectId,
nextConfig,
);
@@ -120,22 +164,26 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
);
}
- toggleAudioEffect(clipId, effectId, true);
+ toggleAudioEffect(audioTargetClipId, existingEffectId, true);
+ setAudioEffectPreviewBypass(audioTargetClipId, existingEffectId, false);
setEnabled(true);
- return effectId;
+ window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"));
+ return existingEffectId;
}
- const applyResult = bridge.applyNoiseReduction(clipId, nextConfig);
+ const applyResult = bridge.applyNoiseReduction(audioTargetClipId, nextConfig);
if (!applyResult.success || !applyResult.effectId) {
throw new Error(applyResult.error ?? "Failed to apply noise reduction");
}
setEffectId(applyResult.effectId);
+ setAudioEffectPreviewBypass(audioTargetClipId, applyResult.effectId, false);
setEnabled(true);
+ window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"));
return applyResult.effectId;
},
- [clipId, effectId, toggleAudioEffect],
+ [audioTargetClipId, effectId, setAudioEffectPreviewBypass, toggleAudioEffect],
);
const handleToggle = useCallback(
@@ -152,12 +200,19 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
return;
}
} else if (effectId) {
- toggleAudioEffect(clipId, effectId, newEnabled);
+ toggleAudioEffect(audioTargetClipId, effectId, newEnabled);
+ window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"));
}
setEnabled(newEnabled);
},
- [applyNoiseReductionConfig, config, effectId, toggleAudioEffect],
+ [
+ applyNoiseReductionConfig,
+ audioTargetClipId,
+ config,
+ effectId,
+ toggleAudioEffect,
+ ],
);
const handleConfigChange = useCallback(
@@ -168,29 +223,148 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
const newConfig = { ...prev, [key]: value };
if (effectId && enabled) {
- bridge.updateNoiseReduction(clipId, effectId, newConfig);
+ bridge.updateNoiseReduction(audioTargetClipId, effectId, newConfig);
+ window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"));
}
return newConfig;
});
},
- [clipId, effectId, enabled],
+ [audioTargetClipId, effectId, enabled],
);
- const handleApplyPreset = useCallback(
- (presetId: NoiseReductionFocus) => {
- const nextConfig = {
- ...getNoiseReductionPreset(presetId).config,
- profile: config.profile,
- };
+ const learnNoiseProfileForClip = useCallback(
+ async (): Promise<LearnedNoiseProfileResult> => {
+ const project = useProjectStore.getState().project;
+ const clip = project.timeline.tracks
+ .flatMap((track) => track.clips)
+ .find((candidate) => candidate.id === audioTargetClipId);
+
+ if (!clip) {
+ throw new Error("Clip not found");
+ }
+
+ const mediaItem = project.mediaLibrary.items.find(
+ (candidate) => candidate.id === clip.mediaId,
+ );
+
+ if (!mediaItem?.blob) {
+ throw new Error("No audio data available for this clip");
+ }
+ let audioContext: AudioContext | null = null;
+
+ try {
+ audioContext = new AudioContext();
+ const audioBuffer = await loadAudioBuffer(
+ audioContext,
+ mediaItem.blob,
+ clip.audioTrackIndex ?? 0,
+ );
+
+ if (!audioBuffer) {
+ throw new Error("Failed to decode audio for analysis");
+ }
+
+ const clipStart = Math.max(0, clip.inPoint || 0);
+ const clipEnd = Math.min(
+ audioBuffer.duration,
+ clip.outPoint > clipStart ? clip.outPoint : clipStart + clip.duration,
+ );
+
+ if (clipEnd <= clipStart) {
+ throw new Error("Clip audio range is empty");
+ }
+
+ const analysisContext = new OfflineAudioContext(
+ audioBuffer.numberOfChannels,
+ Math.max(1, Math.ceil((clipEnd - clipStart) * audioBuffer.sampleRate)),
+ audioBuffer.sampleRate,
+ );
+
+ const clipBuffer = extractAudioSegment(
+ audioBuffer,
+ clipStart,
+ clipEnd,
+ analysisContext,
+ );
+
+ const analyzedProfile = await autoLearnNoiseProfile(
+ clipBuffer,
+ analysisContext,
+ );
+
+ if (!analyzedProfile) {
+ throw new Error(
+ "No quiet section detected to learn noise from. Try a preset, or move the playhead to a noise-only segment and try again.",
+ );
+ }
+
+ const profile: NoiseProfileData = {
+ id: `profile-${audioTargetClipId}`,
+ frequencyBins: analyzedProfile.frequencyBins,
+ magnitudes: analyzedProfile.magnitudes,
+ standardDeviations: analyzedProfile.standardDeviations,
+ sampleRate: analyzedProfile.sampleRate,
+ fftSize: analyzedProfile.fftSize,
+ createdAt: Date.now(),
+ };
+
+ return {
+ profile,
+ serializedProfile: {
+ frequencyBins: Array.from(profile.frequencyBins),
+ magnitudes: Array.from(profile.magnitudes),
+ standardDeviations: profile.standardDeviations
+ ? Array.from(profile.standardDeviations)
+ : undefined,
+ sampleRate: profile.sampleRate,
+ fftSize: profile.fftSize,
+ },
+ };
+ } finally {
+ await audioContext?.close();
+ }
+ },
+ [audioTargetClipId],
+ );
+
+ const handleApplyPreset = useCallback(
+ async (presetId: NoiseReductionFocus) => {
setErrorMessage(null);
- setLearningState("idle");
- setActivePresetId(presetId);
- setConfig(nextConfig);
+ setRecommendation(null);
+ setAppliedMessage(null);
+ setLearningState("applying");
try {
- applyNoiseReductionConfig(nextConfig);
+ const presetConfig = getNoiseReductionPreset(presetId).config;
+ const nextConfig: NoiseReductionConfig = config.profile
+ ? { ...presetConfig, profile: config.profile }
+ : { ...presetConfig };
+
+ setActivePresetId(presetId);
+ setConfig(nextConfig);
+ const nextEffectId = applyNoiseReductionConfig(nextConfig);
+ let message = `${getNoiseReductionPreset(presetId).label} applied to this clip.`;
+
+ try {
+ const { serializedProfile } = await learnNoiseProfileForClip();
+ const profiledConfig: NoiseReductionConfig = {
+ ...presetConfig,
+ profile: serializedProfile,
+ };
+ setConfig(profiledConfig);
+ applyNoiseReductionConfig(profiledConfig, nextEffectId);
+ message = `${getNoiseReductionPreset(presetId).label} learned and applied to this clip.`;
+ } catch {
+ message = `${getNoiseReductionPreset(presetId).label} applied to this clip.`;
+ }
+
+ setAppliedMessage(message);
+ setLearningState("success");
+ setTimeout(() => {
+ setLearningState("idle");
+ }, 2000);
} catch (error) {
setLearningState("error");
setErrorMessage(
@@ -200,7 +374,7 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
);
}
},
- [applyNoiseReductionConfig, config.profile],
+ [applyNoiseReductionConfig, config.profile, learnNoiseProfileForClip],
);
const handleSetPreviewMode = useCallback(
@@ -209,66 +383,20 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
return;
}
- setAudioEffectPreviewBypass(clipId, effectId, mode === "original");
+ setAudioEffectPreviewBypass(audioTargetClipId, effectId, mode === "original");
+ window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"));
},
- [clipId, effectId, setAudioEffectPreviewBypass],
+ [audioTargetClipId, effectId, setAudioEffectPreviewBypass],
);
const handleLearnNoiseProfile = useCallback(async () => {
setLearningState("learning");
setErrorMessage(null);
-
- let audioContext: AudioContext | null = null;
+ setRecommendation(null);
+ setAppliedMessage(null);
try {
- const bridge = getAudioBridgeEffects();
- const project = useProjectStore.getState().project;
-
- const clip = project.timeline.tracks
- .flatMap((track) => track.clips)
- .find((c) => c.id === clipId);
-
- if (!clip) {
- throw new Error("Clip not found");
- }
-
- const mediaItem = project.mediaLibrary.items.find(
- (m) => m.id === clip.mediaId,
- );
-
- if (!mediaItem?.blob) {
- throw new Error("No audio data available for this clip");
- }
-
- audioContext = new AudioContext();
- const arrayBuffer = await mediaItem.blob.arrayBuffer();
- const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
-
- const analysisContext = new OfflineAudioContext(
- audioBuffer.numberOfChannels,
- audioBuffer.length,
- audioBuffer.sampleRate,
- );
-
- const analyzedProfile = await autoLearnNoiseProfile(
- audioBuffer,
- analysisContext,
- );
-
- const profile = analyzedProfile
- ? {
- id: `profile-${clipId}`,
- frequencyBins: analyzedProfile.frequencyBins,
- magnitudes: analyzedProfile.magnitudes,
- sampleRate: analyzedProfile.sampleRate,
- createdAt: Date.now(),
- }
- : await bridge.learnNoiseProfile(audioBuffer, `profile-${clipId}`);
- const serializedProfile: SerializedNoiseProfile = {
- frequencyBins: Array.from(profile.frequencyBins),
- magnitudes: Array.from(profile.magnitudes),
- sampleRate: profile.sampleRate,
- };
+ const { profile, serializedProfile } = await learnNoiseProfileForClip();
const suggestedPresetId = suggestNoiseReductionPreset(profile);
const suggestedConfig = {
@@ -276,14 +404,12 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
profile: serializedProfile,
};
- setConfig(suggestedConfig);
- setActivePresetId(suggestedPresetId);
- applyNoiseReductionConfig(suggestedConfig);
- setLearningState("success");
-
- setTimeout(() => {
- setLearningState("idle");
- }, 2000);
+ setRecommendation({
+ presetId: suggestedPresetId,
+ config: suggestedConfig,
+ profile: serializedProfile,
+ });
+ setLearningState("ready");
} catch (error) {
setLearningState("error");
setErrorMessage(
@@ -296,10 +422,42 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
setLearningState("idle");
setErrorMessage(null);
}, 3000);
- } finally {
- await audioContext?.close();
}
- }, [applyNoiseReductionConfig, clipId]);
+ }, [learnNoiseProfileForClip]);
+
+ const handleApplyRecommendation = useCallback(() => {
+ if (!recommendation) {
+ return;
+ }
+
+ setLearningState("applying");
+ setErrorMessage(null);
+
+ try {
+ setConfig(recommendation.config);
+ setActivePresetId(recommendation.presetId);
+ applyNoiseReductionConfig(recommendation.config);
+ setRecommendation(null);
+ setAppliedMessage(
+ `${getNoiseReductionPreset(recommendation.presetId).label} applied to this clip.`,
+ );
+ setLearningState("success");
+ setTimeout(() => {
+ setLearningState("idle");
+ }, 2000);
+ } catch (error) {
+ setLearningState("error");
+ setErrorMessage(
+ error instanceof Error
+ ? error.message
+ : "Failed to apply recommended cleanup",
+ );
+ }
+ }, [applyNoiseReductionConfig, recommendation]);
+
+ const recommendationPreset = recommendation
+ ? getNoiseReductionPreset(recommendation.presetId)
+ : null;
return (
<div
@@ -342,8 +500,8 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
{isOpen && (
<div className="p-3 space-y-3">
<p className="text-[9px] leading-relaxed text-text-muted">
- Reduce hiss, HVAC, and room tone while keeping the wanted audio in
- front.
+ Reduce white noise, wind, hum, room tone, and background music while
+ keeping speech or the wanted audio in front.
</p>
<div className="grid grid-cols-2 gap-2">
@@ -354,11 +512,12 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
<button
key={preset.id}
onClick={() => handleApplyPreset(preset.id)}
+ disabled={learningState === "learning" || learningState === "applying"}
className={`rounded-lg border px-2 py-2 text-left transition-colors ${
isActive
? "border-primary bg-primary/10 text-text-primary"
: "border-border bg-background-secondary text-text-secondary hover:border-primary/50 hover:bg-primary/5"
- }`}
+ } disabled:cursor-wait disabled:opacity-70`}
>
<div className="text-[10px] font-medium">{preset.label}</div>
<div className="mt-1 text-[9px] leading-relaxed opacity-80">
@@ -370,11 +529,48 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
</div>
<div className="rounded-lg border border-border/70 bg-background-secondary/60 px-2 py-2 text-[9px] text-text-muted">
- Current mode: <span className="text-text-primary">{activePreset.label}</span>
- <br />
- {activePreset.description}
+ <div className="flex items-center justify-between gap-2">
+ <span>
+ Current mode: <span className="text-text-primary">{activePreset.label}</span>
+ </span>
+ <span
+ className={`rounded-full px-2 py-0.5 text-[8px] font-medium ${
+ enabled
+ ? "bg-green-500/15 text-green-400"
+ : "bg-background-tertiary text-text-muted"
+ }`}
+ >
+ {enabled ? "Applied" : "Off"}
+ </span>
+ </div>
+ <div className="mt-1">{activePreset.description}</div>
+ {appliedMessage && (
+ <div className="mt-2 rounded-md border border-green-500/20 bg-green-500/10 px-2 py-1 text-green-400">
+ {appliedMessage}
+ </div>
+ )}
</div>
+ {recommendation && recommendationPreset && (
+ <div className="space-y-2 rounded-lg border border-primary/40 bg-primary/10 px-3 py-3">
+ <div className="flex items-center gap-2 text-primary">
+ <Wand2 size={12} />
+ <span className="text-[10px] font-medium">Recommendation ready</span>
+ </div>
+ <p className="text-[9px] leading-relaxed text-text-secondary">
+ Detected noise best matches {recommendationPreset.label.toLowerCase()}.
+ Apply {Math.round(recommendation.config.reduction * 100)}% cleanup at {recommendation.config.threshold.toFixed(0)} dB to save this profile on the clip.
+ </p>
+ <button
+ onClick={handleApplyRecommendation}
+ disabled={learningState === "applying"}
+ className="w-full rounded-lg bg-primary px-3 py-2 text-[10px] font-medium text-white transition-colors hover:bg-primary-hover disabled:cursor-wait disabled:opacity-70"
+ >
+ {learningState === "applying" ? "Applying..." : "Apply Recommended Cleanup"}
+ </button>
+ </div>
+ )}
+
<div className="space-y-2 rounded-lg border border-border/70 bg-background-secondary/60 px-2 py-2">
<div className="text-[9px] font-medium text-text-primary">
A/B Preview
@@ -446,10 +642,12 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
<button
onClick={handleLearnNoiseProfile}
- disabled={learningState === "learning"}
+ disabled={learningState === "learning" || learningState === "applying"}
className={`w-full py-2 rounded-lg text-[10px] font-medium transition-colors flex items-center justify-center gap-2 ${
- learningState === "learning"
+ learningState === "learning" || learningState === "applying"
? "bg-primary/20 text-primary cursor-wait"
+ : learningState === "ready"
+ ? "bg-primary/10 border border-primary/40 text-primary hover:bg-primary/20"
: learningState === "success"
? "bg-green-500/20 text-green-500"
: learningState === "error"
@@ -462,10 +660,20 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
<div className="w-3 h-3 border-2 border-primary border-t-transparent rounded-full animate-spin" />
Analyzing...
</>
+ ) : learningState === "applying" ? (
+ <>
+ <div className="w-3 h-3 border-2 border-primary border-t-transparent rounded-full animate-spin" />
+ Applying cleanup...
+ </>
+ ) : learningState === "ready" ? (
+ <>
+ <Check size={12} />
+ Recommendation Ready
+ </>
) : learningState === "success" ? (
<>
<Check size={12} />
- Recommended Preset Applied
+ Cleanup Applied
</>
) : learningState === "error" ? (
<>
@@ -486,9 +694,9 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({
</div>
)}
- {config.profile && learningState !== "error" && (
+ {config.profile && !recommendation && learningState !== "error" && (
<div className="text-[9px] text-text-muted text-center">
- Learned noise profile saved for this clip.
+ Learned noise profile is active on this clip.
<br />
Auto-tuned with {activePreset.label.toLowerCase()} and reused for export cleanup.
</div>
diff --git a/apps/web/src/components/editor/inspector/noise-reduction-presets.ts b/apps/web/src/components/editor/inspector/noise-reduction-presets.ts
index 637fb25a..ade05000 100644
--- a/apps/web/src/components/editor/inspector/noise-reduction-presets.ts
+++ b/apps/web/src/components/editor/inspector/noise-reduction-presets.ts
@@ -87,6 +87,32 @@ export const NOISE_REDUCTION_PRESETS: ReadonlyArray<NoiseReductionPreset> = [
focus: "speech",
},
},
+ {
+ id: "whiteNoise",
+ label: "White Noise",
+ description: "Aggressive broadband hiss removal for fans, air, camera preamp noise, and room tone.",
+ config: {
+ ...DEFAULT_NOISE_REDUCTION,
+ threshold: -56,
+ reduction: 0.92,
+ attack: 6,
+ release: 240,
+ focus: "whiteNoise",
+ },
+ },
+ {
+ id: "music",
+ label: "Music Bed",
+ description: "Pushes background music down while keeping speech presence forward.",
+ config: {
+ ...DEFAULT_NOISE_REDUCTION,
+ threshold: -48,
+ reduction: 0.82,
+ attack: 8,
+ release: 220,
+ focus: "music",
+ },
+ },
{
id: "heavy",
label: "Heavy Noise",
@@ -151,11 +177,16 @@ export const suggestNoiseReductionPreset = (
const spectralFlatness = clamp(mean / Math.max(peak, 1e-6), 0, 1);
const subLowEnergy = averageEnergyInRange(profile, 40, 140);
const lowMidEnergy = averageEnergyInRange(profile, 180, 500);
+ const musicFundamentalEnergy = averageEnergyInRange(profile, 180, 1200);
+ const musicPresenceEnergy = averageEnergyInRange(profile, 1200, 5000);
const lowEnergy = averageEnergyInRange(profile, 20, 180);
const voiceEnergy = averageEnergyInRange(profile, 250, 4000);
const airEnergy = averageEnergyInRange(profile, 6000, 18000);
const lowBias = lowEnergy / Math.max(voiceEnergy, 1e-6);
const airBias = airEnergy / Math.max(voiceEnergy, 1e-6);
+ const musicBias =
+ (musicFundamentalEnergy + musicPresenceEnergy) /
+ Math.max(voiceEnergy * 2, 1e-6);
const peakRatio = peak / Math.max(mean, 1e-6);
const normalizedVariability = clamp(
standardDeviation / Math.max(mean, 1e-6) / 3,
@@ -175,10 +206,24 @@ export const suggestNoiseReductionPreset = (
}
if (airBias > 1.35) {
- return spectralFlatness > 0.5 ? "heavy" : "speech";
+ return spectralFlatness > 0.45 ? "whiteNoise" : "speech";
+ }
+
+ if (spectralFlatness > 0.62 || normalizedVariability < 0.18) {
+ return "whiteNoise";
+ }
+
+ if (
+ musicBias > 0.72 &&
+ peakRatio > 2.1 &&
+ normalizedVariability > 0.22 &&
+ lowBias < 1.45 &&
+ airBias < 1.45
+ ) {
+ return "music";
}
- if (spectralFlatness > 0.65 || normalizedVariability < 0.2) {
+ if (spectralFlatness > 0.5 || normalizedVariability < 0.28) {
return "heavy";
}
@@ -216,6 +261,10 @@ export const suggestNoiseReductionConfig = (
const airBias =
averageEnergyInRange(profile, 6000, 18000) /
Math.max(averageEnergyInRange(profile, 250, 4000), 1e-6);
+ const musicBias =
+ (averageEnergyInRange(profile, 180, 1200) +
+ averageEnergyInRange(profile, 1200, 5000)) /
+ Math.max(averageEnergyInRange(profile, 250, 4000) * 2, 1e-6);
return {
...preset.config,
@@ -224,18 +273,20 @@ export const suggestNoiseReductionConfig = (
spectralFlatness * 6 +
normalizedVariability * 4 +
Math.max(0, airBias - 1) * 4 -
- Math.max(0, lowBias - 1) * 2,
- -55,
+ Math.max(0, lowBias - 1) * 2 -
+ Math.max(0, musicBias - 0.7) * 3,
+ -64,
-18,
),
reduction: clamp(
preset.config.reduction +
- spectralFlatness * 0.08 +
+ spectralFlatness * 0.1 +
normalizedVariability * 0.05 +
Math.max(0, airBias - 1) * 0.05 +
- Math.max(0, lowBias - 1) * 0.03,
+ Math.max(0, lowBias - 1) * 0.03 +
+ Math.max(0, musicBias - 0.7) * 0.04,
0.35,
- 0.9,
+ 0.97,
),
attack: clamp(
(preset.config.attack ?? DEFAULT_NOISE_REDUCTION.attack ?? 10) +
diff --git a/apps/web/src/utils/load-audio-buffer.ts b/apps/web/src/utils/load-audio-buffer.ts
new file mode 100644
index 00000000..7ef33b33
--- /dev/null
+++ b/apps/web/src/utils/load-audio-buffer.ts
@@ -0,0 +1,26 @@
+export const loadAudioBuffer = async (
+ audioContext: AudioContext | BaseAudioContext,
+ blob: Blob,
+ audioTrackIndex: number = 0,
+): Promise<AudioBuffer | null> => {
+ try {
+ const { getFFmpegFallback } = await import("@openreel/core/media");
+ const ffmpeg = getFFmpegFallback();
+ const wavBlob = await ffmpeg.extractAudioAsWav(blob, audioTrackIndex);
+ const arrayBuffer = await wavBlob.arrayBuffer();
+ return await audioContext.decodeAudioData(arrayBuffer);
+ } catch {
+ // Fall back to browser decode for the primary track when extraction is unavailable.
+ }
+
+ if (audioTrackIndex === 0) {
+ try {
+ const arrayBuffer = await blob.arrayBuffer();
+ return await audioContext.decodeAudioData(arrayBuffer);
+ } catch {
+ return null;
+ }
+ }
+
+ return null;
+};
\ No newline at end of file
diff --git a/packages/core/src/audio/audio-effect-routing.test.ts b/packages/core/src/audio/audio-effect-routing.test.ts
index 384c8158..90eb354a 100644
--- a/packages/core/src/audio/audio-effect-routing.test.ts
+++ b/packages/core/src/audio/audio-effect-routing.test.ts
@@ -57,6 +57,13 @@ describe("audio effect routing helpers", () => {
});
it("reads pan from audio effects and validates serialized noise profiles", () => {
+ const frequencyBins = Array.from({ length: 1024 }, (_, index) => index * 23.4);
+ const magnitudes = Array.from({ length: 1024 }, (_, index) => 1 - index / 2048);
+ const standardDeviations = Array.from(
+ { length: 1024 },
+ (_, index) => 0.1 - index / 20480,
+ );
+
expect(
getPanFromAudioEffects([
{
@@ -68,12 +75,25 @@ describe("audio effect routing helpers", () => {
]),
).toBe(0.35);
+ expect(
+ isSerializedNoiseProfile({
+ frequencyBins,
+ magnitudes,
+ standardDeviations,
+ sampleRate: 48000,
+ fftSize: 2048,
+ }),
+ ).toBe(true);
+ });
+
+ it("rejects malformed spectral profile variance data", () => {
expect(
isSerializedNoiseProfile({
frequencyBins: [80, 160, 320],
magnitudes: [1, 0.8, 0.6],
+ standardDeviations: [0.1, 0.08],
sampleRate: 48000,
}),
- ).toBe(true);
+ ).toBe(false);
});
});
\ No newline at end of file
diff --git a/packages/core/src/audio/audio-effect-routing.ts b/packages/core/src/audio/audio-effect-routing.ts
index 6062c307..e4606673 100644
--- a/packages/core/src/audio/audio-effect-routing.ts
+++ b/packages/core/src/audio/audio-effect-routing.ts
@@ -4,7 +4,9 @@ import type { Effect } from "../types/timeline";
export interface SerializedNoiseProfile {
readonly frequencyBins: number[];
readonly magnitudes: number[];
+ readonly standardDeviations?: number[];
readonly sampleRate: number;
+ readonly fftSize?: number;
}
const isFiniteNumberArray = (value: unknown): value is number[] =>
@@ -12,6 +14,13 @@ const isFiniteNumberArray = (value: unknown): value is number[] =>
value.length > 0 &&
value.every((entry) => typeof entry === "number" && Number.isFinite(entry));
+const isValidFftSize = (value: unknown, binCount: number): value is number =>
+ typeof value === "number" &&
+ Number.isInteger(value) &&
+ value > 0 &&
+ (value & (value - 1)) === 0 &&
+ value / 2 === binCount;
+
export const isSerializedNoiseProfile = (
value: unknown,
): value is SerializedNoiseProfile => {
@@ -25,8 +34,13 @@ export const isSerializedNoiseProfile = (
isFiniteNumberArray(profile.frequencyBins) &&
isFiniteNumberArray(profile.magnitudes) &&
profile.frequencyBins.length === profile.magnitudes.length &&
+ (profile.standardDeviations === undefined ||
+ (isFiniteNumberArray(profile.standardDeviations) &&
+ profile.standardDeviations.length === profile.magnitudes.length)) &&
typeof profile.sampleRate === "number" &&
- Number.isFinite(profile.sampleRate)
+ Number.isFinite(profile.sampleRate) &&
+ (profile.fftSize === undefined ||
+ isValidFftSize(profile.fftSize, profile.magnitudes.length))
);
};
diff --git a/packages/core/src/audio/audio-effects-engine.test.ts b/packages/core/src/audio/audio-effects-engine.test.ts
new file mode 100644
index 00000000..dbe2efb5
--- /dev/null
+++ b/packages/core/src/audio/audio-effects-engine.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+import { AudioEffectsEngine } from "./audio-effects-engine";
+
+const createAudioBuffer = (samples: Float32Array): AudioBuffer =>
+ ({
+ length: samples.length,
+ duration: samples.length / 48000,
+ sampleRate: 48000,
+ numberOfChannels: 1,
+ getChannelData: () => samples,
+ }) as unknown as AudioBuffer;
+
+describe("AudioEffectsEngine noise profiles", () => {
+ it("learns variance data needed for spectral noise reduction", async () => {
+ const samples = new Float32Array(4096);
+ for (let index = 0; index < samples.length; index += 1) {
+ samples[index] = Math.sin(index * 0.13) * 0.08 + Math.sin(index * 0.41) * 0.03;
+ }
+
+ const engine = new AudioEffectsEngine({} as AudioContext);
+ await engine.initialize({} as AudioContext);
+
+ const profile = await engine.learnNoiseProfile(createAudioBuffer(samples), "noise");
+
+ expect(profile.frequencyBins.length).toBe(profile.magnitudes.length);
+ expect(profile.standardDeviations?.length).toBe(profile.magnitudes.length);
+ expect(profile.fftSize).toBe(2048);
+ });
+});
\ No newline at end of file
diff --git a/packages/core/src/audio/audio-effects-engine.ts b/packages/core/src/audio/audio-effects-engine.ts
index f0519258..cbcabcf6 100644
--- a/packages/core/src/audio/audio-effects-engine.ts
+++ b/packages/core/src/audio/audio-effects-engine.ts
@@ -5,6 +5,10 @@ import {
isSerializedNoiseProfile,
type SerializedNoiseProfile,
} from "./audio-effect-routing";
+import {
+ SpectralNoiseReducer,
+ type NoiseProfile,
+} from "./noise-reduction";
export interface AudioEffectChainConfig {
readonly effects: Effect[];
@@ -22,7 +26,9 @@ export interface ReverbConfig {
export interface SimpleNoiseProfile {
readonly frequencyBins: Float32Array;
readonly magnitudes: Float32Array;
+ readonly standardDeviations?: Float32Array;
readonly sampleRate: number;
+ readonly fftSize?: number;
}
export interface EffectProcessingResult {
@@ -43,6 +49,7 @@ interface NoiseReductionBandSpec {
type: BiquadFilterType;
frequency: number;
q: number;
+ gain?: number;
}
interface NoiseReductionFocusProfile {
@@ -75,28 +82,57 @@ const NOISE_REDUCTION_FOCUS_PROFILES: Record<
speech: {
minimumGain: 0.48,
bandWeights: [1.15, 1.05, 0.92, 0.74, 0.58, 0.54, 0.72, 0.88, 1.02],
- postFilters: [{ type: "highpass", frequency: 65, q: 0.7 }],
+ postFilters: [
+ { type: "highpass", frequency: 65, q: 0.7 },
+ { type: "peaking", frequency: 2800, q: 0.95, gain: 1.6 },
+ ],
+ },
+ whiteNoise: {
+ minimumGain: 0.1,
+ bandWeights: [1.16, 1.12, 1.02, 0.9, 0.82, 0.94, 1.24, 1.48, 1.58],
+ postFilters: [
+ { type: "highpass", frequency: 70, q: 0.7 },
+ { type: "highshelf", frequency: 5200, q: 0.7, gain: -8.5 },
+ { type: "lowpass", frequency: 15500, q: 0.7 },
+ { type: "peaking", frequency: 2800, q: 0.9, gain: 1.2 },
+ ],
+ },
+ music: {
+ minimumGain: 0.18,
+ bandWeights: [1.34, 1.24, 1.08, 0.92, 0.66, 0.58, 0.86, 1.1, 1.22],
+ postFilters: [
+ { type: "highpass", frequency: 90, q: 0.75 },
+ { type: "lowshelf", frequency: 220, q: 0.8, gain: -5 },
+ { type: "peaking", frequency: 520, q: 1.1, gain: -3.5 },
+ { type: "highshelf", frequency: 6400, q: 0.7, gain: -4.5 },
+ { type: "peaking", frequency: 3000, q: 0.9, gain: 2 },
+ ],
},
heavy: {
- minimumGain: 0.2,
+ minimumGain: 0.16,
bandWeights: [1.28, 1.22, 1.12, 1, 0.86, 0.82, 0.96, 1.08, 1.14],
postFilters: [
{ type: "highpass", frequency: 70, q: 0.7 },
+ { type: "highshelf", frequency: 7000, q: 0.7, gain: -4 },
{ type: "lowpass", frequency: 14500, q: 0.7 },
],
},
wind: {
- minimumGain: 0.18,
+ minimumGain: 0.12,
bandWeights: [1.4, 1.34, 1.14, 0.86, 0.67, 0.62, 0.76, 0.9, 1],
- postFilters: [{ type: "highpass", frequency: 95, q: 0.8 }],
+ postFilters: [
+ { type: "highpass", frequency: 110, q: 0.8 },
+ { type: "lowshelf", frequency: 180, q: 0.8, gain: -6 },
+ ],
},
hum: {
- minimumGain: 0.24,
+ minimumGain: 0.18,
bandWeights: [1.32, 1.22, 1.06, 0.9, 0.72, 0.66, 0.8, 0.94, 1],
postFilters: [
{ type: "highpass", frequency: 70, q: 0.7 },
{ type: "notch", frequency: 60, q: 18 },
{ type: "notch", frequency: 120, q: 14 },
+ { type: "notch", frequency: 180, q: 10 },
],
},
};
@@ -153,6 +189,9 @@ const createNoiseReductionPostFiltersForContext = (
filter.type = spec.type;
filter.frequency.value = spec.frequency;
filter.Q.value = spec.q;
+ if (typeof spec.gain === "number") {
+ filter.gain.value = spec.gain;
+ }
return filter;
});
};
@@ -194,6 +233,26 @@ const calculateLowFrequencyEnergy = (
return energy / maxBin;
};
+const calculateRangeEnergy = (
+ magnitudes: Float32Array,
+ binWidth: number,
+ minFrequency: number,
+ maxFrequency: number,
+): number => {
+ const startBin = Math.max(0, Math.floor(minFrequency / binWidth));
+ const endBin = Math.min(magnitudes.length - 1, Math.ceil(maxFrequency / binWidth));
+ if (endBin < startBin) {
+ return 0;
+ }
+
+ let energy = 0;
+ for (let index = startBin; index <= endBin; index += 1) {
+ energy += magnitudes[index];
+ }
+
+ return energy / (endBin - startBin + 1);
+};
+
export const createProfileBasedNoiseReductionFilters = (
context: BaseAudioContext,
profile: SimpleNoiseProfile,
@@ -243,6 +302,12 @@ export const createProfileBasedNoiseReductionFilters = (
const bandCenters = [125, 250, 500, 1000, 2000, 4000, 8000];
const binWidth = profile.sampleRate / (magnitudes.length * 2);
const safeMean = Math.max(mean, 1e-6);
+ const peak = Math.max(...Array.from(magnitudes));
+ const spectralFlatness = Math.min(1, Math.max(0, mean / Math.max(peak, 1e-6)));
+ const airEnergy = calculateRangeEnergy(magnitudes, binWidth, 6000, 18000);
+ const voiceEnergy = calculateRangeEnergy(magnitudes, binWidth, 250, 4000);
+ const lowMidEnergy = calculateRangeEnergy(magnitudes, binWidth, 180, 1200);
+ const airBias = airEnergy / Math.max(voiceEnergy, 1e-6);
for (const centerFrequency of bandCenters) {
const binIndex = Math.round(centerFrequency / binWidth);
@@ -273,6 +338,45 @@ export const createProfileBasedNoiseReductionFilters = (
filters.push(filter);
}
+ if (focus === "whiteNoise" || spectralFlatness > 0.58 || airBias > 1.25) {
+ const airShelf = context.createBiquadFilter();
+ airShelf.type = "highshelf";
+ airShelf.frequency.value = 5200;
+ airShelf.Q.value = 0.7;
+ airShelf.gain.value = -Math.min(12, 5 + reduction * 7 + Math.max(0, airBias - 1) * 2);
+ filters.push(airShelf);
+
+ const hissPeak = context.createBiquadFilter();
+ hissPeak.type = "peaking";
+ hissPeak.frequency.value = 9000;
+ hissPeak.Q.value = 0.8;
+ hissPeak.gain.value = -Math.min(10, 4 + reduction * 6);
+ filters.push(hissPeak);
+ }
+
+ if (focus === "music" || (lowMidEnergy > safeMean * 1.35 && spectralFlatness < 0.58)) {
+ const lowMusicShelf = context.createBiquadFilter();
+ lowMusicShelf.type = "lowshelf";
+ lowMusicShelf.frequency.value = 220;
+ lowMusicShelf.Q.value = 0.8;
+ lowMusicShelf.gain.value = -Math.min(8, 3 + reduction * 5);
+ filters.push(lowMusicShelf);
+
+ const lowMidMusicCut = context.createBiquadFilter();
+ lowMidMusicCut.type = "peaking";
+ lowMidMusicCut.frequency.value = 650;
+ lowMidMusicCut.Q.value = 1.05;
+ lowMidMusicCut.gain.value = -Math.min(7, 2.5 + reduction * 4.5);
+ filters.push(lowMidMusicCut);
+
+ const speechPresence = context.createBiquadFilter();
+ speechPresence.type = "peaking";
+ speechPresence.frequency.value = 3000;
+ speechPresence.Q.value = 0.9;
+ speechPresence.gain.value = 1.5;
+ filters.push(speechPresence);
+ }
+
const lowFrequencyEnergy = calculateLowFrequencyEnergy(magnitudes, binWidth);
if (lowFrequencyEnergy > safeMean * 1.5) {
const highpass = context.createBiquadFilter();
@@ -350,9 +454,205 @@ const toSimpleNoiseProfile = (
): SimpleNoiseProfile => ({
frequencyBins: new Float32Array(profile.frequencyBins),
magnitudes: new Float32Array(profile.magnitudes),
+ standardDeviations: profile.standardDeviations
+ ? new Float32Array(profile.standardDeviations)
+ : undefined,
sampleRate: profile.sampleRate,
+ fftSize: profile.fftSize,
});
+const toSpectralNoiseProfile = (
+ profile: SimpleNoiseProfile,
+): NoiseProfile => {
+ const standardDeviations = profile.standardDeviations
+ ? new Float32Array(profile.standardDeviations)
+ : Float32Array.from(profile.magnitudes, (magnitude) => magnitude * 0.08);
+
+ return {
+ frequencyBins: new Float32Array(profile.frequencyBins),
+ magnitudes: new Float32Array(profile.magnitudes),
+ standardDeviations,
+ sampleRate: profile.sampleRate,
+ fftSize: profile.fftSize ?? profile.magnitudes.length * 2,
+ };
+};
+
+const getSpectralSmoothingForFocus = (
+ focus: NoiseReductionFocus,
+ reduction: number,
+): number => {
+ const baseSmoothing: Record<NoiseReductionFocus, number> = {
+ balanced: 0.22,
+ speech: 0.2,
+ whiteNoise: 0.08,
+ music: 0.12,
+ heavy: 0.1,
+ wind: 0.12,
+ hum: 0.16,
+ };
+
+ return Math.max(0.04, baseSmoothing[focus] - Math.max(0, reduction - 0.75) * 0.12);
+};
+
+const getBufferPeak = (buffer: AudioBuffer): number => {
+ let peak = 0;
+
+ for (let channel = 0; channel < buffer.numberOfChannels; channel += 1) {
+ const channelData = buffer.getChannelData(channel);
+ for (let index = 0; index < channelData.length; index += 1) {
+ const sample = channelData[index];
+ if (!Number.isFinite(sample)) {
+ return Number.NaN;
+ }
+ peak = Math.max(peak, Math.abs(sample));
+ }
+ }
+
+ return peak;
+};
+
+const getBufferRms = (buffer: AudioBuffer): number => {
+ let sumSquares = 0;
+ let sampleCount = 0;
+
+ for (let channel = 0; channel < buffer.numberOfChannels; channel += 1) {
+ const channelData = buffer.getChannelData(channel);
+ sampleCount += channelData.length;
+ for (let index = 0; index < channelData.length; index += 1) {
+ const sample = channelData[index];
+ if (!Number.isFinite(sample)) {
+ return Number.NaN;
+ }
+ sumSquares += sample * sample;
+ }
+ }
+
+ if (sampleCount === 0) {
+ return 0;
+ }
+
+ return Math.sqrt(sumSquares / sampleCount);
+};
+
+const isBufferUsable = (
+ candidate: AudioBuffer,
+ reference: AudioBuffer,
+ minimumRatio: number,
+): boolean => {
+ if (
+ candidate.length !== reference.length ||
+ candidate.numberOfChannels !== reference.numberOfChannels ||
+ candidate.sampleRate !== reference.sampleRate
+ ) {
+ return false;
+ }
+
+ const candidatePeak = getBufferPeak(candidate);
+ const referencePeak = getBufferPeak(reference);
+ const candidateRms = getBufferRms(candidate);
+ const referenceRms = getBufferRms(reference);
+
+ if (
+ !Number.isFinite(candidatePeak) ||
+ !Number.isFinite(referencePeak) ||
+ !Number.isFinite(candidateRms) ||
+ !Number.isFinite(referenceRms)
+ ) {
+ return false;
+ }
+
+ if (referencePeak < 1e-5 && referenceRms < 1e-5) {
+ return true;
+ }
+
+ return (
+ candidatePeak >= Math.max(1e-5, referencePeak * minimumRatio) &&
+ candidateRms >= Math.max(1e-5, referenceRms * minimumRatio)
+ );
+};
+
+const getMaximumMakeupGain = (
+ focus: NoiseReductionFocus,
+ reduction: number,
+): number => {
+ const focusMaximumGain: Record<NoiseReductionFocus, number> = {
+ balanced: 1.18,
+ speech: 1.24,
+ whiteNoise: 1.42,
+ music: 1.28,
+ heavy: 1.34,
+ wind: 1.32,
+ hum: 1.22,
+ };
+
+ return focusMaximumGain[focus] + Math.max(0, reduction - 0.7) * 0.3;
+};
+
+const applyGainToBuffer = (buffer: AudioBuffer, gain: number): AudioBuffer => {
+ if (gain <= 1.001) {
+ return buffer;
+ }
+
+ const context = new OfflineAudioContext(
+ buffer.numberOfChannels,
+ Math.max(1, buffer.length),
+ buffer.sampleRate,
+ );
+ const gainedBuffer = context.createBuffer(
+ buffer.numberOfChannels,
+ Math.max(1, buffer.length),
+ buffer.sampleRate,
+ );
+
+ for (let channel = 0; channel < buffer.numberOfChannels; channel += 1) {
+ const sourceData = buffer.getChannelData(channel);
+ const targetData = gainedBuffer.getChannelData(channel);
+
+ for (let index = 0; index < sourceData.length; index += 1) {
+ targetData[index] = Math.max(-1, Math.min(1, sourceData[index] * gain));
+ }
+ }
+
+ return gainedBuffer;
+};
+
+const restoreVoicePresence = (
+ reference: AudioBuffer,
+ candidate: AudioBuffer,
+ focus: NoiseReductionFocus,
+ reduction: number,
+): AudioBuffer => {
+ const referenceRms = getBufferRms(reference);
+ const candidateRms = getBufferRms(candidate);
+ const candidatePeak = getBufferPeak(candidate);
+
+ if (
+ !Number.isFinite(referenceRms) ||
+ !Number.isFinite(candidateRms) ||
+ !Number.isFinite(candidatePeak) ||
+ referenceRms < 1e-5 ||
+ candidateRms < 1e-5 ||
+ candidatePeak < 1e-5
+ ) {
+ return candidate;
+ }
+
+ const targetRms =
+ referenceRms * Math.max(0.82, 0.92 - Math.max(0, reduction - 0.55) * 0.22);
+ const headroomGain = 0.98 / Math.max(candidatePeak, 1e-5);
+ const desiredGain = targetRms / candidateRms;
+ const gain = Math.max(
+ 1,
+ Math.min(
+ getMaximumMakeupGain(focus, reduction),
+ headroomGain,
+ desiredGain,
+ ),
+ );
+
+ return applyGainToBuffer(candidate, gain);
+};
+
export class AudioEffectsEngine {
private audioContext: AudioContext | OfflineAudioContext | null = null;
private impulseResponses: Map<string, AudioBuffer> = new Map();
@@ -753,6 +1053,7 @@ export class AudioEffectsEngine {
// Accumulate magnitude spectrum across all frames
const magnitudes = new Float32Array(fftSize / 2);
+ const magnitudeSquares = new Float32Array(fftSize / 2);
const frameBuffer = new Float32Array(fftSize);
for (let frame = 0; frame < numFrames; frame++) {
@@ -769,12 +1070,16 @@ export class AudioEffectsEngine {
const frameMagnitude = fft.getMagnitude(real, imag);
for (let i = 0; i < magnitudes.length; i++) {
magnitudes[i] += frameMagnitude[i];
+ magnitudeSquares[i] += frameMagnitude[i] * frameMagnitude[i];
}
}
// Average the magnitudes across all frames
+ const standardDeviations = new Float32Array(fftSize / 2);
for (let i = 0; i < magnitudes.length; i++) {
magnitudes[i] /= numFrames;
+ const variance = magnitudeSquares[i] / numFrames - magnitudes[i] * magnitudes[i];
+ standardDeviations[i] = Math.sqrt(Math.max(0, variance));
}
const frequencyBins = new Float32Array(fftSize / 2);
const binWidth = buffer.sampleRate / fftSize;
@@ -785,7 +1090,9 @@ export class AudioEffectsEngine {
const profile: SimpleNoiseProfile = {
frequencyBins,
magnitudes,
+ standardDeviations,
sampleRate: buffer.sampleRate,
+ fftSize,
};
this.noiseProfiles.set(profileId, profile);
@@ -815,7 +1122,11 @@ export class AudioEffectsEngine {
{
frequencyBins: Array.from(profile.frequencyBins),
magnitudes: Array.from(profile.magnitudes),
+ standardDeviations: profile.standardDeviations
+ ? Array.from(profile.standardDeviations)
+ : undefined,
sampleRate: profile.sampleRate,
+ fftSize: profile.fftSize,
},
reduction,
focus,
@@ -827,6 +1138,7 @@ export class AudioEffectsEngine {
profileData: SerializedNoiseProfile,
reduction: number = 0.5,
focus: NoiseReductionFocus = "balanced",
+ threshold: number = -40,
): Promise<AudioBuffer> {
this.ensureInitialized();
@@ -835,14 +1147,38 @@ export class AudioEffectsEngine {
}
const profile = toSimpleNoiseProfile(profileData);
+ const spectralReducer = new SpectralNoiseReducer({
+ threshold,
+ reduction: Math.max(0, Math.min(1, reduction)),
+ smoothing: getSpectralSmoothingForFocus(focus, reduction),
+ });
+ spectralReducer.setNoiseProfile(toSpectralNoiseProfile(profile));
+
+ const spectralBuffer = await spectralReducer.processBuffer(buffer, {
+ createBuffer: (
+ numberOfChannels: number,
+ length: number,
+ sampleRate: number,
+ ) =>
+ new OfflineAudioContext(
+ numberOfChannels,
+ Math.max(1, length),
+ sampleRate,
+ ).createBuffer(numberOfChannels, Math.max(1, length), sampleRate),
+ } as BaseAudioContext);
+
+ if (!isBufferUsable(spectralBuffer, buffer, 0.025)) {
+ return buffer;
+ }
+
const offlineContext = new OfflineAudioContext(
- buffer.numberOfChannels,
- buffer.length,
- buffer.sampleRate,
+ spectralBuffer.numberOfChannels,
+ spectralBuffer.length,
+ spectralBuffer.sampleRate,
);
const source = offlineContext.createBufferSource();
- source.buffer = buffer;
+ source.buffer = spectralBuffer;
const inputGain = offlineContext.createGain();
const outputGain = offlineContext.createGain();
const filters = createProfileBasedNoiseReductionFilters(
@@ -869,7 +1205,13 @@ export class AudioEffectsEngine {
outputGain.connect(offlineContext.destination);
source.start(0);
- return offlineContext.startRendering();
+ const renderedBuffer = await offlineContext.startRendering();
+
+ if (!isBufferUsable(renderedBuffer, spectralBuffer, 0.15)) {
+ return restoreVoicePresence(buffer, spectralBuffer, focus, reduction);
+ }
+
+ return restoreVoicePresence(buffer, renderedBuffer, focus, reduction);
}
clearImpulseResponseCache(): void {
diff --git a/packages/core/src/audio/audio-engine.ts b/packages/core/src/audio/audio-engine.ts
index bce71ae5..b45d4b2f 100644
--- a/packages/core/src/audio/audio-engine.ts
+++ b/packages/core/src/audio/audio-engine.ts
@@ -16,6 +16,10 @@ import {
getPanFromAudioEffects,
splitProfileAwareNoiseReductionEffects,
} from "./audio-effect-routing";
+import {
+ resolveClipAudioEffects,
+ resolveClipVolumeAutomation,
+} from "./clip-audio-resolution";
import { scheduleVolumeAutomationOnGain } from "./clip-volume-automation";
const SEGMENTED_AUDIO_DECODE_THRESHOLD_SECONDS = 120;
@@ -301,7 +305,7 @@ export class AudioEngine {
muted: track.muted,
solo: track.solo,
clips: clips.map((clip) =>
- this.createClipRenderInfo(clip, startTime, endTime),
+ this.createClipRenderInfo(clip, startTime, endTime, timeline),
),
});
});
@@ -324,12 +328,13 @@ export class AudioEngine {
clip: Clip,
rangeStart: number,
rangeEnd: number,
+ timeline: Timeline,
): AudioClipRenderInfo {
const clipStart = Math.max(clip.startTime, rangeStart);
const clipEnd = Math.min(clip.startTime + clip.duration, rangeEnd);
const offsetInClip = clipStart - clip.startTime;
const sourceTime = clip.inPoint + offsetInClip;
- const clipAudioEffects = clip.audioEffects || [];
+ const clipAudioEffects = resolveClipAudioEffects(clip, timeline);
const pan = getPanFromAudioEffects(
clipAudioEffects.length > 0 ? clipAudioEffects : clip.effects,
);
@@ -342,7 +347,7 @@ export class AudioEngine {
timelineStartTime: clipStart,
duration: clipEnd - clipStart,
volume: clip.volume,
- volumeAutomation: clip.automation?.volume ?? [],
+ volumeAutomation: resolveClipVolumeAutomation(clip, timeline),
pan,
effects: clipAudioEffects,
fadeIn: clip.fade?.fadeIn,
@@ -529,6 +534,7 @@ export class AudioEngine {
params.profile,
params.reduction ?? 0.5,
params.focus ?? "balanced",
+ params.threshold ?? -40,
);
}
diff --git a/packages/core/src/audio/clip-audio-resolution.test.ts b/packages/core/src/audio/clip-audio-resolution.test.ts
new file mode 100644
index 00000000..1726617f
--- /dev/null
+++ b/packages/core/src/audio/clip-audio-resolution.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from "vitest";
+import type { Clip, Timeline, Track } from "../types/timeline";
+import {
+ resolveAudibleAudioTarget,
+ resolveClipAudioEffects,
+ resolveClipVolumeAutomation,
+} from "./clip-audio-resolution";
+
+const createClip = (overrides: Partial<Clip>): Clip => ({
+ id: "clip",
+ mediaId: "media-1",
+ trackId: "video-track",
+ startTime: 0,
+ duration: 10,
+ inPoint: 0,
+ outPoint: 10,
+ effects: [],
+ audioEffects: [],
+ transform: {
+ position: { x: 0, y: 0 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+ },
+ volume: 1,
+ keyframes: [],
+ ...overrides,
+});
+
+const createTrack = (overrides: Partial<Track>): Track => ({
+ id: "track",
+ type: "video",
+ name: "Track",
+ clips: [],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ ...overrides,
+});
+
+const createSeparatedAudioTimeline = (): {
+ timeline: Timeline;
+ videoClip: Clip;
+ audioClip: Clip;
+} => {
+ const noiseEffect = {
+ id: "noise-1",
+ type: "noiseReduction",
+ enabled: true,
+ params: { reduction: 0.8 },
+ };
+ const duckingPoints = [
+ { time: 0, value: 1, curve: "linear" as const },
+ { time: 1, value: 0.35, curve: "linear" as const },
+ ];
+ const videoClip = createClip({
+ id: "video-clip",
+ trackId: "video-track",
+ volume: 0,
+ audioEffects: [noiseEffect],
+ automation: { volume: duckingPoints },
+ });
+ const audioClip = createClip({
+ id: "audio-clip",
+ trackId: "audio-track",
+ volume: 1,
+ });
+ const timeline: Timeline = {
+ tracks: [
+ createTrack({ id: "video-track", type: "video", clips: [videoClip] }),
+ createTrack({ id: "audio-track", type: "audio", clips: [audioClip] }),
+ ],
+ subtitles: [],
+ duration: 10,
+ markers: [],
+ };
+
+ return { timeline, videoClip, audioClip };
+};
+
+describe("clip audio resolution", () => {
+ it("resolves noise reduction effects from a linked separated video clip", () => {
+ const { timeline, audioClip } = createSeparatedAudioTimeline();
+
+ expect(resolveClipAudioEffects(audioClip, timeline)).toEqual([
+ expect.objectContaining({ id: "noise-1" }),
+ ]);
+ });
+
+ it("resolves ducking automation from a linked separated video clip", () => {
+ const { timeline, audioClip } = createSeparatedAudioTimeline();
+
+ expect(resolveClipVolumeAutomation(audioClip, timeline)).toEqual([
+ expect.objectContaining({ value: 1 }),
+ expect.objectContaining({ value: 0.35 }),
+ ]);
+ });
+
+ it("uses the audible linked audio clip as the target for silent separated video", () => {
+ const { timeline, videoClip, audioClip } = createSeparatedAudioTimeline();
+
+ expect(resolveAudibleAudioTarget(videoClip, timeline).id).toBe(audioClip.id);
+ });
+});
\ No newline at end of file
diff --git a/packages/core/src/audio/clip-audio-resolution.ts b/packages/core/src/audio/clip-audio-resolution.ts
new file mode 100644
index 00000000..7e07a732
--- /dev/null
+++ b/packages/core/src/audio/clip-audio-resolution.ts
@@ -0,0 +1,117 @@
+import type { AutomationPoint, Clip, Effect, Timeline, Track } from "../types/timeline";
+
+type TimelineWithTracks = Pick<Timeline, "tracks">;
+
+const LINK_TOLERANCE_SECONDS = 0.01;
+
+const getClipAudioTrackIndex = (clip: Clip): number => clip.audioTrackIndex ?? 0;
+
+const isAlignedLinkedClip = (clip: Clip, candidate: Clip): boolean =>
+ candidate.id !== clip.id &&
+ candidate.mediaId === clip.mediaId &&
+ getClipAudioTrackIndex(candidate) === getClipAudioTrackIndex(clip) &&
+ Math.abs(candidate.startTime - clip.startTime) < LINK_TOLERANCE_SECONDS &&
+ Math.abs(candidate.inPoint - clip.inPoint) < LINK_TOLERANCE_SECONDS;
+
+const getTrackTypePriority = (
+ currentTrackType: Track["type"] | undefined,
+ candidateTrackType: Track["type"],
+): number => {
+ if (currentTrackType === "audio") {
+ if (candidateTrackType === "video") return 0;
+ if (candidateTrackType === "image") return 1;
+ }
+
+ if (candidateTrackType === "audio") return 0;
+ if (candidateTrackType === "video") return 1;
+ if (candidateTrackType === "image") return 2;
+
+ return 3;
+};
+
+export const findClipTrack = (
+ timeline: TimelineWithTracks,
+ clipId: string,
+): { clip: Clip; track: Track } | null => {
+ for (const track of timeline.tracks) {
+ const clip = track.clips.find((candidate) => candidate.id === clipId);
+ if (clip) {
+ return { clip, track };
+ }
+ }
+
+ return null;
+};
+
+export const getLinkedAudioClips = (
+ clip: Clip,
+ timeline: TimelineWithTracks,
+): Array<{ clip: Clip; track: Track }> => {
+ const currentTrack = timeline.tracks.find((track) => track.id === clip.trackId);
+ const linkedClips: Array<{ clip: Clip; track: Track }> = [];
+
+ for (const track of timeline.tracks) {
+ if (track.id === clip.trackId) {
+ continue;
+ }
+
+ for (const candidate of track.clips) {
+ if (isAlignedLinkedClip(clip, candidate)) {
+ linkedClips.push({ clip: candidate, track });
+ }
+ }
+ }
+
+ return linkedClips.sort(
+ (left, right) =>
+ getTrackTypePriority(currentTrack?.type, left.track.type) -
+ getTrackTypePriority(currentTrack?.type, right.track.type),
+ );
+};
+
+export const resolveClipAudioEffects = (
+ clip: Clip,
+ timeline: TimelineWithTracks,
+): Effect[] => {
+ const directEffects = clip.audioEffects ?? [];
+ if (directEffects.length > 0) {
+ return directEffects;
+ }
+
+ const linkedClip = getLinkedAudioClips(clip, timeline).find(
+ (entry) => (entry.clip.audioEffects ?? []).length > 0,
+ );
+
+ return linkedClip?.clip.audioEffects ?? [];
+};
+
+export const resolveClipVolumeAutomation = (
+ clip: Clip,
+ timeline: TimelineWithTracks,
+): AutomationPoint[] => {
+ const directAutomation = clip.automation?.volume ?? [];
+ if (directAutomation.length > 0) {
+ return directAutomation;
+ }
+
+ const linkedClip = getLinkedAudioClips(clip, timeline).find(
+ (entry) => (entry.clip.automation?.volume?.length ?? 0) > 0,
+ );
+
+ return linkedClip?.clip.automation?.volume ?? [];
+};
+
+export const resolveAudibleAudioTarget = (
+ clip: Clip,
+ timeline: TimelineWithTracks,
+): Clip => {
+ if (clip.volume > 0) {
+ return clip;
+ }
+
+ const linkedAudioClip = getLinkedAudioClips(clip, timeline).find(
+ (entry) => entry.track.type === "audio" && entry.clip.volume > 0,
+ );
+
+ return linkedAudioClip?.clip ?? clip;
+};
\ No newline at end of file
diff --git a/packages/core/src/audio/index.ts b/packages/core/src/audio/index.ts
index 10c0f823..6bc0fc7b 100644
--- a/packages/core/src/audio/index.ts
+++ b/packages/core/src/audio/index.ts
@@ -4,6 +4,8 @@ export * from "./fft";
export * from "./audio-engine";
export * from "./realtime-processor";
export * from "./audio-effects-engine";
+export * from "./audio-effect-routing";
+export * from "./clip-audio-resolution";
export * from "./noise-reduction";
export * from "./volume-automation";
export * from "./realtime-audio-graph";
diff --git a/packages/core/src/audio/noise-reduction.test.ts b/packages/core/src/audio/noise-reduction.test.ts
new file mode 100644
index 00000000..ece3bd6e
--- /dev/null
+++ b/packages/core/src/audio/noise-reduction.test.ts
@@ -0,0 +1,125 @@
+import { describe, expect, it } from "vitest";
+import { SpectralNoiseReducer, type NoiseProfile } from "./noise-reduction";
+
+type TestAudioBuffer = AudioBuffer & {
+ readonly data: Float32Array[];
+};
+
+const sampleRate = 48000;
+
+const createAudioBuffer = (samples: Float32Array): TestAudioBuffer =>
+ ({
+ data: [samples],
+ length: samples.length,
+ duration: samples.length / sampleRate,
+ sampleRate,
+ numberOfChannels: 1,
+ getChannelData: (_channel: number) => samples,
+ }) as TestAudioBuffer;
+
+const createContext = (): BaseAudioContext =>
+ ({
+ createBuffer: (numberOfChannels: number, length: number) => {
+ const channels = Array.from(
+ { length: numberOfChannels },
+ () => new Float32Array(length),
+ );
+
+ return {
+ data: channels,
+ length,
+ duration: length / sampleRate,
+ sampleRate,
+ numberOfChannels,
+ getChannelData: (channel: number) => channels[channel],
+ } as TestAudioBuffer;
+ },
+ }) as unknown as BaseAudioContext;
+
+const createSine = (
+ frequency: number,
+ amplitude: number,
+ length: number,
+): Float32Array => {
+ const samples = new Float32Array(length);
+ for (let index = 0; index < length; index += 1) {
+ samples[index] = amplitude * Math.sin((2 * Math.PI * frequency * index) / sampleRate);
+ }
+ return samples;
+};
+
+const estimateSineAmplitude = (samples: Float32Array, frequency: number): number => {
+ let sineProjection = 0;
+ let cosineProjection = 0;
+
+ for (let index = 0; index < samples.length; index += 1) {
+ const phase = (2 * Math.PI * frequency * index) / sampleRate;
+ sineProjection += samples[index] * Math.sin(phase);
+ cosineProjection += samples[index] * Math.cos(phase);
+ }
+
+ return (2 / samples.length) * Math.hypot(sineProjection, cosineProjection);
+};
+
+const createSilentProfile = (): NoiseProfile => {
+ const fftSize = 2048;
+ const frequencyBins = new Float32Array(fftSize / 2);
+ for (let index = 0; index < frequencyBins.length; index += 1) {
+ frequencyBins[index] = (index * sampleRate) / fftSize;
+ }
+
+ return {
+ frequencyBins,
+ magnitudes: new Float32Array(fftSize / 2),
+ standardDeviations: new Float32Array(fftSize / 2),
+ sampleRate,
+ fftSize,
+ };
+};
+
+describe("SpectralNoiseReducer", () => {
+ it("preserves wanted audio level when no noise profile energy is present", async () => {
+ const input = createSine(440, 0.5, 8192);
+ const reducer = new SpectralNoiseReducer({ reduction: 0, smoothing: 0 });
+ reducer.setNoiseProfile(createSilentProfile());
+
+ const output = await reducer.processBuffer(createAudioBuffer(input), createContext());
+ const outputSamples = output.getChannelData(0);
+
+ const inputAmplitude = estimateSineAmplitude(input, 440);
+ const outputAmplitude = estimateSineAmplitude(outputSamples, 440);
+
+ expect(outputAmplitude / inputAmplitude).toBeGreaterThan(0.9);
+ expect(outputAmplitude / inputAmplitude).toBeLessThan(1.1);
+ });
+
+ it("reduces profiled high-frequency noise while retaining speech-band energy", async () => {
+ const length = 8192;
+ const voice = createSine(440, 0.38, length);
+ const noise = createSine(6000, 0.18, length);
+ const mixed = new Float32Array(length);
+
+ for (let index = 0; index < length; index += 1) {
+ mixed[index] = voice[index] + noise[index];
+ }
+
+ const reducer = new SpectralNoiseReducer({
+ reduction: 0.92,
+ smoothing: 0.06,
+ threshold: -55,
+ });
+ const profile = reducer.learnNoiseProfile(createAudioBuffer(noise));
+ reducer.setNoiseProfile(profile);
+
+ const output = await reducer.processBuffer(createAudioBuffer(mixed), createContext());
+ const outputSamples = output.getChannelData(0);
+
+ const inputNoiseAmplitude = estimateSineAmplitude(mixed, 6000);
+ const outputNoiseAmplitude = estimateSineAmplitude(outputSamples, 6000);
+ const inputVoiceAmplitude = estimateSineAmplitude(mixed, 440);
+ const outputVoiceAmplitude = estimateSineAmplitude(outputSamples, 440);
+
+ expect(outputNoiseAmplitude / inputNoiseAmplitude).toBeLessThan(0.65);
+ expect(outputVoiceAmplitude / inputVoiceAmplitude).toBeGreaterThan(0.7);
+ });
+});
\ No newline at end of file
diff --git a/packages/core/src/audio/noise-reduction.ts b/packages/core/src/audio/noise-reduction.ts
index bbfa2f8e..da08c847 100644
--- a/packages/core/src/audio/noise-reduction.ts
+++ b/packages/core/src/audio/noise-reduction.ts
@@ -144,12 +144,15 @@ export class SpectralNoiseReducer {
}
private processChannel(input: Float32Array, output: Float32Array): void {
- const numFrames =
- Math.floor((input.length - this.fftSize) / this.hopSize) + 1;
+ const numFrames = Math.max(
+ 1,
+ Math.ceil(Math.max(0, input.length - this.fftSize) / this.hopSize) + 1,
+ );
output.fill(0);
// Overlap-add buffer for reconstruction
const overlapBuffer = new Float32Array(input.length);
+ const normalizationBuffer = new Float32Array(input.length);
for (let frame = 0; frame < numFrames; frame++) {
const start = frame * this.hopSize;
const frameData = this.extractFrame(input, start);
@@ -163,16 +166,19 @@ export class SpectralNoiseReducer {
// Overlap-add
for (let i = 0; i < this.fftSize; i++) {
- if (start + i < overlapBuffer.length) {
- overlapBuffer[start + i] += reconstructed[i];
+ const outputIndex = start + i;
+ if (outputIndex < overlapBuffer.length) {
+ const window = this.getWindowValue(i);
+ overlapBuffer[outputIndex] += reconstructed[i];
+ normalizationBuffer[outputIndex] += window * window;
}
}
}
- // Normalize by overlap factor and copy to output
- const overlapFactor = this.fftSize / this.hopSize;
for (let i = 0; i < output.length; i++) {
- output[i] = overlapBuffer[i] / overlapFactor;
+ const normalization = normalizationBuffer[i];
+ output[i] =
+ normalization > 1e-6 ? overlapBuffer[i] / normalization : input[i];
}
}
@@ -182,14 +188,17 @@ export class SpectralNoiseReducer {
for (let i = 0; i < this.fftSize; i++) {
const idx = start + i;
const sample = idx < input.length ? input[idx] : 0;
- const window =
- 0.5 * (1 - Math.cos((2 * Math.PI * i) / (this.fftSize - 1)));
+ const window = this.getWindowValue(i);
frame[i] = sample * window;
}
return frame;
}
+ private getWindowValue(index: number): number {
+ return 0.5 * (1 - Math.cos((2 * Math.PI * index) / (this.fftSize - 1)));
+ }
+
private computeMagnitudeSpectrum(frame: Float32Array): Float32Array {
const { real, imag } = this.fft.forward(frame);
return this.fft.getMagnitude(real, imag);
@@ -328,24 +337,111 @@ export async function autoLearnNoiseProfile(
): Promise<NoiseProfile | null> {
const segments = detectNoiseSegments(buffer, -50, 0.5);
- if (segments.length === 0) {
+ let noiseSegmentBuffer: AudioBuffer | null = null;
+
+ if (segments.length > 0) {
+ const longestSegment = segments.reduce((longest, current) => {
+ const currentDuration = current.end - current.start;
+ const longestDuration = longest.end - longest.start;
+ return currentDuration > longestDuration ? current : longest;
+ });
+ noiseSegmentBuffer = extractAudioSegment(
+ buffer,
+ longestSegment.start,
+ longestSegment.end,
+ context,
+ );
+ } else {
+ const quietest = findQuietestContiguousWindow(buffer, 0.5);
+ if (!quietest) {
+ return null;
+ }
+ if (!isLikelyNoiseOnly(buffer, quietest)) {
+ return null;
+ }
+ noiseSegmentBuffer = extractAudioSegment(
+ buffer,
+ quietest.start,
+ quietest.end,
+ context,
+ );
+ }
+
+ const reducer = new SpectralNoiseReducer();
+ return reducer.learnNoiseProfile(noiseSegmentBuffer);
+}
+
+function findQuietestContiguousWindow(
+ buffer: AudioBuffer,
+ minDuration: number,
+): { start: number; end: number } | null {
+ const channelData = buffer.getChannelData(0);
+ const sampleRate = buffer.sampleRate;
+ const windowSize = Math.floor(sampleRate * 0.05);
+ const minWindows = Math.max(1, Math.ceil(minDuration / 0.05));
+ const totalWindows = Math.floor(channelData.length / windowSize);
+
+ if (totalWindows < minWindows) {
return null;
}
- // Use the longest quiet segment
- const longestSegment = segments.reduce((longest, current) => {
- const currentDuration = current.end - current.start;
- const longestDuration = longest.end - longest.start;
- return currentDuration > longestDuration ? current : longest;
- });
- const noiseSegment = extractAudioSegment(
- buffer,
- longestSegment.start,
- longestSegment.end,
- context,
- );
+ const rmsValues: number[] = new Array(totalWindows);
+ for (let w = 0; w < totalWindows; w++) {
+ const start = w * windowSize;
+ const end = start + windowSize;
+ let sumSquares = 0;
+ for (let i = start; i < end; i++) {
+ sumSquares += channelData[i] * channelData[i];
+ }
+ rmsValues[w] = Math.sqrt(sumSquares / windowSize);
+ }
- // Learn profile
- const reducer = new SpectralNoiseReducer();
- return reducer.learnNoiseProfile(noiseSegment);
+ let bestStart = 0;
+ let bestSum = Infinity;
+ let runningSum = 0;
+ for (let i = 0; i < minWindows; i++) {
+ runningSum += rmsValues[i];
+ }
+ bestSum = runningSum;
+ for (let i = minWindows; i < totalWindows; i++) {
+ runningSum += rmsValues[i] - rmsValues[i - minWindows];
+ if (runningSum < bestSum) {
+ bestSum = runningSum;
+ bestStart = i - minWindows + 1;
+ }
+ }
+
+ return {
+ start: (bestStart * windowSize) / sampleRate,
+ end: ((bestStart + minWindows) * windowSize) / sampleRate,
+ };
+}
+
+function isLikelyNoiseOnly(
+ buffer: AudioBuffer,
+ range: { start: number; end: number },
+): boolean {
+ const channelData = buffer.getChannelData(0);
+ const sampleRate = buffer.sampleRate;
+ const startSample = Math.floor(range.start * sampleRate);
+ const endSample = Math.floor(range.end * sampleRate);
+ const totalSamples = channelData.length;
+
+ let segmentSumSquares = 0;
+ for (let i = startSample; i < endSample; i++) {
+ segmentSumSquares += channelData[i] * channelData[i];
+ }
+ const segmentRms = Math.sqrt(segmentSumSquares / (endSample - startSample));
+
+ let totalSumSquares = 0;
+ for (let i = 0; i < totalSamples; i++) {
+ totalSumSquares += channelData[i] * channelData[i];
+ }
+ const totalRms = Math.sqrt(totalSumSquares / totalSamples);
+
+ if (totalRms <= 0) {
+ return false;
+ }
+
+ return segmentRms <= totalRms * 0.4;
}
diff --git a/packages/core/src/audio/realtime-audio-graph.ts b/packages/core/src/audio/realtime-audio-graph.ts
index f5e52a5b..85727a13 100644
--- a/packages/core/src/audio/realtime-audio-graph.ts
+++ b/packages/core/src/audio/realtime-audio-graph.ts
@@ -506,6 +506,9 @@ export class RealtimeAudioGraph {
updateTrackEffects(trackId: string, effects: Effect[]): void {
const config = this.trackConfigs.get(trackId);
if (config) {
+ if (JSON.stringify(config.effects) === JSON.stringify(effects)) {
+ return;
+ }
config.effects = effects;
this.createTrack(config);
}
diff --git a/packages/core/src/types/effects.ts b/packages/core/src/types/effects.ts
index e9eab21a..c95e3dc0 100644
--- a/packages/core/src/types/effects.ts
+++ b/packages/core/src/types/effects.ts
@@ -737,11 +737,13 @@ export interface AudioEffectParams {
reduction: number; // 0 to 1
attack: number; // 0 to 100 ms
release: number; // 0 to 500 ms
- focus?: "balanced" | "speech" | "heavy" | "wind" | "hum";
+ focus?: "balanced" | "speech" | "whiteNoise" | "music" | "heavy" | "wind" | "hum";
profile?: {
frequencyBins: number[];
magnitudes: number[];
+ standardDeviations?: number[];
sampleRate: number;
+ fftSize?: number;
};
};
fadeIn: {