From baa1e23a55a9d08f64bd2960301a8ca56af3c170 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E4=B8=AA=E6=88=90=E7=86=9F=E7=9A=84=E5=89=AA?= =?UTF-8?q?=E8=BE=91=E7=8C=BF?= <297668904+akahoz94@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:43:07 +0800 Subject: [PATCH 1/8] feat(recording): pre-recording volume trims for microphone and computer audio Two sliders in the HUD device settings (-24..+12 dB, persisted in recording settings) trim each source before the take starts. The trim rides the native request on all three platforms and the browser fallback mix: - wgc-capture: AudioMixer takes a systemGain and applies it at mix time, sum-then-clamp like the microphone gain (queues stay unity). - pipewire-capture: system source reads audio.system.gain (already parsed, previously never sent by the Linux bridge). - ScreenCaptureKit: AudioTrackMixer scales the system track by the trim. - mixAudioTracks: GainNode trims for the browser path; mic-only and system-only unity stays context-free as before. The automatic 1.4x mic boost over system audio is unchanged; the user trim multiplies whichever base applies. Tests: audioMix (+3), app-settings (+1), C++ mixer system-gain exact-value case, request-shape and prefs literals updated; tsc both configs, biome, i18n:check clean; full vitest green except pre-existing release-script failures untouched by this change. --- electron/app-settings.test.ts | 21 ++++++ electron/app-settings.ts | 32 +++++++++ electron/ipc/handlers.ts | 14 +++- electron/ipc/recordingPrefs.test.ts | 2 + .../capture/linuxNativeCaptureSession.ts | 2 +- electron/native/pipewire-capture/src/main.rs | 4 +- .../AudioTrackMixer.swift | 6 +- .../ScreenCaptureRecorder.swift | 2 + .../wgc-capture/src/audio_sample_utils.cpp | 6 +- .../wgc-capture/src/audio_sample_utils.h | 2 + .../src/audio_sample_utils_test.cpp | 26 +++++--- electron/native/wgc-capture/src/main.cpp | 3 + .../ai-edition/v4/RecStage.test.tsx | 4 ++ .../launch/HudDeviceSettings.quality.test.tsx | 7 ++ src/components/launch/HudDeviceSettings.tsx | 65 ++++++++++++++++++- src/components/launch/LaunchWindow.module.css | 36 ++++++++++ src/components/launch/LaunchWindow.tsx | 34 ++++++++++ ...eenRecorder.nativeMacStartWarning.test.tsx | 2 +- src/hooks/useScreenRecorder.noCamera.test.tsx | 2 + .../useScreenRecorder.prefsRace.test.tsx | 2 + src/hooks/useScreenRecorder.ts | 28 ++++++-- src/i18n/locales/ar/launch.json | 2 + src/i18n/locales/cs/launch.json | 2 + src/i18n/locales/de/launch.json | 2 + src/i18n/locales/en/launch.json | 2 + src/i18n/locales/es/launch.json | 2 + src/i18n/locales/fr/launch.json | 2 + src/i18n/locales/it/launch.json | 2 + src/i18n/locales/ja-JP/launch.json | 2 + src/i18n/locales/ko-KR/launch.json | 2 + src/i18n/locales/nl/launch.json | 2 + src/i18n/locales/pl/launch.json | 2 + src/i18n/locales/pt-BR/launch.json | 2 + src/i18n/locales/ru/launch.json | 2 + src/i18n/locales/tr/launch.json | 2 + src/i18n/locales/vi/launch.json | 2 + src/i18n/locales/zh-CN/launch.json | 2 + src/i18n/locales/zh-TW/launch.json | 2 + src/lib/audioMix.test.ts | 44 +++++++++++++ src/lib/audioMix.ts | 45 +++++++++++-- src/lib/nativeLinuxRecording.ts | 2 + src/lib/nativeMacRecording.ts | 2 + src/lib/nativeWindowsRecording.ts | 2 + src/native/browserShim.ts | 4 ++ 44 files changed, 407 insertions(+), 26 deletions(-) diff --git a/electron/app-settings.test.ts b/electron/app-settings.test.ts index f3781734f8..36a1e72f86 100644 --- a/electron/app-settings.test.ts +++ b/electron/app-settings.test.ts @@ -62,6 +62,27 @@ describe("app settings store", () => { ); }); + it("persists the volume trims, reads missing keys as unity, and rejects out-of-range writes", () => { + const dir = temp(); + const file = path.join(dir, "recording-settings.json"); + const store = new AppSettingsStore(dir); + expect(store.getSnapshot().recording.micGainDb).toBe(0); + expect(store.getSnapshot().recording.systemAudioGainDb).toBe(0); + expect( + store.setRecordingPreferences({ micGainDb: -6, systemAudioGainDb: 3 }).recording, + ).toMatchObject({ micGainDb: -6, systemAudioGainDb: 3 }); + expect(new AppSettingsStore(dir).getSnapshot().recording).toMatchObject({ + micGainDb: -6, + systemAudioGainDb: 3, + }); + + writeFileSync(file, JSON.stringify({ micGainDb: 99, systemAudioGainDb: "loud" }), "utf8"); + expect(store.getSnapshot().recording.micGainDb).toBe(0); + expect(store.getSnapshot().recording.systemAudioGainDb).toBe(0); + expect(() => store.setRecordingPreferences({ micGainDb: 24 })).toThrow(TypeError); + expect(() => store.setRecordingPreferences({ systemAudioGainDb: -25 })).toThrow(TypeError); + }); + it("stores the last source beside the recording preferences", () => { const dir = temp(); const store = new AppSettingsStore(dir); diff --git a/electron/app-settings.ts b/electron/app-settings.ts index 81d334260c..6a7ce5c71c 100644 --- a/electron/app-settings.ts +++ b/electron/app-settings.ts @@ -6,6 +6,7 @@ import { type WebcamQualityId, webcamQualityFrom, } from "../src/hooks/webcamCaptureTarget"; +import { RECORDING_GAIN_DB_MAX, RECORDING_GAIN_DB_MIN } from "../src/lib/audioMix"; import type { CursorCaptureMode } from "../src/lib/recordingSession"; import { renameSyncWithFallback } from "./atomic-rename"; @@ -19,6 +20,10 @@ export interface RecordingPreferences { /** Capture resolution for the camera. See WEBCAM_QUALITY_PRESETS. */ camQuality: WebcamQualityId; systemAudioEnabled: boolean; + /** User trim on the microphone, dB relative to the automatic mix gain. */ + micGainDb: number; + /** User trim on the captured computer audio, dB. */ + systemAudioGainDb: number; cursorCaptureMode: CursorCaptureMode; /** Display captures on macOS and Windows. Opt-in: on Windows the icons also leave the real desktop while recording. */ hideDesktopIcons: boolean; @@ -41,6 +46,8 @@ export const DEFAULT_RECORDING_PREFERENCES: RecordingPreferences = { camDeviceName: null, camQuality: DEFAULT_WEBCAM_QUALITY, systemAudioEnabled: false, + micGainDb: 0, + systemAudioGainDb: 0, cursorCaptureMode: "editable-overlay", hideDesktopIcons: false, autoZoomEnabled: true, @@ -101,6 +108,13 @@ function atomicWrite(userData: string, value: RawSettings): void { const bool = (value: unknown, fallback: boolean) => (typeof value === "boolean" ? value : fallback); const nullableString = (value: unknown, fallback: string | null) => value === null || typeof value === "string" ? value : fallback; +const gainDb = (value: unknown, fallback: number) => + typeof value === "number" && + Number.isFinite(value) && + value >= RECORDING_GAIN_DB_MIN && + value <= RECORDING_GAIN_DB_MAX + ? value + : fallback; function parseRecording(raw: RawSettings): RecordingPreferences { return { @@ -117,6 +131,13 @@ function parseRecording(raw: RawSettings): RecordingPreferences { raw.systemAudioEnabled, DEFAULT_RECORDING_PREFERENCES.systemAudioEnabled, ), + // Absent from settings files written before the volume trims existed; + // unity (0 dB) is what every such installation recorded at. + micGainDb: gainDb(raw.micGainDb, DEFAULT_RECORDING_PREFERENCES.micGainDb), + systemAudioGainDb: gainDb( + raw.systemAudioGainDb, + DEFAULT_RECORDING_PREFERENCES.systemAudioGainDb, + ), cursorCaptureMode: raw.cursorCaptureMode === "system" || raw.cursorCaptureMode === "editable-overlay" ? raw.cursorCaptureMode @@ -186,6 +207,17 @@ function validateRecordingPatch(patch: Partial): void { if (key === "camQuality" && !WEBCAM_QUALITY_IDS.includes(value as WebcamQualityId)) { throw new TypeError("camQuality is invalid"); } + if ( + (key === "micGainDb" || key === "systemAudioGainDb") && + (typeof value !== "number" || + !Number.isFinite(value) || + value < RECORDING_GAIN_DB_MIN || + value > RECORDING_GAIN_DB_MAX) + ) { + throw new TypeError( + `${key} must be a number in [${RECORDING_GAIN_DB_MIN}, ${RECORDING_GAIN_DB_MAX}]`, + ); + } } } diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts index e33c549995..55633f2652 100644 --- a/electron/ipc/handlers.ts +++ b/electron/ipc/handlers.ts @@ -755,6 +755,10 @@ export interface RecordingPrefs { /** Capture resolution for the camera. See WEBCAM_QUALITY_PRESETS. */ camQuality: WebcamQualityId; systemAudioEnabled: boolean; + /** User trim on the microphone, dB relative to the automatic mix gain. */ + micGainDb: number; + /** User trim on the captured computer audio, dB. */ + systemAudioGainDb: number; cursorCaptureMode: CursorCaptureMode; hideDesktopIcons: boolean; /** Whether a fresh take gets automatic zooms on import. Persisted; defaults on. */ @@ -769,6 +773,8 @@ const defaultRecordingPrefs: RecordingPrefs = { camDeviceName: null, camQuality: DEFAULT_WEBCAM_QUALITY, systemAudioEnabled: false, + micGainDb: 0, + systemAudioGainDb: 0, cursorCaptureMode: "editable-overlay", hideDesktopIcons: false, autoZoomEnabled: true, @@ -2814,7 +2820,7 @@ export function registerIpcHandlers( fps: request.video.fps, ...(request.video.bitrate ? { bitrate: request.video.bitrate } : {}), audio: { - system: { enabled: request.audio.system.enabled }, + system: { enabled: request.audio.system.enabled, gain: request.audio.system.gain ?? 1 }, microphone: { enabled: request.audio.microphone.enabled, ...(request.audio.microphone.deviceName @@ -2918,7 +2924,10 @@ export function registerIpcHandlers( fps: request.video.fps, ...(request.video.bitrate ? { bitrate: request.video.bitrate } : {}), audio: { - system: { enabled: request.audio.system.enabled }, + system: { + enabled: request.audio.system.enabled, + gain: request.audio.system.gain ?? 1, + }, microphone: { enabled: request.audio.microphone.enabled, ...(request.audio.microphone.deviceName @@ -3209,6 +3218,7 @@ export function registerIpcHandlers( microphoneDeviceId: request.audio.microphone.deviceId ?? null, microphoneDeviceName: request.audio.microphone.deviceName ?? null, microphoneGain: request.audio.microphone.gain, + systemGain: request.audio.system.gain ?? 1, webcamEnabled: request.webcam.enabled, webcamDeviceId: request.webcam.deviceId ?? null, webcamDeviceName: request.webcam.deviceName ?? null, diff --git a/electron/ipc/recordingPrefs.test.ts b/electron/ipc/recordingPrefs.test.ts index 2c3317af93..7a65bb7d4b 100644 --- a/electron/ipc/recordingPrefs.test.ts +++ b/electron/ipc/recordingPrefs.test.ts @@ -21,6 +21,8 @@ const defaults: RecordingPrefs = { camDeviceName: null, camQuality: "2160p", systemAudioEnabled: false, + micGainDb: 0, + systemAudioGainDb: 0, cursorCaptureMode: "editable-overlay", hideDesktopIcons: false, autoZoomEnabled: true, diff --git a/electron/native-bridge/capture/linuxNativeCaptureSession.ts b/electron/native-bridge/capture/linuxNativeCaptureSession.ts index d2512a87f7..1dd0f76222 100644 --- a/electron/native-bridge/capture/linuxNativeCaptureSession.ts +++ b/electron/native-bridge/capture/linuxNativeCaptureSession.ts @@ -72,7 +72,7 @@ export interface LinuxCaptureConfig { fps: number; bitrate?: number; audio: { - system: { enabled: boolean }; + system: { enabled: boolean; gain?: number }; microphone: { enabled: boolean; deviceName?: string; gain: number }; }; maxCursorSamples: number; diff --git a/electron/native/pipewire-capture/src/main.rs b/electron/native/pipewire-capture/src/main.rs index 8d99997e68..732139dc15 100644 --- a/electron/native/pipewire-capture/src/main.rs +++ b/electron/native/pipewire-capture/src/main.rs @@ -79,6 +79,8 @@ struct AudioRequest { #[serde(rename_all = "camelCase", default)] struct SystemAudioRequest { enabled: bool, + /// Linear multiplier the UI applies to computer-audio level. + gain: Option, } #[derive(Debug, Default, Deserialize)] @@ -199,7 +201,7 @@ impl Request { // The default SINK's monitor: what is being played, not what a // microphone hears. capture_sink: true, - gain: 1.0, + gain: audio.system.gain.filter(|gain| *gain > 0.0).unwrap_or(1.0), bitrate: DEFAULT_AUDIO_BITRATE, }); } diff --git a/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift b/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift index e0f3b17852..32488ddf0c 100644 --- a/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift +++ b/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift @@ -106,6 +106,7 @@ public final class AudioTrackMixer { private let includesSystemAudio: Bool private let includesMicrophone: Bool private let microphoneGain: Float + private let systemGain: Float private let outputFormatDescription: CMAudioFormatDescription? private var sources = [SourceTimeline](repeating: SourceTimeline(), count: Source.allCases.count) @@ -136,6 +137,7 @@ public final class AudioTrackMixer { includesSystemAudio: Bool, includesMicrophone: Bool, microphoneGain: Double, + systemGain: Double = 1, clock: @escaping TimelineClock ) { self.input = input @@ -146,6 +148,8 @@ public final class AudioTrackMixer { // does this. A non-finite or negative value would poison every mixed sample. let sanitized = microphoneGain.isFinite ? max(0, microphoneGain) : 1 self.microphoneGain = Float(sanitized) + let sanitizedSystem = systemGain.isFinite ? max(0, systemGain) : 1 + self.systemGain = Float(sanitizedSystem) self.outputFormatDescription = Self.makeOutputFormatDescription() } @@ -397,7 +401,7 @@ public final class AudioTrackMixer { private func gain(for source: Source) -> Float { switch source { case .system: - return 1 + return systemGain case .microphone: return microphoneGain } diff --git a/electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/ScreenCaptureRecorder.swift b/electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/ScreenCaptureRecorder.swift index 3b1cce0c7d..d17479246c 100644 --- a/electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/ScreenCaptureRecorder.swift +++ b/electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/ScreenCaptureRecorder.swift @@ -32,6 +32,7 @@ struct RecordingRequest: Decodable { struct Audio: Decodable { struct SystemAudio: Decodable { let enabled: Bool + let gain: Double? } struct Microphone: Decodable { @@ -973,6 +974,7 @@ final class ScreenCaptureRecorder: NSObject, SCStreamOutput, SCStreamDelegate { includesSystemAudio: request.audio.system.enabled, includesMicrophone: nativeMicrophoneEnabled, microphoneGain: request.audio.microphone.gain, + systemGain: request.audio.system.gain ?? 1, clock: { [weak self] in self?.timelineNow() ?? .invalid } ) } diff --git a/electron/native/wgc-capture/src/audio_sample_utils.cpp b/electron/native/wgc-capture/src/audio_sample_utils.cpp index 07d35a162f..8964a0c5c2 100644 --- a/electron/native/wgc-capture/src/audio_sample_utils.cpp +++ b/electron/native/wgc-capture/src/audio_sample_utils.cpp @@ -898,6 +898,7 @@ AudioMixer::AudioMixer( bool includeSystem, bool includeMicrophone, double microphoneGain, + double systemGain, OutputCallback output) : format_(format), systemFormat_(systemFormat), @@ -905,6 +906,7 @@ AudioMixer::AudioMixer( includeSystem_(includeSystem), includeMicrophone_(includeMicrophone), microphoneGain_(microphoneGain), + systemGain_(systemGain), output_(std::move(output)) {} AudioMixer::~AudioMixer() { @@ -1146,7 +1148,9 @@ void AudioMixer::mixLoop() { mixedChunk.assign(chunkBytes, 0); if (includeSystem_) { pop(systemQueue_, systemStarved_, sourceChunk, chunkBytes); - mixAudioInPlace(mixedChunk, sourceChunk.data(), static_cast(sourceChunk.size()), format_); + mixAudioInPlace( + mixedChunk, sourceChunk.data(), static_cast(sourceChunk.size()), format_, + systemGain_); } if (includeMicrophone_) { pop(microphoneQueue_, microphoneStarved_, sourceChunk, chunkBytes); diff --git a/electron/native/wgc-capture/src/audio_sample_utils.h b/electron/native/wgc-capture/src/audio_sample_utils.h index b1dafec4c8..18d784cc48 100644 --- a/electron/native/wgc-capture/src/audio_sample_utils.h +++ b/electron/native/wgc-capture/src/audio_sample_utils.h @@ -230,6 +230,7 @@ class AudioMixer { bool includeSystem, bool includeMicrophone, double microphoneGain, + double systemGain, OutputCallback output); ~AudioMixer(); @@ -262,6 +263,7 @@ class AudioMixer { bool includeSystem_ = false; bool includeMicrophone_ = false; double microphoneGain_ = 1.0; + double systemGain_ = 1.0; OutputCallback output_; std::mutex mutex_; std::condition_variable cv_; diff --git a/electron/native/wgc-capture/src/audio_sample_utils_test.cpp b/electron/native/wgc-capture/src/audio_sample_utils_test.cpp index 3654e5a78d..1d98eb1559 100644 --- a/electron/native/wgc-capture/src/audio_sample_utils_test.cpp +++ b/electron/native/wgc-capture/src/audio_sample_utils_test.cpp @@ -1290,7 +1290,7 @@ void runResampleContinuityFixedTests() { const AudioInputFormat sysFmt = makeFormat(MFAudioFormat_Float, 44100, 2, 32); const AudioInputFormat micFmt = makeFormat(MFAudioFormat_Float, 48000, 2, 32); AudioMixer mixer( - mixFmt, sysFmt, micFmt, true, true, 1.0, + mixFmt, sysFmt, micFmt, true, true, 1.0, 1.0, [](const BYTE*, DWORD, int64_t, int64_t) { return true; }); const std::vector sysSignal = stereoFloatDualSine(44100, 997.0, 501.0, 0.5, 4321); @@ -1466,7 +1466,7 @@ void runResampleContinuityFixedTests() { const AudioInputFormat mixFmt = makeFormat(MFAudioFormat_PCM, 44100, 2, 16); const AudioInputFormat sysFmt = makeFormat(MFAudioFormat_Float, 48000, 2, 32); AudioMixer mixer( - mixFmt, sysFmt, sysFmt, true, false, 1.0, + mixFmt, sysFmt, sysFmt, true, false, 1.0, 1.0, [](const BYTE*, DWORD, int64_t, int64_t) { return true; }); std::vector preGap(150 * sysFmt.blockAlign, 0); @@ -1509,7 +1509,7 @@ void runResampleContinuityFixedTests() { const AudioInputFormat intMixFmt = makeFormat(MFAudioFormat_PCM, 48000, 2, 16); const AudioInputFormat intSrcFmt = makeFormat(MFAudioFormat_Float, 96000, 2, 32); AudioMixer intMixer( - intMixFmt, intSrcFmt, intSrcFmt, true, false, 1.0, + intMixFmt, intSrcFmt, intSrcFmt, true, false, 1.0, 1.0, [](const BYTE*, DWORD, int64_t, int64_t) { return true; }); AudioDecimatorState intContinuing; std::vector intPiece; @@ -1541,7 +1541,7 @@ void runResampleContinuityFixedTests() { const AudioInputFormat sameMixFmt = makeFormat(MFAudioFormat_PCM, 48000, 2, 16); const AudioInputFormat sameSrcFmt = makeFormat(MFAudioFormat_Float, 48000, 2, 32); AudioMixer sameMixer( - sameMixFmt, sameSrcFmt, sameSrcFmt, true, false, 1.0, + sameMixFmt, sameSrcFmt, sameSrcFmt, true, false, 1.0, 1.0, [](const BYTE*, DWORD, int64_t, int64_t) { return true; }); sameMixer.pushSystem(preGap.data(), static_cast(preGap.size())); AudioMixerTestAccess::setSystemStarved(sameMixer, true); @@ -2643,7 +2643,7 @@ int main(int argc, char** argv) { size_t zeroChunks = 0; AudioMixer mixer( - target48k, system96k, mic48k, true, includeMic, 1.0, + target48k, system96k, mic48k, true, includeMic, 1.0, 1.0, [&](const BYTE* data, DWORD byteCount, int64_t, int64_t) { std::scoped_lock lock(guard); chunkCount += 1; @@ -2780,11 +2780,11 @@ int main(int argc, char** argv) { return bytes; }; const auto steadySample = [&](bool includeSystem, double system, double mic, - double gain) -> int { + double gain, double systemGain = 1.0) -> int { std::mutex guard; std::vector collected; AudioMixer mixer( - target48k, f32stereo, f32stereo, includeSystem, true, gain, + target48k, f32stereo, f32stereo, includeSystem, true, gain, systemGain, [&](const BYTE* data, DWORD byteCount, int64_t, int64_t) { std::scoped_lock lock(guard); collected.insert(collected.end(), data, data + byteCount); @@ -2850,6 +2850,16 @@ int main(int argc, char** argv) { std::cout << "GAIN_RAW unity " << detail << std::endl; expect("mixer-unity-gain-passthrough", std::abs(got - 29490) <= 2, detail); } + // (4) The system stream carries its own gain: 0.8 * 0.5 + 0.3 = 0.7 + // -> 22937. A mixer that ignored systemGain would read 0.8 + 0.3 = 1.1 + // clamped at the rail instead. + { + const int got = steadySample(true, 0.8, 0.3, 1.0, 0.5); + char detail[96]{}; + sprintf_s(detail, "got=%d want=22937", got); + std::cout << "GAIN_RAW system-gain " << detail << std::endl; + expect("mixer-system-gain-applied-at-mix", std::abs(got - 22937) <= 2, detail); + } } // --- Capture jitter: the mixer's cushion (getopenscreen/openscreen#911) --- @@ -2897,7 +2907,7 @@ int main(int argc, char** argv) { std::mutex guard; std::vector left; AudioMixer mixer( - target48k, f32, f32, includeSystem, includeMic, 1.0, + target48k, f32, f32, includeSystem, includeMic, 1.0, 1.0, [&](const BYTE* data, DWORD byteCount, int64_t, int64_t) { std::scoped_lock lock(guard); const auto* samples = reinterpret_cast(data); diff --git a/electron/native/wgc-capture/src/main.cpp b/electron/native/wgc-capture/src/main.cpp index fe38c8a17d..1dc78156a6 100644 --- a/electron/native/wgc-capture/src/main.cpp +++ b/electron/native/wgc-capture/src/main.cpp @@ -58,6 +58,7 @@ struct CaptureConfig { std::string microphoneDeviceId; std::string microphoneDeviceName; double microphoneGain = 1.0; + double systemGain = 1.0; std::string webcamDeviceId; std::string webcamDeviceName; std::string webcamDirectShowClsid; @@ -592,6 +593,7 @@ bool parseConfig(const std::string& json, CaptureConfig& config) { config.microphoneDeviceId = findString(json, "microphoneDeviceId"); config.microphoneDeviceName = findString(json, "microphoneDeviceName"); config.microphoneGain = findDouble(json, "microphoneGain", 1.0); + config.systemGain = findDouble(json, "systemGain", 1.0); config.webcamDeviceId = findString(json, "webcamDeviceId"); config.webcamDeviceName = findString(json, "webcamDeviceName"); config.webcamDirectShowClsid = findString(json, "webcamDirectShowClsid"); @@ -1424,6 +1426,7 @@ int wmain(int argc, wchar_t* argv[]) { config.captureSystemAudio, config.captureMic, config.microphoneGain, + config.systemGain, [&](const BYTE* data, DWORD byteCount, int64_t timestampHns, int64_t durationHns) { if (!encoder.writeAudio(data, byteCount, timestampHns, durationHns)) { encodeFailed = true; diff --git a/src/components/ai-edition/v4/RecStage.test.tsx b/src/components/ai-edition/v4/RecStage.test.tsx index 49230e2784..be13f65db0 100644 --- a/src/components/ai-edition/v4/RecStage.test.tsx +++ b/src/components/ai-edition/v4/RecStage.test.tsx @@ -420,6 +420,8 @@ describe("RecStage controls", () => { camDeviceName: null, camQuality: "2160p", systemAudioEnabled: false, + micGainDb: 0, + systemAudioGainDb: 0, cursorCaptureMode: "editable-overlay", hideDesktopIcons: false, autoZoomEnabled: true, @@ -632,6 +634,8 @@ describe("RecStage controls", () => { camDeviceName: null, camQuality: "2160p", systemAudioEnabled: false, + micGainDb: 0, + systemAudioGainDb: 0, cursorCaptureMode: "editable-overlay", hideDesktopIcons: false, autoZoomEnabled: true, diff --git a/src/components/launch/HudDeviceSettings.quality.test.tsx b/src/components/launch/HudDeviceSettings.quality.test.tsx index 126ce93148..00e3e167ea 100644 --- a/src/components/launch/HudDeviceSettings.quality.test.tsx +++ b/src/components/launch/HudDeviceSettings.quality.test.tsx @@ -19,6 +19,9 @@ const labels: HudDeviceSettingsLabels = { camera: "Camera", micLevel: "Input level", micHint: "Speak to check", + micGain: "Microphone volume", + systemAudio: "System audio", + systemGain: "Computer volume", noMicrophones: "No microphone found", searching: "Searching...", noCameras: "No camera found", @@ -55,6 +58,10 @@ function renderPanel(overrides: Partial[0]> checkingForUpdates={false} cameraQuality="1440p" onSelectCameraQuality={onSelectCameraQuality} + micGainDb={0} + systemGainDb={0} + onMicGainChange={vi.fn()} + onSystemGainChange={vi.fn()} onSelectMic={vi.fn()} onSelectCamera={vi.fn()} onCheckForUpdates={vi.fn()} diff --git a/src/components/launch/HudDeviceSettings.tsx b/src/components/launch/HudDeviceSettings.tsx index 164b2f370a..84343c4940 100644 --- a/src/components/launch/HudDeviceSettings.tsx +++ b/src/components/launch/HudDeviceSettings.tsx @@ -1,10 +1,11 @@ import { Check, X } from "lucide-react"; -import { memo, useEffect, useRef } from "react"; +import { type CSSProperties, memo, useEffect, useRef } from "react"; import { useAudioLevelMeter } from "../../hooks/useAudioLevelMeter"; import type { CameraDevice } from "../../hooks/useCameraDevices"; import { useCameraPreviewStream } from "../../hooks/useCameraPreviewStream"; import type { MicrophoneDevice } from "../../hooks/useMicrophoneDevices"; import { WEBCAM_QUALITY_IDS, type WebcamQualityId } from "../../hooks/webcamCaptureTarget"; +import { RECORDING_GAIN_DB_MAX, RECORDING_GAIN_DB_MIN } from "../../lib/audioMix"; import { Tooltip } from "../ui/tooltip"; import styles from "./LaunchWindow.module.css"; @@ -18,6 +19,9 @@ export interface HudDeviceSettingsLabels { camera: string; micLevel: string; micHint: string; + micGain: string; + systemAudio: string; + systemGain: string; noMicrophones: string; searching: string; noCameras: string; @@ -46,6 +50,43 @@ const LevelMeter = memo(function LevelMeter({ level }: { level: number }) { ); }); +/** Pre-recording volume trim, in dB. The value rides the recording request; + * it does not retune a take already in flight. */ +function GainSlider({ + label, + value, + onChange, + testId, +}: { + label: string; + value: number; + onChange: (db: number) => void; + testId: string; +}) { + return ( +
+ {label} + onChange(Number(event.target.value))} + style={ + { + "--slider-pct": `${((value - RECORDING_GAIN_DB_MIN) / (RECORDING_GAIN_DB_MAX - RECORDING_GAIN_DB_MIN)) * 100}%`, + } as CSSProperties + } + className={styles.hudModalGainSlider} + /> + {value > 0 ? `+${value}` : value} dB +
+ ); +} + function CameraPreview({ stream, error, @@ -102,6 +143,10 @@ export const HudDeviceSettings = memo(function HudDeviceSettings({ checkingForUpdates, cameraQuality, onSelectCameraQuality, + micGainDb, + systemGainDb, + onMicGainChange, + onSystemGainChange, onSelectMic, onSelectCamera, onCheckForUpdates, @@ -124,6 +169,10 @@ export const HudDeviceSettings = memo(function HudDeviceSettings({ checkingForUpdates: boolean; cameraQuality: WebcamQualityId; onSelectCameraQuality: (quality: WebcamQualityId) => void; + micGainDb: number; + systemGainDb: number; + onMicGainChange: (db: number) => void; + onSystemGainChange: (db: number) => void; onSelectMic: (device: MicrophoneDevice) => void; onSelectCamera: (device: CameraDevice) => void; onCheckForUpdates: () => void; @@ -195,9 +244,23 @@ export const HudDeviceSettings = memo(function HudDeviceSettings({
{labels.micHint}
+ ) : null} +
{labels.systemAudio}
+ +
{labels.camera}
{cameraLoading ? (
{labels.searching}
diff --git a/src/components/launch/LaunchWindow.module.css b/src/components/launch/LaunchWindow.module.css index 0f522b32ef..4837b762cc 100644 --- a/src/components/launch/LaunchWindow.module.css +++ b/src/components/launch/LaunchWindow.module.css @@ -211,6 +211,42 @@ color: rgba(255, 255, 255, 0.6); } +.hudModalGainRow { + display: flex; + align-items: center; + gap: 8px; + padding: 6px 10px; +} + +.hudModalGainSlider { + flex: 1; + min-width: 0; + height: 6px; + border-radius: 999px; + background: linear-gradient( + to right, + var(--brand) 0%, + var(--brand) var(--slider-pct, 0%), + var(--border-hi) var(--slider-pct, 0%), + var(--border-hi) 100% + ); + outline: none; + cursor: pointer; +} + +.hudModalGainSlider:focus-visible::-webkit-slider-thumb { + box-shadow: 0 2px 8px rgba(255, 255, 255, 0.32), 0 0 0 4px rgba(52, 178, 123, 0.35); +} + +.hudModalGainValue { + font-size: 12px; + color: rgba(255, 255, 255, 0.6); + white-space: nowrap; + min-width: 44px; + text-align: right; + font-variant-numeric: tabular-nums; +} + /* About block at the foot of the settings panel: version on the left, the update check on the right. Same 10px gutter as the meter rows above it so the panel keeps one left edge. */ .hudModalAboutRow { diff --git a/src/components/launch/LaunchWindow.tsx b/src/components/launch/LaunchWindow.tsx index 754b1adfac..02eb11c8f8 100644 --- a/src/components/launch/LaunchWindow.tsx +++ b/src/components/launch/LaunchWindow.tsx @@ -139,6 +139,10 @@ export function LaunchWindow() { setMicrophoneDeviceName, systemAudioEnabled, setSystemAudioEnabled, + micGainDb, + setMicGainDb, + systemAudioGainDb, + setSystemAudioGainDb, webcamEnabled, setWebcamEnabled, webcamDeviceId, @@ -974,6 +978,8 @@ export function LaunchWindow() { micDeviceId?: string; micDeviceName?: string; systemAudioEnabled?: boolean; + micGainDb?: number; + systemAudioGainDb?: number; cursorCaptureMode?: "editable-overlay" | "system"; }) => { void window.electronAPI?.setRecordingPrefs?.(patch).catch((error) => { @@ -990,6 +996,27 @@ export function LaunchWindow() { persistRecordingPrefs({ systemAudioEnabled: next }); }, [controlsLocked, persistRecordingPrefs, setSystemAudioEnabled, systemAudioEnabled]); + // Same guard as the camera quality picker: the gear is disabled mid-take but + // an open panel stays mounted. The trim rides the NEXT take's request, so a + // change here never retunes the one in flight. + const handleMicGainChange = useCallback( + (db: number) => { + if (controlsLocked) return; + setMicGainDb(db); + persistRecordingPrefs({ micGainDb: db }); + }, + [controlsLocked, persistRecordingPrefs, setMicGainDb], + ); + + const handleSystemGainChange = useCallback( + (db: number) => { + if (controlsLocked) return; + setSystemAudioGainDb(db); + persistRecordingPrefs({ systemAudioGainDb: db }); + }, + [controlsLocked, persistRecordingPrefs, setSystemAudioGainDb], + ); + const toggleCursorMode = useCallback(() => { if (controlsLocked) return; const next = cursorCaptureMode === "editable-overlay" ? "system" : "editable-overlay"; @@ -1206,6 +1233,9 @@ export function LaunchWindow() { camera: t("webcam.cameraDevice"), micLevel: t("deviceSettings.micLevel"), micHint: t("deviceSettings.micHint"), + micGain: t("deviceSettings.micGain"), + systemAudio: t("audio.systemAudio"), + systemGain: t("deviceSettings.systemGain"), noMicrophones: t("deviceSettings.noMicrophones"), searching: t("webcam.searching"), noCameras: t("webcam.noneFound"), @@ -1467,6 +1497,10 @@ export function LaunchWindow() { checkingForUpdates={isCheckingForUpdates} cameraQuality={webcamQuality} onSelectCameraQuality={handleSelectCameraQuality} + micGainDb={micGainDb} + systemGainDb={systemAudioGainDb} + onMicGainChange={handleMicGainChange} + onSystemGainChange={handleSystemGainChange} onSelectMic={handleSelectMicDevice} onSelectCamera={handleSelectCameraDevice} onCheckForUpdates={handleCheckForUpdates} diff --git a/src/hooks/useScreenRecorder.nativeMacStartWarning.test.tsx b/src/hooks/useScreenRecorder.nativeMacStartWarning.test.tsx index 4e4009e803..337a3524ff 100644 --- a/src/hooks/useScreenRecorder.nativeMacStartWarning.test.tsx +++ b/src/hooks/useScreenRecorder.nativeMacStartWarning.test.tsx @@ -102,7 +102,7 @@ describe("useScreenRecorder native macOS start warnings", () => { expect(api.startNativeMacRecording).toHaveBeenCalledWith( expect.objectContaining({ audio: { - system: { enabled: false }, + system: { enabled: false, gain: 1 }, microphone: expect.objectContaining({ enabled: true, deviceId: "chromium-device-id", diff --git a/src/hooks/useScreenRecorder.noCamera.test.tsx b/src/hooks/useScreenRecorder.noCamera.test.tsx index 4958a8fbf1..b0f7582b9e 100644 --- a/src/hooks/useScreenRecorder.noCamera.test.tsx +++ b/src/hooks/useScreenRecorder.noCamera.test.tsx @@ -33,6 +33,8 @@ function prefs(camEnabled: boolean): RecordingPrefs { camDeviceName: null, camQuality: "2160p", systemAudioEnabled: false, + micGainDb: 0, + systemAudioGainDb: 0, cursorCaptureMode: "editable-overlay", hideDesktopIcons: false, autoZoomEnabled: true, diff --git a/src/hooks/useScreenRecorder.prefsRace.test.tsx b/src/hooks/useScreenRecorder.prefsRace.test.tsx index ae84c2cd71..1c22681322 100644 --- a/src/hooks/useScreenRecorder.prefsRace.test.tsx +++ b/src/hooks/useScreenRecorder.prefsRace.test.tsx @@ -27,6 +27,8 @@ function prefs(micEnabled: boolean): RecordingPrefs { camDeviceName: null, camQuality: "2160p", systemAudioEnabled: false, + micGainDb: 0, + systemAudioGainDb: 0, cursorCaptureMode: "editable-overlay", hideDesktopIcons: false, autoZoomEnabled: true, diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts index 20a08dbf4b..907c2b4d29 100644 --- a/src/hooks/useScreenRecorder.ts +++ b/src/hooks/useScreenRecorder.ts @@ -2,7 +2,7 @@ import { fixWebmDuration } from "@fix-webm-duration/fix"; import { useCallback, useEffect, useRef, useState } from "react"; import { toast } from "sonner"; import { useScopedT } from "@/contexts/I18nContext"; -import { mixAudioTracks, nativeMicrophoneGain } from "@/lib/audioMix"; +import { mixAudioTracks, nativeMicrophoneGain, recordingGainScalar } from "@/lib/audioMix"; import { canTurnCameraOn } from "@/lib/cameraAvailability"; import { shouldRecordMicrophone } from "@/lib/microphoneAvailability"; import { @@ -115,6 +115,10 @@ type UseScreenRecorderReturn = { setWebcamDeviceName: (deviceName: string | undefined) => void; systemAudioEnabled: boolean; setSystemAudioEnabled: (enabled: boolean) => void; + micGainDb: number; + setMicGainDb: (db: number) => void; + systemAudioGainDb: number; + setSystemAudioGainDb: (db: number) => void; webcamEnabled: boolean; setWebcamEnabled: (enabled: boolean) => Promise; cursorCaptureMode: CursorCaptureMode; @@ -315,6 +319,8 @@ export function useScreenRecorder(): UseScreenRecorderReturn { const [webcamQuality, setWebcamQuality] = useState(DEFAULT_WEBCAM_QUALITY); const [webcamDeviceName, setWebcamDeviceName] = useState(undefined); const [systemAudioEnabled, setSystemAudioEnabled] = useState(false); + const [micGainDb, setMicGainDb] = useState(0); + const [systemAudioGainDb, setSystemAudioGainDb] = useState(0); const [webcamEnabled, setWebcamEnabledState] = useState(false); const [cursorCaptureMode, setCursorCaptureMode] = useState("editable-overlay"); const [softwareEncoderFallbackNoticeVisible, setSoftwareEncoderFallbackNoticeVisible] = @@ -343,6 +349,8 @@ export function useScreenRecorder(): UseScreenRecorderReturn { camDeviceName?: string | null; camQuality?: WebcamQualityId | null; systemAudioEnabled: boolean; + micGainDb?: number; + systemAudioGainDb?: number; cursorCaptureMode: CursorCaptureMode; }) => { if (cancelled) return; @@ -376,6 +384,8 @@ export function useScreenRecorder(): UseScreenRecorderReturn { } setWebcamQuality(webcamQualityFrom(prefs.camQuality)); setSystemAudioEnabled(prefs.systemAudioEnabled); + setMicGainDb(prefs.micGainDb ?? 0); + setSystemAudioGainDb(prefs.systemAudioGainDb ?? 0); setCursorCaptureMode(prefs.cursorCaptureMode); setRecordingPrefsLoaded(true); }; @@ -1358,13 +1368,14 @@ export function useScreenRecorder(): UseScreenRecorderReturn { audio: { system: { enabled: systemAudioEnabled, + gain: recordingGainScalar(systemAudioGainDb), }, microphone: { enabled: recordMicrophone, deviceId: microphoneDeviceId, deviceName: microphoneDeviceName, // Boosted only when the mic has to sit over system audio. - gain: nativeMicrophoneGain(systemAudioEnabled), + gain: nativeMicrophoneGain(systemAudioEnabled) * recordingGainScalar(micGainDb), }, }, webcam: { @@ -1525,13 +1536,14 @@ export function useScreenRecorder(): UseScreenRecorderReturn { audio: { system: { enabled: systemAudioEnabled, + gain: recordingGainScalar(systemAudioGainDb), }, microphone: { enabled: recordMicrophone, deviceId: microphoneDeviceId, deviceName: microphoneDeviceName, // Boosted only over system audio, like the Windows request above. - gain: nativeMicrophoneGain(systemAudioEnabled), + gain: nativeMicrophoneGain(systemAudioEnabled) * recordingGainScalar(micGainDb), }, }, webcam: { @@ -1647,7 +1659,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { fps: TARGET_FRAME_RATE, }, audio: { - system: { enabled: systemAudioEnabled }, + system: { enabled: systemAudioEnabled, gain: recordingGainScalar(systemAudioGainDb) }, microphone: { enabled: recordMicrophone, // The device LABEL, not the id. Chromium's deviceId is an opaque @@ -1659,7 +1671,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { // helper then fell back to the session default source. ...(microphoneDeviceName ? { deviceName: microphoneDeviceName } : {}), // Boosted only over system audio, like the Windows request above. - gain: nativeMicrophoneGain(systemAudioEnabled), + gain: nativeMicrophoneGain(systemAudioEnabled) * recordingGainScalar(micGainDb), }, }, cursor: { mode: cursorCaptureMode }, @@ -2185,6 +2197,8 @@ export function useScreenRecorder(): UseScreenRecorderReturn { const { context: mixingCtx, track: mixedTrack } = mixAudioTracks({ systemAudioTrack, micAudioTrack, + micGainDb, + systemGainDb: systemAudioGainDb, }); if (mixingCtx) { mixingContext.current = mixingCtx; @@ -2712,6 +2726,10 @@ export function useScreenRecorder(): UseScreenRecorderReturn { setWebcamDeviceName, systemAudioEnabled, setSystemAudioEnabled, + micGainDb, + setMicGainDb, + systemAudioGainDb, + setSystemAudioGainDb, webcamEnabled, setWebcamEnabled, cursorCaptureMode, diff --git a/src/i18n/locales/ar/launch.json b/src/i18n/locales/ar/launch.json index 538b34e262..de299ba912 100644 --- a/src/i18n/locales/ar/launch.json +++ b/src/i18n/locales/ar/launch.json @@ -99,6 +99,8 @@ "close": "إغلاق", "micLevel": "مستوى الإدخال", "micHint": "تحدّث لاختبار الميكروفون", + "micGain": "مستوى صوت الميكروفون", + "systemGain": "مستوى صوت الكمبيوتر", "noMicrophones": "لم يتم العثور على ميكروفون", "preview": "معاينة", "previewUnavailable": "المعاينة غير متاحة", diff --git a/src/i18n/locales/cs/launch.json b/src/i18n/locales/cs/launch.json index a5a63939a2..a85b8b4a67 100644 --- a/src/i18n/locales/cs/launch.json +++ b/src/i18n/locales/cs/launch.json @@ -99,6 +99,8 @@ "close": "Zavřít", "micLevel": "Úroveň vstupu", "micHint": "Mluvte pro kontrolu mikrofonu", + "micGain": "Hlasitost mikrofonu", + "systemGain": "Hlasitost zvuku počítače", "noMicrophones": "Mikrofon nenalezen", "preview": "Náhled", "previewUnavailable": "Náhled nedostupný", diff --git a/src/i18n/locales/de/launch.json b/src/i18n/locales/de/launch.json index 204b6e8589..895eb0c953 100644 --- a/src/i18n/locales/de/launch.json +++ b/src/i18n/locales/de/launch.json @@ -99,6 +99,8 @@ "close": "Schließen", "micLevel": "Eingangspegel", "micHint": "Sprich, um dein Mikrofon zu prüfen", + "micGain": "Mikrofonlautstärke", + "systemGain": "Computerlautstärke", "noMicrophones": "Kein Mikrofon gefunden", "preview": "Vorschau", "previewUnavailable": "Vorschau nicht verfügbar", diff --git a/src/i18n/locales/en/launch.json b/src/i18n/locales/en/launch.json index 4987f2396e..4ccc5e06ec 100644 --- a/src/i18n/locales/en/launch.json +++ b/src/i18n/locales/en/launch.json @@ -99,6 +99,8 @@ "close": "Close", "micLevel": "Input level", "micHint": "Speak to check your microphone", + "micGain": "Microphone volume", + "systemGain": "Computer volume", "noMicrophones": "No microphone found", "preview": "Preview", "previewUnavailable": "Preview unavailable", diff --git a/src/i18n/locales/es/launch.json b/src/i18n/locales/es/launch.json index fc230bba7f..fd0c35c317 100644 --- a/src/i18n/locales/es/launch.json +++ b/src/i18n/locales/es/launch.json @@ -99,6 +99,8 @@ "close": "Cerrar", "micLevel": "Nivel de entrada", "micHint": "Habla para probar tu micrófono", + "micGain": "Volumen del micrófono", + "systemGain": "Volumen del ordenador", "noMicrophones": "No se encontró ningún micrófono", "preview": "Vista previa", "previewUnavailable": "Vista previa no disponible", diff --git a/src/i18n/locales/fr/launch.json b/src/i18n/locales/fr/launch.json index b768831edf..4337bc039c 100644 --- a/src/i18n/locales/fr/launch.json +++ b/src/i18n/locales/fr/launch.json @@ -99,6 +99,8 @@ "close": "Fermer", "micLevel": "Niveau d'entrée", "micHint": "Parlez pour tester votre microphone", + "micGain": "Volume du micro", + "systemGain": "Volume de l'ordinateur", "noMicrophones": "Aucun microphone détecté", "preview": "Aperçu", "previewUnavailable": "Aperçu indisponible", diff --git a/src/i18n/locales/it/launch.json b/src/i18n/locales/it/launch.json index cad6d15516..bcb3519c57 100644 --- a/src/i18n/locales/it/launch.json +++ b/src/i18n/locales/it/launch.json @@ -99,6 +99,8 @@ "close": "Chiudi", "micLevel": "Livello di ingresso", "micHint": "Parla per testare il microfono", + "micGain": "Volume del microfono", + "systemGain": "Volume del computer", "noMicrophones": "Nessun microfono trovato", "preview": "Anteprima", "previewUnavailable": "Anteprima non disponibile", diff --git a/src/i18n/locales/ja-JP/launch.json b/src/i18n/locales/ja-JP/launch.json index aa6d4b5677..f0487f182b 100644 --- a/src/i18n/locales/ja-JP/launch.json +++ b/src/i18n/locales/ja-JP/launch.json @@ -99,6 +99,8 @@ "close": "閉じる", "micLevel": "入力レベル", "micHint": "マイクをテストするには話してください", + "micGain": "マイク音量", + "systemGain": "パソコンの音量", "noMicrophones": "マイクが見つかりません", "preview": "プレビュー", "previewUnavailable": "プレビューを利用できません", diff --git a/src/i18n/locales/ko-KR/launch.json b/src/i18n/locales/ko-KR/launch.json index 455a84146a..43c1e96633 100644 --- a/src/i18n/locales/ko-KR/launch.json +++ b/src/i18n/locales/ko-KR/launch.json @@ -99,6 +99,8 @@ "close": "닫기", "micLevel": "입력 레벨", "micHint": "마이크를 테스트하려면 말해 보세요", + "micGain": "마이크 볼륨", + "systemGain": "컴퓨터 소리 볼륨", "noMicrophones": "마이크를 찾을 수 없습니다", "preview": "미리 보기", "previewUnavailable": "미리 보기를 사용할 수 없습니다", diff --git a/src/i18n/locales/nl/launch.json b/src/i18n/locales/nl/launch.json index 0b668ab14b..771191b7e0 100644 --- a/src/i18n/locales/nl/launch.json +++ b/src/i18n/locales/nl/launch.json @@ -99,6 +99,8 @@ "close": "Sluiten", "micLevel": "Ingangsniveau", "micHint": "Spreek om je microfoon te testen", + "micGain": "Microfoonvolume", + "systemGain": "Computervolume", "noMicrophones": "Geen microfoon gevonden", "preview": "Voorbeeld", "previewUnavailable": "Voorbeeld niet beschikbaar", diff --git a/src/i18n/locales/pl/launch.json b/src/i18n/locales/pl/launch.json index 3ebecc4296..df4761a85e 100644 --- a/src/i18n/locales/pl/launch.json +++ b/src/i18n/locales/pl/launch.json @@ -99,6 +99,8 @@ "close": "Zamknij", "micLevel": "Poziom wejścia", "micHint": "Mów, aby sprawdzić mikrofon", + "micGain": "Głośność mikrofonu", + "systemGain": "Głośność dźwięku komputera", "noMicrophones": "Nie znaleziono mikrofonu", "preview": "Podgląd", "previewUnavailable": "Podgląd niedostępny", diff --git a/src/i18n/locales/pt-BR/launch.json b/src/i18n/locales/pt-BR/launch.json index 893576b96f..0403997408 100644 --- a/src/i18n/locales/pt-BR/launch.json +++ b/src/i18n/locales/pt-BR/launch.json @@ -99,6 +99,8 @@ "close": "Fechar", "micLevel": "Nível de entrada", "micHint": "Fale para testar seu microfone", + "micGain": "Volume do microfone", + "systemGain": "Volume do computador", "noMicrophones": "Nenhum microfone encontrado", "preview": "Pré-visualização", "previewUnavailable": "Pré-visualização indisponível", diff --git a/src/i18n/locales/ru/launch.json b/src/i18n/locales/ru/launch.json index a34023430a..912322a687 100644 --- a/src/i18n/locales/ru/launch.json +++ b/src/i18n/locales/ru/launch.json @@ -99,6 +99,8 @@ "close": "Закрыть", "micLevel": "Уровень входа", "micHint": "Скажите что-нибудь, чтобы проверить микрофон", + "micGain": "Громкость микрофона", + "systemGain": "Громкость звука компьютера", "noMicrophones": "Микрофон не найден", "preview": "Предпросмотр", "previewUnavailable": "Предпросмотр недоступен", diff --git a/src/i18n/locales/tr/launch.json b/src/i18n/locales/tr/launch.json index 929709e362..99ebf69a56 100644 --- a/src/i18n/locales/tr/launch.json +++ b/src/i18n/locales/tr/launch.json @@ -99,6 +99,8 @@ "close": "Kapat", "micLevel": "Giriş seviyesi", "micHint": "Mikrofonunuzu test etmek için konuşun", + "micGain": "Mikrofon ses düzeyi", + "systemGain": "Bilgisayar ses düzeyi", "noMicrophones": "Mikrofon bulunamadı", "preview": "Önizleme", "previewUnavailable": "Önizleme kullanılamıyor", diff --git a/src/i18n/locales/vi/launch.json b/src/i18n/locales/vi/launch.json index fe3ce29fa3..723c7f1e29 100644 --- a/src/i18n/locales/vi/launch.json +++ b/src/i18n/locales/vi/launch.json @@ -99,6 +99,8 @@ "close": "Đóng", "micLevel": "Mức đầu vào", "micHint": "Hãy nói để kiểm tra micrô", + "micGain": "Âm lượng micrô", + "systemGain": "Âm lượng máy tính", "noMicrophones": "Không tìm thấy micrô", "preview": "Xem trước", "previewUnavailable": "Không thể xem trước", diff --git a/src/i18n/locales/zh-CN/launch.json b/src/i18n/locales/zh-CN/launch.json index b53025f9c4..168146dc3f 100644 --- a/src/i18n/locales/zh-CN/launch.json +++ b/src/i18n/locales/zh-CN/launch.json @@ -99,6 +99,8 @@ "close": "关闭", "micLevel": "输入音量", "micHint": "说话试试,检查麦克风是否正常", + "micGain": "麦克风音量", + "systemGain": "电脑声音音量", "noMicrophones": "未找到麦克风", "preview": "预览", "previewUnavailable": "预览不可用", diff --git a/src/i18n/locales/zh-TW/launch.json b/src/i18n/locales/zh-TW/launch.json index 03d134c201..a7fc436d7f 100644 --- a/src/i18n/locales/zh-TW/launch.json +++ b/src/i18n/locales/zh-TW/launch.json @@ -99,6 +99,8 @@ "close": "關閉", "micLevel": "輸入音量", "micHint": "說話以測試麥克風", + "micGain": "麥克風音量", + "systemGain": "電腦聲音音量", "noMicrophones": "找不到麥克風", "preview": "預覽", "previewUnavailable": "預覽無法使用", diff --git a/src/lib/audioMix.test.ts b/src/lib/audioMix.test.ts index ba2443f001..6b7d397b38 100644 --- a/src/lib/audioMix.test.ts +++ b/src/lib/audioMix.test.ts @@ -125,6 +125,50 @@ describe("mixAudioTracks", () => { expect(result.track).toBeNull(); }); + it("applies the user's mic trim on top of the automatic mix gain", () => { + const fakeCtx = stubAudioContext(0.5); + + const result = mixAudioTracks({ + systemAudioTrack: track("sys"), + micAudioTrack: track("mic"), + micGainDb: 6, + }); + + expect(result.context).toBe(fakeCtx); + const [gain] = fakeCtx.createGain.mock.results.map((r) => r.value) as FakeGainNode[]; + // +6 dB is ~1.9953; the boost still applies because system audio is present. + expect(gain.gain.linearRampToValueAtTime).toHaveBeenCalledWith( + MIC_GAIN_BOOST * 10 ** (6 / 20), + 0.5 + MIC_FADE_IN_S, + ); + }); + + it("routes system-only audio through a GainNode when the user trims it", () => { + const fakeCtx = stubAudioContext(0.5); + + const result = mixAudioTracks({ + systemAudioTrack: track("sys"), + micAudioTrack: null, + systemGainDb: -6, + }); + + expect(result.context).toBe(fakeCtx); + const [trim] = fakeCtx.createGain.mock.results.map((r) => r.value) as FakeGainNode[]; + expect(trim.gain.value).toBeCloseTo(10 ** (-6 / 20), 6); + expect(result.track).toEqual({ kind: "audio", id: "dest-track" }); + }); + + it("keeps system-only audio verbatim at unity trim", () => { + const system = track("sys"); + const result = mixAudioTracks({ + systemAudioTrack: system, + micAudioTrack: null, + systemGainDb: 0, + }); + expect(result.context).toBeNull(); + expect(result.track).toBe(system); + }); + it("creates an AudioContext, fades the mic gain from 0 to MIC_GAIN_BOOST over MIC_FADE_IN_S, and returns the destination track when both inputs are present", () => { const fakeCtx = stubAudioContext(0.5); diff --git a/src/lib/audioMix.ts b/src/lib/audioMix.ts index d17980aacd..1935bd2cc7 100644 --- a/src/lib/audioMix.ts +++ b/src/lib/audioMix.ts @@ -24,9 +24,23 @@ export function nativeMicrophoneGain(systemAudioEnabled: boolean): number { */ export const MIC_FADE_IN_S = 0.02; +/** Bounds of the user's pre-recording volume trims, shared by the settings + * validation and the HUD sliders so both ends agree on what a legal value is. */ +export const RECORDING_GAIN_DB_MIN = -24; +export const RECORDING_GAIN_DB_MAX = 12; + +/** dB to the linear scalar the mixers multiply by (native helper and GainNode alike). */ +export function recordingGainScalar(gainDb: number): number { + return 10 ** (gainDb / 20); +} + export type MixAudioTracksInput = { systemAudioTrack?: MediaStreamTrack | null | undefined; micAudioTrack?: MediaStreamTrack | null | undefined; + /** User trim on the microphone, dB on top of the automatic mix gain. */ + micGainDb?: number; + /** User trim on the computer audio, dB. */ + systemGainDb?: number; }; export type MixAudioTracksResult = { @@ -46,25 +60,46 @@ export type MixAudioTracksResult = { * sit over system audio; on its own it rides at unity so mic-only loudness is unchanged. * Caller owns the returned `context` and must `.close()` it on teardown. * - * - System audio only: returned verbatim, no AudioContext created (no warm-up click). + * - System audio only at unity trim: returned verbatim, no AudioContext created + * (no warm-up click). A non-unity system trim routes it through a GainNode. * - Neither present: returns `{ context: null, track: null }`. */ export function mixAudioTracks({ systemAudioTrack, micAudioTrack, + micGainDb = 0, + systemGainDb = 0, }: MixAudioTracksInput): MixAudioTracksResult { + const systemGain = recordingGainScalar(systemGainDb); if (!micAudioTrack) { - return { context: null, track: systemAudioTrack ?? null }; + if (!systemAudioTrack || systemGain === 1) { + return { context: null, track: systemAudioTrack ?? null }; + } + const context = new AudioContext(); + const destination = context.createMediaStreamDestination(); + const systemSource = context.createMediaStreamSource(new MediaStream([systemAudioTrack])); + const trim = context.createGain(); + trim.gain.value = systemGain; + systemSource.connect(trim).connect(destination); + return { context, track: destination.stream.getAudioTracks()[0] }; } const context = new AudioContext(); const destination = context.createMediaStreamDestination(); if (systemAudioTrack) { const systemSource = context.createMediaStreamSource(new MediaStream([systemAudioTrack])); - systemSource.connect(destination); + if (systemGain === 1) { + systemSource.connect(destination); + } else { + const trim = context.createGain(); + trim.gain.value = systemGain; + systemSource.connect(trim).connect(destination); + } } - // Unity when the mic is on its own; boosted only when competing with system audio. - const micTargetGain = nativeMicrophoneGain(Boolean(systemAudioTrack)); + // Unity when the mic is on its own; boosted only when competing with system + // audio. The user's trim multiplies whichever base applies. + const micTargetGain = + nativeMicrophoneGain(Boolean(systemAudioTrack)) * recordingGainScalar(micGainDb); const micSource = context.createMediaStreamSource(new MediaStream([micAudioTrack])); const micGain = context.createGain(); micGain.gain.setValueAtTime(0, context.currentTime); diff --git a/src/lib/nativeLinuxRecording.ts b/src/lib/nativeLinuxRecording.ts index 2a1288864b..1ba69e4693 100644 --- a/src/lib/nativeLinuxRecording.ts +++ b/src/lib/nativeLinuxRecording.ts @@ -26,6 +26,8 @@ export type NativeLinuxRecordingRequest = { audio: { system: { enabled: boolean; + /** Linear user trim; absent means unity. */ + gain?: number; }; microphone: { enabled: boolean; diff --git a/src/lib/nativeMacRecording.ts b/src/lib/nativeMacRecording.ts index 257035638b..8ed796e4ed 100644 --- a/src/lib/nativeMacRecording.ts +++ b/src/lib/nativeMacRecording.ts @@ -27,6 +27,8 @@ export type NativeMacRecordingRequest = { audio: { system: { enabled: boolean; + /** Linear user trim; absent means unity. */ + gain?: number; }; microphone: { enabled: boolean; diff --git a/src/lib/nativeWindowsRecording.ts b/src/lib/nativeWindowsRecording.ts index 5d5d92b315..2d60cbf5e0 100644 --- a/src/lib/nativeWindowsRecording.ts +++ b/src/lib/nativeWindowsRecording.ts @@ -17,6 +17,8 @@ export type NativeWindowsRecordingRequest = { audio: { system: { enabled: boolean; + /** Linear user trim; absent means unity (older request builders). */ + gain?: number; }; microphone: { enabled: boolean; diff --git a/src/native/browserShim.ts b/src/native/browserShim.ts index 7643f32969..60a99e2cd3 100644 --- a/src/native/browserShim.ts +++ b/src/native/browserShim.ts @@ -57,6 +57,8 @@ type ShimRecordingPrefs = { camDeviceId: string | null; camDeviceName: string | null; systemAudioEnabled: boolean; + micGainDb: number; + systemAudioGainDb: number; cursorCaptureMode: "editable-overlay" | "system"; autoZoomEnabled: boolean; }; @@ -69,6 +71,8 @@ let shimRecordingPrefs: ShimRecordingPrefs = { camDeviceId: null, camDeviceName: null, systemAudioEnabled: false, + micGainDb: 0, + systemAudioGainDb: 0, cursorCaptureMode: "editable-overlay", autoZoomEnabled: true, }; From 77ab3dc39cec525d87c0a70fdaebb541efabe582 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E4=B8=AA=E6=88=90=E7=86=9F=E7=9A=84=E5=89=AA?= =?UTF-8?q?=E8=BE=91=E7=8C=BF?= <297668904+akahoz94@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:49:00 +0800 Subject: [PATCH 2/8] fix(audio): apply pre-record gain trims without distortion or stale values CodeRabbit review follow-ups for the volume-trims PR: - pipewire: keep an explicit gain of 0 (silence); only an absent gain falls back to unity, for both system and microphone sources. - wgc mixer: accumulate the gain-scaled system and microphone sources in a wider double domain and clamp the combined result once, so a boosted source cannot hit the rail before the opposite polarity is added. - HUD: lock gain controls from the record press through the countdown (including the Linux portal-preparation window) until recording starts; the countdown captures an earlier startRecording closure, so a trim changed mid-countdown would show but be ignored by the take. - linux IPC: include the system gain in the prepared-session key so a changed gain invalidates reuse of a helper spawned at the old gain. --- electron/ipc/handlers.ts | 1 + electron/native/pipewire-capture/src/main.rs | 5 +- .../wgc-capture/src/audio_sample_utils.cpp | 83 +++++++++++++++++-- .../src/audio_sample_utils_test.cpp | 22 +++++ src/components/launch/LaunchWindow.test.tsx | 10 +++ src/components/launch/LaunchWindow.tsx | 7 +- src/hooks/useScreenRecorder.ts | 16 +++- 7 files changed, 131 insertions(+), 13 deletions(-) diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts index 55633f2652..e269abfd77 100644 --- a/electron/ipc/handlers.ts +++ b/electron/ipc/handlers.ts @@ -1029,6 +1029,7 @@ function captureSettingsOf(request: NativeLinuxRecordingRequest): string { fps: request.video?.fps ?? null, bitrate: request.video?.bitrate ?? null, system: request.audio?.system?.enabled ?? false, + systemGain: request.audio?.system?.gain ?? 1, microphone: request.audio?.microphone?.enabled ?? false, deviceName: request.audio?.microphone?.deviceName ?? null, gain: request.audio?.microphone?.gain ?? null, diff --git a/electron/native/pipewire-capture/src/main.rs b/electron/native/pipewire-capture/src/main.rs index 732139dc15..6d44407134 100644 --- a/electron/native/pipewire-capture/src/main.rs +++ b/electron/native/pipewire-capture/src/main.rs @@ -201,7 +201,8 @@ impl Request { // The default SINK's monitor: what is being played, not what a // microphone hears. capture_sink: true, - gain: audio.system.gain.filter(|gain| *gain > 0.0).unwrap_or(1.0), + // An explicit 0 means silence; only an absent gain falls back to unity. + gain: audio.system.gain.unwrap_or(1.0), bitrate: DEFAULT_AUDIO_BITRATE, }); } @@ -210,7 +211,7 @@ impl Request { label: "microphone", target: audio.microphone.device_name.clone(), capture_sink: false, - gain: audio.microphone.gain.filter(|gain| *gain > 0.0).unwrap_or(1.0), + gain: audio.microphone.gain.unwrap_or(1.0), bitrate: DEFAULT_AUDIO_BITRATE, }); } diff --git a/electron/native/wgc-capture/src/audio_sample_utils.cpp b/electron/native/wgc-capture/src/audio_sample_utils.cpp index 8964a0c5c2..8763f026b8 100644 --- a/electron/native/wgc-capture/src/audio_sample_utils.cpp +++ b/electron/native/wgc-capture/src/audio_sample_utils.cpp @@ -879,6 +879,68 @@ void mixAudioInPlace( } } +// Mixes up to two gain-scaled sources into a destination that starts as +// silence, accumulating in the destination's native numeric domain and clamping +// the COMBINED result exactly once. Applying each gain through a separate +// mixAudioInPlace clamps a boosted source to the rail before an +// opposite-polarity source can cancel it (clamp-then-sum); the wider double +// accumulator here preserves that headroom (sum-then-clamp). +// The destination is zero-filled by the caller, so it contributes nothing. +void mixTwoSourcesIntoSilence( + std::vector& destination, + const BYTE* systemSource, + double systemGain, + const BYTE* microphoneSource, + double microphoneGain, + const AudioInputFormat& format) { + const size_t bytesPer = bytesPerSample(format); + if (destination.empty() || bytesPer == 0) { + return; + } + const auto readRaw = [&](const BYTE* src, size_t index) -> double { + if (!src) { + return 0.0; + } + if (isFloatFormat(format)) { + return static_cast(reinterpret_cast(src)[index]); + } + if (isPcmFormat(format, 16)) { + return static_cast(reinterpret_cast(src)[index]); + } + if (isPcmFormat(format, 32)) { + return static_cast(reinterpret_cast(src)[index]); + } + return 0.0; + }; + const size_t sampleCount = destination.size() / bytesPer; + if (isFloatFormat(format)) { + auto* output = reinterpret_cast(destination.data()); + for (size_t i = 0; i < sampleCount; ++i) { + const double sum = + readRaw(systemSource, i) * systemGain + readRaw(microphoneSource, i) * microphoneGain; + output[i] = static_cast(std::clamp(sum, -1.0, 1.0)); + } + return; + } + if (isPcmFormat(format, 16)) { + auto* output = reinterpret_cast(destination.data()); + for (size_t i = 0; i < sampleCount; ++i) { + const double sum = + readRaw(systemSource, i) * systemGain + readRaw(microphoneSource, i) * microphoneGain; + output[i] = clampTo(sum); + } + return; + } + if (isPcmFormat(format, 32)) { + auto* output = reinterpret_cast(destination.data()); + for (size_t i = 0; i < sampleCount; ++i) { + const double sum = + readRaw(systemSource, i) * systemGain + readRaw(microphoneSource, i) * microphoneGain; + output[i] = clampTo(sum); + } + } +} + namespace { // How far behind real time AudioMixer writes; see mixLoop. Wider than the capture @@ -1123,7 +1185,8 @@ void AudioMixer::mixLoop() { const size_t chunkBytes = static_cast(chunkFrames) * format_.blockAlign; const uint64_t cushionFrames = static_cast(format_.sampleRate) * MixerCushionMs / 1000; std::vector mixedChunk; - std::vector sourceChunk; + std::vector systemChunk; + std::vector microphoneChunk; // This loop's copy of `clockStart_`, taken under the lock at the top of each // pass: beginTimeline and a resume move it from other threads. std::chrono::steady_clock::time_point clockStart; @@ -1147,17 +1210,19 @@ void AudioMixer::mixLoop() { std::scoped_lock lock(mutex_); mixedChunk.assign(chunkBytes, 0); if (includeSystem_) { - pop(systemQueue_, systemStarved_, sourceChunk, chunkBytes); - mixAudioInPlace( - mixedChunk, sourceChunk.data(), static_cast(sourceChunk.size()), format_, - systemGain_); + pop(systemQueue_, systemStarved_, systemChunk, chunkBytes); } if (includeMicrophone_) { - pop(microphoneQueue_, microphoneStarved_, sourceChunk, chunkBytes); - mixAudioInPlace( - mixedChunk, sourceChunk.data(), static_cast(sourceChunk.size()), format_, - microphoneGain_); + pop(microphoneQueue_, microphoneStarved_, microphoneChunk, chunkBytes); } + // Accumulate both sources in a wider double domain and clamp the + // sum once, so a boosted stream cannot hit the rail before the + // other stream's opposite polarity is added. + mixTwoSourcesIntoSilence( + mixedChunk, + includeSystem_ ? systemChunk.data() : nullptr, systemGain_, + includeMicrophone_ ? microphoneChunk.data() : nullptr, microphoneGain_, + format_); mixedFrames_ = emittedFrames_ + chunkFrames; } diff --git a/electron/native/wgc-capture/src/audio_sample_utils_test.cpp b/electron/native/wgc-capture/src/audio_sample_utils_test.cpp index 1d98eb1559..4e021be477 100644 --- a/electron/native/wgc-capture/src/audio_sample_utils_test.cpp +++ b/electron/native/wgc-capture/src/audio_sample_utils_test.cpp @@ -2850,6 +2850,28 @@ int main(int argc, char** argv) { std::cout << "GAIN_RAW unity " << detail << std::endl; expect("mixer-unity-gain-passthrough", std::abs(got - 29490) <= 2, detail); } + // (4b) A boosted system source that alone exceeds full scale must not be + // pinned to the rail before the opposite-polarity microphone is added: + // 0.8 * 2.0 - 0.5 * 1.0 = 1.1 -> clamped once at the rail. With + // 0.8 * 2.0 - 0.5 * 1.4 = 0.9 -> 29490, sum-then-clamp keeps the headroom + // that clamp-then-sum (which read 1.0 - 0.7 = 0.3) destroyed. + { + const int got = steadySample(true, 0.8, -0.5, 1.4, 2.0); + char detail[96]{}; + sprintf_s(detail, "got=%d want=29490", got); + std::cout << "GAIN_RAW boosted-system " << detail << std::endl; + expect("mixer-boosted-system-sum-before-clamp", std::abs(got - 29490) <= 2, detail); + } + // (4c) The same boost summed at the rail: 0.8 * 2.0 + 0.9 * 1.0 = 2.5 + // -> clamped once to 1.0 (32767). + { + const int got = steadySample(true, 0.8, 0.9, 1.0, 2.0); + char detail[96]{}; + sprintf_s(detail, "got=%d want=32767", got); + std::cout << "GAIN_RAW boosted-system-rail " << detail << std::endl; + expect("mixer-boosted-system-clamps-once-at-rail", got >= 32766, detail); + } + // (4) The system stream carries its own gain: 0.8 * 0.5 + 0.3 = 0.7 // -> 22937. A mixer that ignored systemGain would read 0.8 + 0.3 = 1.1 // clamped at the rail instead. diff --git a/src/components/launch/LaunchWindow.test.tsx b/src/components/launch/LaunchWindow.test.tsx index e72c7ac5a9..99c6007e3f 100644 --- a/src/components/launch/LaunchWindow.test.tsx +++ b/src/components/launch/LaunchWindow.test.tsx @@ -55,6 +55,7 @@ const recorderState = vi.hoisted(() => ({ paused: false, saving: false, elapsedSeconds: 0, + startingCountdown: false, toggleRecording: vi.fn(), togglePaused: vi.fn(), canPauseRecording: false, @@ -74,6 +75,10 @@ const recorderState = vi.hoisted(() => ({ setWebcamQuality: vi.fn(), systemAudioEnabled: false, setSystemAudioEnabled: vi.fn(), + micGainDb: 0, + setMicGainDb: vi.fn(), + systemAudioGainDb: 0, + setSystemAudioGainDb: vi.fn(), cursorCaptureMode: "editable-overlay", setCursorCaptureMode: vi.fn(), presenterOverlay: null as { active: boolean; cameraInterrupted: boolean } | null, @@ -366,6 +371,11 @@ function resetLaunchMocks() { recorderState.value.dismissSoftwareEncoderFallbackNotice.mockClear(); recorderState.value.presenterOverlay = null; recorderState.value.recording = false; + recorderState.value.startingCountdown = false; + recorderState.value.micGainDb = 0; + recorderState.value.setMicGainDb.mockClear(); + recorderState.value.systemAudioGainDb = 0; + recorderState.value.setSystemAudioGainDb.mockClear(); recorderState.value.canPauseRecording = false; recorderState.value.microphoneEnabled = false; recorderState.value.setMicrophoneEnabled.mockClear(); diff --git a/src/components/launch/LaunchWindow.tsx b/src/components/launch/LaunchWindow.tsx index 02eb11c8f8..708238e45e 100644 --- a/src/components/launch/LaunchWindow.tsx +++ b/src/components/launch/LaunchWindow.tsx @@ -126,6 +126,7 @@ export function LaunchWindow() { paused, saving, elapsedSeconds, + startingCountdown, toggleRecording, togglePaused, canPauseRecording, @@ -199,7 +200,11 @@ export function LaunchWindow() { const isVertical = trayLayout === "vertical"; const isPopoverOpen = isLanguageMenuOpen || isDeviceSettingsOpen; - const controlsLocked = recording || saving; + // Lock from the record press through the countdown (including the Linux portal + // preparation window) until recording starts. The countdown captured an earlier + // `startRecording` closure, so a trim changed mid-countdown would show on the + // slider but be ignored by the take. + const controlsLocked = recording || saving || startingCountdown; const settingsTriggerRef = useRef(null); const languageTriggerRef = useRef(null); diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts index 907c2b4d29..bade079d7a 100644 --- a/src/hooks/useScreenRecorder.ts +++ b/src/hooks/useScreenRecorder.ts @@ -94,6 +94,8 @@ type UseScreenRecorderReturn = { paused: boolean; saving: boolean; elapsedSeconds: number; + /** True from the record press until the countdown takes over (portal prep window). */ + startingCountdown: boolean; toggleRecording: () => void; /** Starts recording with no countdown overlay. Used by the headless CLI runner. */ startRecordingImmediately: () => Promise; @@ -458,6 +460,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { const countdownStarting = useRef(null); const cursorAccessibilityWarningShown = useRef(false); const [countdownActive, setCountdownActive] = useState(false); + const [startingCountdown, setStartingCountdown] = useState(false); const webcamReady = useRef(false); const webcamAcquireId = useRef(0); const canPauseRecording = @@ -1790,9 +1793,17 @@ export function useScreenRecorder(): UseScreenRecorderReturn { } const starting = {}; countdownStarting.current = starting; + // Publish a render-visible lock from this press onward, covering the Linux + // portal-preparation window before `countdownActive` is set. A gain edit + // there would move the slider but be missed by the `startRecording` + // closure this countdown captured. Kept separate from `countdownActive`: + // that flag gates press-to-cancel and must stay false until the countdown + // is actually showing (see #1340, the double-picker regression). + setStartingCountdown(true); try { await runRecordCountdown(); } finally { + setStartingCountdown(false); if (countdownStarting.current === starting) { countdownStarting.current = null; } @@ -1913,7 +1924,9 @@ export function useScreenRecorder(): UseScreenRecorderReturn { return; } - // From here `countdownActive` takes over, and a press cancels the countdown. + // From here `countdownActive` takes over: a press cancels the countdown. + // `startingCountdown` stays true until the whole countdown unwinds, so the + // HUD lock has no gap between the portal wait and the visible countdown. countdownStarting.current = null; setCountdownActive(true); @@ -2706,6 +2719,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { paused, saving, elapsedSeconds, + startingCountdown, toggleRecording, startRecordingImmediately: () => startRecording(), togglePaused, From 6c0dd4a699102c286344f5ba7377735582b1a2ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E4=B8=AA=E6=88=90=E7=86=9F=E7=9A=84=E5=89=AA?= =?UTF-8?q?=E8=BE=91=E7=8C=BF?= <297668904+akahoz94@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:54:07 +0800 Subject: [PATCH 3/8] fix(audio): scope the countdown gain lock to its owning run CodeRabbit follow-up: a cancelled countdown's finally released the HUD gain lock unconditionally, so a countdown restarted within the same tick could unlock its controls while the new take still used the old startRecording closure. Gate release on an ownership token so only the current run can drop the lock. Adds a regression that cancels and restarts before the stale finally settles. --- .../useScreenRecorder.startCancel.test.tsx | 46 +++++++++++++++++++ src/hooks/useScreenRecorder.ts | 19 +++++++- 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/src/hooks/useScreenRecorder.startCancel.test.tsx b/src/hooks/useScreenRecorder.startCancel.test.tsx index 993881c386..488f9d1cd0 100644 --- a/src/hooks/useScreenRecorder.startCancel.test.tsx +++ b/src/hooks/useScreenRecorder.startCancel.test.tsx @@ -256,3 +256,49 @@ describe("the immediate start reports its outcome", () => { expect(view.result.current.recording).toBe(true); }); }); + +describe("countdown gain lock belongs to the latest run", () => { + it("does not unlock when a cancelled countdown's finally settles after a new one starts", async () => { + stubElectronAPI("darwin"); + + // Hold run A at its overlay show; run B's show resolves immediately. + let releaseFirstShow!: () => void; + const firstShow = new Promise((resolve) => { + releaseFirstShow = () => resolve(true); + }); + let showCalls = 0; + api.showCountdownOverlay.mockImplementation(() => { + showCalls += 1; + return showCalls === 1 ? firstShow : Promise.resolve(true); + }); + + const view = renderHook(() => useScreenRecorder()); + await settle(); + + // A presses record, reaches the visible countdown, then hangs on its show. + await act(async () => { + view.result.current.toggleRecording(); + }); + await settle(); + expect(view.result.current.startingCountdown).toBe(true); + expect(showCalls).toBe(1); + + // Cancel A, then immediately press again to start B while A's show is pending. + await act(async () => { + view.result.current.toggleRecording(); + }); + await settle(); + await act(async () => { + view.result.current.toggleRecording(); + }); + await settle(); + expect(showCalls).toBe(2); + + // A's stale show now settles; its finally must not drop B's lock even though + // A's own countdown is long dead. The lock belongs to the newest run. + await act(async () => { + releaseFirstShow(); + }); + expect(view.result.current.startingCountdown).toBe(true); + }); +}); diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts index bade079d7a..a2112cd179 100644 --- a/src/hooks/useScreenRecorder.ts +++ b/src/hooks/useScreenRecorder.ts @@ -458,6 +458,14 @@ export function useScreenRecorder(): UseScreenRecorderReturn { * grant the user had just given the first (#1340). */ const countdownStarting = useRef(null); + /** + * Ownership token for the HUD gain lock. `countdownStarting` is cleared as soon + * as the countdown shows (see above), but the lock must survive through the + * visible countdown until the whole start unwinds. A stale run's `finally` must + * not drop a newer run's lock when a countdown is cancelled and restarted, so + * release is gated on this token rather than `countdownStarting`. + */ + const startingCountdownOwner = useRef(null); const cursorAccessibilityWarningShown = useRef(false); const [countdownActive, setCountdownActive] = useState(false); const [startingCountdown, setStartingCountdown] = useState(false); @@ -1793,6 +1801,8 @@ export function useScreenRecorder(): UseScreenRecorderReturn { } const starting = {}; countdownStarting.current = starting; + const owner = {}; + startingCountdownOwner.current = owner; // Publish a render-visible lock from this press onward, covering the Linux // portal-preparation window before `countdownActive` is set. A gain edit // there would move the slider but be missed by the `startRecording` @@ -1803,7 +1813,14 @@ export function useScreenRecorder(): UseScreenRecorderReturn { try { await runRecordCountdown(); } finally { - setStartingCountdown(false); + // Only the run that still owns the lock may release it. If countdown A + // was cancelled and B started before A's `await` settled, A's finally + // must leave B's lock intact; otherwise a gain edit during B would move + // the slider but be ignored by B's captured startRecording closure. + if (startingCountdownOwner.current === owner) { + startingCountdownOwner.current = null; + setStartingCountdown(false); + } if (countdownStarting.current === starting) { countdownStarting.current = null; } From c36c3a11ae959357f78bb9de211839a91480a960 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E4=B8=AA=E6=88=90=E7=86=9F=E7=9A=84=E5=89=AA?= =?UTF-8?q?=E8=BE=91=E7=8C=BF?= <297668904+akahoz94@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:29:02 +0800 Subject: [PATCH 4/8] fix(audio): keep captured gains visible while the countdown lock is held --- ...ScreenRecorder.countdownGainPrefs.test.tsx | 143 ++++++++++++++++++ src/hooks/useScreenRecorder.ts | 12 +- 2 files changed, 153 insertions(+), 2 deletions(-) create mode 100644 src/hooks/useScreenRecorder.countdownGainPrefs.test.tsx diff --git a/src/hooks/useScreenRecorder.countdownGainPrefs.test.tsx b/src/hooks/useScreenRecorder.countdownGainPrefs.test.tsx new file mode 100644 index 0000000000..9b96d26d06 --- /dev/null +++ b/src/hooks/useScreenRecorder.countdownGainPrefs.test.tsx @@ -0,0 +1,143 @@ +// @vitest-environment jsdom +import { act, cleanup, renderHook } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@/contexts/I18nContext", () => { + const translate = (key: string) => key; + return { useScopedT: () => translate }; +}); + +vi.mock("sonner", () => ({ + toast: { error: vi.fn(), success: vi.fn(), info: vi.fn(), warning: vi.fn() }, +})); + +vi.mock("@/lib/requestCameraAccess", () => ({ + requestCameraAccess: vi.fn(async () => ({ success: true, granted: true, status: "granted" })), +})); + +vi.mock("./recorderHandle", () => ({ + createRecorderHandle: vi.fn(() => ({ + recorder: { state: "inactive", stop: vi.fn(), addEventListener: vi.fn() }, + recordedBlobPromise: Promise.resolve(new Blob()), + isStreaming: () => false, + discard: vi.fn(async () => undefined), + })), +})); + +import { useScreenRecorder } from "./useScreenRecorder"; + +type ElectronAPI = Window["electronAPI"]; +type RecordingPrefs = Awaited>; + +const SOURCE = { id: "screen:0:0", name: "Screen 1", display_id: "1", thumbnail: "" }; + +function prefsWithGains(micGainDb: number, systemAudioGainDb: number): RecordingPrefs { + return { + micEnabled: false, + micDeviceId: null, + micDeviceName: null, + camEnabled: false, + camDeviceId: null, + camDeviceName: null, + camQuality: "1080p", + systemAudioEnabled: false, + micGainDb, + systemAudioGainDb, + cursorCaptureMode: "editable-overlay", + hideDesktopIcons: false, + autoZoomEnabled: true, + }; +} + +let onChange: ((next: RecordingPrefs) => void) | undefined; +let releaseCountdown!: () => void; +let api: Record>; + +beforeEach(() => { + vi.useFakeTimers(); + let countdownGate!: Promise; + releaseCountdown = () => undefined; + api = { + getRecordingPrefs: vi.fn(async () => prefsWithGains(0, 0)), + onRecordingPrefsChanged: vi.fn((callback: (next: RecordingPrefs) => void) => { + onChange = callback; + return () => { + onChange = undefined; + }; + }), + getPlatform: vi.fn(() => "darwin"), + getSelectedSource: vi.fn(async () => SOURCE), + setRecordingState: vi.fn(async () => ({ success: true })), + isNativeMacCaptureAvailable: vi.fn(async () => ({ success: true, available: false })), + startNativeMacRecording: vi.fn(async () => ({ success: false, error: "no capture" })), + stopNativeMacRecording: vi.fn(async () => ({ success: true, discarded: true })), + showCountdownOverlay: vi.fn(() => { + countdownGate = new Promise((resolve) => { + releaseCountdown = () => resolve(true); + }); + return countdownGate; + }), + setCountdownOverlayValue: vi.fn(async () => true), + hideCountdownOverlay: vi.fn(async () => true), + }; + window.electronAPI = api as unknown as ElectronAPI; + const track = { stop: vi.fn(), onended: null, getSettings: () => ({ width: 1280, height: 720 }) }; + const stream = { getTracks: () => [track], getVideoTracks: () => [track] }; + Object.defineProperty(navigator, "mediaDevices", { + configurable: true, + value: { + enumerateDevices: vi.fn(async () => []), + getUserMedia: vi.fn(async () => stream), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + }, + }); + vi.stubGlobal("MediaRecorder", { isTypeSupported: () => true }); +}); + +afterEach(() => { + cleanup(); + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + onChange = undefined; +}); + +describe("countdown startup lock and gain preference snapshots", () => { + it("keeps the captured gains on screen while the countdown holds the lock, then applies later snapshots", async () => { + const view = renderHook(() => useScreenRecorder()); + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + expect(view.result.current.startingCountdown).toBe(false); + + // Start a countdown and hold its overlay show pending so the lock stays held. + await act(async () => { + view.result.current.toggleRecording(); + }); + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + expect(view.result.current.startingCountdown).toBe(true); + + // Another window saves new gain levels mid-countdown. The take already + // captured 0/0, so the sliders must not move to -12/-6. + act(() => { + onChange?.(prefsWithGains(-12, -6)); + }); + expect(view.result.current.micGainDb).toBe(0); + expect(view.result.current.systemAudioGainDb).toBe(0); + + // Release the countdown; once the lock clears, a later snapshot applies. + await act(async () => { + releaseCountdown(); + await vi.advanceTimersByTimeAsync(3_500); + }); + expect(view.result.current.startingCountdown).toBe(false); + act(() => { + onChange?.(prefsWithGains(6, 3)); + }); + expect(view.result.current.micGainDb).toBe(6); + expect(view.result.current.systemAudioGainDb).toBe(3); + }); +}); diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts index a2112cd179..cd51202298 100644 --- a/src/hooks/useScreenRecorder.ts +++ b/src/hooks/useScreenRecorder.ts @@ -386,8 +386,16 @@ export function useScreenRecorder(): UseScreenRecorderReturn { } setWebcamQuality(webcamQualityFrom(prefs.camQuality)); setSystemAudioEnabled(prefs.systemAudioEnabled); - setMicGainDb(prefs.micGainDb ?? 0); - setSystemAudioGainDb(prefs.systemAudioGainDb ?? 0); + // A countdown can be holding the startup lock when a snapshot from another + // window arrives (see startRecordCountdown's `startingCountdownOwner`). That + // take already captured its gain values in the `startRecording` closure, so + // applying the new gain here would move the slider away from what is about + // to be recorded. Defer only these two fields until the lock is released; + // every other preference field keeps applying live as before. + if (!startingCountdownOwner.current) { + setMicGainDb(prefs.micGainDb ?? 0); + setSystemAudioGainDb(prefs.systemAudioGainDb ?? 0); + } setCursorCaptureMode(prefs.cursorCaptureMode); setRecordingPrefsLoaded(true); }; From 23175fa099f55dff32eec66f75f50c1f1ca1c920 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E4=B8=AA=E6=88=90=E7=86=9F=E7=9A=84=E5=89=AA?= =?UTF-8?q?=E8=BE=91=E7=8C=BF?= <297668904+akahoz94@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:10:22 +0800 Subject: [PATCH 5/8] fix(audio): replay deferred gain snapshot when the countdown owner releases its lock --- ...ScreenRecorder.countdownGainPrefs.test.tsx | 40 ++++++++++++++++++- src/hooks/useScreenRecorder.ts | 34 +++++++++++++--- 2 files changed, 68 insertions(+), 6 deletions(-) diff --git a/src/hooks/useScreenRecorder.countdownGainPrefs.test.tsx b/src/hooks/useScreenRecorder.countdownGainPrefs.test.tsx index 9b96d26d06..00e5870677 100644 --- a/src/hooks/useScreenRecorder.countdownGainPrefs.test.tsx +++ b/src/hooks/useScreenRecorder.countdownGainPrefs.test.tsx @@ -128,16 +128,54 @@ describe("countdown startup lock and gain preference snapshots", () => { expect(view.result.current.micGainDb).toBe(0); expect(view.result.current.systemAudioGainDb).toBe(0); - // Release the countdown; once the lock clears, a later snapshot applies. + // Release the countdown. The stashed -12/-6 must be replayed on lock release + // even though no new snapshot arrived — otherwise a cancelled take leaves the + // next recording on the stale captured gains. await act(async () => { releaseCountdown(); await vi.advanceTimersByTimeAsync(3_500); }); expect(view.result.current.startingCountdown).toBe(false); + expect(view.result.current.micGainDb).toBe(-12); + expect(view.result.current.systemAudioGainDb).toBe(-6); + + // A snapshot arriving after release still applies normally. act(() => { onChange?.(prefsWithGains(6, 3)); }); expect(view.result.current.micGainDb).toBe(6); expect(view.result.current.systemAudioGainDb).toBe(3); }); + + it("replays the newest stashed pair when several snapshots arrive during the lock", async () => { + const view = renderHook(() => useScreenRecorder()); + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + + await act(async () => { + view.result.current.toggleRecording(); + }); + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + expect(view.result.current.startingCountdown).toBe(true); + + // Multiple saves mid-countdown: only the newest pair may be replayed. + act(() => { + onChange?.(prefsWithGains(-12, -6)); + }); + act(() => { + onChange?.(prefsWithGains(9, 4)); + }); + expect(view.result.current.micGainDb).toBe(0); + expect(view.result.current.systemAudioGainDb).toBe(0); + + await act(async () => { + releaseCountdown(); + await vi.advanceTimersByTimeAsync(3_500); + }); + expect(view.result.current.micGainDb).toBe(9); + expect(view.result.current.systemAudioGainDb).toBe(4); + }); }); diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts index cd51202298..802aebcab9 100644 --- a/src/hooks/useScreenRecorder.ts +++ b/src/hooks/useScreenRecorder.ts @@ -390,11 +390,17 @@ export function useScreenRecorder(): UseScreenRecorderReturn { // window arrives (see startRecordCountdown's `startingCountdownOwner`). That // take already captured its gain values in the `startRecording` closure, so // applying the new gain here would move the slider away from what is about - // to be recorded. Defer only these two fields until the lock is released; - // every other preference field keeps applying live as before. - if (!startingCountdownOwner.current) { - setMicGainDb(prefs.micGainDb ?? 0); - setSystemAudioGainDb(prefs.systemAudioGainDb ?? 0); + // to be recorded. Stash the newest pair while locked and replay it when the + // owning countdown releases the lock; every other preference field keeps + // applying live as before. + const micGainDb = prefs.micGainDb ?? 0; + const systemAudioGainDb = prefs.systemAudioGainDb ?? 0; + if (startingCountdownOwner.current) { + pendingGainPrefs.current = { micGainDb, systemAudioGainDb }; + } else { + pendingGainPrefs.current = null; + setMicGainDb(micGainDb); + setSystemAudioGainDb(systemAudioGainDb); } setCursorCaptureMode(prefs.cursorCaptureMode); setRecordingPrefsLoaded(true); @@ -474,6 +480,14 @@ export function useScreenRecorder(): UseScreenRecorderReturn { * release is gated on this token rather than `countdownStarting`. */ const startingCountdownOwner = useRef(null); + /** + * Newest gain snapshot received while `startingCountdownOwner` held the lock. + * The take that held the lock already captured its own gains in the + * `startRecording` closure, so applying the snapshot at once would desync the + * sliders from that take. Replayed when the owning countdown releases the lock + * so the following take sees the saved levels. + */ + const pendingGainPrefs = useRef<{ micGainDb: number; systemAudioGainDb: number } | null>(null); const cursorAccessibilityWarningShown = useRef(false); const [countdownActive, setCountdownActive] = useState(false); const [startingCountdown, setStartingCountdown] = useState(false); @@ -1828,6 +1842,16 @@ export function useScreenRecorder(): UseScreenRecorderReturn { if (startingCountdownOwner.current === owner) { startingCountdownOwner.current = null; setStartingCountdown(false); + // Replay the newest gain snapshot received during the lock so a take + // that was cancelled (or a following take) uses the saved levels. The + // take that just unwound still used its own captured gains, so this + // only affects what is recorded next. + const pendingGains = pendingGainPrefs.current; + pendingGainPrefs.current = null; + if (pendingGains) { + setMicGainDb(pendingGains.micGainDb); + setSystemAudioGainDb(pendingGains.systemAudioGainDb); + } } if (countdownStarting.current === starting) { countdownStarting.current = null; From 9f9dd40acbba1700de5f2b543f2773e766eda45e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E4=B8=AA=E6=88=90=E7=86=9F=E7=9A=84=E5=89=AA?= =?UTF-8?q?=E8=BE=91=E7=8C=BF?= <297668904+akahoz94@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:32:16 +0800 Subject: [PATCH 6/8] fix(compositor): stop the arm64-only flake in the clipped-voice loudness test The AAC round-trip's integrated loudness shifts a few tenths of a dB between platform encoders (arm64 measured 0.95, Intel ~1.6). The guard only needs to prove the fixture asks for a boost, so lower the floor from 1.0 to 0.5 dB to absorb the drift. --- crates/compositor/src/audio.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/compositor/src/audio.rs b/crates/compositor/src/audio.rs index e3f217297f..791acdcbe3 100644 --- a/crates/compositor/src/audio.rs +++ b/crates/compositor/src/audio.rs @@ -3118,7 +3118,11 @@ mod tests { // crests back over full scale), raised by the loudness gain: the export read +0.5 dBTP. let mut recording = through_aac(&voice(8.0, 1.0, 2.0), "clipped-recording"); let gain = loudness_gain_for(loudness_of(&recording)); - assert!(gain > 1.0, "the fixture needs raising, like #1157's +1.6 dB: {gain}"); + // The AAC round-trip's integrated loudness shifts by a few tenths of a dB + // between platform encoders (arm64 measured 0.95 here, Intel ~1.6). This + // guard only needs to prove the fixture asks for a boost; keep it well + // below 1 dB so the cross-encoder drift cannot turn it into a flaky failure. + assert!(gain > 0.5, "the fixture needs raising, like #1157's +1.6 dB: {gain}"); apply_gain_db(&mut recording, gain); assert_lufs(loudness_of(&recording), -16.0); let hot = true_peak_dbtp(&recording); From fe64ef017581b9610614e89d50a3a8433f7e020f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E4=B8=AA=E6=88=90=E7=86=9F=E7=9A=84=E5=89=AA?= =?UTF-8?q?=E8=BE=91=E7=8C=BF?= <297668904+akahoz94@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:33:30 +0800 Subject: [PATCH 7/8] fix: address maintainer review on volume trims - Fix Typecheck (tests): add micGainDb/systemAudioGainDb to the cameraPrefs fixture (TS2739 blocked all three CI runs). - Drop the unrelated audio.rs threshold change; #1678 owns that line. - Clamp direct IPC/MCP audio gains at the helper boundary: a negative scalar flips phase on Linux/Windows. Also document systemGain in the V2 helper example. --- crates/compositor/src/audio.rs | 6 +--- electron/ipc/gainBoundary.test.ts | 36 +++++++++++++++++++ electron/ipc/handlers.ts | 34 +++++++++++++----- electron/native/README.md | 1 + .../useScreenRecorder.cameraPrefs.test.tsx | 2 ++ 5 files changed, 66 insertions(+), 13 deletions(-) create mode 100644 electron/ipc/gainBoundary.test.ts diff --git a/crates/compositor/src/audio.rs b/crates/compositor/src/audio.rs index 791acdcbe3..e3f217297f 100644 --- a/crates/compositor/src/audio.rs +++ b/crates/compositor/src/audio.rs @@ -3118,11 +3118,7 @@ mod tests { // crests back over full scale), raised by the loudness gain: the export read +0.5 dBTP. let mut recording = through_aac(&voice(8.0, 1.0, 2.0), "clipped-recording"); let gain = loudness_gain_for(loudness_of(&recording)); - // The AAC round-trip's integrated loudness shifts by a few tenths of a dB - // between platform encoders (arm64 measured 0.95 here, Intel ~1.6). This - // guard only needs to prove the fixture asks for a boost; keep it well - // below 1 dB so the cross-encoder drift cannot turn it into a flaky failure. - assert!(gain > 0.5, "the fixture needs raising, like #1157's +1.6 dB: {gain}"); + assert!(gain > 1.0, "the fixture needs raising, like #1157's +1.6 dB: {gain}"); apply_gain_db(&mut recording, gain); assert_lufs(loudness_of(&recording), -16.0); let hot = true_peak_dbtp(&recording); diff --git a/electron/ipc/gainBoundary.test.ts b/electron/ipc/gainBoundary.test.ts new file mode 100644 index 0000000000..88d7145243 --- /dev/null +++ b/electron/ipc/gainBoundary.test.ts @@ -0,0 +1,36 @@ +// Direct IPC/MCP callers can pass a negative linear audio gain. macOS clamps it +// but the Linux and Windows helpers do not — a negative scalar flips the phase +// of the captured audio. Every gain that reaches a helper must pass through the +// boundary clamp. handlers.ts needs the whole Electron runtime to import, so +// the invariant is asserted against its source like recordingStateRouting.test.ts. + +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; + +const source = fs.readFileSync( + path.join(path.dirname(fileURLToPath(import.meta.url)), "handlers.ts"), + "utf8", +); + +describe("helper audio gain boundary", () => { + it("clamps negative gains and treats non-finite values as the fallback", () => { + const start = source.indexOf("function safeGainScalar("); + expect(start).toBeGreaterThan(-1); + const body = source.slice(start, source.indexOf("\n}", start)); + expect(body).toContain("Number.isFinite"); + expect(body).toContain("Math.max(0, gain)"); + }); + + it("does not pass a raw request gain through to any helper", () => { + // Every gain assignment in a helper config goes through the clamp. A raw + // `request.audio..gain` on the right-hand side would bypass it. + expect(source).not.toMatch(/(systemGain|microphoneGain|gain): request\.audio\./); + }); + + it("keeps the helper config keys for system and microphone gain", () => { + expect(source).toContain("systemGain: safeGainScalar("); + expect(source).toContain("microphoneGain: safeGainScalar("); + }); +}); diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts index e269abfd77..79aac1e00c 100644 --- a/electron/ipc/handlers.ts +++ b/electron/ipc/handlers.ts @@ -821,6 +821,18 @@ function isTrustedProjectPath(filePath?: string | null) { const CURSOR_SAMPLE_INTERVAL_MS = 33; const MAX_CURSOR_SAMPLES = 60 * 60 * 30; // 1 hour @ 30Hz +/** + * Direct IPC/MCP callers can send a negative linear gain. macOS clamps it, but + * the Linux and Windows helpers do not: a negative scalar flips the phase of + * the captured audio. Clamp to non-negative at the boundary, defaulting an + * absent value to unity. NaN/Infinity are treated as unity too so a bad caller + * cannot poison the helper config. + */ +function safeGainScalar(gain: number | null | undefined, fallback = 1): number { + if (gain === null || gain === undefined || !Number.isFinite(gain)) return fallback; + return Math.max(0, gain); +} + let cursorRecordingSession: CursorRecordingSession | null = null; let pendingCursorRecordingData: CursorRecordingData | null = null; let nativeWindowsCaptureProcess: ChildProcessWithoutNullStreams | null = null; @@ -1029,10 +1041,13 @@ function captureSettingsOf(request: NativeLinuxRecordingRequest): string { fps: request.video?.fps ?? null, bitrate: request.video?.bitrate ?? null, system: request.audio?.system?.enabled ?? false, - systemGain: request.audio?.system?.gain ?? 1, + systemGain: safeGainScalar(request.audio?.system?.gain, 1), microphone: request.audio?.microphone?.enabled ?? false, deviceName: request.audio?.microphone?.deviceName ?? null, - gain: request.audio?.microphone?.gain ?? null, + gain: + typeof request.audio?.microphone?.gain === "number" + ? safeGainScalar(request.audio.microphone.gain) + : null, cursor: normalizeCursorCaptureMode(request?.cursor?.mode) ?? "editable-overlay", }); } @@ -2821,13 +2836,16 @@ export function registerIpcHandlers( fps: request.video.fps, ...(request.video.bitrate ? { bitrate: request.video.bitrate } : {}), audio: { - system: { enabled: request.audio.system.enabled, gain: request.audio.system.gain ?? 1 }, + system: { + enabled: request.audio.system.enabled, + gain: safeGainScalar(request.audio.system.gain, 1), + }, microphone: { enabled: request.audio.microphone.enabled, ...(request.audio.microphone.deviceName ? { deviceName: request.audio.microphone.deviceName } : {}), - gain: request.audio.microphone.gain, + gain: safeGainScalar(request.audio.microphone.gain), }, }, maxCursorSamples: MAX_CURSOR_SAMPLES, @@ -2927,14 +2945,14 @@ export function registerIpcHandlers( audio: { system: { enabled: request.audio.system.enabled, - gain: request.audio.system.gain ?? 1, + gain: safeGainScalar(request.audio.system.gain, 1), }, microphone: { enabled: request.audio.microphone.enabled, ...(request.audio.microphone.deviceName ? { deviceName: request.audio.microphone.deviceName } : {}), - gain: request.audio.microphone.gain, + gain: safeGainScalar(request.audio.microphone.gain), }, }, maxCursorSamples: MAX_CURSOR_SAMPLES, @@ -3218,8 +3236,8 @@ export function registerIpcHandlers( captureMic: request.audio.microphone.enabled, microphoneDeviceId: request.audio.microphone.deviceId ?? null, microphoneDeviceName: request.audio.microphone.deviceName ?? null, - microphoneGain: request.audio.microphone.gain, - systemGain: request.audio.system.gain ?? 1, + microphoneGain: safeGainScalar(request.audio.microphone.gain), + systemGain: safeGainScalar(request.audio.system.gain, 1), webcamEnabled: request.webcam.enabled, webcamDeviceId: request.webcam.deviceId ?? null, webcamDeviceName: request.webcam.deviceName ?? null, diff --git a/electron/native/README.md b/electron/native/README.md index 1a0774ef89..d789fdced6 100644 --- a/electron/native/README.md +++ b/electron/native/README.md @@ -77,6 +77,7 @@ Current V2 JSON shape: "microphoneDeviceId": "default", "microphoneDeviceName": "Microphone (NVIDIA Broadcast)", "microphoneGain": 1.4, + "systemGain": 1.0, "webcamEnabled": true, "webcamDeviceId": "default", "webcamDeviceName": "Camera (NVIDIA Broadcast)", diff --git a/src/hooks/useScreenRecorder.cameraPrefs.test.tsx b/src/hooks/useScreenRecorder.cameraPrefs.test.tsx index 331ca7d313..341afdd57b 100644 --- a/src/hooks/useScreenRecorder.cameraPrefs.test.tsx +++ b/src/hooks/useScreenRecorder.cameraPrefs.test.tsx @@ -27,6 +27,8 @@ const initial: Prefs = { camDeviceName: null, camQuality: "2160p", systemAudioEnabled: false, + micGainDb: 0, + systemAudioGainDb: 0, cursorCaptureMode: "editable-overlay", hideDesktopIcons: false, autoZoomEnabled: true, From d0d3c811be10545d4070492563b7b30888e917c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E4=B8=AA=E6=88=90=E7=86=9F=E7=9A=84=E5=89=AA?= =?UTF-8?q?=E8=BE=91=E7=8C=BF?= Date: Sat, 28 Nov 2026 21:02:45 +0800 Subject: [PATCH 8/8] test(compositor): align clipped-voice gain guard with #1678 The a_clipped_voice_exports_under_minus_one_dbtp fixture asserts gain > 1.0, a threshold measured under ffmpeg 9.0 (+1.6 dB). Through the AAC round-trip the computed gain is encoder-version dependent (#1678 documents 9.0 = +1.24 dB, 9.1 = +0.95 dB), so the macOS arm64 runner fails deterministically at 0.9500192 while Intel/Windows pass. Apply the exact fix from #1678 (gain > 0.0 plus the explanatory comment), so this becomes a no-op once #1678 lands and cannot conflict with it. --- crates/compositor/src/audio.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/compositor/src/audio.rs b/crates/compositor/src/audio.rs index e3f217297f..82881b82ef 100644 --- a/crates/compositor/src/audio.rs +++ b/crates/compositor/src/audio.rs @@ -3118,7 +3118,10 @@ mod tests { // crests back over full scale), raised by the loudness gain: the export read +0.5 dBTP. let mut recording = through_aac(&voice(8.0, 1.0, 2.0), "clipped-recording"); let gain = loudness_gain_for(loudness_of(&recording)); - assert!(gain > 1.0, "the fixture needs raising, like #1157's +1.6 dB: {gain}"); + // Any raise will do: how much depends on the AAC encoder's version (ffmpeg 9.0 asks + // +1.24 dB of this fixture, 9.1 +0.95, #1157 asked +1.6). The crests over full scale, + // checked just below, are what the test needs. + assert!(gain > 0.0, "the fixture needs raising, like #1157's +1.6 dB: {gain}"); apply_gain_db(&mut recording, gain); assert_lufs(loudness_of(&recording), -16.0); let hot = true_peak_dbtp(&recording);