Skip to content

Commit 59dae4f

Browse files
committed
fix(tui): stop audio engine when playback goes idle
The engine started on first play and stayed open for the lifetime of the process. A device left open while idle can wedge (observed: an ALSA timer fd stuck readable across suspend/resume) and spin the engine poll loop at 100% CPU indefinitely, also leaking memory. Stop the engine once voices drain (play() restarts it on demand) and release it on attention teardown. Fixes: anomalyco#54513
1 parent 35ef229 commit 59dae4f

4 files changed

Lines changed: 194 additions & 1 deletion

File tree

‎packages/tui/src/attention.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,9 @@ export function createTuiAttention(input: {
184184
disposed = true
185185
input.renderer.off("focus", onFocus)
186186
input.renderer.off("blur", onBlur)
187+
// Release the shared engine; otherwise its device stays open for the
188+
// lifetime of the process even after the TUI is gone.
189+
if (audio === TuiAudio) TuiAudio.dispose()
187190
},
188191
}
189192
}

‎packages/tui/src/audio.ts‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,54 @@ import { readFile } from "node:fs/promises"
44
let audio: Audio | null | undefined
55
const sounds = new Map<string, Promise<AudioSound | null>>()
66

7+
// Stop the engine this long after the last play once no voices are active.
8+
// Stopping closes the native playback device, and play() restarts it on
9+
// demand, so the device is only open around actual playback. A device left
10+
// open while idle can wedge (e.g. an ALSA timer fd stuck readable across
11+
// suspend/resume) and spin the engine's poll loop at 100% CPU indefinitely.
12+
const IDLE_STOP_MS = 1000
13+
let idleTimer: ReturnType<typeof setTimeout> | undefined
14+
15+
function clearIdleTimer() {
16+
if (idleTimer === undefined) return
17+
clearTimeout(idleTimer)
18+
idleTimer = undefined
19+
}
20+
21+
function scheduleIdleStop() {
22+
clearIdleTimer()
23+
idleTimer = setTimeout(stopWhenIdle, IDLE_STOP_MS).unref()
24+
}
25+
26+
function stopWhenIdle() {
27+
idleTimer = undefined
28+
const current = audio
29+
if (!current?.isStarted()) return
30+
if (voicesActive(current) > 0) {
31+
scheduleIdleStop()
32+
return
33+
}
34+
if (!stopSafely(current)) dispose()
35+
}
36+
37+
function voicesActive(engine: Audio) {
38+
try {
39+
return engine.getStats()?.voicesActive ?? 0
40+
} catch (error) {
41+
console.debug("failed to read tui audio stats", { error })
42+
return 0
43+
}
44+
}
45+
46+
function stopSafely(engine: Audio) {
47+
try {
48+
return engine.stop()
49+
} catch (error) {
50+
console.debug("failed to stop idle tui audio", { error })
51+
return false
52+
}
53+
}
54+
755
function getAudio() {
856
if (audio !== undefined) return audio
957
try {
@@ -39,10 +87,13 @@ export function play(sound: AudioSound, options?: AudioPlayOptions) {
3987
const current = getAudio()
4088
if (!current) return null
4189
if (!current.isStarted() && !current.start()) return null
42-
return current.play(sound, options)
90+
const voice = current.play(sound, options)
91+
if (voice !== null) scheduleIdleStop()
92+
return voice
4393
}
4494

4595
export function dispose() {
96+
clearIdleTimer()
4697
audio?.dispose()
4798
audio = undefined
4899
sounds.clear()

‎packages/tui/test/audio-fake.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// Test double for the native audio engine. Lives in its own module so the
2+
// mock.module() factory in audio.test.ts can reference it: the factory runs
3+
// while imports are still being evaluated, so anything it touches must
4+
// already be initialized (a helper module imported first satisfies that).
5+
6+
export const engines: FakeAudio[] = []
7+
8+
export function resetFakes() {
9+
engines.length = 0
10+
}
11+
12+
export class FakeAudio {
13+
started = false
14+
stopCalls = 0
15+
stopResult = true
16+
disposed = false
17+
voices = 0
18+
sounds = 0
19+
20+
static create() {
21+
const engine = new FakeAudio()
22+
engines.push(engine)
23+
return engine
24+
}
25+
26+
on() {
27+
return this
28+
}
29+
30+
isStarted() {
31+
return this.started
32+
}
33+
34+
start() {
35+
this.started = true
36+
return true
37+
}
38+
39+
play() {
40+
this.voices += 1
41+
return this.voices
42+
}
43+
44+
getStats() {
45+
return {
46+
soundsLoaded: this.sounds,
47+
voicesActive: this.voices,
48+
framesMixed: 0n,
49+
lockMisses: 0,
50+
lastPeak: 0,
51+
lastRms: 0,
52+
}
53+
}
54+
55+
stop() {
56+
this.stopCalls += 1
57+
this.started = false
58+
return this.stopResult
59+
}
60+
61+
loadSound() {
62+
this.sounds += 1
63+
return this.sounds
64+
}
65+
66+
dispose() {
67+
this.disposed = true
68+
}
69+
}
70+
71+
export const currentEngine = () => engines[engines.length - 1]

‎packages/tui/test/audio.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { beforeEach, describe, expect, mock, test } from "bun:test"
2+
import { currentEngine, FakeAudio, resetFakes } from "./audio-fake"
3+
4+
mock.module("@opentui/core", () => ({ Audio: FakeAudio }))
5+
6+
const { dispose, play } = await import("../src/audio")
7+
8+
async function idleSettled() {
9+
await Bun.sleep(1300)
10+
}
11+
12+
beforeEach(() => {
13+
dispose()
14+
resetFakes()
15+
})
16+
17+
describe("tui audio idle stop", () => {
18+
test("stops the engine once voices drain", async () => {
19+
const voice = play(1)
20+
expect(voice).toBe(1)
21+
const engine = currentEngine()
22+
expect(engine.isStarted()).toBe(true)
23+
24+
engine.voices = 0
25+
await idleSettled()
26+
27+
expect(engine.stopCalls).toBe(1)
28+
expect(engine.isStarted()).toBe(false)
29+
expect(engine.disposed).toBe(false)
30+
})
31+
32+
test("keeps the engine running while voices are active", async () => {
33+
play(1)
34+
const engine = currentEngine()
35+
36+
await idleSettled()
37+
expect(engine.stopCalls).toBe(0)
38+
39+
engine.voices = 0
40+
await idleSettled()
41+
expect(engine.stopCalls).toBe(1)
42+
})
43+
44+
test("restarts a stopped engine on the next play", async () => {
45+
play(1)
46+
const engine = currentEngine()
47+
engine.voices = 0
48+
await idleSettled()
49+
expect(engine.isStarted()).toBe(false)
50+
51+
play(1)
52+
expect(engine.isStarted()).toBe(true)
53+
expect(engine.stopCalls).toBe(1)
54+
})
55+
56+
test("disposes an engine that refuses to stop", async () => {
57+
play(1)
58+
const engine = currentEngine()
59+
engine.voices = 0
60+
engine.stopResult = false
61+
await idleSettled()
62+
63+
expect(engine.disposed).toBe(true)
64+
65+
play(1)
66+
expect(currentEngine()).not.toBe(engine)
67+
})
68+
})

0 commit comments

Comments
 (0)