From b0e51c42da7390bd4bcb0848e0a44b0b47e52960 Mon Sep 17 00:00:00 2001 From: Fede Ciliberti Date: Sat, 31 Oct 2026 17:12:07 -0300 Subject: [PATCH] fix(stt): capture through parec instead of sox -t pulseaudio on Linux detectAudioBackend() assumed that a reachable PulseAudio server implies sox can open a pulseaudio source. Stock Debian/Ubuntu sox ships only libsox-fmt-alsa and libsox-fmt-base, so recording died with: Recording error: sox FAIL formats: no handler for given file type `pulseaudio' Capture now goes through parec (pulseaudio-utils, present wherever pactl is) and its stdout is piped into sox as raw PCM, which needs no sox format plugin. The sox pulseaudio path stays for systems that do have the handler; parec is only preferred when the binary exists, and the coreaudio/alsa paths are untouched. Stopping waits a 500ms grace period before SIGINT so the server-side buffer drains into the pipe instead of discarding the tail of the speech, and waitForSoxExit gets a longer budget for the pipe to flush. --- README.md | 10 +++- lib/stt.js | 143 ++++++++++++++++++++++++++++++++++++++++++----- test/stt.test.js | 19 +++++++ 3 files changed, 156 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 1146a9e..1327128 100644 --- a/README.md +++ b/README.md @@ -58,9 +58,13 @@ rm -rf ~/.cache/opencode/packages/@renjfk/ ### Speech-to-text The plugin uses [whisper.cpp](https://github.com/ggml-org/whisper.cpp) via a -`whisper-cli` binary and `sox` for microphone capture. Follow the subsection -for your OS to install the binary and verify your microphone, then run the -shared **Download model & smoke test** step at the end. +`whisper-cli` binary and `sox` for microphone capture. On Linux the capture +itself goes through `parec` (from `pulseaudio-utils`, always present on +PipeWire/PulseAudio systems) piped into `sox`, because Debian and Ubuntu ship +`sox` without the pulseaudio format handler unless `libsox-fmt-pulse` is +installed. Follow the subsection for your OS to install the binary and verify +your microphone, then run the shared **Download model & smoke test** step at the +end. #### macOS diff --git a/lib/stt.js b/lib/stt.js index fa6ea80..e6fa5a7 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -12,6 +12,12 @@ let sttApiKeyEnv = null; const WAV_FILENAME = "opencode-stt.wav"; let tmpDir = "/tmp"; +// Grace period before killing parec: PulseAudio holds captured audio in its +// server-side buffer, so killing immediately discards the tail of the speech. +const STOP_GRACE_MS = 500; +// Capture latency asked from parec: lower means less audio in flight. +const PAREC_LATENCY_MSEC = 50; + const MODELS_DIRS = [ path.join(os.homedir(), ".local", "share", "whisper-cpp"), "/opt/homebrew/share/whisper-cpp/models", @@ -101,14 +107,37 @@ function getModelsDir() { // ---- Audio backend detection (coreaudio / pulseaudio / sox default) ---- +function commandExists(name) { + try { + execSync(`command -v ${name}`, { stdio: "ignore", timeout: 3000 }); + return true; + } catch { + return false; + } +} + +// Debian/Ubuntu ship sox without the pulseaudio format handler unless +// libsox-fmt-pulse is installed, and then `sox -t pulseaudio` dies with +// "no handler for given file type `pulseaudio'". parec ships with +// pulseaudio-utils (always present where pactl is), reads the same sources and +// needs no sox format plugin, so it is preferred on Linux. function detectAudioBackend() { if (process.platform === "darwin") return "coreaudio"; try { execSync("pactl --version", { stdio: "ignore", timeout: 3000 }); - return "pulseaudio"; } catch { return "default"; } + if (commandExists("parec")) return "parec"; + try { + const help = execSync("sox --help", { encoding: "utf-8", timeout: 3000 }); + if (/pulseaudio/i.test(help)) return "pulseaudio"; + } catch {} + return "default"; +} + +export function isPulseLikeBackend(backend) { + return backend === "pulseaudio" || backend === "parec"; } // ---- Audio server diagnostics ---- @@ -130,7 +159,7 @@ function pulseServerHealth() { // User-facing hint for missing devices / recording failures. On WSL the audio // server is WSLg's PulseAudio, which can wedge and needs a `wsl --shutdown`. export function buildAudioHint({ backend, serverOk, isWsl }) { - if (backend !== "pulseaudio") return "No input devices found"; + if (!isPulseLikeBackend(backend)) return "No input devices found"; if (serverOk) return "No input devices found - check your audio input source configuration"; if (isWsl) { return 'Audio server unreachable. On WSL, WSLg\'s PulseAudio may be stuck - run "wsl --shutdown" on Windows, then reopen Ubuntu'; @@ -141,7 +170,7 @@ export function buildAudioHint({ backend, serverOk, isWsl }) { // Appends a server-health hint to recording failure messages when the // PulseAudio server is unreachable (e.g. wedged WSLg on WSL). function audioFailureSuffix(backend) { - if (backend !== "pulseaudio") return ""; + if (!isPulseLikeBackend(backend)) return ""; if (pulseServerHealth().ok) return ""; return `. ${buildAudioHint({ backend, serverOk: false, isWsl: isWSL() })}`; } @@ -183,7 +212,7 @@ function listInputDevices(backend) { return []; } } - if (backend === "pulseaudio") { + if (isPulseLikeBackend(backend)) { try { const json = execSync("pactl -f json list sources 2>/dev/null", { encoding: "utf-8", @@ -214,11 +243,24 @@ export function buildRecordArgs(backend, mic) { // ---- Recording state and control ---- let soxProc = null; +let parecProc = null; +let stopGraceTimer = null; let soxStderr = ""; let recording = false; let processing = false; function forceKillSox(logger) { + if (stopGraceTimer) { + clearTimeout(stopGraceTimer); + stopGraceTimer = null; + } + if (parecProc) { + try { + process.kill(parecProc.pid, "SIGKILL"); + logger?.log("STT", `Killed parec pid=${parecProc.pid}`, "debug"); + } catch {} + parecProc = null; + } if (soxProc) { try { process.kill(soxProc.pid, "SIGKILL"); @@ -253,14 +295,70 @@ function startRecording(kv, backend, toast, logger, trimSilence = true) { ); const silenceArgs = trimSilence ? ["silence", "1", "0.1", "1%"] : []; - soxProc = spawn( - "sox", - [...inputArgs, "-r", "16000", "-c", "1", "-b", "16", wavFile, ...silenceArgs], - { - stdio: ["ignore", "ignore", "pipe"], - detached: false, - }, - ); + + if (backend === "parec") { + // parec captures from PulseAudio/PipeWire and its stdout is piped into sox, + // which only sees a raw PCM stream. Stopping is: SIGINT to parec -> its + // stdout closes -> sox sees EOF -> flushes and exits cleanly. + parecProc = spawn( + "parec", + [ + "--device", + mic || "@DEFAULT_SOURCE@", + "--format", + "s16le", + "--rate", + "16000", + "--channels", + "1", + "--latency-msec", + String(PAREC_LATENCY_MSEC), + ], + { stdio: ["ignore", "pipe", "pipe"] }, + ); + + parecProc.on("error", (err) => { + parecProc = null; + logger?.log("STT", `parec failed: ${err.message}`, "error"); + if (recording && !processing) { + recording = false; + forceKillSox(logger); + toast(`Recording failed: ${err.message}`, "error"); + } + }); + + soxProc = spawn( + "sox", + [ + "-t", + "raw", + "-r", + "16000", + "-c", + "1", + "-b", + "16", + "-e", + "signed-integer", + "-", + wavFile, + ...silenceArgs, + ], + { stdio: ["pipe", "ignore", "pipe"], detached: false }, + ); + + parecProc.stdout.pipe(soxProc.stdin); + logger?.log("STT", `parec pipeline connected device=${mic || "@DEFAULT_SOURCE@"}`, "debug"); + } else { + soxProc = spawn( + "sox", + [...inputArgs, "-r", "16000", "-c", "1", "-b", "16", wavFile, ...silenceArgs], + { + stdio: ["ignore", "ignore", "pipe"], + detached: false, + }, + ); + } soxProc.stderr.on("data", (chunk) => { soxStderr += chunk.toString(); @@ -297,6 +395,25 @@ function startRecording(kv, backend, toast, logger, trimSilence = true) { function stopRecording(logger) { logger?.log("STT", "Stopping recording", "debug"); + if (parecProc) { + // Let the server-side buffer drain into the pipe before cutting capture, + // otherwise the last ~0.5s of speech is lost. + const p = parecProc; + logger?.log("STT", `Stopping parec after ${STOP_GRACE_MS}ms grace`, "debug"); + stopGraceTimer = setTimeout(() => { + stopGraceTimer = null; + if (parecProc === p) parecProc = null; + try { + p.kill("SIGINT"); + } catch {} + setTimeout(() => { + try { + p.kill("SIGKILL"); + } catch {} + }, 3000); + }, STOP_GRACE_MS); + return; + } if (soxProc) soxProc.kill("SIGINT"); } @@ -555,7 +672,7 @@ async function doTranscribePipeline( try { logger?.log("STT", `Pipeline started submit=${submit}`, "debug"); stopRecording(logger); - await waitForSoxExit(logger); + await waitForSoxExit(logger, 4000); toast("Transcribing..."); const result = sttApiEndpoint ? await transcribeApi(kv, logger) : await transcribe(kv, logger); diff --git a/test/stt.test.js b/test/stt.test.js index 5418a59..dc5e40b 100644 --- a/test/stt.test.js +++ b/test/stt.test.js @@ -7,6 +7,7 @@ import { buildRecordArgs, buildWhisperArgs, isOpenRouterEndpoint, + isPulseLikeBackend, isWSL, parsePactlSources, parsePactlSourcesShort, @@ -132,3 +133,21 @@ test("builds whisper-cli args with language", () => { "-nt", ]); }); + +test("parec is handled as a pulse-like backend", () => { + assert.equal(isPulseLikeBackend("parec"), true); + assert.equal(isPulseLikeBackend("pulseaudio"), true); + assert.equal(isPulseLikeBackend("default"), false); + assert.equal(isPulseLikeBackend("coreaudio"), false); +}); + +test("audio hints cover the parec backend", () => { + assert.equal( + buildAudioHint({ backend: "parec", serverOk: true, isWsl: false }), + "No input devices found - check your audio input source configuration", + ); + assert.match( + buildAudioHint({ backend: "parec", serverOk: false, isWsl: false }), + /Audio server unreachable/, + ); +});