diff --git a/.changeset/surround-system-audio.md b/.changeset/surround-system-audio.md new file mode 100644 index 0000000..54eee5b --- /dev/null +++ b/.changeset/surround-system-audio.md @@ -0,0 +1,5 @@ +--- +'lyra': patch +--- + +Calls are recorded on Windows 11 even when your headset or speakers are set to surround sound (7.1), where Lyra used to record only your microphone. Computer audio is now taken from every app but Lyra, on whichever device it plays. When computer audio can't be recorded, Lyra tries again and says so with a Retry button, and the speaker meter dims, instead of quietly recording your microphone only. diff --git a/apps/lyra/src/main/index.ts b/apps/lyra/src/main/index.ts index c39bfe3..64f1640 100644 --- a/apps/lyra/src/main/index.ts +++ b/apps/lyra/src/main/index.ts @@ -14,8 +14,10 @@ import { type IpcMainInvokeEvent, type WebContents } from 'electron' +import { release } from 'node:os' import { join } from 'node:path' import { electronApp, optimizer, is } from '@electron-toolkit/utils' +import { systemAudioSource } from './systemAudioSource' import { installAppMenu } from './appMenu' import { isAppPage, type AppPages } from './appOrigin' import { checkConfig, config, ConfigError, configSummary } from './config' @@ -506,6 +508,8 @@ function registerPermissions(): void { }) // Meetings ask for system audio via getDisplayMedia; answer with the loopback // device and the primary screen (its video track is discarded), so no picker shows. + const audio = systemAudioSource(process.platform, release()) + log('capture', 'system audio source', { audio }) session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { const main = getMainWindow() const frame = request.frame @@ -515,7 +519,10 @@ function registerPermissions(): void { } desktopCapturer.getSources({ types: ['screen'] }).then( ([screen]) => { - callback(screen ? { video: screen, audio: 'loopback' } : {}) + // Electron types `audio` as 'loopback' | 'loopbackWithMute', but hands any of Chromium's + // loopback ids through; `loopbackWithoutChrome` is one (see systemAudioSource.ts). + // @ts-expect-error -- Chromium's process-loopback id isn't in Electron's type + callback(screen ? { video: screen, audio } : {}) }, (error: unknown) => { log('capture', 'could not list screens for system audio', String(error)) diff --git a/apps/lyra/src/main/systemAudioSource.test.ts b/apps/lyra/src/main/systemAudioSource.test.ts new file mode 100644 index 0000000..6c605d7 --- /dev/null +++ b/apps/lyra/src/main/systemAudioSource.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' +import { systemAudioSource } from './systemAudioSource' + +describe('systemAudioSource', () => { + it('uses process loopback on Windows builds that have it', () => { + expect(systemAudioSource('win32', '10.0.22631')).toBe('loopbackWithoutChrome') + expect(systemAudioSource('win32', '10.0.20348')).toBe('loopbackWithoutChrome') + }) + + it('keeps device loopback on older Windows builds', () => { + expect(systemAudioSource('win32', '10.0.19045')).toBe('loopback') + }) + + it('keeps device loopback when the build cannot be read', () => { + expect(systemAudioSource('win32', '10.0')).toBe('loopback') + expect(systemAudioSource('win32', '')).toBe('loopback') + }) + + it('uses loopback on macOS and Linux', () => { + expect(systemAudioSource('darwin', '24.1.0')).toBe('loopback') + expect(systemAudioSource('linux', '6.8.0-45-generic')).toBe('loopback') + }) +}) diff --git a/apps/lyra/src/main/systemAudioSource.ts b/apps/lyra/src/main/systemAudioSource.ts new file mode 100644 index 0000000..4b1ba36 --- /dev/null +++ b/apps/lyra/src/main/systemAudioSource.ts @@ -0,0 +1,21 @@ +/** + * Which of Chromium's system-audio sources the display-media handler answers with. + * + * `loopback` on Windows opens WASAPI loopback on the default output in Chromium's own format + * (stereo float). An output set to surround (a 7.1 gaming headset) refuses that with + * AUDCLNT_E_UNSUPPORTED_FORMAT, so nothing of the call is recorded. `loopbackWithoutChrome` + * uses Windows' process loopback instead: every app's audio but Lyra's own, converted by + * Windows to the format asked for, on whichever device it plays. It needs Windows 10 build + * 20348 or later; older builds keep device loopback. Elsewhere `loopback` is the only source. + */ +export type SystemAudioSource = 'loopback' | 'loopbackWithoutChrome' + +/** The first Windows build with process loopback capture (Windows 11 and Server 2022). */ +export const PROCESS_LOOPBACK_BUILD = 20348 + +/** `release` is `os.release()`: "10.0.22631" on Windows 11. */ +export function systemAudioSource(platform: string, release: string): SystemAudioSource { + if (platform !== 'win32') return 'loopback' + const build = Number(release.split('.')[2]) + return Number.isInteger(build) && build >= PROCESS_LOOPBACK_BUILD ? 'loopbackWithoutChrome' : 'loopback' +} diff --git a/apps/lyra/src/renderer/src/App.tsx b/apps/lyra/src/renderer/src/App.tsx index 08590ad..5b122a7 100644 --- a/apps/lyra/src/renderer/src/App.tsx +++ b/apps/lyra/src/renderer/src/App.tsx @@ -3,7 +3,7 @@ import { PANEL_WIDTHS } from '../../shared/settings' import { summarySections } from '../../shared/summarySections' import type { PageSummary, WhisperStatus } from '../../shared/types' import type { TranscriptSegment } from '../../shared/sessionDoc' -import { DictationMessage, RecordControl } from './components/Capture' +import { DictationMessage, RecordControl, SystemAudioMessage } from './components/Capture' import { useContextMenu } from './components/ContextMenu' import { SummaryButton } from './components/SummaryButton' import { SummaryPane } from './components/SummaryPane' @@ -767,7 +767,8 @@ export default function App(): React.JSX.Element { ) : null @@ -1174,6 +1175,13 @@ export default function App(): React.JSX.Element { /> ) : null} + {dictation.systemAudioMessageShown ? ( + + ) : null} {toastElement} diff --git a/apps/lyra/src/renderer/src/audio/capture.ts b/apps/lyra/src/renderer/src/audio/capture.ts index 6500362..0aff8be 100644 --- a/apps/lyra/src/renderer/src/audio/capture.ts +++ b/apps/lyra/src/renderer/src/audio/capture.ts @@ -2,6 +2,7 @@ import { log } from '../lib/log' import { SAMPLE_RATE } from '../../../shared/audio/vad' import { RECONNECT_DELAYS_MS, + SYSTEM_START_DELAYS_MS, microphoneDidNotStart, microphoneErrorMessage, retryOpen, @@ -75,11 +76,14 @@ export type CaptureHandle = { context: string track: string muted: boolean + system: 'live' | 'none' | 'off' systemReopens: number micReopens: number } /** Frames stopped arriving: resume the audio engine, and reopen a microphone that died. */ recover: () => void + /** Tries computer audio again now (the user pressed Retry); nothing while it's recording. */ + retrySystem: () => void stop: () => void } @@ -87,6 +91,11 @@ export type CaptureHandle = { export type CaptureEvent = | { type: 'mic-reconnecting'; micName: string } | { type: 'mic-restored'; micName: string } + /** Computer audio isn't being recorded, and is being opened (again). */ + | { type: 'system-retrying' } + | { type: 'system-restored' } + /** Every try failed: the recording carries on with the mic and a silent computer track. */ + | { type: 'system-unavailable' } export type OpenedMicrophone = { stream: MediaStream @@ -157,8 +166,11 @@ export async function openMicrophone(deviceId: string | null = null): Promise Promise /** @@ -246,7 +258,8 @@ export async function startCapture( } const { system, onTracks, reopenSystem, reopenMic, onEvent } = options - const channels = system ? 2 : 1 + const wantsSystem = system !== undefined + const channels = wantsSystem ? 2 : 1 let micStream = stream let micSource = context.createMediaStreamSource(stream) const highPass = new BiquadFilterNode(context, { @@ -262,6 +275,7 @@ export async function startCapture( keepAlive.start() let systemStream = system ?? null let systemSource = system ? context.createMediaStreamSource(system) : null + const systemLive = (): boolean => systemStream?.getAudioTracks()[0]?.readyState === 'live' const collector = new AudioWorkletNode(context, 'frame-collector', { channelCount: channels, channelCountMode: 'explicit', @@ -286,12 +300,12 @@ export async function startCapture( if (!stopped) onLost('The audio processor stopped unexpectedly.') } let merger: ChannelMergerNode | null = null - if (systemSource) { + if (wantsSystem) { // Each merger input is downmixed to mono: channel 0 = mic, channel 1 = system audio. While - // system audio is being reopened its input is silent, so the two tracks stay aligned. + // system audio is being (re)opened its input is silent, so the two tracks stay aligned. merger = new ChannelMergerNode(context, { numberOfInputs: 2 }) highPass.connect(merger, 0, 0) - systemSource.connect(merger, 0, 1) + systemSource?.connect(merger, 0, 1) merger.connect(collector) } else { highPass.connect(collector) @@ -319,19 +333,25 @@ export async function startCapture( * the default output changed: loopback opens on whatever output was the default at the time, * and may keep listening to it after the call moves to headphones. A gap is silence, not drift. */ - const reconnectSystem = async (reason: string): Promise => { + const reconnectSystem = async ( + reason: string, + delays: readonly number[] = RECONNECT_DELAYS_MS + ): Promise => { const input = merger if (!input || !reopenSystem || reopening || stopped) return reopening = true + // Following a default output that moved is quiet; only a lost or missing track is news. + if (!systemLive()) onEvent?.({ type: 'system-retrying' }) try { const result = await retryOpen(reopenSystem, { - delays: RECONNECT_DELAYS_MS, + delays, cancelled: isStopped, dispose: stopTracks }) if (!result) { if (!isStopped()) { log('capture', 'system audio could not be reopened; recording the mic only', { reason }) + if (!systemLive()) onEvent?.({ type: 'system-unavailable' }) } return } @@ -344,6 +364,7 @@ export async function startCapture( systemReopens++ await rememberOutput() log('capture', 'system audio reopened', { reason, attempt: result.attempt }) + onEvent?.({ type: 'system-restored' }) } finally { reopening = false } @@ -361,10 +382,11 @@ export async function startCapture( if (isStopped()) return void logDevices('changed') // Only system audio follows the default output; a recording without it has nothing to move. - if (!system) return + if (!wantsSystem) return void defaultOutput().then((after) => { if (isStopped()) return - const trackEnded = systemStream?.getAudioTracks()[0]?.readyState !== 'live' + // Also when it never opened: a different output device is worth another try. + const trackEnded = !systemLive() if (shouldReopenSystem({ trackEnded, before: outputKey, after })) { void reconnectSystem('devicechange') } @@ -464,6 +486,7 @@ export async function startCapture( system: system?.getAudioTracks()[0]?.getSettings() ?? null }) void logDevices('started') + if (wantsSystem && !system) void reconnectSystem('unavailable at start', SYSTEM_START_DELAYS_MS) return { micName, @@ -472,6 +495,7 @@ export async function startCapture( context: context.state, track: micReopening ? 'reopening' : (micTrack?.readyState ?? 'none'), muted: micTrack?.muted ?? false, + system: !wantsSystem ? 'off' : systemLive() ? 'live' : 'none', systemReopens, micReopens }), @@ -480,6 +504,10 @@ export async function startCapture( resumeContext() if (micTrack?.readyState === 'ended') void reconnectMic() }, + retrySystem: () => { + if (stopped || systemLive()) return + void reconnectSystem('retry', [0]) + }, stop: () => { if (stopped) return stopped = true diff --git a/apps/lyra/src/renderer/src/audio/recovery.test.ts b/apps/lyra/src/renderer/src/audio/recovery.test.ts index fb9c17f..421d381 100644 --- a/apps/lyra/src/renderer/src/audio/recovery.test.ts +++ b/apps/lyra/src/renderer/src/audio/recovery.test.ts @@ -3,6 +3,7 @@ import { RECONNECT_DELAYS_MS, microphoneErrorMessage, nextStall, + nextSystemAudio, retryOpen, shouldReopenSystem, type StallState @@ -140,3 +141,32 @@ describe('microphoneErrorMessage', () => { expect(microphoneErrorMessage('TypeError', 'darwin')).toBeNull() }) }) + +describe('nextSystemAudio', () => { + it('goes live when computer audio opens, from any try', () => { + expect(nextSystemAudio('retrying', 'restored')).toBe('live') + expect(nextSystemAudio('unavailable', 'restored')).toBe('live') + expect(nextSystemAudio('blocked', 'restored')).toBe('live') + }) + + it('gives up after the retries, and tries again on request', () => { + expect(nextSystemAudio('retrying', 'unavailable')).toBe('unavailable') + expect(nextSystemAudio('unavailable', 'retrying')).toBe('retrying') + expect(nextSystemAudio('live', 'retrying')).toBe('retrying') + }) + + it('keeps an OS refusal over the retries, which cannot fix it', () => { + expect(nextSystemAudio('retrying', 'blocked')).toBe('blocked') + expect(nextSystemAudio('blocked', 'retrying')).toBe('blocked') + expect(nextSystemAudio('blocked', 'unavailable')).toBe('blocked') + }) + + it('ignores a late refusal once computer audio is recording', () => { + expect(nextSystemAudio('live', 'blocked')).toBe('live') + }) + + it('stays off when computer audio was not asked for', () => { + expect(nextSystemAudio('off', 'restored')).toBe('off') + expect(nextSystemAudio('off', 'unavailable')).toBe('off') + }) +}) diff --git a/apps/lyra/src/renderer/src/audio/recovery.ts b/apps/lyra/src/renderer/src/audio/recovery.ts index ac1d3c7..33283fb 100644 --- a/apps/lyra/src/renderer/src/audio/recovery.ts +++ b/apps/lyra/src/renderer/src/audio/recovery.ts @@ -70,6 +70,34 @@ export function shouldReopenSystem(change: { return change.before !== change.after } +/** + * When computer audio didn't open as recording started: three more tries with backoff, since the + * output device is often briefly busy (another app opening it, a headset's software starting up). + */ +export const SYSTEM_START_DELAYS_MS: readonly number[] = [1000, 2000, 4000] + +/** + * Computer audio during a recording: not asked for, being recorded, being opened (again), given + * up on (a Retry away), or refused by the OS (a settings page away). + */ +export type SystemAudioState = 'off' | 'live' | 'retrying' | 'unavailable' | 'blocked' + +export type SystemAudioChange = 'retrying' | 'restored' | 'unavailable' | 'blocked' + +/** Follows what the capture reports about computer audio. A refusal by the OS outlasts the retries. */ +export function nextSystemAudio(state: SystemAudioState, change: SystemAudioChange): SystemAudioState { + if (state === 'off') return 'off' + switch (change) { + case 'restored': + return 'live' + case 'blocked': + return state === 'live' ? 'live' : 'blocked' + case 'retrying': + case 'unavailable': + return state === 'blocked' ? 'blocked' : change + } +} + /** How many stalled heartbeats in a row before the user is told nothing is being captured. */ export const STALLS_BEFORE_NOTICE = 2 diff --git a/apps/lyra/src/renderer/src/components/Capture.tsx b/apps/lyra/src/renderer/src/components/Capture.tsx index 1169b6e..7cc4081 100644 --- a/apps/lyra/src/renderer/src/components/Capture.tsx +++ b/apps/lyra/src/renderer/src/components/Capture.tsx @@ -1,5 +1,6 @@ import { useState, type ReactNode } from 'react' -import { SYSTEM_AUDIO_BLOCKED_NOTICE, type DictationPhase } from '../hooks/useDictation' +import type { SystemAudioState } from '../audio/recovery' +import type { DictationPhase } from '../hooks/useDictation' import { shortcutLabel } from '../lib/format' import { cn } from '../lib/utils' import { phaseAnnouncement } from '../lib/status' @@ -177,30 +178,69 @@ export function DictationMessage({ }) { if (error) return if (!notice) return null - return ( - { - window.api.openPermissionSettings('screen').then( - (opened) => { - if (!opened) notify('Open your system settings to change this.') - }, - () => { - notify('Couldn’t open system settings.') - } - ) - }} - > - Open Settings - - ) : null - } - /> - ) + return +} + +/** + * While computer audio was asked for but isn't being recorded: trying again, given up (Retry), + * or refused by macOS (Open Settings; it applies the change at launch). Stays until it's back, + * the recording stops, or it's closed. + */ +export function SystemAudioMessage({ + state, + onRetry, + onDismiss +}: { + state: SystemAudioState + onRetry: () => void + onDismiss: () => void +}) { + switch (state) { + case 'off': + case 'live': + return null + case 'retrying': + return ( + + ) + case 'unavailable': + return ( + + Retry + + } + /> + ) + case 'blocked': + return ( + { + window.api.openPermissionSettings('screen').then( + (opened) => { + if (!opened) notify('Open your system settings to change this.') + }, + () => { + notify('Couldn’t open system settings.') + } + ) + }} + > + Open Settings + + } + /> + ) + } } diff --git a/apps/lyra/src/renderer/src/hooks/useDictation.ts b/apps/lyra/src/renderer/src/hooks/useDictation.ts index 1752c61..8484eff 100644 --- a/apps/lyra/src/renderer/src/hooks/useDictation.ts +++ b/apps/lyra/src/renderer/src/hooks/useDictation.ts @@ -6,7 +6,13 @@ import { type CaptureEvent, type CaptureHandle } from '../audio/capture' -import { nextStall, type StallState } from '../audio/recovery' +import { + nextStall, + nextSystemAudio, + type StallState, + type SystemAudioChange, + type SystemAudioState +} from '../audio/recovery' import { SessionRecorder } from '../audio/sessionRecorder' import { rms } from '../../../shared/audio/vad' import type { TranscriptProgress } from '../../../shared/types' @@ -28,10 +34,6 @@ const SILENT_MIC_RMS = 0.0002 const SILENT_MIC_MS = 8000 /** How long "Reconnected to …" stays up. */ const RESTORED_NOTICE_MS = 8000 -const NO_SYSTEM_AUDIO_NOTICE = 'Couldn’t capture computer audio. Recording your microphone only.' -/** The dock offers the system settings page beside this one. macOS applies the change at launch. */ -export const SYSTEM_AUDIO_BLOCKED_NOTICE = - 'macOS isn’t letting Lyra record computer audio, so this is your microphone only. Allow it, then restart Lyra.' const SILENT_MIC_NOTICE = 'Your microphone isn’t picking anything up. Check that it isn’t muted.' const NARROWBAND_NOTICE = 'Your microphone is a headset in call mode, which lowers the quality of your voice and the computer’s audio. A built-in or wired mic transcribes better.' @@ -59,6 +61,7 @@ type Session = { /** The start that made this session: state is only reset by the stop of the newest one. */ owner: Attempt stop: () => Promise + retrySystem: () => void } const level = (samples: Float32Array): number => Math.min(1, rms(samples) * 14) @@ -95,6 +98,12 @@ export function useDictation({ getDeviceId }: Options) { const [micName, setMicName] = useState('') const [error, setError] = useState(null) const [notice, setNotice] = useState(null) + /** + * Computer audio, apart from `notice`: a mic notice mustn't hide that the other side of a call + * isn't being recorded. `systemHidden`: the user closed its message; the next change shows it. + */ + const [systemAudio, setSystemAudio] = useState('off') + const [systemHidden, setSystemHidden] = useState(false) const [progress, setProgress] = useState(null) /** The session being recorded (or starting, or finishing), wherever the window has navigated. */ const [pageId, setPageId] = useState(null) @@ -145,6 +154,8 @@ export function useDictation({ getDeviceId }: Options) { const cancelled = (): boolean => attempt.cancelled setError(null) setNotice(null) + setSystemAudio('off') + setSystemHidden(false) setProgress(null) setPageId(record.pageId) setPhase('starting') @@ -185,20 +196,25 @@ export function useDictation({ getDeviceId }: Options) { system = record.systemAudio ? await openSystemAudio() : null if (cancelled()) return await giveUp() + const changeSystem = (change: SystemAudioChange): void => { + if (owner.current !== attempt) return + setSystemAudio((current) => nextSystemAudio(current, change)) + setSystemHidden(false) + } + // When it didn't open, the capture keeps a silent computer track and tries again. + setSystemAudio(!record.systemAudio ? 'off' : system ? 'live' : 'retrying') if (record.systemAudio && !system) { - setNotice(NO_SYSTEM_AUDIO_NOTICE) // Why, when the OS can say: a refused permission has a settings page to send them to. window.api.permissionStatus().then( (status) => { - if (status.screen === 'granted') return - setNotice((current) => (current === NO_SYSTEM_AUDIO_NOTICE ? SYSTEM_AUDIO_BLOCKED_NOTICE : current)) + if (status.screen !== 'granted') changeSystem('blocked') }, () => { - // The plain notice stands. + // The plain message stands. } ) } - recorder = await SessionRecorder.start(record.pageId, system !== null) + recorder = await SessionRecorder.start(record.pageId, record.systemAudio) if (cancelled()) return await giveUp() const activeRecorder = recorder @@ -228,6 +244,18 @@ export function useDictation({ getDeviceId }: Options) { }, RESTORED_NOTICE_MS) break } + case 'system-retrying': { + changeSystem('retrying') + break + } + case 'system-restored': { + changeSystem('restored') + break + } + case 'system-unavailable': { + changeSystem('unavailable') + break + } } } const reopenMic = async (): Promise => @@ -240,7 +268,7 @@ export function useDictation({ getDeviceId }: Options) { void stopRef.current() }, { - ...(system ? { system, reopenSystem: openSystemAudio } : {}), + ...(record.systemAudio ? { system, reopenSystem: openSystemAudio } : {}), reopenMic, onEvent: onCaptureEvent, onTracks: (micFrame: Float32Array, other: Float32Array | null) => { @@ -306,10 +334,13 @@ export function useDictation({ getDeviceId }: Options) { if (restoredTimer) clearTimeout(restoredTimer) handle.stop() levelListeners.current.forEach((listener) => { - listener({ mic: 0, system: system ? 0 : null }) + listener({ mic: 0, system: record.systemAudio ? 0 : null }) }) // Main transcribes what's left before this resolves. await activeRecorder.stop() + }, + retrySystem: () => { + handle.retrySystem() } } setMicName(handle.micName) @@ -324,6 +355,7 @@ export function useDictation({ getDeviceId }: Options) { log('dictation', 'failed to start', errorText(caught)) if (owner.current === attempt) { setError(caught instanceof Error ? caught.message : 'Recording failed') + setSystemAudio('off') setPageId(null) setPhase('idle') } @@ -366,6 +398,7 @@ export function useDictation({ getDeviceId }: Options) { recordingPage.current = null setProgress(null) setMicName('') + setSystemAudio('off') setPageId(null) setPhase('idle') } @@ -407,6 +440,14 @@ export function useDictation({ getDeviceId }: Options) { setNotice(null) }, []) + /** The Retry on "Couldn't capture computer audio". */ + const retrySystemAudio = useCallback(() => { + session.current?.retrySystem() + }, []) + const dismissSystemAudio = useCallback(() => { + setSystemHidden(true) + }, []) + return { phase, recording: phase === 'listening' || phase === 'starting', @@ -416,6 +457,10 @@ export function useDictation({ getDeviceId }: Options) { error, notice, dismissMessage, + systemAudio, + systemAudioMessageShown: !systemHidden, + retrySystemAudio, + dismissSystemAudio, start, stop, subscribeLevel