Skip to content
Open
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
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
143 changes: 130 additions & 13 deletions lib/stt.js
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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 ----
Expand All @@ -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';
Expand All @@ -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() })}`;
}
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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");
}

Expand Down Expand Up @@ -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);
Expand Down
19 changes: 19 additions & 0 deletions test/stt.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
buildRecordArgs,
buildWhisperArgs,
isOpenRouterEndpoint,
isPulseLikeBackend,
isWSL,
parsePactlSources,
parsePactlSourcesShort,
Expand Down Expand Up @@ -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/,
);
});