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: 4 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,10 @@ jobs:
cache: pip
# sounddevice needs PortAudio; phonemizer (pulled in by kokoro-onnx) needs espeak-ng.
- name: install system audio/phoneme deps
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libportaudio2 espeak-ng
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends libportaudio2 espeak-ng pulseaudio
pulseaudio --start --exit-idle-time=-1
- run: pip install -e ".[dev]"
- name: run tests (with coverage on 3.12)
run: |
Expand Down
54 changes: 37 additions & 17 deletions stackvox/daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
DEFAULT_SPEED,
DEFAULT_VOICE,
MLX_OPTIONS,
OutputStalledError,
Playback,
Stackvox,
)
Expand Down Expand Up @@ -213,13 +214,13 @@ def _exit_wedged() -> None:
"""Exit hard so a fresh daemon can take over from a wedged one.

On macOS the worker has been seen deadlocked inside PortAudio's stream stop,
waiting on a CoreAudio lock held by CoreAudio's own IO thread, and parked
for days in a blocking write to an output device that stopped taking audio,
which `cancel`'s stream abort didn't release. A normal shutdown didn't get
out of the first (`stop` timed out with the process still alive), so this
uses `os._exit`. The socket goes first: clients that start
the daemon on demand do so when the socket is missing, and until it is gone
they keep getting `busy`.
waiting on a CoreAudio lock held by CoreAudio's own IO thread. It was also
seen parked for days in a blocking write to an output device that stopped
taking audio, which the engine now gives up on by itself (`OutputStalledError`,
replayed by `_play`). A normal shutdown didn't get out of the first (`stop`
timed out with the process still alive), so this uses `os._exit`. The socket
goes first: clients that start the daemon on demand do so when the socket is
missing, and until it is gone they keep getting `busy`.
"""
_remove_runtime_files()
os._exit(os.EX_SOFTWARE)
Expand Down Expand Up @@ -290,16 +291,7 @@ def _worker(self) -> None:
_refresh_audio_devices()
_audio_dirty.clear()
try:
generation_kwargs: dict[str, Any] = {
key: req.get(key, self.generation_defaults.get(key)) for key in MLX_OPTIONS
}
playback = self.tts.speak(
req["text"],
voice=req.get("voice"),
speed=req.get("speed"),
lang=req.get("lang"),
**generation_kwargs,
)
playback = self._play(req)
except Exception:
logger.exception("playback error")
# Failed playback might be a stale audio context; mark dirty
Expand All @@ -314,6 +306,34 @@ def _worker(self) -> None:
)
self.deadline = None

def _play(self, req: dict) -> Playback | None:
"""Speak one request, replaying it once on a fresh stream if the output
device stops taking audio.

PortAudio is reset first, in case the device went away or the default
output changed. The replay gets a fresh deadline.
"""
try:
return self._speak(req)
except OutputStalledError:
logger.warning("output device stopped taking audio; resetting audio devices and replaying")
_refresh_audio_devices()
_audio_dirty.clear()
self.deadline = time.monotonic() + _utterance_budget(req["text"])
return self._speak(req)

def _speak(self, req: dict) -> Playback | None:
generation_kwargs: dict[str, Any] = {
key: req.get(key, self.generation_defaults.get(key)) for key in MLX_OPTIONS
}
return self.tts.speak(
req["text"],
voice=req.get("voice"),
speed=req.get("speed"),
lang=req.get("lang"),
**generation_kwargs,
)

def overrun(self, now: float) -> float | None:
"""Seconds the current request has run past its deadline, or None if
the worker is idle or still within budget."""
Expand Down
47 changes: 44 additions & 3 deletions stackvox/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@
# silence, and ramp the opening samples up from zero to avoid an onset click.
_PRIME_SILENCE_SECONDS = 0.12
_FADE_IN_SECONDS = 0.008
# How long the output device may take no audio before playback gives up on it.
# Well past a Bluetooth codec switch, which can hold the device for a second or
# two before it starts pulling.
_STALL_SECONDS = 5.0
_WRITE_POLL_SECONDS = 0.005


class OutputStalledError(RuntimeError):
"""The output device stopped taking audio partway through playback."""


@dataclass(frozen=True)
Expand Down Expand Up @@ -173,6 +182,29 @@ def _fade_in(samples: np.ndarray, sample_rate: int) -> np.ndarray:
return faded


def _write(stream: sd.OutputStream, samples: np.ndarray, stop_event: threading.Event) -> None:
"""Write ``samples`` as the device makes room, raising ``OutputStalledError``
if it takes nothing for ``_STALL_SECONDS``.

A plain blocking ``write`` waits for room forever, and on macOS a device that
stops pulling audio (seen with a USB DAC) leaves it parked with no CoreAudio
IO thread left to drain the buffer. Returns early once ``stop_event`` is set.
"""
written = 0
last_progress = time.monotonic()
while written < len(samples) and not stop_event.is_set():
available = stream.write_available
if available > 0:
end = written + available
stream.write(samples[written:end])
written = min(end, len(samples))
last_progress = time.monotonic()
elif time.monotonic() - last_progress > _STALL_SECONDS:
raise OutputStalledError(f"output device took no audio for {_STALL_SECONDS:.0f}s")
else:
time.sleep(_WRITE_POLL_SECONDS)


class Stackvox:
"""Reusable TTS engine. Load the model once, speak many times.

Expand Down Expand Up @@ -551,6 +583,7 @@ def _stream_play(
top_k=top_k,
)
stream: sd.OutputStream | None = None
stalled = False
first_audio_at: float | None = None
audio_seconds = 0.0
try:
Expand All @@ -568,16 +601,19 @@ def _stream_play(
self._stream = stream
prime = int(sample_rate * _PRIME_SILENCE_SECONDS)
if prime > 0:
stream.write(np.zeros(prime, dtype="float32"))
_write(stream, np.zeros(prime, dtype="float32"), stop_event)
samples = _fade_in(samples, sample_rate)
first_audio_at = time.monotonic()
try:
stream.write(samples)
_write(stream, samples, stop_event)
except Exception:
if stop_event.is_set():
break # aborted by stop(); expected
raise
audio_seconds += len(samples) / sample_rate
except OutputStalledError:
stalled = True
raise
finally:
# Release the output device before draining the synth thread, so a
# stop() doesn't hold the device open for however long the in-flight
Expand All @@ -586,7 +622,12 @@ def _stream_play(
self._stream = None
if stream is not None:
try:
stream.stop()
# stop() waits for the queued audio to play out, which a
# stalled device never does.
if stalled:
stream.abort()
else:
stream.stop()
stream.close()
except Exception:
logger.debug("stream teardown failed", exc_info=True)
Expand Down
44 changes: 43 additions & 1 deletion tests/test_daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import pytest

from stackvox import daemon
from stackvox.engine import Playback
from stackvox.engine import OutputStalledError, Playback


class TestPidAlive:
Expand Down Expand Up @@ -427,6 +427,48 @@ def test_logs_nothing_when_playback_fails(self, state, caplog):
assert not any("spoke" in message for message in caplog.messages)


class TestStalledOutput:
def test_resets_audio_devices_and_replays_the_request(self, state, caplog, mocker):
refresh = mocker.patch.object(daemon, "_refresh_audio_devices")
refreshes_before_each_attempt = []

def speak(*args, **kwargs):
refreshes_before_each_attempt.append(refresh.call_count)
if len(refreshes_before_each_attempt) == 1:
raise OutputStalledError("output device took no audio for 5s")
return Playback(first_audio_at=time.monotonic(), audio_seconds=1.0)

state.tts.speak.side_effect = speak

with caplog.at_level(logging.INFO, logger="stackvox.daemon"):
state.submit({"text": "hello"})
_wait_until(lambda: any("spoke" in message for message in caplog.messages))

first, second = refreshes_before_each_attempt
assert second == first + 1
assert any("stopped taking audio" in message for message in caplog.messages)
assert any(message.startswith("spoke 5 chars") for message in caplog.messages)

def test_replays_only_once(self, state, caplog):
state.tts.speak.side_effect = OutputStalledError("output device took no audio for 5s")

with caplog.at_level(logging.INFO, logger="stackvox.daemon"):
state.submit({"text": "hello"})
_wait_until(lambda: any("playback error" in message for message in caplog.messages))

assert state.tts.speak.call_count == 2
assert state.deadline is None

def test_does_not_replay_other_playback_errors(self, state, caplog):
state.tts.speak.side_effect = RuntimeError("device gone")

with caplog.at_level(logging.INFO, logger="stackvox.daemon"):
state.submit({"text": "hello"})
_wait_until(lambda: any("playback error" in message for message in caplog.messages))

assert state.tts.speak.call_count == 1


class TestOverrun:
def test_is_none_while_idle(self, state):
assert state.overrun(time.monotonic()) is None
Expand Down
83 changes: 81 additions & 2 deletions tests/test_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import logging
import threading
import time

import numpy as np
import pytest
Expand Down Expand Up @@ -42,8 +43,10 @@ def fake_ort(mocker):

@pytest.fixture
def fake_audio(mocker):
"""Mock the sounddevice surface used by Stackvox (streaming + speak_sequence)."""
mocker.patch.object(engine.sd, "OutputStream")
"""Mock the sounddevice surface used by Stackvox (streaming + speak_sequence).
The stream always has room, so each chunk goes out in one write."""
output_stream = mocker.patch.object(engine.sd, "OutputStream")
output_stream.return_value.write_available = 1_000_000
mocker.patch.object(engine.sd, "play")
mocker.patch.object(engine.sd, "wait")
mocker.patch.object(engine.sd, "stop")
Expand Down Expand Up @@ -358,6 +361,82 @@ def test_speak_after_stop_still_plays(self, fake_kokoro, fake_audio):
tts.speak("hello world")
engine.sd.OutputStream.assert_called()

def test_drains_the_stream_when_playback_finishes(self, fake_kokoro, fake_audio):
fake_kokoro.return_value.create.return_value = (np.zeros(4, dtype=np.float32), 24000)

engine.Stackvox().speak("hello")

stream = engine.sd.OutputStream.return_value
stream.stop.assert_called_once()
stream.abort.assert_not_called()

def test_aborts_the_stream_when_the_device_stops_taking_audio(self, fake_kokoro, fake_audio, mocker):
# stop() would wait for the queued audio to play out, which a stalled
# device never does.
mocker.patch.object(engine, "_STALL_SECONDS", 0.02)
fake_kokoro.return_value.create.return_value = (np.zeros(4, dtype=np.float32), 24000)
stream = engine.sd.OutputStream.return_value
stream.write_available = 0

with pytest.raises(engine.OutputStalledError):
engine.Stackvox().speak("hello")

stream.abort.assert_called_once()
stream.stop.assert_not_called()
stream.close.assert_called_once()


class TestWrite:
def test_writes_only_what_the_device_has_room_for(self, mocker):
stream = mocker.Mock()
type(stream).write_available = mocker.PropertyMock(side_effect=[3, 3, 10])
samples = np.arange(8, dtype=np.float32)

engine._write(stream, samples, threading.Event())

actual = [call.args[0].tolist() for call in stream.write.call_args_list]
assert actual == [[0, 1, 2], [3, 4, 5], [6, 7]]

def test_waits_while_the_device_is_briefly_full(self, mocker):
stream = mocker.Mock()
type(stream).write_available = mocker.PropertyMock(side_effect=[0, 0, 8])

engine._write(stream, np.zeros(8, dtype=np.float32), threading.Event())

stream.write.assert_called_once()

def test_raises_once_the_device_takes_nothing_for_the_stall_limit(self, mocker):
mocker.patch.object(engine, "_STALL_SECONDS", 0.02)
stream = mocker.Mock(write_available=0)

with pytest.raises(engine.OutputStalledError):
engine._write(stream, np.zeros(8, dtype=np.float32), threading.Event())

stream.write.assert_not_called()

def test_measures_the_stall_from_the_last_write_that_went_through(self, mocker):
# Slow but moving output (one frame a poll) is not a stall, however
# long the whole chunk takes.
mocker.patch.object(engine, "_STALL_SECONDS", 0.05)
frames = 12
stream = mocker.Mock()
type(stream).write_available = mocker.PropertyMock(side_effect=[1, 0, 0] * frames)
started = time.monotonic()

engine._write(stream, np.zeros(frames, dtype=np.float32), threading.Event())

assert stream.write.call_count == frames
assert time.monotonic() - started > engine._STALL_SECONDS

def test_returns_without_writing_once_stopped(self, mocker):
stream = mocker.Mock(write_available=0)
stop_event = threading.Event()
stop_event.set()

engine._write(stream, np.zeros(8, dtype=np.float32), stop_event)

stream.write.assert_not_called()


class TestSplitSentences:
def test_splits_on_sentence_punctuation(self):
Expand Down
Loading