Skip to content

Commit 9988695

Browse files
committed
fix(tts): drain Kokoro buffer on streamStop and add canFlush insert option
`Kokoro::stream` hung when the buffer held content without an end-of-sentence character: the force-flush branch still used `chunkSize = 0`, so the loop reset its skip counter without draining anything and `streamStop(false)` never returned (#1153). Two changes: - Force-flush now grabs the entire searchable window instead of 0 characters, and `streamStop(false)` sets a dedicated drain flag so the remaining tail is always released — `streamStop(false)` is now guaranteed to return. - `streamInsert(text, { canFlush })` lets the caller opt out of the skipped-iterations force-flush. LLM-style callers feeding partial tokens pass `canFlush: false` to avoid mid-sentence flushes; the trailing tail is still drained when they call `streamStop(false)`. The speech app's LLM-to-TTS demo is updated to pass `canFlush: false`. Fixes #1153.
1 parent 72e2d55 commit 9988695

8 files changed

Lines changed: 127 additions & 14 deletions

File tree

‎apps/speech/screens/TextToSpeechLLMScreen.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,9 @@ export const TextToSpeechLLMScreen = ({ onBack }: TextToSpeechLLMProps) => {
7878
const previousLength = processedLengthRef.current;
7979
if (llm.response.length > previousLength && isTtsStreaming) {
8080
const newChunk = llm.response.slice(previousLength);
81-
tts.streamInsert(newChunk);
81+
// Incremental LLM tokens — disable mid-sentence force-flushes; the
82+
// trailing tail is drained by `streamStop(false)` in the finally block.
83+
tts.streamInsert(newChunk, { canFlush: false });
8284
processedLengthRef.current = llm.response.length;
8385
}
8486
} else {

‎packages/react-native-executorch/common/rnexecutorch/host_objects/JsiConversions.h‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
#include <rnexecutorch/models/speech_to_text/common/types/Segment.h>
2727
#include <rnexecutorch/models/speech_to_text/common/types/TranscriptionResult.h>
2828
#include <rnexecutorch/models/style_transfer/Types.h>
29+
#include <rnexecutorch/models/text_to_speech/kokoro/Types.h>
2930
#include <rnexecutorch/models/voice_activity_detection/Types.h>
3031
#include <rnexecutorch/utils/computer_vision/Types.h>
3132

@@ -129,6 +130,24 @@ inline JSTensorViewIn getValue<JSTensorViewIn>(const jsi::Value &val,
129130
return tensorView;
130131
}
131132

133+
// Reads a `Kokoro::streamInsert` options object. Each field is optional —
134+
// missing keys keep their struct defaults.
135+
template <>
136+
inline rnexecutorch::models::text_to_speech::kokoro::StreamInsertOptions
137+
getValue<rnexecutorch::models::text_to_speech::kokoro::StreamInsertOptions>(
138+
const jsi::Value &val, jsi::Runtime &runtime) {
139+
rnexecutorch::models::text_to_speech::kokoro::StreamInsertOptions opts;
140+
if (!val.isObject()) {
141+
return opts;
142+
}
143+
jsi::Object obj = val.asObject(runtime);
144+
if (obj.hasProperty(runtime, "canFlush")) {
145+
opts.canFlush =
146+
getValue<bool>(obj.getProperty(runtime, "canFlush"), runtime);
147+
}
148+
return opts;
149+
}
150+
132151
// C++ set from JS array. Set with heterogenerous look-up (adding std::less<>
133152
// enables querying with std::string_view).
134153
template <>

‎packages/react-native-executorch/common/rnexecutorch/models/text_to_speech/kokoro/Kokoro.cpp‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ void Kokoro::stream(std::shared_ptr<jsi::Function> callback, float speed,
174174

175175
isStreaming_ = true;
176176
stopOnEmptyBuffer_ = stopOnEmptyBuffer;
177+
streamStopRequested_ = false;
177178

178179
// The outer streaming loop is responsible for handling the input buffer.
179180
// The extracted text is then passed to the inner loop, which performs a
@@ -206,9 +207,19 @@ void Kokoro::stream(std::shared_ptr<jsi::Function> callback, float speed,
206207
: 0;
207208

208209
// To maximize the quality of the speech, we try to avoid processing
209-
// chunks which end in the middle of a sentence.
210-
if (chunkSize > 0 ||
211-
streamSkippedIterations >= params::kStreamMaxSkippedIterations) {
210+
// chunks which end in the middle of a sentence. A force-flush picks up
211+
// the entire searchable window when no EOS is in sight; we only allow it
212+
// when the most recent insert opted in via `canFlush`, or when
213+
// `streamStop(false)` requested an unconditional drain — otherwise the
214+
// loop holds back partial content (relevant for LLM token streaming).
215+
const bool forceFlushAllowed =
216+
lastInsertCanFlush_.load() &&
217+
streamSkippedIterations >= params::kStreamMaxSkippedIterations;
218+
const bool drainOnStop = streamStopRequested_.load();
219+
if (chunkSize > 0 || forceFlushAllowed || drainOnStop) {
220+
if (chunkSize == 0) {
221+
chunkSize = searchLimit;
222+
}
212223
input = inputTextBuffer_.substr(0, chunkSize);
213224
inputTextBuffer_.erase(0, chunkSize);
214225
streamSkippedIterations = 0;
@@ -318,6 +329,8 @@ void Kokoro::stream(std::shared_ptr<jsi::Function> callback, float speed,
318329
inputTextBuffer_.clear();
319330
isStreaming_ = false;
320331
streamSkippedIterations = 0;
332+
streamStopRequested_ = false;
333+
lastInsertCanFlush_ = true;
321334
}
322335
}
323336

@@ -405,15 +418,22 @@ std::vector<float> Kokoro::synthesize(std::u32string_view phonemes, float speed,
405418
return {audio.begin(), audio.end()};
406419
}
407420

408-
void Kokoro::streamInsert(std::u32string chunk) noexcept {
421+
void Kokoro::streamInsert(std::u32string chunk,
422+
StreamInsertOptions opts) noexcept {
409423
std::scoped_lock<std::mutex> lock(inputTextBufferMutex_);
410424
inputTextBuffer_.append(chunk);
425+
// Latest-insert-wins: the most recent caller's intent decides whether the
426+
// streaming loop may force-flush during the next idle window.
427+
lastInsertCanFlush_ = opts.canFlush;
411428
}
412429

413430
void Kokoro::streamStop(bool instant) noexcept {
414431
if (instant) {
415432
isStreaming_ = false;
416433
} else {
434+
// Ensure trailing un-terminated content is drained before the loop exits,
435+
// even if the most recent insert set `canFlush = false`.
436+
streamStopRequested_ = true;
417437
stopOnEmptyBuffer_ = true;
418438
}
419439
}

‎packages/react-native-executorch/common/rnexecutorch/models/text_to_speech/kokoro/Kokoro.h‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,18 @@ class Kokoro {
5757
* Appends new input data (either text or phonemes) to the buffer.
5858
*
5959
* @param chunk A text/phonemes chunk to be added to the streaming buffer.
60+
* @param opts Per-call options — see `StreamInsertOptions` for the meaning
61+
* of `canFlush` and the guarantees the caller must uphold when disabling it.
6062
*/
61-
void streamInsert(std::u32string chunk) noexcept;
63+
void streamInsert(std::u32string chunk, StreamInsertOptions opts) noexcept;
6264

6365
/**
6466
* Signals the streaming process to stop.
6567
*
6668
* @param instant If true, stops immediately, discarding remaining buffered
67-
* text. If false, finishes processing the current buffer before stopping.
69+
* text. If false, finishes processing the current buffer before stopping —
70+
* any trailing un-terminated content is force-flushed regardless of the
71+
* most recent `StreamInsertOptions::canFlush` value.
6872
*/
6973
void streamStop(bool instant) noexcept;
7074

@@ -100,6 +104,15 @@ class Kokoro {
100104
// --- Streaming control State ---
101105
std::atomic<bool> isStreaming_{false};
102106
std::atomic<bool> stopOnEmptyBuffer_{true};
107+
// Reflects the `canFlush` flag of the most recent `streamInsert` call. When
108+
// false, the streaming loop will not trip the skipped-iterations
109+
// force-flush — the caller is in control of when partial content gets sent
110+
// to the synthesizer.
111+
std::atomic<bool> lastInsertCanFlush_{true};
112+
// Set by `streamStop(false)` to request an unconditional drain on the next
113+
// stream iteration, bypassing `lastInsertCanFlush_`. Cleared when `stream()`
114+
// exits.
115+
std::atomic<bool> streamStopRequested_{false};
103116
int32_t streamSkippedIterations = 0;
104117
};
105118
} // namespace models::text_to_speech::kokoro

‎packages/react-native-executorch/common/rnexecutorch/models/text_to_speech/kokoro/Types.h‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,23 @@ struct Timestamp {
2828
size_t end = 0;
2929
};
3030

31+
/**
32+
* Type definition - per-call options for `Kokoro::streamInsert`.
33+
*
34+
* Grouped into a struct so additional knobs can be added without breaking the
35+
* JSI binding's positional-argument contract.
36+
*/
37+
struct StreamInsertOptions {
38+
/**
39+
* Whether the streaming loop is allowed to force-flush the pending buffer
40+
* after `kStreamMaxSkippedIterations` idle iterations.
41+
*
42+
* Pass `false` when feeding partial fragments (e.g. LLM tokens) where
43+
* mid-sentence flushes would degrade speech quality — the caller is then
44+
* responsible for ending the buffer with an EOS-bearing insert or
45+
* `streamStop(false)` to release any trailing un-terminated tail.
46+
*/
47+
bool canFlush = true;
48+
};
49+
3150
} // namespace rnexecutorch::models::text_to_speech::kokoro

‎packages/react-native-executorch/src/hooks/natural_language_processing/useTextToSpeech.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
TextToSpeechInput,
55
TextToSpeechModelConfig,
66
TextToSpeechStreamingInput,
7+
TextToSpeechStreamInsertOptions,
78
TextToSpeechType,
89
} from '../../types/tts';
910
import { RnExecutorchErrorCode } from '../../errors/ErrorCodes';
@@ -133,9 +134,9 @@ export const useTextToSpeech = (
133134
);
134135

135136
const streamInsert = useCallback(
136-
(text: string) => {
137+
(text: string, options?: TextToSpeechStreamInsertOptions) => {
137138
if (moduleInstance) {
138-
moduleInstance.streamInsert(text);
139+
moduleInstance.streamInsert(text, options);
139140
}
140141
},
141142
[moduleInstance]

‎packages/react-native-executorch/src/modules/natural_language_processing/TextToSpeechModule.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
TextToSpeechModelConfig,
77
TextToSpeechModelSources,
88
TextToSpeechStreamingInput,
9+
TextToSpeechStreamInsertOptions,
910
} from '../../types/tts';
1011
import { Logger } from '../../common/Logger';
1112

@@ -186,9 +187,16 @@ export class TextToSpeechModule {
186187
/**
187188
* Inserts new content (text or IPA phonemes) into the buffer to be processed in streaming mode.
188189
* @param input - The text or phoneme fragment to append to the streaming buffer.
190+
* @param options - Optional per-call options. Set `canFlush: false` when feeding
191+
* partial fragments (e.g. LLM tokens) to prevent the streaming
192+
* loop from force-flushing mid-sentence. See
193+
* {@link TextToSpeechStreamInsertOptions} for full semantics.
189194
*/
190-
public streamInsert(input: string): void {
191-
this.nativeModule.streamInsert(input);
195+
public streamInsert(
196+
input: string,
197+
options: TextToSpeechStreamInsertOptions = {}
198+
): void {
199+
this.nativeModule.streamInsert(input, { canFlush: options.canFlush ?? true });
192200
}
193201

194202
/**

‎packages/react-native-executorch/src/types/tts.ts‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,28 @@ export interface TextToSpeechInput {
9191
phonemize?: boolean;
9292
}
9393

94+
/**
95+
* Per-call options for {@link TextToSpeechType.streamInsert}.
96+
*
97+
* Grouped into an object so additional knobs can be added later without
98+
* breaking call sites.
99+
* @category Types
100+
*/
101+
export interface TextToSpeechStreamInsertOptions {
102+
/**
103+
* Whether the streaming loop is allowed to force-flush the pending buffer
104+
* after a short idle window (default: `true`).
105+
*
106+
* Pass `false` when feeding partial fragments (e.g. incremental LLM tokens)
107+
* where mid-sentence flushes would degrade speech quality. The caller is
108+
* then responsible for ending the buffer either with a follow-up insert
109+
* that contains an end-of-sentence character or with `streamStop(false)` —
110+
* otherwise any trailing un-terminated tail will sit in the buffer until
111+
* the stream is interrupted.
112+
*/
113+
canFlush?: boolean;
114+
}
115+
94116
/**
95117
* Return type for the `useTextToSpeech` hook.
96118
* Manages the state and operations for Text-to-Speech generation.
@@ -135,14 +157,23 @@ export interface TextToSpeechType {
135157
stream: (input: TextToSpeechStreamingInput) => Promise<void>;
136158

137159
/**
138-
* Inserts new text chunk into the buffer to be processed in streaming mode.
160+
* Inserts a new text chunk into the buffer to be processed in streaming mode.
161+
* @param textChunk - Text (or IPA phonemes) to append to the streaming buffer.
162+
* @param options - Optional per-call options; see {@link TextToSpeechStreamInsertOptions.canFlush}
163+
* for how to disable mid-sentence force-flushes in LLM-style streaming.
139164
*/
140-
streamInsert: (textChunk: string) => void;
165+
streamInsert: (
166+
textChunk: string,
167+
options?: TextToSpeechStreamInsertOptions
168+
) => void;
141169

142170
/**
143171
* Interrupts and stops the currently active audio generation stream.
144172
* @param instant If true, stops the streaming as soon as possible. Otherwise
145-
* allows the module to complete processing for the remains of the buffer.
173+
* allows the module to complete processing for the remains of
174+
* the buffer — any trailing un-terminated content is
175+
* force-flushed regardless of the most recent `canFlush`
176+
* value, so this call always returns.
146177
*/
147178
streamStop: (instant?: boolean) => void;
148179
}

0 commit comments

Comments
 (0)