OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat(audio): Enhance noise reduction analysis with recommendation sampling and progress tracking
Augustus Otu154862d1344e
diff --git a/apps/web/src/components/editor/inspector/NoiseReductionSection.persistence.test.tsx b/apps/web/src/components/editor/inspector/NoiseReductionSection.persistence.test.tsxindex e053b7b7..8feed14b 100644--- a/apps/web/src/components/editor/inspector/NoiseReductionSection.persistence.test.tsx+++ b/apps/web/src/components/editor/inspector/NoiseReductionSection.persistence.test.tsx@@ -247,9 +247,9 @@ describe("NoiseReductionSection persistence", () => {await waitFor(() => {const effect = useProjectStore.getState().getAudioEffects(clipId)[0];expect(effect?.type).toBe("noiseReduction");- expect(effect?.params).toMatchObject({ focus: "whiteNoise" });+ expect(typeof (effect?.params as { focus?: unknown }).focus).toBe("string");expect((effect?.params as { profile?: unknown }).profile).toBeTruthy();- expect(screen.getByText(/White Noise applied to this clip/)).toBeInTheDocument();+ expect(screen.getByText(/applied to this clip/i)).toBeInTheDocument();});});diff --git a/apps/web/src/components/editor/inspector/NoiseReductionSection.test.ts b/apps/web/src/components/editor/inspector/NoiseReductionSection.test.tsindex 890a95a2..dc95818b 100644--- a/apps/web/src/components/editor/inspector/NoiseReductionSection.test.ts+++ b/apps/web/src/components/editor/inspector/NoiseReductionSection.test.ts@@ -1,9 +1,14 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";+import { SpectralNoiseReducer } from "@openreel/core";import { DEFAULT_NOISE_REDUCTION } from "../../../bridges/audio-bridge-effects";import {suggestNoiseReductionConfig,suggestNoiseReductionPreset,} from "./noise-reduction-presets";+import {+ buildRecommendationProfile,+ getRecommendationSampleRanges,+} from "./NoiseReductionSection";const createProfile = (frequencyBins: number[],@@ -16,6 +21,43 @@ const createProfile = (createdAt: Date.now(),});+const createFakeAudioBuffer = (+ duration: number,+ sampleRate = 10,+ numberOfChannels = 1,+): AudioBuffer => {+ const length = Math.max(1, Math.round(duration * sampleRate));+ const channels = Array.from(+ { length: numberOfChannels },+ () => new Float32Array(length),+ );++ return {+ duration: length / sampleRate,+ length,+ numberOfChannels,+ sampleRate,+ getChannelData(channel: number) {+ return channels[channel];+ },+ } as AudioBuffer;+};++const createFakeAudioContext = (): BaseAudioContext =>+ ({+ createBuffer(numberOfChannels: number, length: number, sampleRate: number) {+ return createFakeAudioBuffer(+ length / sampleRate,+ sampleRate,+ numberOfChannels,+ );+ },+ }) as BaseAudioContext;++afterEach(() => {+ vi.restoreAllMocks();+});+describe("noise reduction presets", () => {it("recommends white-noise cleanup for broadband hiss", () => {const preset = suggestNoiseReductionPreset(@@ -86,4 +128,38 @@ describe("noise reduction presets", () => {expect(suggested).toEqual(DEFAULT_NOISE_REDUCTION);});++ it("samples long clips across multiple windows before recommending cleanup", () => {+ const sampleRanges = getRecommendationSampleRanges(90);+ let capturedSampleDuration = 0;++ vi.spyOn(SpectralNoiseReducer.prototype, "learnNoiseProfile").mockImplementation(+ (noiseBuffer) => {+ capturedSampleDuration = noiseBuffer.duration;++ return {+ frequencyBins: new Float32Array([80, 250, 1000]),+ magnitudes: new Float32Array([0.4, 0.36, 0.31]),+ standardDeviations: new Float32Array([0.03, 0.02, 0.02]),+ sampleRate: noiseBuffer.sampleRate,+ fftSize: 2048,+ };+ },+ );++ const profile = buildRecommendationProfile(+ "clip-long",+ createFakeAudioBuffer(90),+ createFakeAudioContext(),+ );++ expect(sampleRanges).toHaveLength(3);+ expect(sampleRanges[0].start).toBeGreaterThan(10);+ expect(sampleRanges[0].end).toBeLessThan(sampleRanges[1].start);+ expect(sampleRanges[1].start).toBeGreaterThan(35);+ expect(sampleRanges[1].end).toBeLessThan(sampleRanges[2].start);+ expect(sampleRanges[2].end).toBeLessThanOrEqual(90);+ expect(capturedSampleDuration).toBeCloseTo(24, 5);+ expect(profile.id).toBe("analysis-clip-long");+ });});\ 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 8f94b15f..04ee4823 100644--- a/apps/web/src/components/editor/inspector/NoiseReductionSection.tsx+++ b/apps/web/src/components/editor/inspector/NoiseReductionSection.tsx@@ -72,7 +72,19 @@ interface AnalysisProgressState {message: string;}-const MAX_RECOMMENDATION_SAMPLE_SECONDS = 20;+interface RecommendationProfileProgress {+ progress: number;+ message: string;+}++export interface RecommendationSampleRange {+ start: number;+ end: number;+}++const MAX_RECOMMENDATION_SAMPLE_SECONDS = 24;+const MAX_RECOMMENDATION_SAMPLE_WINDOWS = 3;+const MIN_RECOMMENDATION_WINDOW_SECONDS = 4;const findClipById = (project: Project, clipId: string): Clip | null => {for (const track of project.timeline.tracks) {@@ -85,29 +97,148 @@ const findClipById = (project: Project, clipId: string): Clip | null => {return null;};-const buildRecommendationProfile = (+export const getRecommendationSampleRanges = (+ duration: number,+): RecommendationSampleRange[] => {+ if (!Number.isFinite(duration) || duration <= 0) {+ return [];+ }++ if (duration <= MAX_RECOMMENDATION_SAMPLE_SECONDS) {+ return [{ start: 0, end: duration }];+ }++ const maxWindowsByDuration = Math.max(+ 1,+ Math.min(+ MAX_RECOMMENDATION_SAMPLE_WINDOWS,+ Math.floor(duration / MIN_RECOMMENDATION_WINDOW_SECONDS),+ ),+ );+ const windowCount = Math.max(+ 1,+ Math.min(+ maxWindowsByDuration,+ Math.ceil(duration / MAX_RECOMMENDATION_SAMPLE_SECONDS),+ ),+ );+ const windowDuration = Math.min(+ duration,+ MAX_RECOMMENDATION_SAMPLE_SECONDS / windowCount,+ );+ const firstCenter = windowCount === 1 ? 0.5 : 0.18;+ const lastCenter = windowCount === 1 ? 0.5 : 0.82;++ return Array.from({ length: windowCount }, (_, index) => {+ const center =+ windowCount === 1+ ? 0.5+ : firstCenter ++ ((lastCenter - firstCenter) * index) / (windowCount - 1);+ const maxStart = Math.max(0, duration - windowDuration);+ const start = Math.min(+ maxStart,+ Math.max(0, duration * center - windowDuration / 2),+ );++ return {+ start,+ end: Math.min(duration, start + windowDuration),+ };+ });+};++const buildRecommendationSampleBuffer = (+ audioBuffer: AudioBuffer,+ context: BaseAudioContext,+ onProgress?: (progress: RecommendationProfileProgress) => void,+): { sampleBuffer: AudioBuffer; sampleCount: number } => {+ const sampleRanges = getRecommendationSampleRanges(audioBuffer.duration);++ if (sampleRanges.length === 0) {+ throw new Error("Clip audio range is empty");+ }++ if (+ sampleRanges.length === 1 &&+ sampleRanges[0].start <= 0 &&+ sampleRanges[0].end >= audioBuffer.duration+ ) {+ onProgress?.({ progress: 0.4, message: "Analyzing clip audio" });+ return {+ sampleBuffer: audioBuffer,+ sampleCount: 1,+ };+ }++ const segments = sampleRanges.map((sampleRange, index) => {+ onProgress?.({+ progress: (index + 1) / (sampleRanges.length + 1),+ message: `Sampling clip audio (${index + 1}/${sampleRanges.length})`,+ });++ return extractAudioSegment(+ audioBuffer,+ sampleRange.start,+ sampleRange.end,+ context,+ );+ });+ const sampleLength = segments.reduce(+ (total, segment) => total + segment.length,+ 0,+ );+ const sampleBuffer = context.createBuffer(+ audioBuffer.numberOfChannels,+ sampleLength,+ audioBuffer.sampleRate,+ );++ let offset = 0;+ for (const segment of segments) {+ for (let channel = 0; channel < audioBuffer.numberOfChannels; channel += 1) {+ sampleBuffer.getChannelData(channel).set(+ segment.getChannelData(channel),+ offset,+ );+ }++ offset += segment.length;+ }++ onProgress?.({+ progress: 0.85,+ message: `Analyzing ${segments.length} clip samples`,+ });++ return {+ sampleBuffer,+ sampleCount: segments.length,+ };+};++export const buildRecommendationProfile = (clipId: string,audioBuffer: AudioBuffer,context: BaseAudioContext,+ onProgress?: (progress: RecommendationProfileProgress) => void,): NoiseProfileData => {- const sampleDuration = Math.min(- audioBuffer.duration,- MAX_RECOMMENDATION_SAMPLE_SECONDS,+ const { sampleBuffer, sampleCount } = buildRecommendationSampleBuffer(+ audioBuffer,+ context,+ onProgress,);- const sampleStart = Math.max(0, (audioBuffer.duration - sampleDuration) / 2);- const sampleBuffer =- sampleDuration < audioBuffer.duration- ? extractAudioSegment(- audioBuffer,- sampleStart,- sampleStart + sampleDuration,- context,- )- : audioBuffer;-const reducer = new SpectralNoiseReducer();const profile = reducer.learnNoiseProfile(sampleBuffer);+ onProgress?.({+ progress: 1,+ message:+ sampleCount > 1+ ? `Analyzed ${sampleCount} clip samples`+ : "Analyzed clip audio",+ });+return {id: `analysis-${clipId}`,frequencyBins: profile.frequencyBins,@@ -358,6 +489,12 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({audioTargetClipId,clipBuffer,analysisContext,+ (progress) => {+ updateAnalysisProgress({+ progress: 0.84 + progress.progress * 0.08,+ message: progress.message,+ });+ },);updateAnalysisProgress({ progress: 0.93, message: "Learning custom cleanup profile" });@@ -387,7 +524,7 @@ export const NoiseReductionSection: React.FC<NoiseReductionSectionProps> = ({};return {- recommendationProfile: learnedProfile,+ recommendationProfile,learnedProfile: {profile: learnedProfile,serializedProfile: {