Skip to content
Merged
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: 5 additions & 0 deletions .changeset/surround-system-audio.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 8 additions & 1 deletion apps/lyra/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
Expand All @@ -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))
Expand Down
23 changes: 23 additions & 0 deletions apps/lyra/src/main/systemAudioSource.test.ts
Original file line number Diff line number Diff line change
@@ -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')
})
})
21 changes: 21 additions & 0 deletions apps/lyra/src/main/systemAudioSource.ts
Original file line number Diff line number Diff line change
@@ -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'
}
12 changes: 10 additions & 2 deletions apps/lyra/src/renderer/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -767,7 +767,8 @@ export default function App(): React.JSX.Element {
<RecordingReadout
startedAt={listeningSince}
micName={dictation.micName}
systemAudio={systemAudio}
// Mic only in the readout while computer audio isn't actually being recorded.
systemAudio={dictation.systemAudio === 'live'}
subscribeLevel={dictation.subscribeLevel}
/>
) : null
Expand Down Expand Up @@ -1174,6 +1175,13 @@ export default function App(): React.JSX.Element {
/>
) : null}
<DictationMessage error={dictation.error} notice={dictation.notice} onDismiss={dictation.dismissMessage} />
{dictation.systemAudioMessageShown ? (
<SystemAudioMessage
state={dictation.systemAudio}
onRetry={dictation.retrySystemAudio}
onDismiss={dictation.dismissSystemAudio}
/>
) : null}
{toastElement}
</ToastStack>
</div>
Expand Down
48 changes: 38 additions & 10 deletions apps/lyra/src/renderer/src/audio/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -75,18 +76,26 @@ 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
}

/** Things the user should hear about while the capture carries on by itself. */
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
Expand Down Expand Up @@ -157,8 +166,11 @@ export async function openMicrophone(deviceId: string | null = null): Promise<Op
}

export type CaptureOptions = {
/** System audio (the other side of a call), recorded as its own track. */
system?: MediaStream
/**
* System audio (the other side of a call), recorded as its own track. Null when it was asked
* for but didn't open: the track is kept (silent) and `reopenSystem` keeps trying.
*/
system?: MediaStream | null
/** Opens system audio again, when its track ends or the default output changes. */
reopenSystem?: () => Promise<MediaStream | null>
/**
Expand Down Expand Up @@ -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, {
Expand All @@ -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',
Expand All @@ -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)
Expand Down Expand Up @@ -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<void> => {
const reconnectSystem = async (
reason: string,
delays: readonly number[] = RECONNECT_DELAYS_MS
): Promise<void> => {
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
}
Expand All @@ -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
}
Expand All @@ -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')
}
Expand Down Expand Up @@ -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,
Expand All @@ -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
}),
Expand All @@ -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
Expand Down
30 changes: 30 additions & 0 deletions apps/lyra/src/renderer/src/audio/recovery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
RECONNECT_DELAYS_MS,
microphoneErrorMessage,
nextStall,
nextSystemAudio,
retryOpen,
shouldReopenSystem,
type StallState
Expand Down Expand Up @@ -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')
})
})
28 changes: 28 additions & 0 deletions apps/lyra/src/renderer/src/audio/recovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading
Loading