Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion crates/compositor/src/audio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
21 changes: 21 additions & 0 deletions electron/app-settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
32 changes: 32 additions & 0 deletions electron/app-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -186,6 +207,17 @@ function validateRecordingPatch(patch: Partial<RecordingPreferences>): 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}]`,
);
}
}
}

Expand Down
36 changes: 36 additions & 0 deletions electron/ipc/gainBoundary.test.ts
Original file line number Diff line number Diff line change
@@ -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.<source>.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(");
});
});
41 changes: 35 additions & 6 deletions electron/ipc/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -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,
Expand Down Expand Up @@ -815,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;
Expand Down Expand Up @@ -1023,9 +1041,13 @@ function captureSettingsOf(request: NativeLinuxRecordingRequest): string {
fps: request.video?.fps ?? null,
bitrate: request.video?.bitrate ?? null,
system: request.audio?.system?.enabled ?? false,
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",
});
}
Expand Down Expand Up @@ -2814,13 +2836,16 @@ 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: 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,
Expand Down Expand Up @@ -2918,13 +2943,16 @@ 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: 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,
Expand Down Expand Up @@ -3208,7 +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,
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,
Expand Down
2 changes: 2 additions & 0 deletions electron/ipc/recordingPrefs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ const defaults: RecordingPrefs = {
camDeviceName: null,
camQuality: "2160p",
systemAudioEnabled: false,
micGainDb: 0,
systemAudioGainDb: 0,
cursorCaptureMode: "editable-overlay",
hideDesktopIcons: false,
autoZoomEnabled: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions electron/native/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)",
Expand Down
7 changes: 5 additions & 2 deletions electron/native/pipewire-capture/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<f32>,
}

#[derive(Debug, Default, Deserialize)]
Expand Down Expand Up @@ -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,
});
}
Expand All @@ -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,
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -136,6 +137,7 @@ public final class AudioTrackMixer {
includesSystemAudio: Bool,
includesMicrophone: Bool,
microphoneGain: Double,
systemGain: Double = 1,
clock: @escaping TimelineClock
) {
self.input = input
Expand All @@ -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()
}

Expand Down Expand Up @@ -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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ struct RecordingRequest: Decodable {
struct Audio: Decodable {
struct SystemAudio: Decodable {
let enabled: Bool
let gain: Double?
}

struct Microphone: Decodable {
Expand Down Expand Up @@ -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 }
)
}
Expand Down
Loading
Loading