OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat(audio): integrate audio effects engine and volume automation
Augustus Otuc298103d39f7
diff --git a/apps/web/src/bridges/audio-bridge-effects.ts b/apps/web/src/bridges/audio-bridge-effects.tsindex 77269e98..b39cf4f3 100644--- a/apps/web/src/bridges/audio-bridge-effects.ts+++ b/apps/web/src/bridges/audio-bridge-effects.ts@@ -44,6 +44,23 @@ export interface DelayConfig {wetLevel: number;}+export interface SerializedNoiseProfile {+ frequencyBins: number[];+ magnitudes: number[];+ sampleRate: number;+}++export const NOISE_REDUCTION_FOCUS_OPTIONS = [+ "balanced",+ "speech",+ "heavy",+ "wind",+ "hum",+] as const;++export type NoiseReductionFocus =+ (typeof NOISE_REDUCTION_FOCUS_OPTIONS)[number];+/*** Noise reduction parameters*/@@ -52,6 +69,8 @@ export interface NoiseReductionConfig {reduction: number;attack?: number;release?: number;+ focus?: NoiseReductionFocus;+ profile?: SerializedNoiseProfile;}/**@@ -124,6 +143,31 @@ export const DEFAULT_NOISE_REDUCTION: NoiseReductionConfig = {reduction: 0.5,attack: 10,release: 100,+ focus: "balanced",+};++const isSerializedNoiseProfile = (+ profile: unknown,+): profile is SerializedNoiseProfile => {+ if (!profile || typeof profile !== "object") {+ return false;+ }++ const candidate = profile as Record<string, unknown>;++ return (+ Array.isArray(candidate.frequencyBins) &&+ candidate.frequencyBins.every(+ (value) => typeof value === "number" && Number.isFinite(value),+ ) &&+ Array.isArray(candidate.magnitudes) &&+ candidate.magnitudes.every(+ (value) => typeof value === "number" && Number.isFinite(value),+ ) &&+ candidate.frequencyBins.length === candidate.magnitudes.length &&+ typeof candidate.sampleRate === "number" &&+ Number.isFinite(candidate.sampleRate)+ );};/**@@ -220,11 +264,26 @@ export function validateDelay(config: Partial<DelayConfig>): DelayConfig {export function validateNoiseReduction(config: Partial<NoiseReductionConfig>,): NoiseReductionConfig {+ const focus = NOISE_REDUCTION_FOCUS_OPTIONS.includes(+ (config.focus ?? DEFAULT_NOISE_REDUCTION.focus) as NoiseReductionFocus,+ )+ ? (config.focus ?? DEFAULT_NOISE_REDUCTION.focus)+ : DEFAULT_NOISE_REDUCTION.focus;+ const profile = isSerializedNoiseProfile(config.profile)+ ? {+ frequencyBins: [...config.profile.frequencyBins],+ magnitudes: [...config.profile.magnitudes],+ sampleRate: config.profile.sampleRate,+ }+ : undefined;+return {threshold: Math.max(-80, Math.min(0, config.threshold ?? -40)),reduction: Math.max(0, Math.min(1, config.reduction ?? 0.5)),attack: Math.max(0, Math.min(100, config.attack ?? 10)),release: Math.max(0, Math.min(500, config.release ?? 100)),+ focus,+ profile,};}diff --git a/apps/web/src/bridges/index.ts b/apps/web/src/bridges/index.tsindex 96f5a21a..8e23f3f3 100644--- a/apps/web/src/bridges/index.ts+++ b/apps/web/src/bridges/index.ts@@ -87,6 +87,8 @@ export {type CompressorConfig,type ReverbConfig,type DelayConfig,+ type SerializedNoiseProfile,+ type NoiseReductionFocus,type NoiseReductionConfig,type NoiseProfileData,type AudioEffectResult,diff --git a/apps/web/src/components/editor/InspectorPanel.tsx b/apps/web/src/components/editor/InspectorPanel.tsxindex 99e5876d..7bb7a03d 100644--- a/apps/web/src/components/editor/InspectorPanel.tsx+++ b/apps/web/src/components/editor/InspectorPanel.tsx@@ -22,6 +22,7 @@ import {MaskSection,ColorGradingSection,AudioEffectsSection,+ NoiseReductionSection,TextSection,TextAnimationSection,ShapeSection,@@ -59,10 +60,10 @@ import {import {getAudioBridgeEffects,initializeAudioBridgeEffects,- DEFAULT_EQ_BANDS,DEFAULT_NOISE_REDUCTION,} from "../../bridges/audio-bridge-effects";import { toast } from "../../stores/notification-store";+import { getNoiseReductionPreset } from "./inspector/noise-reduction-presets";import {Input,LabeledSlider,@@ -403,7 +404,13 @@ export const InspectorPanel: React.FC = () => {[selectedClip],);- const { addVideoEffect, updateVideoEffect } = useProjectStore();+ const {+ addVideoEffect,+ updateVideoEffect,+ getAudioEffects,+ updateAudioEffect,+ toggleAudioEffect,+ } = useProjectStore();const handleRemoveBackground = useCallback(() => {if (!selectedClip) return;@@ -422,38 +429,59 @@ export const InspectorPanel: React.FC = () => {try {await initializeAudioBridgeEffects();const bridge = getAudioBridgeEffects();- const nrResult = bridge.applyNoiseReduction(selectedClip.id, {+ const noiseCleanupConfig = {...DEFAULT_NOISE_REDUCTION,- threshold: -35,- reduction: 0.6,- });- const speechEQBands = DEFAULT_EQ_BANDS.map((band, i) => {- let gain = 0;- if (i === 0) gain = -3;- if (i === 1) gain = 2;- if (i === 2) gain = 4;- if (i === 3) gain = 3;- if (i === 4) gain = -2;- return { ...band, gain };- });- const eqResult = bridge.applyEQ(selectedClip.id, speechEQBands);- const compResult = bridge.applyCompressor(selectedClip.id, {- threshold: -18,- ratio: 3,- attack: 0.005,- release: 0.15,- });- if (nrResult.success && eqResult.success && compResult.success) {- setAudioEnhanced(true);- setTimeout(() => setAudioEnhanced(false), 2000);+ ...getNoiseReductionPreset("speech").config,+ };++ const existingNoiseReduction = getAudioEffects(selectedClip.id).find(+ (effect) => effect.type === "noiseReduction",+ );++ if (existingNoiseReduction) {+ updateAudioEffect(+ selectedClip.id,+ existingNoiseReduction.id,+ noiseCleanupConfig as unknown as Record<string, unknown>,+ );+ toggleAudioEffect(selectedClip.id, existingNoiseReduction.id, true);+ } else {+ const result = bridge.applyNoiseReduction(+ selectedClip.id,+ noiseCleanupConfig,+ );++ if (!result.success) {+ throw new Error(result.error ?? "Failed to apply noise cleanup");+ }}++ setAudioEnhanced(true);+ setTimeout(() => setAudioEnhanced(false), 2000);+ toast.success(+ "Noise cleanup applied",+ "Fine-tune or switch presets in Background Noise Removal.",+ );+forceUpdate();} catch (error) {console.error("Failed to enhance audio:", error);+ toast.error(+ "Could not clean up audio",+ error instanceof Error+ ? error.message+ : "Noise cleanup could not be applied to this clip.",+ );} finally {setIsEnhancingAudio(false);}- }, [selectedClip, forceUpdate]);+ }, [+ selectedClip,+ forceUpdate,+ getAudioEffects,+ toggleAudioEffect,+ updateAudioEffect,+ ]);const handleAutoColor = useCallback(() => {if (!selectedClip) return;@@ -628,6 +656,14 @@ export const InspectorPanel: React.FC = () => {const showTextSection = clipType === "text";const showShapeSection = clipType === "shape";const showSVGSection = clipType === "svg";+ const selectedNoiseReductionEffect = selectedTimelineClip?.audioEffects?.find(+ (effect) => effect.type === "noiseReduction",+ );+ const noiseReductionSectionTitle = selectedNoiseReductionEffect+ ? selectedNoiseReductionEffect.enabled+ ? "Background Noise Removal (Active)"+ : "Background Noise Removal (Configured)"+ : "Background Noise Removal";const appliedEditingTemplates =selectedTimelineClip?.metadata?.appliedTemplates || [];const handleRecipeControlChange = useCallback(@@ -1454,6 +1490,16 @@ export const InspectorPanel: React.FC = () => {</Section>)}+ {showAudioEffects && (+ <Section+ title={noiseReductionSectionTitle}+ sectionId="background-noise-removal"+ defaultOpen={Boolean(selectedNoiseReductionEffect)}+ >+ <NoiseReductionSection clipId={clipId} />+ </Section>+ )}+{showAudioEffects && (<Sectiontitle="Audio Effects"@@ -1544,12 +1590,12 @@ export const InspectorPanel: React.FC = () => {{isEnhancingAudio ? (<><Loader2 size={12} className="animate-spin" />- Enhancing...+ Cleaning up...</>) : audioEnhanced ? (- "✓ Enhanced"+ "✓ Noise Reduced") : (- "Enhance Audio"+ "Quick Dialogue Cleanup")}</button>)}diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsxindex 6ea0a622..afca063f 100644--- a/apps/web/src/components/editor/Preview.tsx+++ b/apps/web/src/components/editor/Preview.tsx@@ -1243,6 +1243,7 @@ export const Preview: React.FC = () => {endTime: clipEnd,mediaOffset,volume: audioClip.volume ?? 1,+ volumeAutomation: audioClip.automation?.volume ?? [],pan: 0,effects: enabledEffects,speed: audioClip.speed ?? 1,@@ -1337,6 +1338,7 @@ export const Preview: React.FC = () => {endTime: clipEnd,mediaOffset: clip.inPoint || 0,volume: clip.volume ?? 1,+ volumeAutomation: clip.automation?.volume ?? [],pan: 0,effects: audioEffects,speed: clip.speed ?? 1,@@ -2503,6 +2505,7 @@ export const Preview: React.FC = () => {endTime: audioClip.startTime + audioClip.duration,mediaOffset: audioClip.inPoint || 0,volume: audioClip.volume ?? 1,+ volumeAutomation: audioClip.automation?.volume ?? [],pan: 0,effects: [],speed: audioClip.speed ?? 1,diff --git a/apps/web/src/components/editor/inspector/AudioDuckingSection.test.tsx b/apps/web/src/components/editor/inspector/AudioDuckingSection.test.tsxnew file mode 100644index 00000000..e1e88040--- /dev/null+++ b/apps/web/src/components/editor/inspector/AudioDuckingSection.test.tsx@@ -0,0 +1,127 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";+import type { Project } from "@openreel/core";+import { createEmptyProject } from "../../../stores/project/project-helpers";+import { useProjectStore } from "../../../stores/project-store";+import { AudioDuckingSection } from "./AudioDuckingSection";++const targetClipId = "clip-music";+const triggerTrackId = "track-dialogue";++const createProjectWithPersistedDucking = (): Project => {+ const project = createEmptyProject("Audio Ducking Persistence");++ return {+ ...project,+ timeline: {+ ...project.timeline,+ duration: 8,+ tracks: [+ {+ id: "track-music",+ type: "audio",+ name: "Music Bed",+ clips: [+ {+ id: targetClipId,+ mediaId: "media-music",+ trackId: "track-music",+ startTime: 0,+ duration: 8,+ inPoint: 0,+ outPoint: 8,+ 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,+ automation: {+ volume: [+ { time: 0, value: 1 },+ { time: 0.25, value: 0.3 },+ { time: 1.2, value: 1 },+ ],+ },+ keyframes: [],+ metadata: {+ audioDucking: {+ enabled: true,+ sourceTrackId: triggerTrackId,+ threshold: -28,+ reduction: 0.7,+ attack: 0.08,+ release: 0.4,+ holdTime: 0.2,+ },+ },+ },+ ],+ transitions: [],+ locked: false,+ hidden: false,+ muted: false,+ solo: false,+ },+ {+ id: triggerTrackId,+ type: "video",+ name: "Dialogue Track",+ clips: [+ {+ id: "clip-dialogue",+ mediaId: "media-dialogue",+ trackId: triggerTrackId,+ startTime: 0,+ duration: 5,+ inPoint: 0,+ outPoint: 5,+ 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("AudioDuckingSection", () => {+ beforeEach(() => {+ useProjectStore.setState({+ project: createProjectWithPersistedDucking(),+ });+ });++ afterEach(() => {+ cleanup();+ useProjectStore.setState({ project: createEmptyProject("Reset") });+ });++ it("rehydrates persisted ducking and shows video tracks as valid trigger sources", () => {+ render(<AudioDuckingSection clipId={targetClipId} />);++ expect(screen.getByText("Ducking Applied")).toBeInTheDocument();+ expect(screen.getByText("Ducking Enabled")).toBeInTheDocument();+ expect(screen.getByText("Dialogue Track")).toBeInTheDocument();+ expect(screen.getByText("Trigger Source (Voice Track)")).toBeInTheDocument();+ });+});\ No newline at end of filediff --git a/apps/web/src/components/editor/inspector/AudioDuckingSection.tsx b/apps/web/src/components/editor/inspector/AudioDuckingSection.tsxindex e0cfecaf..6a2012bf 100644--- a/apps/web/src/components/editor/inspector/AudioDuckingSection.tsx+++ b/apps/web/src/components/editor/inspector/AudioDuckingSection.tsx@@ -1,4 +1,4 @@-import React, { useState, useCallback, useMemo } from "react";+import React, { useCallback, useEffect, useMemo, useState } from "react";import {Volume2,VolumeX,@@ -8,26 +8,18 @@ import {ChevronRight,Check,RefreshCw,+ AlertCircle,} from "lucide-react";+import { AudioDucker, type Clip, type Project, type Track } from "@openreel/core";import { Slider } from "@openreel/ui";import { useProjectStore } from "../../../stores/project-store";-import type { Track } from "@openreel/core";+import type { AudioDuckingSettings } from "../../../stores/project";interface AudioDuckingSectionProps {clipId: string;}-interface DuckingSettings {- enabled: boolean;- sourceTrackId: string | null;- threshold: number;- reduction: number;- attack: number;- release: number;- holdTime: number;-}--const DEFAULT_SETTINGS: DuckingSettings = {+const DEFAULT_SETTINGS: AudioDuckingSettings = {enabled: false,sourceTrackId: null,threshold: -30,@@ -40,7 +32,7 @@ const DEFAULT_SETTINGS: DuckingSettings = {const PRESET_CONFIGS: {id: string;name: string;- settings: Partial<DuckingSettings>;+ settings: Partial<AudioDuckingSettings>;}[] = [{id: "subtle",@@ -70,19 +62,155 @@ const PRESET_CONFIGS: {},];+const isAudioDuckingSettings = (+ value: unknown,+): value is AudioDuckingSettings => {+ if (!value || typeof value !== "object") {+ return false;+ }++ const candidate = value as Partial<AudioDuckingSettings>;++ return (+ typeof candidate.enabled === "boolean" &&+ (typeof candidate.sourceTrackId === "string" ||+ candidate.sourceTrackId === null) &&+ typeof candidate.threshold === "number" &&+ typeof candidate.reduction === "number" &&+ typeof candidate.attack === "number" &&+ typeof candidate.release === "number" &&+ typeof candidate.holdTime === "number"+ );+};++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;+};++const getTrackLabel = (track: Track): string => {+ const prefix = track.type === "video" ? "Video" : "Audio";+ return track.name || `${prefix} ${track.id.slice(-4)}`;+};++const buildTriggerTrackBuffer = async (+ project: Project,+ backgroundClip: Clip,+ sourceTrack: Track,+): Promise<AudioBuffer> => {+ const overlappingClips = sourceTrack.clips.filter((sourceClip) => {+ const sourceEnd = sourceClip.startTime + sourceClip.duration;+ const backgroundEnd = backgroundClip.startTime + backgroundClip.duration;+ return (+ sourceClip.id !== backgroundClip.id &&+ sourceClip.startTime < backgroundEnd &&+ sourceEnd > backgroundClip.startTime+ );+ });++ if (overlappingClips.length === 0) {+ throw new Error("No overlapping trigger clips were found for this clip.");+ }++ const decodeContext = new AudioContext();++ try {+ const offlineContext = new OfflineAudioContext(+ Math.max(1, project.settings.channels),+ Math.max(1, Math.ceil(backgroundClip.duration * project.settings.sampleRate)),+ project.settings.sampleRate,+ );++ let scheduledSources = 0;++ for (const sourceClip of overlappingClips) {+ if (sourceClip.reversed) {+ continue;+ }++ const mediaItem = project.mediaLibrary.items.find(+ (item) => item.id === sourceClip.mediaId,+ );++ if (!mediaItem?.blob) {+ continue;+ }++ const overlapStart = Math.max(backgroundClip.startTime, sourceClip.startTime);+ const overlapEnd = Math.min(+ backgroundClip.startTime + backgroundClip.duration,+ sourceClip.startTime + sourceClip.duration,+ );++ if (overlapEnd <= overlapStart) {+ continue;+ }++ try {+ const arrayBuffer = await mediaItem.blob.arrayBuffer();+ const decodedBuffer = await decodeContext.decodeAudioData(arrayBuffer.slice(0));+ const source = offlineContext.createBufferSource();+ const gainNode = offlineContext.createGain();+ const playbackRate = Math.max(0.1, sourceClip.speed ?? 1);+ const timelineOffset = overlapStart - backgroundClip.startTime;+ const mediaOffset =+ sourceClip.inPoint ++ Math.max(0, overlapStart - sourceClip.startTime) * playbackRate;+ const renderDuration = overlapEnd - overlapStart;++ source.buffer = decodedBuffer;+ source.playbackRate.value = playbackRate;+ gainNode.gain.value = sourceClip.volume;++ source.connect(gainNode);+ gainNode.connect(offlineContext.destination);+ source.start(timelineOffset, mediaOffset, renderDuration * playbackRate);+ scheduledSources += 1;+ } catch {+ continue;+ }+ }++ if (scheduledSources === 0) {+ throw new Error("No decodable trigger audio was found on the selected source track.");+ }++ return offlineContext.startRendering();+ } finally {+ await decodeContext.close();+ }+};+export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({clipId,}) => {const project = useProjectStore((state) => state.project);- const [settings, setSettings] = useState<DuckingSettings>(DEFAULT_SETTINGS);+ const setClipAudioDucking = useProjectStore(+ (state) => state.setClipAudioDucking,+ );+ const clearClipAudioDucking = useProjectStore(+ (state) => state.clearClipAudioDucking,+ );+ const [settings, setSettings] = useState<AudioDuckingSettings>(DEFAULT_SETTINGS);const [showAdvanced, setShowAdvanced] = useState(false);- const [isApplied, setIsApplied] = useState(false);+ const [isApplying, setIsApplying] = useState(false);+ const [errorMessage, setErrorMessage] = useState<string | null>(null);++ const selectedClip = useMemo(() => findClipById(project, clipId), [project, clipId]);- const audioTracks = useMemo(() => {+ const availableSourceTracks = useMemo(() => {return project.timeline.tracks.filter(- (track): track is Track => track.type === "audio",+ (track): track is Track =>+ (track.type === "audio" || track.type === "video") &&+ !track.clips.every((clip) => clip.id === clipId),);- }, [project.timeline.tracks]);+ }, [clipId, project.timeline.tracks]);const currentTrack = useMemo(() => {for (const track of project.timeline.tracks) {@@ -95,43 +223,108 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({return null;}, [project.timeline.tracks, clipId]);- const availableSourceTracks = useMemo(() => {- return audioTracks.filter((track) => track.id !== currentTrack?.id);- }, [audioTracks, currentTrack]);+ const persistedSettings = useMemo(() => {+ const candidate = selectedClip?.metadata?.audioDucking;+ return isAudioDuckingSettings(candidate) ? candidate : null;+ }, [selectedClip]);++ const hasAppliedDucking = Boolean(+ persistedSettings?.enabled &&+ (selectedClip?.automation?.volume?.length ?? 0) > 0,+ );+ const showControls = settings.enabled || hasAppliedDucking;++ useEffect(() => {+ if (persistedSettings) {+ setSettings({ ...DEFAULT_SETTINGS, ...persistedSettings });+ } else {+ setSettings(DEFAULT_SETTINGS);+ }++ setErrorMessage(null);+ }, [clipId, persistedSettings]);const updateSetting = useCallback(- <K extends keyof DuckingSettings>(key: K, value: DuckingSettings[K]) => {+ <K extends keyof AudioDuckingSettings>(+ key: K,+ value: AudioDuckingSettings[K],+ ) => {setSettings((prev) => ({ ...prev, [key]: value }));- if (isApplied) {- setIsApplied(false);- }+ setErrorMessage(null);},- [isApplied],+ [],);const applyPreset = useCallback((presetId: string) => {const preset = PRESET_CONFIGS.find((p) => p.id === presetId);if (preset) {setSettings((prev) => ({ ...prev, ...preset.settings }));+ setErrorMessage(null);}}, []);- const handleApplyDucking = useCallback(() => {- if (!settings.sourceTrackId) return;+ const handleApplyDucking = useCallback(async () => {+ if (!selectedClip || !settings.sourceTrackId) {+ return;+ }++ const sourceTrack = project.timeline.tracks.find(+ (track) => track.id === settings.sourceTrackId,+ );++ if (!sourceTrack) {+ setErrorMessage("Select a valid trigger source track.");+ return;+ }- setIsApplied(true);- useProjectStore.setState((state) => ({- project: { ...state.project, modifiedAt: Date.now() },- }));- }, [settings]);+ setIsApplying(true);+ setErrorMessage(null);++ try {+ const triggerBuffer = await buildTriggerTrackBuffer(+ project,+ selectedClip,+ sourceTrack,+ );+ const ducker = new AudioDucker();+ const keyframes = ducker.generateDuckingKeyframes(+ triggerBuffer,+ settings,+ selectedClip.volume,+ );++ if (keyframes.length === 0) {+ throw new Error(+ "No speech crossed the trigger threshold. Lower the threshold or choose a louder source track.",+ );+ }++ const persisted = { ...settings, enabled: true };+ const applied = setClipAudioDucking(selectedClip.id, persisted, keyframes);++ if (!applied) {+ throw new Error("Failed to persist ducking on this clip.");+ }+ } catch (error) {+ setErrorMessage(+ error instanceof Error ? error.message : "Failed to apply ducking.",+ );+ } finally {+ setIsApplying(false);+ }+ }, [project, selectedClip, setClipAudioDucking, settings]);const handleRemoveDucking = useCallback(() => {+ const cleared = clearClipAudioDucking(clipId);++ if (!cleared) {+ setErrorMessage("Failed to remove ducking from this clip.");+ return;+ }+setSettings(DEFAULT_SETTINGS);- setIsApplied(false);- useProjectStore.setState((state) => ({- project: { ...state.project, modifiedAt: Date.now() },- }));- }, []);+ setErrorMessage(null);+ }, [clearClipAudioDucking, clipId]);return (<div className="space-y-3">@@ -151,28 +344,28 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({<div className="flex items-center gap-2"><divclassName={`w-2 h-2 rounded-full ${- settings.enabled ? "bg-green-400" : "bg-gray-500"+ showControls ? "bg-green-400" : "bg-gray-500"}`}/><span className="text-[10px] font-medium text-text-primary">- {settings.enabled ? "Ducking Enabled" : "Ducking Disabled"}+ {showControls ? "Ducking Enabled" : "Ducking Disabled"}</span></div><buttononClick={() => updateSetting("enabled", !settings.enabled)}className={`relative w-10 h-5 rounded-full transition-colors ${- settings.enabled ? "bg-primary" : "bg-background-secondary"+ showControls ? "bg-primary" : "bg-background-secondary"}`}><divclassName={`absolute top-0.5 w-4 h-4 bg-white rounded-full transition-transform ${- settings.enabled ? "translate-x-5" : "translate-x-0.5"+ showControls ? "translate-x-5" : "translate-x-0.5"}`}/></button></div>- {settings.enabled && (+ {showControls && (<><div className="space-y-2"><label className="text-[10px] font-medium text-text-secondary flex items-center gap-2">@@ -181,7 +374,9 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({</label>{availableSourceTracks.length > 0 ? (<div className="space-y-1">- {availableSourceTracks.map((track) => (+ {availableSourceTracks+ .filter((track) => track.id !== currentTrack?.id)+ .map((track) => (<buttonkey={track.id}onClick={() => updateSetting("sourceTrackId", track.id)}@@ -193,7 +388,7 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({><Volume2 size={12} className="text-text-muted" /><span className="flex-1 text-[10px] text-text-primary">- {track.name || `Audio ${track.id.slice(-4)}`}+ {getTrackLabel(track)}</span>{settings.sourceTrackId === track.id && (<Check size={12} className="text-primary" />@@ -208,7 +403,7 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({className="mx-auto mb-1 text-text-muted opacity-50"/><p className="text-[10px] text-text-muted">- Add another audio track to use as trigger+ Add another audio or video track with speech to use as trigger</p></div>)}@@ -367,13 +562,23 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({</div>)}- {!isApplied ? (+ {!hasAppliedDucking ? (<buttononClick={handleApplyDucking}- className="w-full py-2.5 bg-primary hover:bg-primary-hover rounded-lg text-[11px] font-medium text-white flex items-center justify-center gap-2 transition-colors"+ disabled={isApplying}+ className="w-full py-2.5 bg-primary hover:bg-primary-hover rounded-lg text-[11px] font-medium text-white flex items-center justify-center gap-2 transition-colors disabled:cursor-wait disabled:opacity-60">- <VolumeX size={14} />- Apply Ducking+ {isApplying ? (+ <>+ <RefreshCw size={14} className="animate-spin" />+ Analyzing...+ </>+ ) : (+ <>+ <VolumeX size={14} />+ Apply Ducking+ </>+ )}</button>) : (<div className="space-y-2">@@ -386,13 +591,18 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({<div className="grid grid-cols-2 gap-2"><buttononClick={handleApplyDucking}- className="flex items-center justify-center gap-1 py-2 bg-background-tertiary rounded-lg text-[10px] text-text-secondary hover:text-text-primary transition-colors"+ disabled={isApplying}+ className="flex items-center justify-center gap-1 py-2 bg-background-tertiary rounded-lg text-[10px] text-text-secondary hover:text-text-primary transition-colors disabled:cursor-wait disabled:opacity-60">- <RefreshCw size={10} />- Update+ <RefreshCw+ size={10}+ className={isApplying ? "animate-spin" : undefined}+ />+ {isApplying ? "Updating..." : "Update"}</button><buttononClick={handleRemoveDucking}+ disabled={isApplying}className="py-2 bg-red-500/10 border border-red-500/20 rounded-lg text-[10px] text-red-400 hover:bg-red-500/20 transition-colors">Remove@@ -405,6 +615,13 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({</>)}+ {errorMessage && (+ <div className="flex items-center gap-2 rounded-lg border border-red-500/20 bg-red-500/10 px-2 py-2 text-[9px] text-red-400">+ <AlertCircle size={12} />+ <span>{errorMessage}</span>+ </div>+ )}+<div className="pt-2 border-t border-border"><p className="text-[9px] text-text-muted text-center">Automatically reduces music volume when voice is detecteddiff --git a/apps/web/src/components/editor/inspector/NoiseReductionSection.persistence.test.tsx b/apps/web/src/components/editor/inspector/NoiseReductionSection.persistence.test.tsxnew file mode 100644index 00000000..623ae5a1--- /dev/null+++ b/apps/web/src/components/editor/inspector/NoiseReductionSection.persistence.test.tsx@@ -0,0 +1,109 @@+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 { createEmptyProject } from "../../../stores/project/project-helpers";+import { useProjectStore } from "../../../stores/project-store";+import {+ createNoiseReductionEffect,+ DEFAULT_NOISE_REDUCTION,+} from "../../../bridges/audio-bridge-effects";+import * as audioBridgeEffects from "../../../bridges/audio-bridge-effects";+import { NoiseReductionSection } from "./NoiseReductionSection";++const clipId = "clip-noise";+const trackId = "track-audio";++const createProjectWithNoiseReduction = (): Project => {+ const project = createEmptyProject("Noise Reduction Persistence");+ const noiseReductionEffect = createNoiseReductionEffect({+ ...DEFAULT_NOISE_REDUCTION,+ threshold: -36,+ reduction: 0.64,+ attack: 9,+ release: 130,+ focus: "speech",+ profile: {+ frequencyBins: [80, 250, 1000, 4000],+ magnitudes: [0.35, 0.28, 0.12, 0.08],+ sampleRate: 48000,+ },+ });++ return {+ ...project,+ 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: [noiseReductionEffect],+ 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(() => {+ vi.spyOn(audioBridgeEffects, "initializeAudioBridgeEffects").mockResolvedValue(+ audioBridgeEffects.getAudioBridgeEffects(),+ );+ useProjectStore.setState({+ project: createProjectWithNoiseReduction(),+ });+ });++ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ useProjectStore.setState({ project: createEmptyProject("Reset") });+ });++ it("rehydrates persisted noise removal after the clip is selected again", async () => {+ const firstRender = render(<NoiseReductionSection clipId={clipId} />);++ await waitFor(() => {+ expect(screen.getByRole("button", { name: "Hear Original" })).not.toBeDisabled();+ expect(screen.getByRole("button", { name: "Hear Cleaned" })).not.toBeDisabled();+ expect(screen.getByText(/Current mode:/)).toHaveTextContent("Speech Focus");+ });++ firstRender.unmount();++ render(<NoiseReductionSection clipId={clipId} />);++ await waitFor(() => {+ expect(screen.getByRole("button", { name: "Hear Original" })).not.toBeDisabled();+ expect(screen.getByText(/Current mode:/)).toHaveTextContent("Speech Focus");+ });+ });+});\ No newline at end of filediff --git a/apps/web/src/components/editor/inspector/NoiseReductionSection.test.ts b/apps/web/src/components/editor/inspector/NoiseReductionSection.test.tsnew file mode 100644index 00000000..586af204--- /dev/null+++ b/apps/web/src/components/editor/inspector/NoiseReductionSection.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from "vitest";+import { DEFAULT_NOISE_REDUCTION } from "../../../bridges/audio-bridge-effects";+import {+ suggestNoiseReductionConfig,+ suggestNoiseReductionPreset,+} from "./noise-reduction-presets";++const createProfile = (+ frequencyBins: number[],+ magnitudes: number[],+) => ({+ id: "profile-test",+ frequencyBins: new Float32Array(frequencyBins),+ magnitudes: new Float32Array(magnitudes),+ sampleRate: 48000,+ createdAt: Date.now(),+});++describe("noise reduction presets", () => {+ it("recommends heavy cleanup for broadband high-energy noise", () => {+ const preset = suggestNoiseReductionPreset(+ createProfile(+ [80, 250, 1000, 4000, 8000, 12000],+ [0.78, 0.82, 0.8, 0.79, 0.81, 0.8],+ ),+ );++ expect(preset).toBe("heavy");+ });++ it("detects low-end tonal noise as hum or HVAC", () => {+ const preset = suggestNoiseReductionPreset(+ createProfile(+ [60, 120, 250, 1000, 4000, 8000],+ [1.3, 1.1, 0.35, 0.12, 0.08, 0.05],+ ),+ );++ expect(preset).toBe("hum");+ });++ it("uses wind cleanup when low-frequency rumble dominates", () => {+ const config = suggestNoiseReductionConfig(+ createProfile(+ [40, 80, 160, 500, 1500, 4000, 8000],+ [1.1, 1, 0.82, 0.25, 0.18, 0.12, 0.08],+ ),+ );++ expect(config.focus).toBe("wind");+ expect(config.reduction).toBeGreaterThan(0.7);+ });++ it("falls back to the default denoise settings when the profile is unusable", () => {+ const suggested = suggestNoiseReductionConfig(+ createProfile(+ [80, 250, 1000],+ [Number.NaN, Number.POSITIVE_INFINITY, 0],+ ),+ );++ expect(suggested).toEqual(DEFAULT_NOISE_REDUCTION);+ });+});\ No newline at end of filediff --git a/apps/web/src/components/editor/inspector/NoiseReductionSection.tsx b/apps/web/src/components/editor/inspector/NoiseReductionSection.tsxindex fd5b9873..b8a6c262 100644--- a/apps/web/src/components/editor/inspector/NoiseReductionSection.tsx+++ b/apps/web/src/components/editor/inspector/NoiseReductionSection.tsx@@ -1,14 +1,22 @@import React, { useCallback, useEffect, useState } from "react";import { ChevronDown, Volume2, Wand2, AlertCircle, Check } from "lucide-react";+import { autoLearnNoiseProfile } from "@openreel/core";import {getAudioBridgeEffects,initializeAudioBridgeEffects,type NoiseReductionConfig,- type NoiseProfileData,+ type NoiseReductionFocus,+ type SerializedNoiseProfile,DEFAULT_NOISE_REDUCTION,} from "../../../bridges/audio-bridge-effects";import { useProjectStore } from "../../../stores/project-store";import { LabeledSlider as Slider } from "@openreel/ui";+import {+ NOISE_REDUCTION_PRESETS,+ getNoiseReductionPreset,+ suggestNoiseReductionConfig,+ suggestNoiseReductionPreset,+} from "./noise-reduction-presets";/*** NoiseReductionSection Props@@ -17,6 +25,14 @@ interface NoiseReductionSectionProps {clipId: string;}+const DEFAULT_NOISE_REDUCTION_STATE: NoiseReductionConfig = {+ threshold: DEFAULT_NOISE_REDUCTION.threshold,+ reduction: DEFAULT_NOISE_REDUCTION.reduction,+ attack: DEFAULT_NOISE_REDUCTION.attack,+ release: DEFAULT_NOISE_REDUCTION.release,+ focus: DEFAULT_NOISE_REDUCTION.focus,+};+/*** Learning state for noise profile*/@@ -32,74 +48,118 @@ type LearningState = "idle" | "learning" | "success" | "error";export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({clipId,}) => {- // Get store methods+ const defaultFocus = DEFAULT_NOISE_REDUCTION.focus ?? "balanced";+ const audioEffects = useProjectStore((state) => state.getAudioEffects(clipId));+ const setAudioEffectPreviewBypass = useProjectStore(+ (state) => state.setAudioEffectPreviewBypass,+ );const toggleAudioEffect = useProjectStore((state) => state.toggleAudioEffect);- const getAudioEffects = useProjectStore((state) => state.getAudioEffects);- // Local stateconst [enabled, setEnabled] = useState(false);const [effectId, setEffectId] = useState<string | null>(null);- const [config, setConfig] = useState<NoiseReductionConfig>({- threshold: DEFAULT_NOISE_REDUCTION.threshold,- reduction: DEFAULT_NOISE_REDUCTION.reduction,- attack: DEFAULT_NOISE_REDUCTION.attack,- release: DEFAULT_NOISE_REDUCTION.release,- });-- // Noise profile state- const [learningState, setLearningState] = useState<LearningState>("idle");- const [noiseProfile, setNoiseProfile] = useState<NoiseProfileData | null>(- null,+ const [config, setConfig] = useState<NoiseReductionConfig>(+ DEFAULT_NOISE_REDUCTION_STATE,);++ const [learningState, setLearningState] = useState<LearningState>("idle");+ const [activePresetId, setActivePresetId] =+ useState<NoiseReductionFocus>(defaultFocus);const [errorMessage, setErrorMessage] = useState<string | null>(null);- // Collapsible stateconst [isOpen, setIsOpen] = useState(true);- // Initialize bridge and load existing effects+ const activePreset = getNoiseReductionPreset(activePresetId);+ const activeEffect = audioEffects.find((effect) => effect.type === "noiseReduction");+ const previewingOriginal = activeEffect?.metadata?.previewBypass === true;+useEffect(() => {- const initBridge = async () => {- try {- await initializeAudioBridgeEffects();- } catch (error) {- console.error("Failed to initialize AudioBridgeEffects:", error);- }- };- initBridge();+ initializeAudioBridgeEffects().catch((error) => {+ console.error("Failed to initialize AudioBridgeEffects:", error);+ });+ }, []);++ useEffect(() => {+ const noiseEffect = audioEffects.find((effect) => effect.type === "noiseReduction");- // Load existing noise reduction effect from clip- const effects = getAudioEffects(clipId);- const noiseEffect = effects.find((e) => e.type === "noiseReduction");if (noiseEffect) {setEnabled(noiseEffect.enabled);setEffectId(noiseEffect.id);const params = noiseEffect.params as Partial<NoiseReductionConfig>;- setConfig((prev) => ({ ...prev, ...params }));+ setConfig({+ ...DEFAULT_NOISE_REDUCTION_STATE,+ ...params,+ });+ setActivePresetId((params.focus ?? defaultFocus) as NoiseReductionFocus);+ setLearningState("idle");+ setErrorMessage(null);+ return;}- }, [clipId, getAudioEffects]);- // Handle enable toggle- const handleToggle = useCallback(- (newEnabled: boolean) => {+ setEnabled(false);+ setEffectId(null);+ setConfig(DEFAULT_NOISE_REDUCTION_STATE);+ setActivePresetId(defaultFocus);+ setLearningState("idle");+ setErrorMessage(null);+ }, [audioEffects, clipId, defaultFocus]);++ const applyNoiseReductionConfig = useCallback(+ (nextConfig: NoiseReductionConfig) => {const bridge = getAudioBridgeEffects();+ if (effectId) {+ const updateResult = bridge.updateNoiseReduction(+ clipId,+ effectId,+ nextConfig,+ );++ if (!updateResult.success) {+ throw new Error(+ updateResult.error ?? "Failed to update noise reduction",+ );+ }++ toggleAudioEffect(clipId, effectId, true);+ setEnabled(true);+ return effectId;+ }++ const applyResult = bridge.applyNoiseReduction(clipId, nextConfig);++ if (!applyResult.success || !applyResult.effectId) {+ throw new Error(applyResult.error ?? "Failed to apply noise reduction");+ }++ setEffectId(applyResult.effectId);+ setEnabled(true);+ return applyResult.effectId;+ },+ [clipId, effectId, toggleAudioEffect],+ );++ const handleToggle = useCallback(+ (newEnabled: boolean) => {if (newEnabled && !effectId) {- // Create new noise reduction effect- const result = bridge.applyNoiseReduction(clipId, config);- if (result.success && result.effectId) {- setEffectId(result.effectId);+ try {+ applyNoiseReductionConfig(config);+ } catch (error) {+ setErrorMessage(+ error instanceof Error+ ? error.message+ : "Failed to apply noise reduction",+ );+ return;}} else if (effectId) {- // Toggle existing effecttoggleAudioEffect(clipId, effectId, newEnabled);}setEnabled(newEnabled);},- [clipId, effectId, config, toggleAudioEffect],+ [applyNoiseReductionConfig, config, effectId, toggleAudioEffect],);- // Handle config changeconst handleConfigChange = useCallback((key: keyof NoiseReductionConfig, value: number) => {const bridge = getAudioBridgeEffects();@@ -117,11 +177,49 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({[clipId, effectId, enabled],);- // Handle learn noise profile+ const handleApplyPreset = useCallback(+ (presetId: NoiseReductionFocus) => {+ const nextConfig = {+ ...getNoiseReductionPreset(presetId).config,+ profile: config.profile,+ };++ setErrorMessage(null);+ setLearningState("idle");+ setActivePresetId(presetId);+ setConfig(nextConfig);++ try {+ applyNoiseReductionConfig(nextConfig);+ } catch (error) {+ setLearningState("error");+ setErrorMessage(+ error instanceof Error+ ? error.message+ : "Failed to apply noise reduction preset",+ );+ }+ },+ [applyNoiseReductionConfig, config.profile],+ );++ const handleSetPreviewMode = useCallback(+ (mode: "original" | "cleaned") => {+ if (!effectId) {+ return;+ }++ setAudioEffectPreviewBypass(clipId, effectId, mode === "original");+ },+ [clipId, effectId, setAudioEffectPreviewBypass],+ );+const handleLearnNoiseProfile = useCallback(async () => {setLearningState("learning");setErrorMessage(null);+ let audioContext: AudioContext | null = null;+try {const bridge = getAudioBridgeEffects();const project = useProjectStore.getState().project;@@ -142,26 +240,50 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({throw new Error("No audio data available for this clip");}- const audioContext = new AudioContext();+ audioContext = new AudioContext();const arrayBuffer = await mediaItem.blob.arrayBuffer();const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);- const profile = await bridge.learnNoiseProfile(+ const analysisContext = new OfflineAudioContext(+ audioBuffer.numberOfChannels,+ audioBuffer.length,+ audioBuffer.sampleRate,+ );++ const analyzedProfile = await autoLearnNoiseProfile(audioBuffer,- `profile-${clipId}`,+ analysisContext,);- setNoiseProfile(profile);- setLearningState("success");- if (!enabled) {- handleToggle(true);- }+ 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 suggestedPresetId = suggestNoiseReductionPreset(profile);+ const suggestedConfig = {+ ...suggestNoiseReductionConfig(profile),+ profile: serializedProfile,+ };++ setConfig(suggestedConfig);+ setActivePresetId(suggestedPresetId);+ applyNoiseReductionConfig(suggestedConfig);+ setLearningState("success");setTimeout(() => {setLearningState("idle");}, 2000);-- await audioContext.close();} catch (error) {setLearningState("error");setErrorMessage(@@ -174,8 +296,10 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({setLearningState("idle");setErrorMessage(null);}, 3000);+ } finally {+ await audioContext?.close();}- }, [clipId, enabled, handleToggle]);+ }, [applyNoiseReductionConfig, clipId]);return (<div@@ -183,7 +307,6 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({enabled ? "border-border" : "border-border/50 opacity-60"}`}>- {/* Header */}<div className="flex items-center gap-2 p-2 bg-background-tertiary"><buttononClick={() => setIsOpen(!isOpen)}@@ -216,9 +339,75 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({</button></div>- {/* Content */}{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.+ </p>++ <div className="grid grid-cols-2 gap-2">+ {NOISE_REDUCTION_PRESETS.map((preset) => {+ const isActive = preset.id === activePresetId;++ return (+ <button+ key={preset.id}+ onClick={() => handleApplyPreset(preset.id)}+ 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"+ }`}+ >+ <div className="text-[10px] font-medium">{preset.label}</div>+ <div className="mt-1 text-[9px] leading-relaxed opacity-80">+ {preset.description}+ </div>+ </button>+ );+ })}+ </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>++ <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+ </div>+ <div className="grid grid-cols-2 gap-2">+ <button+ onClick={() => handleSetPreviewMode("original")}+ disabled={!effectId}+ className={`rounded-lg border px-2 py-1.5 text-[10px] transition-colors ${+ previewingOriginal+ ? "border-primary bg-primary/10 text-text-primary"+ : "border-border bg-background-secondary text-text-secondary hover:border-primary/50"+ } disabled:cursor-not-allowed disabled:opacity-50`}+ >+ Hear Original+ </button>+ <button+ onClick={() => handleSetPreviewMode("cleaned")}+ disabled={!effectId}+ className={`rounded-lg border px-2 py-1.5 text-[10px] transition-colors ${+ !previewingOriginal+ ? "border-primary bg-primary/10 text-text-primary"+ : "border-border bg-background-secondary text-text-secondary hover:border-primary/50"+ } disabled:cursor-not-allowed disabled:opacity-50`}+ >+ Hear Cleaned+ </button>+ </div>+ <p className="text-[9px] leading-relaxed text-text-muted">+ Preview only. Export still uses the cleaned audio effect chain.+ </p>+ </div>+<Sliderlabel="Threshold"value={config.threshold}@@ -237,7 +426,6 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({unit="%"/>- {/* Attack */}<Sliderlabel="Attack"value={config.attack ?? 10}@@ -247,7 +435,6 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({unit="ms"/>- {/* Release */}<Sliderlabel="Release"value={config.release ?? 100}@@ -273,39 +460,37 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({{learningState === "learning" ? (<><div className="w-3 h-3 border-2 border-primary border-t-transparent rounded-full animate-spin" />- Learning...+ Analyzing...</>) : learningState === "success" ? (<><Check size={12} />- Profile Learned+ Recommended Preset Applied</>) : learningState === "error" ? (<><AlertCircle size={12} />- Failed+ Analysis Failed</>) : (<><Wand2 size={12} />- Learn Noise Profile+ Analyze & Recommend</>)}</button>- {/* Error message */}{errorMessage && (<div className="text-[9px] text-red-500 text-center">{errorMessage}</div>)}- {/* Profile info */}- {noiseProfile && learningState !== "error" && (+ {config.profile && learningState !== "error" && (<div className="text-[9px] text-text-muted text-center">- Profile: {noiseProfile.id.substring(0, 16)}...+ Learned noise profile saved for this clip.<br />- Sample rate: {noiseProfile.sampleRate}Hz+ Auto-tuned with {activePreset.label.toLowerCase()} and reused for export cleanup.</div>)}</div>diff --git a/apps/web/src/components/editor/inspector/noise-reduction-presets.ts b/apps/web/src/components/editor/inspector/noise-reduction-presets.tsnew file mode 100644index 00000000..637fb25a--- /dev/null+++ b/apps/web/src/components/editor/inspector/noise-reduction-presets.ts@@ -0,0 +1,256 @@+import {+ DEFAULT_NOISE_REDUCTION,+ type NoiseReductionConfig,+ type NoiseReductionFocus,+ type NoiseProfileData,+} from "../../../bridges/audio-bridge-effects";++export interface NoiseReductionPreset {+ id: NoiseReductionFocus;+ label: string;+ description: string;+ config: NoiseReductionConfig;+}++const clamp = (value: number, min: number, max: number): number =>+ Math.min(max, Math.max(min, value));++const calculateMean = (values: number[]): number => {+ if (values.length === 0) {+ return 0;+ }++ return values.reduce((sum, value) => sum + value, 0) / values.length;+};++const calculateStandardDeviation = (values: number[], mean: number): number => {+ if (values.length === 0) {+ return 0;+ }++ const variance =+ values.reduce((sum, value) => sum + (value - mean) ** 2, 0) /+ values.length;++ return Math.sqrt(variance);+};++const averageEnergyInRange = (+ profile: Pick<NoiseProfileData, "frequencyBins" | "magnitudes">,+ minFrequency: number,+ maxFrequency: number,+): number => {+ const energies: number[] = [];++ for (let index = 0; index < profile.frequencyBins.length; index += 1) {+ const frequency = profile.frequencyBins[index];+ const magnitude = profile.magnitudes[index];++ if (+ Number.isFinite(frequency) &&+ Number.isFinite(magnitude) &&+ magnitude > 0 &&+ frequency >= minFrequency &&+ frequency <= maxFrequency+ ) {+ energies.push(magnitude);+ }+ }++ return calculateMean(energies);+};++export const NOISE_REDUCTION_PRESETS: ReadonlyArray<NoiseReductionPreset> = [+ {+ id: "balanced",+ label: "Balanced",+ description: "General cleanup for moderate room noise without pushing too hard.",+ config: {+ ...DEFAULT_NOISE_REDUCTION,+ threshold: -34,+ reduction: 0.56,+ attack: 10,+ release: 120,+ focus: "balanced",+ },+ },+ {+ id: "speech",+ label: "Speech Focus",+ description: "Preserve dialog presence while reducing hiss and ambient bed.",+ config: {+ ...DEFAULT_NOISE_REDUCTION,+ threshold: -36,+ reduction: 0.64,+ attack: 9,+ release: 130,+ focus: "speech",+ },+ },+ {+ id: "heavy",+ label: "Heavy Noise",+ description: "More aggressive broadband cleanup for loud air, fan, and street wash.",+ config: {+ ...DEFAULT_NOISE_REDUCTION,+ threshold: -42,+ reduction: 0.8,+ attack: 14,+ release: 190,+ focus: "heavy",+ },+ },+ {+ id: "wind",+ label: "Wind & Rumble",+ description: "Targets low-end rumble, handling noise, and outdoor wind pressure.",+ config: {+ ...DEFAULT_NOISE_REDUCTION,+ threshold: -40,+ reduction: 0.74,+ attack: 8,+ release: 210,+ focus: "wind",+ },+ },+ {+ id: "hum",+ label: "Hum & HVAC",+ description: "Focused cleanup for tonal hum, AC drone, and power-line style noise.",+ config: {+ ...DEFAULT_NOISE_REDUCTION,+ threshold: -38,+ reduction: 0.7,+ attack: 12,+ release: 170,+ focus: "hum",+ },+ },+] as const;++export const getNoiseReductionPreset = (+ presetId: NoiseReductionFocus,+): NoiseReductionPreset =>+ NOISE_REDUCTION_PRESETS.find((preset) => preset.id === presetId) ??+ NOISE_REDUCTION_PRESETS[0];++export const suggestNoiseReductionPreset = (+ profile: Pick<NoiseProfileData, "frequencyBins" | "magnitudes">,+): NoiseReductionFocus => {+ const magnitudes = Array.from(profile.magnitudes).filter(+ (value) => Number.isFinite(value) && value > 0,+ );++ if (magnitudes.length === 0) {+ return DEFAULT_NOISE_REDUCTION.focus ?? "balanced";+ }++ const mean = calculateMean(magnitudes);+ const peak = Math.max(...magnitudes);+ const standardDeviation = calculateStandardDeviation(magnitudes, mean);+ const spectralFlatness = clamp(mean / Math.max(peak, 1e-6), 0, 1);+ const subLowEnergy = averageEnergyInRange(profile, 40, 140);+ const lowMidEnergy = averageEnergyInRange(profile, 180, 500);+ 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 peakRatio = peak / Math.max(mean, 1e-6);+ const normalizedVariability = clamp(+ standardDeviation / Math.max(mean, 1e-6) / 3,+ 0,+ 1,+ );++ if (lowBias > 1.55) {+ if (+ (peakRatio > 5 && spectralFlatness < 0.35) ||+ (subLowEnergy > lowMidEnergy * 2.2 && peakRatio > 2.4)+ ) {+ return "hum";+ }++ return "wind";+ }++ if (airBias > 1.35) {+ return spectralFlatness > 0.5 ? "heavy" : "speech";+ }++ if (spectralFlatness > 0.65 || normalizedVariability < 0.2) {+ return "heavy";+ }++ if (peakRatio > 5.5 && lowBias > 0.9) {+ return "hum";+ }++ return "speech";+};++export const suggestNoiseReductionConfig = (+ profile: Pick<NoiseProfileData, "frequencyBins" | "magnitudes">,+): NoiseReductionConfig => {+ const magnitudes = Array.from(profile.magnitudes).filter(+ (value) => Number.isFinite(value) && value > 0,+ );++ if (magnitudes.length === 0) {+ return DEFAULT_NOISE_REDUCTION;+ }++ const preset = getNoiseReductionPreset(suggestNoiseReductionPreset(profile));+ const mean = calculateMean(magnitudes);+ const peak = Math.max(...magnitudes);+ const standardDeviation = calculateStandardDeviation(magnitudes, mean);+ const spectralFlatness = clamp(mean / Math.max(peak, 1e-6), 0, 1);+ const normalizedVariability = clamp(+ standardDeviation / Math.max(mean, 1e-6) / 3,+ 0,+ 1,+ );+ const lowBias =+ averageEnergyInRange(profile, 20, 180) /+ Math.max(averageEnergyInRange(profile, 250, 4000), 1e-6);+ const airBias =+ averageEnergyInRange(profile, 6000, 18000) /+ Math.max(averageEnergyInRange(profile, 250, 4000), 1e-6);++ return {+ ...preset.config,+ threshold: clamp(+ preset.config.threshold ++ spectralFlatness * 6 ++ normalizedVariability * 4 ++ Math.max(0, airBias - 1) * 4 -+ Math.max(0, lowBias - 1) * 2,+ -55,+ -18,+ ),+ reduction: clamp(+ preset.config.reduction ++ spectralFlatness * 0.08 ++ normalizedVariability * 0.05 ++ Math.max(0, airBias - 1) * 0.05 ++ Math.max(0, lowBias - 1) * 0.03,+ 0.35,+ 0.9,+ ),+ attack: clamp(+ (preset.config.attack ?? DEFAULT_NOISE_REDUCTION.attack ?? 10) ++ normalizedVariability * 12 -+ spectralFlatness * 5,+ 5,+ 35,+ ),+ release: clamp(+ (preset.config.release ?? DEFAULT_NOISE_REDUCTION.release ?? 100) ++ spectralFlatness * 40 ++ Math.max(0, lowBias - 1) * 30,+ 60,+ 260,+ ),+ focus: preset.config.focus,+ };+};\ No newline at end of filediff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.tsindex b53eb9d9..40879266 100644--- a/apps/web/src/stores/project-store.ts+++ b/apps/web/src/stores/project-store.ts@@ -6,6 +6,7 @@ import type {MediaItem,Track,Clip,+ AutomationPoint,Transition,Action,ActionResult,@@ -57,6 +58,7 @@ import { getMediaBridge, initializeMediaBridge } from "../bridges/media-bridge";import {createEmptyProject,calculateTimelineDuration,+ type AudioDuckingSettings,type EditingTemplateApplicationState,type ClipHistoryEntry,type EditingTemplateHistoryEntry,@@ -431,7 +433,18 @@ export interface ProjectState {effectId: string,enabled: boolean,) => boolean;+ setAudioEffectPreviewBypass: (+ clipId: string,+ effectId: string,+ bypassed: boolean,+ ) => boolean;getAudioEffects: (clipId: string) => Effect[];+ setClipAudioDucking: (+ clipId: string,+ settings: AudioDuckingSettings,+ points: AutomationPoint[],+ ) => boolean;+ clearClipAudioDucking: (clipId: string) => boolean;// Keyframe actionsupdateClipKeyframes: (clipId: string, keyframes: Keyframe[]) => boolean;@@ -5722,6 +5735,70 @@ export const useProjectStore = create<ProjectState>()(return false;},+ setAudioEffectPreviewBypass: (+ clipId: string,+ effectId: string,+ bypassed: boolean,+ ) => {+ const { project } = get();++ for (const track of project.timeline.tracks) {+ const clipIndex = track.clips.findIndex((c) => c.id === clipId);+ if (clipIndex !== -1) {+ const clip = track.clips[clipIndex];+ const audioEffects = clip.audioEffects || [];+ const effectIndex = audioEffects.findIndex(+ (effect) => effect.id === effectId,+ );++ if (effectIndex === -1) {+ return false;+ }++ const effect = audioEffects[effectIndex];+ const nextMetadata = { ...(effect.metadata ?? {}) } as Record<+ string,+ unknown+ >;++ if (bypassed) {+ nextMetadata.previewBypass = true;+ } else {+ delete nextMetadata.previewBypass;+ }++ const updatedEffect = {+ ...effect,+ metadata:+ Object.keys(nextMetadata).length > 0 ? nextMetadata : undefined,+ };++ const updatedAudioEffects = [...audioEffects];+ updatedAudioEffects[effectIndex] = updatedEffect;++ const updatedClip = {+ ...clip,+ audioEffects: updatedAudioEffects,+ };+ const updatedClips = [...track.clips];+ updatedClips[clipIndex] = updatedClip;+ const updatedTrack = { ...track, clips: updatedClips };+ const updatedTracks = project.timeline.tracks.map((candidate) =>+ candidate.id === track.id ? updatedTrack : candidate,+ );+ const updatedProject = {+ ...project,+ timeline: { ...project.timeline, tracks: updatedTracks },+ modifiedAt: Date.now(),+ };+ set({ project: updatedProject });+ return true;+ }+ }++ return false;+ },+/*** Get all audio effects for a clip*/@@ -5737,6 +5814,61 @@ export const useProjectStore = create<ProjectState>()(return [];},+ setClipAudioDucking: (+ clipId: string,+ settings: AudioDuckingSettings,+ points: AutomationPoint[],+ ) => {+ const { project } = get();+ const updatedProject = updateProjectClip(project, clipId, (clip) => ({+ ...clip,+ automation: {+ ...(clip.automation ?? {}),+ volume: points.map((point) => ({ ...point })),+ },+ metadata: {+ ...(clip.metadata ?? {}),+ audioDucking: { ...settings },+ },+ }));++ if (!updatedProject) {+ return false;+ }++ set({ project: updatedProject });+ return true;+ },++ clearClipAudioDucking: (clipId: string) => {+ const { project } = get();+ const updatedProject = updateProjectClip(project, clipId, (clip) => {+ const nextMetadata = { ...(clip.metadata ?? {}) } as Record<+ string,+ unknown+ >;+ delete nextMetadata.audioDucking;++ const nextAutomation = { ...(clip.automation ?? {}) };+ delete nextAutomation.volume;++ return {+ ...clip,+ automation:+ Object.keys(nextAutomation).length > 0 ? nextAutomation : undefined,+ metadata:+ Object.keys(nextMetadata).length > 0 ? nextMetadata : undefined,+ };+ });++ if (!updatedProject) {+ return false;+ }++ set({ project: updatedProject });+ return true;+ },+/*** Update keyframes for a clip* Keyframe animation supportdiff --git a/apps/web/src/stores/project/types.ts b/apps/web/src/stores/project/types.tsindex bb65d186..5ed1256f 100644--- a/apps/web/src/stores/project/types.ts+++ b/apps/web/src/stores/project/types.ts@@ -4,6 +4,7 @@ import type {MediaItem,Track,Clip,+ AutomationPoint,Transition,Action,ActionResult,@@ -80,6 +81,16 @@ export interface EditingTemplateHistoryEntrypreviousState?: EditingTemplateApplicationState;}+export interface AudioDuckingSettings {+ enabled: boolean;+ sourceTrackId: string | null;+ threshold: number;+ reduction: number;+ attack: number;+ release: number;+ holdTime: number;+}+export interface ProjectState {project: Project;photoProjects: Map<string, PhotoProject>;@@ -343,7 +354,18 @@ export interface ProjectState {effectId: string,enabled: boolean,) => boolean;+ setAudioEffectPreviewBypass: (+ clipId: string,+ effectId: string,+ bypassed: boolean,+ ) => boolean;getAudioEffects: (clipId: string) => Effect[];+ setClipAudioDucking: (+ clipId: string,+ settings: AudioDuckingSettings,+ points: AutomationPoint[],+ ) => boolean;+ clearClipAudioDucking: (clipId: string) => boolean;updateClipKeyframes: (clipId: string, keyframes: Keyframe[]) => boolean;diff --git a/packages/core/src/audio/audio-effect-routing.test.ts b/packages/core/src/audio/audio-effect-routing.test.tsnew file mode 100644index 00000000..384c8158--- /dev/null+++ b/packages/core/src/audio/audio-effect-routing.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from "vitest";+import {+ getPanFromAudioEffects,+ getPreviewAudioEffects,+ isSerializedNoiseProfile,+ splitProfileAwareNoiseReductionEffects,+} from "./audio-effect-routing";++describe("audio effect routing helpers", () => {+ it("filters preview-bypassed effects from realtime playback", () => {+ const effects = getPreviewAudioEffects([+ {+ id: "noise",+ type: "noiseReduction",+ enabled: true,+ params: {},+ metadata: { previewBypass: true },+ },+ {+ id: "eq",+ type: "eq",+ enabled: true,+ params: {},+ },+ ]);++ expect(effects.map((effect) => effect.id)).toEqual(["eq"]);+ });++ it("splits profile-aware denoise effects from realtime node effects", () => {+ const effects = splitProfileAwareNoiseReductionEffects([+ {+ id: "profile-noise",+ type: "noiseReduction",+ enabled: true,+ params: {+ reduction: 0.8,+ profile: {+ frequencyBins: [60, 120],+ magnitudes: [1.2, 0.8],+ sampleRate: 48000,+ },+ },+ },+ {+ id: "eq",+ type: "eq",+ enabled: true,+ params: {},+ },+ ]);++ expect(effects.profileAwareNoiseEffects.map((effect) => effect.id)).toEqual([+ "profile-noise",+ ]);+ expect(effects.realtimeEffects.map((effect) => effect.id)).toEqual(["eq"]);+ });++ it("reads pan from audio effects and validates serialized noise profiles", () => {+ expect(+ getPanFromAudioEffects([+ {+ id: "pan",+ type: "pan",+ enabled: true,+ params: { value: 0.35 },+ },+ ]),+ ).toBe(0.35);++ expect(+ isSerializedNoiseProfile({+ frequencyBins: [80, 160, 320],+ magnitudes: [1, 0.8, 0.6],+ sampleRate: 48000,+ }),+ ).toBe(true);+ });+});\ No newline at end of filediff --git a/packages/core/src/audio/audio-effect-routing.ts b/packages/core/src/audio/audio-effect-routing.tsnew file mode 100644index 00000000..6062c307--- /dev/null+++ b/packages/core/src/audio/audio-effect-routing.ts@@ -0,0 +1,80 @@+import type { AudioEffectParams } from "../types/effects";+import type { Effect } from "../types/timeline";++export interface SerializedNoiseProfile {+ readonly frequencyBins: number[];+ readonly magnitudes: number[];+ readonly sampleRate: number;+}++const isFiniteNumberArray = (value: unknown): value is number[] =>+ Array.isArray(value) &&+ value.length > 0 &&+ value.every((entry) => typeof entry === "number" && Number.isFinite(entry));++export const isSerializedNoiseProfile = (+ value: unknown,+): value is SerializedNoiseProfile => {+ if (!value || typeof value !== "object") {+ return false;+ }++ const profile = value as Record<string, unknown>;++ return (+ isFiniteNumberArray(profile.frequencyBins) &&+ isFiniteNumberArray(profile.magnitudes) &&+ profile.frequencyBins.length === profile.magnitudes.length &&+ typeof profile.sampleRate === "number" &&+ Number.isFinite(profile.sampleRate)+ );+};++export const getPreviewAudioEffects = (effects: readonly Effect[]): Effect[] =>+ effects.filter((effect) => effect.metadata?.previewBypass !== true);++export const getPanFromAudioEffects = (effects: readonly Effect[]): number => {+ const panEffect = effects.find(+ (effect) =>+ effect.type === "pan" &&+ typeof (effect.params as AudioEffectParams["pan"]).value === "number",+ );++ if (!panEffect) {+ return 0;+ }++ return Math.max(+ -1,+ Math.min(1, (panEffect.params as AudioEffectParams["pan"]).value),+ );+};++export const splitProfileAwareNoiseReductionEffects = (+ effects: readonly Effect[],+): {+ profileAwareNoiseEffects: Effect[];+ realtimeEffects: Effect[];+} => {+ const profileAwareNoiseEffects: Effect[] = [];+ const realtimeEffects: Effect[] = [];++ for (const effect of effects) {+ if (+ effect.type === "noiseReduction" &&+ isSerializedNoiseProfile(+ (effect.params as Partial<AudioEffectParams["noiseReduction"]>).profile,+ )+ ) {+ profileAwareNoiseEffects.push(effect);+ continue;+ }++ realtimeEffects.push(effect);+ }++ return {+ profileAwareNoiseEffects,+ realtimeEffects,+ };+};\ No newline at end of filediff --git a/packages/core/src/audio/audio-effects-engine.ts b/packages/core/src/audio/audio-effects-engine.tsindex 95d3ab64..f0519258 100644--- a/packages/core/src/audio/audio-effects-engine.ts+++ b/packages/core/src/audio/audio-effects-engine.ts@@ -1,6 +1,10 @@import type { Effect } from "../types/timeline";import type { AudioEffectParams, EQBand } from "../types/effects";import { FFT } from "./fft";+import {+ isSerializedNoiseProfile,+ type SerializedNoiseProfile,+} from "./audio-effect-routing";export interface AudioEffectChainConfig {readonly effects: Effect[];@@ -31,6 +35,324 @@ interface EffectNodePair {output: AudioNode;}+type NoiseReductionFocus = NonNullable<+ AudioEffectParams["noiseReduction"]["focus"]+>;++interface NoiseReductionBandSpec {+ type: BiquadFilterType;+ frequency: number;+ q: number;+}++interface NoiseReductionFocusProfile {+ minimumGain: number;+ bandWeights: number[];+ postFilters: Array<NoiseReductionBandSpec>;+}++const NOISE_REDUCTION_BAND_SPECS: NoiseReductionBandSpec[] = [+ { type: "lowpass", frequency: 90, q: 0.707 },+ { type: "bandpass", frequency: 160, q: 0.85 },+ { type: "bandpass", frequency: 315, q: 0.9 },+ { type: "bandpass", frequency: 630, q: 0.95 },+ { type: "bandpass", frequency: 1250, q: 1 },+ { type: "bandpass", frequency: 2500, q: 1 },+ { type: "bandpass", frequency: 5000, q: 0.95 },+ { type: "bandpass", frequency: 9000, q: 0.9 },+ { type: "highpass", frequency: 12000, q: 0.707 },+];++const NOISE_REDUCTION_FOCUS_PROFILES: Record<+ NoiseReductionFocus,+ NoiseReductionFocusProfile+> = {+ balanced: {+ minimumGain: 0.42,+ bandWeights: [1.05, 1, 0.95, 0.85, 0.72, 0.68, 0.8, 0.92, 1],+ postFilters: [{ type: "highpass", frequency: 55, q: 0.6 }],+ },+ 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 }],+ },+ heavy: {+ minimumGain: 0.2,+ 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: "lowpass", frequency: 14500, q: 0.7 },+ ],+ },+ wind: {+ minimumGain: 0.18,+ 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 }],+ },+ hum: {+ minimumGain: 0.24,+ 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 },+ ],+ },+};++export interface NoiseReductionNodeChain {+ input: AudioNode;+ output: AudioNode;+ nodes: AudioNode[];+}++const createNoiseReductionBandsForContext = (+ context: BaseAudioContext,+ params?: AudioEffectParams["noiseReduction"],+ focus: NoiseReductionFocus = "balanced",+): Array<{ filter: BiquadFilterNode; gate: GainNode }> => {+ const threshold = params?.threshold ?? -40;+ const reduction = params?.reduction ?? 0.5;+ const focusProfile = NOISE_REDUCTION_FOCUS_PROFILES[focus];+ const thresholdAggression = Math.min(+ 1,+ Math.max(0.15, (Math.abs(threshold) - 18) / 42),+ );+ const bands: Array<{ filter: BiquadFilterNode; gate: GainNode }> = [];++ for (let i = 0; i < NOISE_REDUCTION_BAND_SPECS.length; i++) {+ const bandSpec = NOISE_REDUCTION_BAND_SPECS[i];+ const filter = context.createBiquadFilter();+ filter.type = bandSpec.type;+ filter.frequency.value = bandSpec.frequency;+ filter.Q.value = bandSpec.q;++ const gate = context.createGain();+ const attenuation =+ reduction * thresholdAggression * focusProfile.bandWeights[i];+ gate.gain.value = Math.min(+ 1,+ Math.max(focusProfile.minimumGain, 1 - attenuation),+ );++ bands.push({ filter, gate });+ }++ return bands;+};++const createNoiseReductionPostFiltersForContext = (+ context: BaseAudioContext,+ focus: NoiseReductionFocus,+): BiquadFilterNode[] => {+ const focusProfile = NOISE_REDUCTION_FOCUS_PROFILES[focus];++ return focusProfile.postFilters.map((spec) => {+ const filter = context.createBiquadFilter();+ filter.type = spec.type;+ filter.frequency.value = spec.frequency;+ filter.Q.value = spec.q;+ return filter;+ });+};++const calculateNoiseStatistics = (magnitudes: Float32Array): {+ mean: number;+ stdDev: number;+} => {+ let sum = 0;+ for (let index = 0; index < magnitudes.length; index += 1) {+ sum += magnitudes[index];+ }++ const mean = sum / magnitudes.length;+ let varianceSum = 0;++ for (let index = 0; index < magnitudes.length; index += 1) {+ const diff = magnitudes[index] - mean;+ varianceSum += diff * diff;+ }++ return {+ mean,+ stdDev: Math.sqrt(varianceSum / magnitudes.length),+ };+};++const calculateLowFrequencyEnergy = (+ magnitudes: Float32Array,+ binWidth: number,+): number => {+ const maxBin = Math.min(magnitudes.length, Math.ceil(200 / binWidth));+ let energy = 0;++ for (let index = 0; index < maxBin; index += 1) {+ energy += magnitudes[index];+ }++ return energy / maxBin;+};++export const createProfileBasedNoiseReductionFilters = (+ context: BaseAudioContext,+ profile: SimpleNoiseProfile,+ reduction: number,+ focus: NoiseReductionFocus,+ includePostFilters: boolean = true,+): BiquadFilterNode[] => {+ const filters: BiquadFilterNode[] = [];+ const magnitudes = profile.magnitudes;+ const frequencyBins = profile.frequencyBins;+ const { mean, stdDev } = calculateNoiseStatistics(magnitudes);+ const peakThreshold = mean + stdDev * 2;+ const addressedBins = new Set<number>();++ for (let index = 2; index < magnitudes.length - 2; index += 1) {+ const magnitude = magnitudes[index];+ const frequency = frequencyBins[index];++ if (frequency < 60 || addressedBins.has(index)) {+ continue;+ }++ const isPeak =+ magnitude > magnitudes[index - 2] &&+ magnitude > magnitudes[index - 1] &&+ magnitude > magnitudes[index + 1] &&+ magnitude > magnitudes[index + 2] &&+ magnitude > peakThreshold;++ if (!isPeak) {+ continue;+ }++ const filter = context.createBiquadFilter();+ filter.type = "notch";+ filter.frequency.value = Math.max(20, Math.min(20000, frequency));+ const peakSharpness =+ magnitude / ((magnitudes[index - 1] + magnitudes[index + 1]) / 2);+ filter.Q.value = Math.min(30, Math.max(5, peakSharpness * 10));+ filters.push(filter);++ for (let bin = index - 2; bin <= index + 2; bin += 1) {+ addressedBins.add(bin);+ }+ }++ const bandCenters = [125, 250, 500, 1000, 2000, 4000, 8000];+ const binWidth = profile.sampleRate / (magnitudes.length * 2);+ const safeMean = Math.max(mean, 1e-6);++ for (const centerFrequency of bandCenters) {+ const binIndex = Math.round(centerFrequency / binWidth);+ if (binIndex >= magnitudes.length || addressedBins.has(binIndex)) {+ continue;+ }++ const bandStart = Math.max(0, binIndex - 5);+ const bandEnd = Math.min(magnitudes.length - 1, binIndex + 5);+ let bandAverage = 0;++ for (let index = bandStart; index <= bandEnd; index += 1) {+ bandAverage += magnitudes[index];+ }++ bandAverage /= bandEnd - bandStart + 1;++ if (bandAverage <= safeMean * 1.2) {+ continue;+ }++ const filter = context.createBiquadFilter();+ filter.type = "peaking";+ filter.frequency.value = centerFrequency;+ filter.Q.value = 1.4;+ const noiseRatio = (bandAverage - safeMean) / safeMean;+ filter.gain.value = -reduction * Math.min(12, noiseRatio * 6);+ filters.push(filter);+ }++ const lowFrequencyEnergy = calculateLowFrequencyEnergy(magnitudes, binWidth);+ if (lowFrequencyEnergy > safeMean * 1.5) {+ const highpass = context.createBiquadFilter();+ highpass.type = "highpass";+ highpass.frequency.value = 80;+ highpass.Q.value = 0.707;+ filters.push(highpass);+ }++ if (includePostFilters) {+ filters.push(...createNoiseReductionPostFiltersForContext(context, focus));+ }++ if (filters.length === 0) {+ const highpass = context.createBiquadFilter();+ highpass.type = "highpass";+ highpass.frequency.value = 60;+ highpass.Q.value = 0.5;+ filters.push(highpass);+ }++ return filters;+};++export const createNoiseReductionNodeChain = (+ context: BaseAudioContext,+ effect: Effect,+): NoiseReductionNodeChain => {+ const params = effect.params as AudioEffectParams["noiseReduction"];+ const focus = params?.focus ?? "balanced";++ const inputGain = context.createGain();+ const outputGain = context.createGain();++ const bands = createNoiseReductionBandsForContext(context, params, focus);+ const nodes: AudioNode[] = [inputGain, outputGain];+ let bandInput: AudioNode = inputGain;++ if (params?.profile && isSerializedNoiseProfile(params.profile)) {+ const profileFilters = createProfileBasedNoiseReductionFilters(+ context,+ toSimpleNoiseProfile(params.profile),+ params.reduction ?? 0.5,+ focus,+ false,+ );++ for (const filter of profileFilters) {+ nodes.push(filter);+ bandInput.connect(filter);+ bandInput = filter;+ }+ }++ for (const band of bands) {+ nodes.push(band.filter, band.gate);+ bandInput.connect(band.filter);+ band.filter.connect(band.gate);+ band.gate.connect(outputGain);+ }++ let lastNode: AudioNode = outputGain;++ for (const filter of createNoiseReductionPostFiltersForContext(context, focus)) {+ nodes.push(filter);+ lastNode.connect(filter);+ lastNode = filter;+ }++ return { input: inputGain, output: lastNode, nodes };+};++const toSimpleNoiseProfile = (+ profile: SerializedNoiseProfile,+): SimpleNoiseProfile => ({+ frequencyBins: new Float32Array(profile.frequencyBins),+ magnitudes: new Float32Array(profile.magnitudes),+ sampleRate: profile.sampleRate,+});+export class AudioEffectsEngine {private audioContext: AudioContext | OfflineAudioContext | null = null;private impulseResponses: Map<string, AudioBuffer> = new Map();@@ -402,20 +724,8 @@ export class AudioEffectsEngine {context: BaseAudioContext,effect: Effect,): EffectNodePair {- const params = effect.params as AudioEffectParams["noiseReduction"];-- const inputGain = context.createGain();- const outputGain = context.createGain();-- const bands = this.createNoiseReductionBands(context, params);-- for (const band of bands) {- inputGain.connect(band.filter);- band.filter.connect(band.gate);- band.gate.connect(outputGain);- }-- return { input: inputGain, output: outputGain };+ const chain = createNoiseReductionNodeChain(context, effect);+ return { input: chain.input, output: chain.output };}createNoiseReductionNode(@@ -426,37 +736,6 @@ export class AudioEffectsEngine {return pair.input;}- private createNoiseReductionBands(- context: BaseAudioContext,- params?: AudioEffectParams["noiseReduction"],- ): Array<{ filter: BiquadFilterNode; gate: GainNode }> {- const threshold = params?.threshold ?? -40;- const reduction = params?.reduction ?? 0.5;- const thresholdLinear = Math.pow(10, threshold / 20);-- // Define frequency bands (octave-based)- const frequencies = [63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000];- const bands: Array<{ filter: BiquadFilterNode; gate: GainNode }> = [];-- for (let i = 0; i < frequencies.length; i++) {- const filter = context.createBiquadFilter();- filter.type = "peaking";- filter.frequency.value = frequencies[i];- filter.Q.value = 1.4; // ~1 octave bandwidth-- const gate = context.createGain();- // Lower frequencies typically have more noise, apply more reduction- const frequencyFactor = 1 - (i / frequencies.length) * 0.3;- // Scale reduction by threshold sensitivity- const thresholdScale = Math.min(1, thresholdLinear * 10);- gate.gain.value = 1 - reduction * frequencyFactor * thresholdScale;-- bands.push({ filter, gate });- }-- return bands;- }-async learnNoiseProfile(buffer: AudioBuffer,profileId: string,@@ -522,6 +801,7 @@ export class AudioEffectsEngine {buffer: AudioBuffer,profileId: string,reduction: number = 0.5,+ focus: NoiseReductionFocus = "balanced",): Promise<AudioBuffer> {this.ensureInitialized();@@ -529,6 +809,32 @@ export class AudioEffectsEngine {if (!profile) {throw new Error(`Noise profile '${profileId}' not found`);}++ return this.applyNoiseReductionWithProfileData(+ buffer,+ {+ frequencyBins: Array.from(profile.frequencyBins),+ magnitudes: Array.from(profile.magnitudes),+ sampleRate: profile.sampleRate,+ },+ reduction,+ focus,+ );+ }++ async applyNoiseReductionWithProfileData(+ buffer: AudioBuffer,+ profileData: SerializedNoiseProfile,+ reduction: number = 0.5,+ focus: NoiseReductionFocus = "balanced",+ ): Promise<AudioBuffer> {+ this.ensureInitialized();++ if (!isSerializedNoiseProfile(profileData)) {+ throw new Error("Noise profile data is invalid");+ }++ const profile = toSimpleNoiseProfile(profileData);const offlineContext = new OfflineAudioContext(buffer.numberOfChannels,buffer.length,@@ -539,10 +845,11 @@ export class AudioEffectsEngine {source.buffer = buffer;const inputGain = offlineContext.createGain();const outputGain = offlineContext.createGain();- const filters = this.createProfileBasedFilters(+ const filters = createProfileBasedNoiseReductionFilters(offlineContext,profile,reduction,+ focus,);source.connect(inputGain);@@ -565,147 +872,6 @@ export class AudioEffectsEngine {return offlineContext.startRendering();}- private createProfileBasedFilters(- context: BaseAudioContext,- profile: SimpleNoiseProfile,- reduction: number,- ): BiquadFilterNode[] {- const filters: BiquadFilterNode[] = [];- const magnitudes = profile.magnitudes;- const frequencyBins = profile.frequencyBins;- const { mean, stdDev } = this.calculateNoiseStatistics(magnitudes);- const peakThreshold = mean + stdDev * 2; // Peaks are 2 std devs above mean-- // Track which frequency regions have been addressed- const addressedBins = new Set<number>();-- // Pass 1: Identify and filter tonal noise peaks (narrow-band noise like hum or buzz)- // Tonal noise has narrow frequency bandwidth, so we use notch filters for surgical removal- for (let i = 2; i < magnitudes.length - 2; i++) {- const mag = magnitudes[i];- const freq = frequencyBins[i];-- // Skip very low frequencies (handled separately) and already addressed bins- if (freq < 60 || addressedBins.has(i)) continue;-- // Detect local peaks using 5-point comparison for robustness against noise- const isPeak =- mag > magnitudes[i - 2] &&- mag > magnitudes[i - 1] &&- mag > magnitudes[i + 1] &&- mag > magnitudes[i + 2] &&- mag > peakThreshold;-- if (isPeak) {- const filter = context.createBiquadFilter();- filter.type = "notch"; // Narrow-band attenuation- filter.frequency.value = Math.max(20, Math.min(20000, freq));- // Peak sharpness determines Q (quality factor): sharper peaks need narrower filters- const peakSharpness =- mag / ((magnitudes[i - 1] + magnitudes[i + 1]) / 2);- filter.Q.value = Math.min(30, Math.max(5, peakSharpness * 10));-- filters.push(filter);-- // Mark surrounding bins as addressed to avoid overlapping filters- for (let j = i - 2; j <= i + 2; j++) {- addressedBins.add(j);- }- }- }-- // Pass 2: Add broadband noise reduction using parametric EQ- // Broadband noise (like air conditioning) is spread across frequencies; use gentle EQ reduction- // Divide spectrum into musical octave-based bands for natural-sounding processing- const bandCenters = [125, 250, 500, 1000, 2000, 4000, 8000];- const binWidth = profile.sampleRate / (magnitudes.length * 2);-- for (const centerFreq of bandCenters) {- const binIndex = Math.round(centerFreq / binWidth);- if (binIndex >= magnitudes.length || addressedBins.has(binIndex))- continue;-- // Calculate local average energy for this frequency band- const bandStart = Math.max(0, binIndex - 5);- const bandEnd = Math.min(magnitudes.length - 1, binIndex + 5);- let bandAvg = 0;- for (let i = bandStart; i <= bandEnd; i++) {- bandAvg += magnitudes[i];- }- bandAvg /= bandEnd - bandStart + 1;-- // Only reduce bands with elevated noise (>20% above mean)- if (bandAvg > mean * 1.2) {- const filter = context.createBiquadFilter();- filter.type = "peaking"; // Gentle reduction vs surgical notch- filter.frequency.value = centerFreq;- filter.Q.value = 1.4; // ~1 octave bandwidth for natural sound- // Gain reduction proportional to noise excess above baseline- const noiseRatio = (bandAvg - mean) / mean;- const gainReduction = -reduction * Math.min(12, noiseRatio * 6);- filter.gain.value = gainReduction;-- filters.push(filter);- }- }-- // Pass 3: Add high-pass filter for low frequency rumble (wind noise, vibration, etc.)- // Low frequency energy concentrated <200Hz is typically noise, not signal- const lowFreqEnergy = this.calculateLowFrequencyEnergy(- magnitudes,- binWidth,- );- if (lowFreqEnergy > mean * 1.5) {- const highpass = context.createBiquadFilter();- highpass.type = "highpass";- highpass.frequency.value = 80;- highpass.Q.value = 0.707; // Butterworth: maximally flat response- filters.push(highpass);- }- // Fallback: always add minimal high-pass to remove DC/sub-bass artifacts- if (filters.length === 0) {- const highpass = context.createBiquadFilter();- highpass.type = "highpass";- highpass.frequency.value = 60;- highpass.Q.value = 0.5;- filters.push(highpass);- }-- return filters;- }-- private calculateNoiseStatistics(magnitudes: Float32Array): {- mean: number;- stdDev: number;- } {- let sum = 0;- for (let i = 0; i < magnitudes.length; i++) {- sum += magnitudes[i];- }- const mean = sum / magnitudes.length;-- let varianceSum = 0;- for (let i = 0; i < magnitudes.length; i++) {- const diff = magnitudes[i] - mean;- varianceSum += diff * diff;- }- const stdDev = Math.sqrt(varianceSum / magnitudes.length);-- return { mean, stdDev };- }-- private calculateLowFrequencyEnergy(- magnitudes: Float32Array,- binWidth: number,- ): number {- const maxBin = Math.min(magnitudes.length, Math.ceil(200 / binWidth));- let energy = 0;- for (let i = 0; i < maxBin; i++) {- energy += magnitudes[i];- }- return energy / maxBin;- }-clearImpulseResponseCache(): void {this.impulseResponses.clear();}diff --git a/packages/core/src/audio/audio-engine.ts b/packages/core/src/audio/audio-engine.tsindex 446a01b7..bce71ae5 100644--- a/packages/core/src/audio/audio-engine.ts+++ b/packages/core/src/audio/audio-engine.ts@@ -1,4 +1,5 @@import type { Timeline, Track, Clip, Effect } from "../types/timeline";+import type { AudioEffectParams } from "../types/effects";import type { MediaItem, Project } from "../types/project";import type {AudioEngineConfig,@@ -10,6 +11,12 @@ import type {TimeRange,} from "./types";import { DEFAULT_AUDIO_CONFIG } from "./types";+import { AudioEffectsEngine } from "./audio-effects-engine";+import {+ getPanFromAudioEffects,+ splitProfileAwareNoiseReductionEffects,+} from "./audio-effect-routing";+import { scheduleVolumeAutomationOnGain } from "./clip-volume-automation";const SEGMENTED_AUDIO_DECODE_THRESHOLD_SECONDS = 120;@@ -110,6 +117,7 @@ export class AudioEngine {private trackNodes: Map<string, AudioTrackNodes> = new Map();private mediaBuffers: Map<string, AudioBuffer> = new Map();private segmentedAudioDecoders: Map<string, SegmentedAudioDecoder> = new Map();+ private effectsEngine: AudioEffectsEngine | null = null;/*** Creates a new AudioEngine instance.@@ -135,6 +143,8 @@ export class AudioEngine {this.masterGain = this.audioContext.createGain();this.masterGain.connect(this.audioContext.destination);+ this.effectsEngine = new AudioEffectsEngine();+ await this.effectsEngine.initialize();this.initialized = true;} catch (error) {@@ -319,21 +329,22 @@ export class AudioEngine {const clipEnd = Math.min(clip.startTime + clip.duration, rangeEnd);const offsetInClip = clipStart - clip.startTime;const sourceTime = clip.inPoint + offsetInClip;- const panEffect = clip.effects.find((e) => e.type === "pan");- const pan =- panEffect && typeof panEffect.params.value === "number"- ? panEffect.params.value- : 0;+ const clipAudioEffects = clip.audioEffects || [];+ const pan = getPanFromAudioEffects(+ clipAudioEffects.length > 0 ? clipAudioEffects : clip.effects,+ );return {clipId: clip.id,mediaId: clip.mediaId,sourceTime,+ clipOffset: offsetInClip,timelineStartTime: clipStart,duration: clipEnd - clipStart,volume: clip.volume,+ volumeAutomation: clip.automation?.volume ?? [],pan,- effects: clip.effects,+ effects: clipAudioEffects,fadeIn: clip.fade?.fadeIn,fadeOut: clip.fade?.fadeOut,speed: (clip as any).speed || 1,@@ -425,27 +436,38 @@ export class AudioEngine {return;}- const { gainNode } = this.createClipOutputNodes(context, clipInfo);+ const { volumeGainNode, fadeGainNode } = this.createClipOutputNodes(+ context,+ clipInfo,+ );const source = context.createBufferSource();- source.buffer = audioBuffer;const speed = clipInfo.speed || 1;const reversed = clipInfo.reversed || false;+ const processedClip = await this.processClipBuffer(audioBuffer, clipInfo);++ source.buffer = processedClip.buffer;+source.playbackRate.value = reversed ? -speed : speed;- source.connect(gainNode);+ source.connect(volumeGainNode);const contextStartTime = Math.max(0,clipInfo.timelineStartTime - renderStartTime,);- this.applyFades(gainNode, clipInfo, contextStartTime);+ this.applyVolumeAutomation(volumeGainNode, clipInfo, contextStartTime);+ this.applyFades(fadeGainNode, clipInfo, contextStartTime);const startOffset = reversed- ? audioBuffer.duration - clipInfo.sourceTime- : clipInfo.sourceTime;+ ? processedClip.buffer.duration - processedClip.startOffset+ : processedClip.startOffset;- source.start(contextStartTime, startOffset, clipInfo.duration);+ source.start(+ contextStartTime,+ Math.max(0, startOffset),+ Math.min(clipInfo.duration, processedClip.renderDuration),+ );}private shouldUseSegmentedAudioDecoding(@@ -455,10 +477,101 @@ export class AudioEngine {return (mediaItem.metadata.duration >= SEGMENTED_AUDIO_DECODE_THRESHOLD_SECONDS &&(clipInfo.speed || 1) === 1 &&- !clipInfo.reversed+ !clipInfo.reversed &&+ !clipInfo.effects.some((effect) => effect.enabled));}+ private async processClipBuffer(+ audioBuffer: AudioBuffer,+ clipInfo: AudioClipRenderInfo,+ ): Promise<{+ buffer: AudioBuffer;+ startOffset: number;+ renderDuration: number;+ }> {+ const enabledEffects = clipInfo.effects.filter(+ (effect) =>+ effect.enabled && effect.type !== "pan" && effect.type !== "fadeIn" && effect.type !== "fadeOut",+ );++ if (+ enabledEffects.length === 0 ||+ (clipInfo.speed ?? 1) !== 1 ||+ clipInfo.reversed ||+ !this.effectsEngine+ ) {+ return {+ buffer: audioBuffer,+ startOffset: clipInfo.sourceTime,+ renderDuration: clipInfo.duration,+ };+ }++ const segmentBuffer = this.extractAudioSegment(+ audioBuffer,+ clipInfo.sourceTime,+ clipInfo.duration,+ );+ const { profileAwareNoiseEffects, realtimeEffects } =+ splitProfileAwareNoiseReductionEffects(enabledEffects);++ let processedBuffer = segmentBuffer;++ for (const effect of profileAwareNoiseEffects) {+ const params = effect.params as AudioEffectParams["noiseReduction"];+ if (!params.profile) {+ continue;+ }++ processedBuffer = await this.effectsEngine.applyNoiseReductionWithProfileData(+ processedBuffer,+ params.profile,+ params.reduction ?? 0.5,+ params.focus ?? "balanced",+ );+ }++ if (realtimeEffects.length > 0) {+ const result = await this.effectsEngine.applyEffectChain(+ processedBuffer,+ realtimeEffects,+ );+ processedBuffer = result.buffer;+ }++ return {+ buffer: processedBuffer,+ startOffset: 0,+ renderDuration: processedBuffer.duration,+ };+ }++ private extractAudioSegment(+ sourceBuffer: AudioBuffer,+ startTime: number,+ duration: number,+ ): AudioBuffer {+ const startSample = Math.max(0, Math.floor(startTime * sourceBuffer.sampleRate));+ const length = Math.max(1, Math.ceil(duration * sourceBuffer.sampleRate));+ const segmentBuffer = this.audioContext!.createBuffer(+ sourceBuffer.numberOfChannels,+ length,+ sourceBuffer.sampleRate,+ );++ for (let channel = 0; channel < sourceBuffer.numberOfChannels; channel++) {+ const sourceData = sourceBuffer.getChannelData(channel);+ const targetData = segmentBuffer.getChannelData(channel);++ for (let index = 0; index < length; index++) {+ targetData[index] = sourceData[startSample + index] || 0;+ }+ }++ return segmentBuffer;+ }+private async renderClipToContextFromSegments(context: OfflineAudioContext,mediaItem: MediaItem,@@ -476,12 +589,16 @@ export class AudioEngine {return false;}- const { gainNode } = this.createClipOutputNodes(context, clipInfo);+ const { volumeGainNode, fadeGainNode } = this.createClipOutputNodes(+ context,+ clipInfo,+ );const contextStartTime = Math.max(0,clipInfo.timelineStartTime - renderStartTime,);- this.applyFades(gainNode, clipInfo, contextStartTime);+ this.applyVolumeAutomation(volumeGainNode, clipInfo, contextStartTime);+ this.applyFades(fadeGainNode, clipInfo, contextStartTime);let rendered = false;@@ -497,7 +614,7 @@ export class AudioEngine {const source = context.createBufferSource();source.buffer = wrapped.buffer;- source.connect(gainNode);+ source.connect(volumeGainNode);source.start(contextStartTime + (overlapStart - rangeStart),overlapStart - bufferStart,@@ -513,19 +630,39 @@ export class AudioEngine {context: OfflineAudioContext,clipInfo: AudioClipRenderInfo,): {- gainNode: GainNode;+ volumeGainNode: GainNode;+ fadeGainNode: GainNode;pannerNode: StereoPannerNode;} {- const gainNode = context.createGain();- gainNode.gain.value = clipInfo.volume;+ const volumeGainNode = context.createGain();+ volumeGainNode.gain.value = clipInfo.volume;++ const fadeGainNode = context.createGain();+ fadeGainNode.gain.value = 1;const pannerNode = context.createStereoPanner();pannerNode.pan.value = Math.max(-1, Math.min(1, clipInfo.pan));- gainNode.connect(pannerNode);+ volumeGainNode.connect(fadeGainNode);+ fadeGainNode.connect(pannerNode);pannerNode.connect(context.destination);- return { gainNode, pannerNode };+ return { volumeGainNode, fadeGainNode, pannerNode };+ }++ private applyVolumeAutomation(+ gainNode: GainNode,+ clipInfo: AudioClipRenderInfo,+ startTime: number,+ ): void {+ scheduleVolumeAutomationOnGain(+ gainNode,+ clipInfo.volumeAutomation,+ clipInfo.volume,+ clipInfo.clipOffset,+ clipInfo.duration,+ startTime,+ );}private async getSegmentedAudioDecoder(@@ -557,16 +694,18 @@ export class AudioEngine {clipInfo: AudioClipRenderInfo,startTime: number,): void {- const { fadeIn, fadeOut, duration, volume } = clipInfo;+ const { fadeIn, fadeOut, duration } = clipInfo;++ gainNode.gain.setValueAtTime(1, startTime);if (fadeIn && fadeIn > 0) {gainNode.gain.setValueAtTime(0, startTime);- gainNode.gain.linearRampToValueAtTime(volume, startTime + fadeIn);+ gainNode.gain.linearRampToValueAtTime(1, startTime + fadeIn);}if (fadeOut && fadeOut > 0) {const fadeOutStart = startTime + duration - fadeOut;- gainNode.gain.setValueAtTime(volume, fadeOutStart);+ gainNode.gain.setValueAtTime(1, fadeOutStart);gainNode.gain.linearRampToValueAtTime(0, startTime + duration);}}@@ -817,6 +956,8 @@ export class AudioEngine {async dispose(): Promise<void> {this.clearCache();this.trackNodes.clear();+ await this.effectsEngine?.dispose();+ this.effectsEngine = null;if (this.audioContext) {await this.audioContext.close();diff --git a/packages/core/src/audio/clip-volume-automation.test.ts b/packages/core/src/audio/clip-volume-automation.test.tsnew file mode 100644index 00000000..0ba1627b--- /dev/null+++ b/packages/core/src/audio/clip-volume-automation.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vitest";+import { getVolumeAutomationPointsForRange } from "./clip-volume-automation";++describe("clip volume automation", () => {+ it("trims automation to a clip range and interpolates the start and end", () => {+ const points = getVolumeAutomationPointsForRange(+ [+ { time: 0.5, value: 0.4 },+ { time: 1, value: 1 },+ ],+ 0.75,+ 0.2,+ 1,+ );++ expect(points).toEqual([+ { time: 0, value: 0.7 },+ { time: 0.2, value: 0.94 },+ ]);+ });++ it("keeps in-range keyframes and preserves the base volume before the first point", () => {+ const points = getVolumeAutomationPointsForRange(+ [+ { time: 0.4, value: 0.5 },+ { time: 0.9, value: 1 },+ ],+ 0,+ 0.6,+ 0.8,+ );++ expect(points).toEqual([+ { time: 0, value: 0.8 },+ { time: 0.4, value: 0.5 },+ { time: 0.6, value: 0.7 },+ ]);+ });+});\ No newline at end of filediff --git a/packages/core/src/audio/clip-volume-automation.ts b/packages/core/src/audio/clip-volume-automation.tsnew file mode 100644index 00000000..5f5ee331--- /dev/null+++ b/packages/core/src/audio/clip-volume-automation.ts@@ -0,0 +1,153 @@+import type { AutomationPoint } from "../types/timeline";+import { clampVolume } from "./volume-automation";++const sanitizePoints = (+ points: readonly AutomationPoint[] | undefined,+): AutomationPoint[] =>+ (points ?? [])+ .filter(+ (point) =>+ Number.isFinite(point.time) &&+ point.time >= 0 &&+ Number.isFinite(point.value),+ )+ .map((point) => ({+ time: point.time,+ value: clampVolume(point.value),+ }))+ .sort((left, right) => left.time - right.time);++const getAutomationValueAtTime = (+ points: readonly AutomationPoint[],+ time: number,+ baseVolume: number,+): number => {+ if (points.length === 0) {+ return baseVolume;+ }++ let previous: AutomationPoint | null = null;++ for (const point of points) {+ if (Math.abs(point.time - time) <= 0.0001) {+ return point.value;+ }++ if (point.time > time) {+ if (!previous) {+ return baseVolume;+ }++ const span = point.time - previous.time;+ if (span <= 0.0001) {+ return point.value;+ }++ const progress = (time - previous.time) / span;+ return clampVolume(+ previous.value + (point.value - previous.value) * progress,+ );+ }++ previous = point;+ }++ return previous ? previous.value : baseVolume;+};++export const getVolumeAutomationPointsForRange = (+ points: readonly AutomationPoint[] | undefined,+ clipOffset: number,+ clipDuration: number,+ baseVolume: number,+): AutomationPoint[] => {+ const sanitizedPoints = sanitizePoints(points);+ const clampedBaseVolume = clampVolume(baseVolume);++ if (clipDuration <= 0 || sanitizedPoints.length === 0) {+ return [];+ }++ const rangeStart = Math.max(0, clipOffset);+ const rangeEnd = rangeStart + clipDuration;+ const result: AutomationPoint[] = [+ {+ time: 0,+ value: getAutomationValueAtTime(+ sanitizedPoints,+ rangeStart,+ clampedBaseVolume,+ ),+ },+ ];++ for (const point of sanitizedPoints) {+ if (point.time <= rangeStart || point.time >= rangeEnd) {+ continue;+ }++ result.push({+ time: point.time - rangeStart,+ value: point.value,+ });+ }++ result.push({+ time: clipDuration,+ value: getAutomationValueAtTime(+ sanitizedPoints,+ rangeEnd,+ clampedBaseVolume,+ ),+ });++ const deduped: AutomationPoint[] = [];++ for (const point of result) {+ const lastPoint = deduped[deduped.length - 1];+ if (lastPoint && Math.abs(lastPoint.time - point.time) <= 0.0001) {+ deduped[deduped.length - 1] = point;+ continue;+ }++ deduped.push(point);+ }++ return deduped;+};++export const scheduleVolumeAutomationOnGain = (+ gainNode: GainNode,+ points: readonly AutomationPoint[] | undefined,+ baseVolume: number,+ clipOffset: number,+ clipDuration: number,+ startTime: number,+): void => {+ const clampedBaseVolume = clampVolume(baseVolume);+ const rangePoints = getVolumeAutomationPointsForRange(+ points,+ clipOffset,+ clipDuration,+ clampedBaseVolume,+ );++ gainNode.gain.cancelScheduledValues(startTime);++ if (rangePoints.length === 0) {+ gainNode.gain.setValueAtTime(clampedBaseVolume, startTime);+ return;+ }++ gainNode.gain.setValueAtTime(rangePoints[0].value, startTime);++ for (let index = 1; index < rangePoints.length; index += 1) {+ const point = rangePoints[index];+ gainNode.gain.linearRampToValueAtTime(point.value, startTime + point.time);+ }++ const lastPoint = rangePoints[rangePoints.length - 1];+ if (lastPoint.time < clipDuration) {+ gainNode.gain.setValueAtTime(lastPoint.value, startTime + lastPoint.time);+ }+};\ No newline at end of filediff --git a/packages/core/src/audio/index.ts b/packages/core/src/audio/index.tsindex 680915b8..10c0f823 100644--- a/packages/core/src/audio/index.ts+++ b/packages/core/src/audio/index.ts@@ -1,4 +1,5 @@export * from "./types";+export * from "./clip-volume-automation";export * from "./fft";export * from "./audio-engine";export * from "./realtime-processor";diff --git a/packages/core/src/audio/realtime-audio-graph.ts b/packages/core/src/audio/realtime-audio-graph.tsindex ec34c48f..f5e52a5b 100644--- a/packages/core/src/audio/realtime-audio-graph.ts+++ b/packages/core/src/audio/realtime-audio-graph.ts@@ -2,7 +2,9 @@ import {getMasterClock,MasterTimelineClock,} from "../playback/master-timeline-clock";-import type { Effect } from "../types/timeline";+import type { AutomationPoint, Effect } from "../types/timeline";+import { createNoiseReductionNodeChain } from "./audio-effects-engine";+import { scheduleVolumeAutomationOnGain } from "./clip-volume-automation";export interface AudioClipSchedule {clipId: string;@@ -12,6 +14,7 @@ export interface AudioClipSchedule {endTime: number;mediaOffset: number;volume: number;+ volumeAutomation: AutomationPoint[];pan: number;effects: Effect[];speed: number;@@ -58,6 +61,7 @@ interface TrackNodes {outputGain: GainNode;compressor: DynamicsCompressorNode | null;eqFilters: BiquadFilterNode[];+ noiseReductionNodes: AudioNode[];reverbNodes: ReverbNodes | null;delayNodes: DelayNodes | null;}@@ -131,6 +135,7 @@ export class RealtimeAudioGraph {effectChainOutput,compressor,eqFilters,+ noiseReductionNodes,reverbNodes,delayNodes,} = this.buildEffectChain(config.effects);@@ -148,6 +153,7 @@ export class RealtimeAudioGraph {outputGain,compressor,eqFilters,+ noiseReductionNodes,reverbNodes,delayNodes,};@@ -163,12 +169,14 @@ export class RealtimeAudioGraph {effectChainOutput: AudioNode;compressor: DynamicsCompressorNode | null;eqFilters: BiquadFilterNode[];+ noiseReductionNodes: AudioNode[];reverbNodes: ReverbNodes | null;delayNodes: DelayNodes | null;} {const passthrough = this.audioContext.createGain();let compressor: DynamicsCompressorNode | null = null;const eqFilters: BiquadFilterNode[] = [];+ const noiseReductionNodes: AudioNode[] = [];let reverbNodes: ReverbNodes | null = null;let delayNodes: DelayNodes | null = null;@@ -179,6 +187,7 @@ export class RealtimeAudioGraph {effectChainOutput: passthrough,compressor,eqFilters,+ noiseReductionNodes,reverbNodes,delayNodes,};@@ -207,6 +216,13 @@ export class RealtimeAudioGraph {}break;}+ case "noiseReduction": {+ const chain = createNoiseReductionNodeChain(this.audioContext, effect);+ currentNode.connect(chain.input);+ currentNode = chain.output;+ noiseReductionNodes.push(...chain.nodes);+ break;+ }case "reverb": {reverbNodes = this.createReverbNodes(effect);currentNode.connect(reverbNodes.inputGain);@@ -227,6 +243,7 @@ export class RealtimeAudioGraph {effectChainOutput: currentNode,compressor,eqFilters,+ noiseReductionNodes,reverbNodes,delayNodes,};@@ -379,6 +396,7 @@ export class RealtimeAudioGraph {nodes.outputGain.disconnect();if (nodes.compressor) nodes.compressor.disconnect();for (const filter of nodes.eqFilters) filter.disconnect();+ for (const node of nodes.noiseReductionNodes) node.disconnect();if (nodes.reverbNodes) {nodes.reverbNodes.inputGain.disconnect();nodes.reverbNodes.dryGain.disconnect();@@ -522,7 +540,6 @@ export class RealtimeAudioGraph {source.playbackRate.value = schedule.speed;const clipGain = this.audioContext.createGain();- clipGain.gain.value = schedule.volume;source.connect(clipGain);clipGain.connect(trackNodes.inputGain);@@ -533,17 +550,43 @@ export class RealtimeAudioGraph {this.masterClock.currentTime;const duration = schedule.endTime - schedule.startTime;+ let playbackStartTime = contextStartTime;+ let clipOffset = 0;+ let playbackDuration = duration;+if (contextStartTime > this.audioContext.currentTime) {+ scheduleVolumeAutomationOnGain(+ clipGain,+ schedule.volumeAutomation,+ schedule.volume,+ clipOffset,+ playbackDuration,+ playbackStartTime,+ );source.start(contextStartTime, schedule.mediaOffset, duration);} else {- const offset =- this.masterClock.currentTime -- schedule.startTime +- schedule.mediaOffset;- const remainingDuration =- duration - (this.masterClock.currentTime - schedule.startTime);- if (remainingDuration > 0 && offset < schedule.audioBuffer.duration) {- source.start(0, offset, remainingDuration);+ clipOffset = this.masterClock.currentTime - schedule.startTime;+ const sourceOffset = clipOffset + schedule.mediaOffset;+ playbackDuration = duration - clipOffset;+ playbackStartTime = this.audioContext.currentTime;++ if (+ playbackDuration > 0 &&+ sourceOffset < schedule.audioBuffer.duration+ ) {+ scheduleVolumeAutomationOnGain(+ clipGain,+ schedule.volumeAutomation,+ schedule.volume,+ clipOffset,+ playbackDuration,+ playbackStartTime,+ );+ source.start(0, sourceOffset, playbackDuration);+ } else {+ source.disconnect();+ clipGain.disconnect();+ return;}}@@ -551,7 +594,7 @@ export class RealtimeAudioGraph {clipId: schedule.clipId,source,startedAt: schedule.startTime,- duration,+ duration: playbackDuration,};const sources = this.scheduledSources.get(schedule.trackId) || [];diff --git a/packages/core/src/audio/types.ts b/packages/core/src/audio/types.tsindex 9f7b99a2..00588bda 100644--- a/packages/core/src/audio/types.ts+++ b/packages/core/src/audio/types.ts@@ -1,4 +1,4 @@-import type { Effect } from "../types/timeline";+import type { AutomationPoint, Effect } from "../types/timeline";export interface AudioWaveformData {readonly peaks: Float32Array;@@ -33,9 +33,11 @@ export interface AudioClipRenderInfo {readonly clipId: string;readonly mediaId: string;readonly sourceTime: number;+ readonly clipOffset: number;readonly timelineStartTime: number;readonly duration: number;readonly volume: number;+ readonly volumeAutomation: AutomationPoint[];readonly pan: number;readonly effects: Effect[];readonly fadeIn?: number;diff --git a/packages/core/src/playback/playback-controller.ts b/packages/core/src/playback/playback-controller.tsindex aa5f518d..229cf6b9 100644--- a/packages/core/src/playback/playback-controller.ts+++ b/packages/core/src/playback/playback-controller.ts@@ -22,6 +22,10 @@ import {initializeRealtimeAudioGraph,type AudioClipSchedule,} from "../audio/realtime-audio-graph";+import {+ getPanFromAudioEffects,+ getPreviewAudioEffects,+} from "../audio/audio-effect-routing";export class PlaybackController {private videoEngine: VideoEngine | null = null;@@ -574,8 +578,9 @@ export class PlaybackController {endTime: clipEnd,mediaOffset: clip.inPoint,volume: clip.volume,- pan: 0,- effects: clip.audioEffects || [],+ volumeAutomation: clip.automation?.volume ?? [],+ pan: getPanFromAudioEffects(clip.audioEffects || []),+ effects: getPreviewAudioEffects(clip.audioEffects || []),speed: clip.speed ?? 1,});}diff --git a/packages/core/src/types/effects.ts b/packages/core/src/types/effects.tsindex 10ed32e8..e9eab21a 100644--- a/packages/core/src/types/effects.ts+++ b/packages/core/src/types/effects.ts@@ -737,6 +737,12 @@ export interface AudioEffectParams {reduction: number; // 0 to 1attack: number; // 0 to 100 msrelease: number; // 0 to 500 ms+ focus?: "balanced" | "speech" | "heavy" | "wind" | "hum";+ profile?: {+ frequencyBins: number[];+ magnitudes: number[];+ sampleRate: number;+ };};fadeIn: {duration: number; // In seconds