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 e4bab0f5cb..27298f1182 100644 --- a/electron/ipc/handlers.ts +++ b/electron/ipc/handlers.ts @@ -736,6 +736,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. */ @@ -750,6 +754,8 @@ const defaultRecordingPrefs: RecordingPrefs = { camDeviceName: null, camQuality: DEFAULT_WEBCAM_QUALITY, systemAudioEnabled: false, + micGainDb: 0, + systemAudioGainDb: 0, cursorCaptureMode: "editable-overlay", hideDesktopIcons: false, autoZoomEnabled: true, @@ -1004,6 +1010,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, @@ -2795,7 +2802,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 @@ -2899,7 +2906,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 @@ -3190,6 +3200,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 fa4a3767dc..e6f1e4ca86 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..6d44407134 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,8 @@ impl Request { // The default SINK's monitor: what is being played, not what a // microphone hears. capture_sink: true, - gain: 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, }); } @@ -208,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/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..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 @@ -898,6 +960,7 @@ AudioMixer::AudioMixer( bool includeSystem, bool includeMicrophone, double microphoneGain, + double systemGain, OutputCallback output) : format_(format), systemFormat_(systemFormat), @@ -905,6 +968,7 @@ AudioMixer::AudioMixer( includeSystem_(includeSystem), includeMicrophone_(includeMicrophone), microphoneGain_(microphoneGain), + systemGain_(systemGain), output_(std::move(output)) {} AudioMixer::~AudioMixer() { @@ -1121,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; @@ -1145,15 +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_); + 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.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..4e021be477 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,38 @@ 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. + { + 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 +2929,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.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 754b1adfac..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, @@ -139,6 +140,10 @@ export function LaunchWindow() { setMicrophoneDeviceName, systemAudioEnabled, setSystemAudioEnabled, + micGainDb, + setMicGainDb, + systemAudioGainDb, + setSystemAudioGainDb, webcamEnabled, setWebcamEnabled, webcamDeviceId, @@ -195,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); @@ -974,6 +983,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 +1001,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 +1238,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 +1502,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.startCancel.test.tsx b/src/hooks/useScreenRecorder.startCancel.test.tsx index e5d714bbcc..bc6fbf6ded 100644 --- a/src/hooks/useScreenRecorder.startCancel.test.tsx +++ b/src/hooks/useScreenRecorder.startCancel.test.tsx @@ -208,3 +208,49 @@ describe("a failed native start never leaves the webcam recording", () => { expect(handle.discard).not.toHaveBeenCalled(); }); }); + +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 f4ef513918..48ffabbc8c 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 { @@ -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; @@ -115,6 +117,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; @@ -309,6 +315,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] = @@ -337,6 +345,8 @@ export function useScreenRecorder(): UseScreenRecorderReturn { camDeviceName?: string | null; camQuality?: WebcamQualityId | null; systemAudioEnabled: boolean; + micGainDb?: number; + systemAudioGainDb?: number; cursorCaptureMode: CursorCaptureMode; }) => { if (cancelled) return; @@ -370,6 +380,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); }; @@ -440,8 +452,17 @@ 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); const webcamReady = useRef(false); const webcamAcquireId = useRef(0); const canPauseRecording = @@ -1352,13 +1373,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: { @@ -1519,13 +1541,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: { @@ -1641,7 +1664,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 @@ -1653,7 +1676,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 }, @@ -1772,9 +1795,26 @@ 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` + // 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 { + // 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; } @@ -1895,7 +1935,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); @@ -2179,6 +2221,8 @@ export function useScreenRecorder(): UseScreenRecorderReturn { const { context: mixingCtx, track: mixedTrack } = mixAudioTracks({ systemAudioTrack, micAudioTrack, + micGainDb, + systemGainDb: systemAudioGainDb, }); if (mixingCtx) { mixingContext.current = mixingCtx; @@ -2684,6 +2728,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { paused, saving, elapsedSeconds, + startingCountdown, toggleRecording, startRecordingImmediately: () => startRecording(), togglePaused, @@ -2704,6 +2749,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, };