diff --git a/src/main/speech/stt-recognizer.ts b/src/main/speech/stt-recognizer.ts index 1998151130c..fb440a87295 100644 --- a/src/main/speech/stt-recognizer.ts +++ b/src/main/speech/stt-recognizer.ts @@ -29,4 +29,6 @@ export type SttRecognizer = { finish(streamId: string): Promise /** Drop the stream's audio undecoded. */ discard(streamId: string): void + /** Called on a cancel's arrival, ahead of the queue: skip the stream's remaining chunks; the running decode finishes. */ + cancel(streamId: string): void } diff --git a/src/main/speech/stt-transcribe-cpp-recognizer.ts b/src/main/speech/stt-transcribe-cpp-recognizer.ts index 9d5b51f0852..f292db59403 100644 --- a/src/main/speech/stt-transcribe-cpp-recognizer.ts +++ b/src/main/speech/stt-transcribe-cpp-recognizer.ts @@ -174,9 +174,15 @@ export async function createTranscribeCppRecognizer( }) } + // Canceled streams, until their queued discard runs; also covers a finish that already closed its stream. + const canceled = new Set() + const decode = async (streamId: string, stream: StreamCoverage, chunks: Float32Array[]) => { let undecoded = chunks.reduce((total, chunk) => total + chunk.length, 0) for (const chunk of chunks) { + if (canceled.has(streamId)) { + return + } const startedAt = performance.now() const text = await transcribeChunk(chunk, stream.options) const decodeMs = performance.now() - startedAt @@ -254,7 +260,11 @@ export async function createTranscribeCppRecognizer( } }, discard(streamId) { + canceled.delete(streamId) closeStream(streamId)?.vad?.dispose() + }, + cancel(streamId) { + canceled.add(streamId) } } } diff --git a/src/main/speech/stt-worker.ts b/src/main/speech/stt-worker.ts index c85146e3bd2..ebcbdcc64b4 100644 --- a/src/main/speech/stt-worker.ts +++ b/src/main/speech/stt-worker.ts @@ -114,6 +114,7 @@ async function handleStop(streamId: string): Promise { // A cancel answers at once, even during Finish, and the stream's queued audio is skipped rather than decoded. function cancelStream(streamId: string): void { discarded.add(streamId) + recognizer?.cancel(streamId) const input = audioPorts.get(streamId) audioPorts.delete(streamId) input?.port.close()