@livekit/agents-plugin-inworld 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/dist/index.cjs +35 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/tts.cjs +481 -0
- package/dist/tts.cjs.map +1 -0
- package/dist/tts.d.cts +91 -0
- package/dist/tts.d.ts +91 -0
- package/dist/tts.d.ts.map +1 -0
- package/dist/tts.js +457 -0
- package/dist/tts.js.map +1 -0
- package/package.json +51 -0
- package/src/index.ts +19 -0
- package/src/tts.ts +637 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
|
|
2
|
+
//
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import { Plugin } from '@livekit/agents';
|
|
5
|
+
import './tts.js';
|
|
6
|
+
|
|
7
|
+
export * from './tts.js';
|
|
8
|
+
|
|
9
|
+
class InworldPlugin extends Plugin {
|
|
10
|
+
constructor() {
|
|
11
|
+
super({
|
|
12
|
+
title: 'Inworld',
|
|
13
|
+
version: '0.1.0',
|
|
14
|
+
package: '@livekit/agents-plugin-inworld',
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
Plugin.registerPlugin(new InworldPlugin());
|
package/src/tts.ts
ADDED
|
@@ -0,0 +1,637 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2025 LiveKit, Inc.
|
|
2
|
+
//
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import { AudioByteStream, log, shortuuid, tokenize, tts } from '@livekit/agents';
|
|
5
|
+
import { type RawData, WebSocket } from 'ws';
|
|
6
|
+
|
|
7
|
+
const DEFAULT_BIT_RATE = 64000;
|
|
8
|
+
const DEFAULT_ENCODING = 'LINEAR16';
|
|
9
|
+
const DEFAULT_MODEL = 'inworld-tts-1';
|
|
10
|
+
const DEFAULT_SAMPLE_RATE = 24000;
|
|
11
|
+
const DEFAULT_URL = 'https://api.inworld.ai/';
|
|
12
|
+
const DEFAULT_WS_URL = 'wss://api.inworld.ai/';
|
|
13
|
+
const DEFAULT_VOICE = 'Ashley';
|
|
14
|
+
const DEFAULT_TEMPERATURE = 1.1;
|
|
15
|
+
const DEFAULT_SPEAKING_RATE = 1.0;
|
|
16
|
+
const DEFAULT_BUFFER_CHAR_THRESHOLD = 100;
|
|
17
|
+
const DEFAULT_MAX_BUFFER_DELAY_MS = 3000;
|
|
18
|
+
const NUM_CHANNELS = 1;
|
|
19
|
+
|
|
20
|
+
export type Encoding = 'LINEAR16' | 'MP3' | 'OGG_OPUS' | 'ALAW' | 'MULAW' | 'FLAC' | string;
|
|
21
|
+
export type TimestampType = 'TIMESTAMP_TYPE_UNSPECIFIED' | 'WORD' | 'CHARACTER';
|
|
22
|
+
export type TextNormalization = 'APPLY_TEXT_NORMALIZATION_UNSPECIFIED' | 'ON' | 'OFF';
|
|
23
|
+
|
|
24
|
+
export interface TTSOptions {
|
|
25
|
+
apiKey?: string;
|
|
26
|
+
voice: string;
|
|
27
|
+
model: string;
|
|
28
|
+
encoding: Encoding;
|
|
29
|
+
bitRate: number;
|
|
30
|
+
sampleRate: number;
|
|
31
|
+
speakingRate: number;
|
|
32
|
+
temperature: number;
|
|
33
|
+
timestampType?: TimestampType;
|
|
34
|
+
textNormalization?: TextNormalization;
|
|
35
|
+
bufferCharThreshold: number;
|
|
36
|
+
maxBufferDelayMs: number;
|
|
37
|
+
baseURL: string;
|
|
38
|
+
wsURL: string;
|
|
39
|
+
tokenizer?: tokenize.SentenceTokenizer;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// API request/response types
|
|
43
|
+
interface AudioConfig {
|
|
44
|
+
audioEncoding: Encoding;
|
|
45
|
+
sampleRateHertz: number;
|
|
46
|
+
bitrate: number;
|
|
47
|
+
speakingRate: number;
|
|
48
|
+
temperature?: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface SynthesizeRequest {
|
|
52
|
+
text: string;
|
|
53
|
+
voiceId: string;
|
|
54
|
+
modelId: string;
|
|
55
|
+
audioConfig: AudioConfig;
|
|
56
|
+
temperature: number;
|
|
57
|
+
timestampType?: TimestampType;
|
|
58
|
+
applyTextNormalization?: TextNormalization;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface CreateContextConfig {
|
|
62
|
+
voiceId: string;
|
|
63
|
+
modelId: string;
|
|
64
|
+
audioConfig: AudioConfig;
|
|
65
|
+
temperature: number;
|
|
66
|
+
bufferCharThreshold: number;
|
|
67
|
+
maxBufferDelayMs: number;
|
|
68
|
+
timestampType?: TimestampType;
|
|
69
|
+
applyTextNormalization?: TextNormalization;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface WordAlignment {
|
|
73
|
+
words: string[];
|
|
74
|
+
wordStartTimeSeconds: number[];
|
|
75
|
+
wordEndTimeSeconds: number[];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
interface CharacterAlignment {
|
|
79
|
+
characters: string[];
|
|
80
|
+
characterStartTimeSeconds: number[];
|
|
81
|
+
characterEndTimeSeconds: number[];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
interface TimestampInfo {
|
|
85
|
+
wordAlignment?: WordAlignment;
|
|
86
|
+
characterAlignment?: CharacterAlignment;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
interface AudioChunk {
|
|
90
|
+
audioContent?: string;
|
|
91
|
+
timestampInfo?: TimestampInfo;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
interface InworldResult {
|
|
95
|
+
contextId?: string;
|
|
96
|
+
contextCreated?: boolean;
|
|
97
|
+
contextClosed?: boolean;
|
|
98
|
+
audioChunk?: AudioChunk;
|
|
99
|
+
audioContent?: string;
|
|
100
|
+
status?: { code: number; message: string };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
interface InworldMessage {
|
|
104
|
+
result?: InworldResult;
|
|
105
|
+
contextId?: string;
|
|
106
|
+
error?: { message: string };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface Voice {
|
|
110
|
+
voiceId: string;
|
|
111
|
+
displayName: string;
|
|
112
|
+
description: string;
|
|
113
|
+
languages: string[];
|
|
114
|
+
tags: string[];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
interface ListVoicesResponse {
|
|
118
|
+
voices: Voice[];
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const defaultTTSOptionsBase: Omit<TTSOptions, 'tokenizer'> = {
|
|
122
|
+
apiKey: process.env.INWORLD_API_KEY,
|
|
123
|
+
voice: DEFAULT_VOICE,
|
|
124
|
+
model: DEFAULT_MODEL,
|
|
125
|
+
encoding: DEFAULT_ENCODING as Encoding,
|
|
126
|
+
bitRate: DEFAULT_BIT_RATE,
|
|
127
|
+
sampleRate: DEFAULT_SAMPLE_RATE,
|
|
128
|
+
speakingRate: DEFAULT_SPEAKING_RATE,
|
|
129
|
+
temperature: DEFAULT_TEMPERATURE,
|
|
130
|
+
bufferCharThreshold: DEFAULT_BUFFER_CHAR_THRESHOLD,
|
|
131
|
+
maxBufferDelayMs: DEFAULT_MAX_BUFFER_DELAY_MS,
|
|
132
|
+
baseURL: DEFAULT_URL,
|
|
133
|
+
wsURL: DEFAULT_WS_URL,
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const MAX_RETRIES = 2;
|
|
137
|
+
const BASE_DELAY_MS = 1000;
|
|
138
|
+
|
|
139
|
+
class WSConnectionPool {
|
|
140
|
+
#ws?: WebSocket;
|
|
141
|
+
#url: string;
|
|
142
|
+
#auth: string;
|
|
143
|
+
#connecting?: Promise<WebSocket>;
|
|
144
|
+
#listeners: Map<string, (msg: InworldMessage) => void> = new Map();
|
|
145
|
+
#logger = log();
|
|
146
|
+
|
|
147
|
+
constructor(url: string, auth: string) {
|
|
148
|
+
this.#url = url;
|
|
149
|
+
this.#auth = auth;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async getConnection(): Promise<WebSocket> {
|
|
153
|
+
if (this.#ws && this.#ws.readyState === WebSocket.OPEN) {
|
|
154
|
+
return this.#ws;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (this.#connecting) {
|
|
158
|
+
return this.#connecting;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
this.#connecting = this.#connectWithRetry();
|
|
162
|
+
return this.#connecting;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async #connectWithRetry(): Promise<WebSocket> {
|
|
166
|
+
let lastError: Error | undefined;
|
|
167
|
+
|
|
168
|
+
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
169
|
+
try {
|
|
170
|
+
return await this.#attemptConnection();
|
|
171
|
+
} catch (err) {
|
|
172
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
173
|
+
this.#connecting = undefined;
|
|
174
|
+
|
|
175
|
+
if (attempt < MAX_RETRIES) {
|
|
176
|
+
// Exponential backoff: 1s, 2s
|
|
177
|
+
const delayMs = BASE_DELAY_MS * Math.pow(2, attempt);
|
|
178
|
+
this.#logger.warn(
|
|
179
|
+
{ error: lastError, attempt: attempt + 1, maxRetries: MAX_RETRIES + 1, delayMs },
|
|
180
|
+
`Failed to connect to Inworld, retrying in ${delayMs}ms`,
|
|
181
|
+
);
|
|
182
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
throw new Error(
|
|
188
|
+
`Failed to connect to Inworld after ${MAX_RETRIES + 1} attempts: ${lastError?.message}`,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
#attemptConnection(): Promise<WebSocket> {
|
|
193
|
+
return new Promise((resolve, reject) => {
|
|
194
|
+
const wsUrl = new URL('tts/v1/voice:streamBidirectional', this.#url);
|
|
195
|
+
if (wsUrl.protocol === 'https:') wsUrl.protocol = 'wss:';
|
|
196
|
+
else if (wsUrl.protocol === 'http:') wsUrl.protocol = 'ws:';
|
|
197
|
+
|
|
198
|
+
const ws = new WebSocket(wsUrl.toString(), {
|
|
199
|
+
headers: { Authorization: this.#auth },
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
ws.on('open', () => {
|
|
203
|
+
this.#ws = ws;
|
|
204
|
+
this.#connecting = undefined;
|
|
205
|
+
resolve(ws);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
ws.on('error', (err) => {
|
|
209
|
+
if (this.#connecting) {
|
|
210
|
+
reject(err);
|
|
211
|
+
} else {
|
|
212
|
+
this.#logger.error({ err }, 'Inworld WebSocket error');
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
ws.on('close', () => {
|
|
217
|
+
this.#ws = undefined;
|
|
218
|
+
this.#connecting = undefined;
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
ws.on('message', (data: RawData) => {
|
|
222
|
+
try {
|
|
223
|
+
const json = JSON.parse(data.toString()) as InworldMessage;
|
|
224
|
+
const result = json.result;
|
|
225
|
+
if (result) {
|
|
226
|
+
const contextId = result.contextId || json.contextId;
|
|
227
|
+
if (contextId && this.#listeners.has(contextId)) {
|
|
228
|
+
this.#listeners.get(contextId)!(json);
|
|
229
|
+
}
|
|
230
|
+
} else if (json.error) {
|
|
231
|
+
this.#logger.warn({ error: json.error }, 'Inworld received error message');
|
|
232
|
+
}
|
|
233
|
+
} catch (e) {
|
|
234
|
+
this.#logger.warn({ error: e }, 'Failed to parse Inworld WebSocket message');
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
registerListener(contextId: string, cb: (msg: InworldMessage) => void) {
|
|
241
|
+
this.#listeners.set(contextId, cb);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
unregisterListener(contextId: string) {
|
|
245
|
+
this.#listeners.delete(contextId);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
close() {
|
|
249
|
+
if (this.#ws) {
|
|
250
|
+
this.#ws.close();
|
|
251
|
+
this.#ws = undefined;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export class TTS extends tts.TTS {
|
|
257
|
+
#opts: TTSOptions;
|
|
258
|
+
#pool: WSConnectionPool;
|
|
259
|
+
#authorization: string;
|
|
260
|
+
label = 'inworld.TTS';
|
|
261
|
+
|
|
262
|
+
constructor(opts: Partial<TTSOptions> = {}) {
|
|
263
|
+
const mergedOpts = { ...defaultTTSOptionsBase, ...opts };
|
|
264
|
+
if (!mergedOpts.apiKey) {
|
|
265
|
+
throw new Error('Inworld API key required. Set INWORLD_API_KEY or provide apiKey.');
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
super(mergedOpts.sampleRate, NUM_CHANNELS, {
|
|
269
|
+
streaming: true,
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
this.#opts = mergedOpts as TTSOptions;
|
|
273
|
+
if (!this.#opts.tokenizer) {
|
|
274
|
+
this.#opts.tokenizer = new tokenize.basic.SentenceTokenizer();
|
|
275
|
+
}
|
|
276
|
+
this.#authorization = `Basic ${mergedOpts.apiKey}`;
|
|
277
|
+
this.#pool = new WSConnectionPool(this.#opts.wsURL, this.#authorization);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
get pool(): WSConnectionPool {
|
|
281
|
+
return this.#pool;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
get authorization(): string {
|
|
285
|
+
return this.#authorization;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* List all available voices in the workspace associated with the API key.
|
|
290
|
+
* @param language - Optional ISO 639-1 language code to filter voices (e.g., 'en', 'es', 'fr')
|
|
291
|
+
*/
|
|
292
|
+
async listVoices(language?: string): Promise<Voice[]> {
|
|
293
|
+
const url = new URL('tts/v1/voices', this.#opts.baseURL);
|
|
294
|
+
if (language) {
|
|
295
|
+
url.searchParams.set('filter', `language=${language}`);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const response = await fetch(url.toString(), {
|
|
299
|
+
method: 'GET',
|
|
300
|
+
headers: {
|
|
301
|
+
Authorization: this.#authorization,
|
|
302
|
+
},
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
if (!response.ok) {
|
|
306
|
+
const errorBody = await response.json().catch(() => ({}));
|
|
307
|
+
throw new Error(
|
|
308
|
+
`Inworld API error: ${response.status} ${response.statusText}${errorBody.message ? ` - ${errorBody.message}` : ''}`,
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const data = (await response.json()) as ListVoicesResponse;
|
|
313
|
+
return data.voices;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
synthesize(text: string): tts.ChunkedStream {
|
|
317
|
+
return new ChunkedStream(this, text, this.#opts);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
stream(): tts.SynthesizeStream {
|
|
321
|
+
return new SynthesizeStream(this, this.#opts);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
updateOptions(opts: Partial<TTSOptions>) {
|
|
325
|
+
this.#opts = { ...this.#opts, ...opts };
|
|
326
|
+
if (opts.apiKey) {
|
|
327
|
+
this.#authorization = `Basic ${opts.apiKey}`;
|
|
328
|
+
this.#pool.close();
|
|
329
|
+
this.#pool = new WSConnectionPool(this.#opts.wsURL, this.#authorization);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async close() {
|
|
334
|
+
this.#pool.close();
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
class ChunkedStream extends tts.ChunkedStream {
|
|
339
|
+
#opts: TTSOptions;
|
|
340
|
+
#tts: TTS;
|
|
341
|
+
label = 'inworld.ChunkedStream';
|
|
342
|
+
|
|
343
|
+
constructor(ttsInstance: TTS, text: string, opts: TTSOptions) {
|
|
344
|
+
super(text, ttsInstance);
|
|
345
|
+
this.#tts = ttsInstance;
|
|
346
|
+
this.#opts = opts;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
protected async run() {
|
|
350
|
+
const audioConfig: AudioConfig = {
|
|
351
|
+
audioEncoding: this.#opts.encoding,
|
|
352
|
+
bitrate: this.#opts.bitRate,
|
|
353
|
+
sampleRateHertz: this.#opts.sampleRate,
|
|
354
|
+
temperature: this.#opts.temperature,
|
|
355
|
+
speakingRate: this.#opts.speakingRate,
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
const bodyParams: SynthesizeRequest = {
|
|
359
|
+
text: this.inputText,
|
|
360
|
+
voiceId: this.#opts.voice,
|
|
361
|
+
modelId: this.#opts.model,
|
|
362
|
+
audioConfig: audioConfig,
|
|
363
|
+
temperature: this.#opts.temperature,
|
|
364
|
+
timestampType: this.#opts.timestampType,
|
|
365
|
+
applyTextNormalization: this.#opts.textNormalization,
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
const url = new URL('tts/v1/voice:stream', this.#opts.baseURL);
|
|
369
|
+
|
|
370
|
+
const response = await fetch(url.toString(), {
|
|
371
|
+
method: 'POST',
|
|
372
|
+
headers: {
|
|
373
|
+
Authorization: this.#tts.authorization,
|
|
374
|
+
'Content-Type': 'application/json',
|
|
375
|
+
},
|
|
376
|
+
body: JSON.stringify(bodyParams),
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
if (!response.ok) {
|
|
380
|
+
throw new Error(`Inworld API error: ${response.status} ${response.statusText}`);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
if (!response.body) {
|
|
384
|
+
throw new Error('No response body');
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const reader = response.body.getReader();
|
|
388
|
+
const decoder = new TextDecoder();
|
|
389
|
+
let buffer = '';
|
|
390
|
+
|
|
391
|
+
const requestId = shortuuid();
|
|
392
|
+
const bstream = new AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);
|
|
393
|
+
|
|
394
|
+
while (true) {
|
|
395
|
+
const { done, value } = await reader.read();
|
|
396
|
+
if (done) break;
|
|
397
|
+
|
|
398
|
+
buffer += decoder.decode(value, { stream: true });
|
|
399
|
+
const lines = buffer.split('\n');
|
|
400
|
+
buffer = lines.pop() || '';
|
|
401
|
+
|
|
402
|
+
for (const line of lines) {
|
|
403
|
+
if (line.trim()) {
|
|
404
|
+
try {
|
|
405
|
+
const data = JSON.parse(line);
|
|
406
|
+
if (data.result) {
|
|
407
|
+
if (data.result.audioContent) {
|
|
408
|
+
const audio = Buffer.from(data.result.audioContent, 'base64');
|
|
409
|
+
|
|
410
|
+
let pcmData = audio;
|
|
411
|
+
if (audio.length > 44 && audio.subarray(0, 4).toString() === 'RIFF') {
|
|
412
|
+
// This is a WAV header, skip 44 bytes
|
|
413
|
+
pcmData = audio.subarray(44);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
for (const frame of bstream.write(
|
|
417
|
+
pcmData.buffer.slice(pcmData.byteOffset, pcmData.byteOffset + pcmData.byteLength),
|
|
418
|
+
)) {
|
|
419
|
+
this.queue.put({
|
|
420
|
+
requestId,
|
|
421
|
+
segmentId: requestId,
|
|
422
|
+
frame,
|
|
423
|
+
final: false,
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
} else if (data.error) {
|
|
428
|
+
throw new Error(data.error.message);
|
|
429
|
+
}
|
|
430
|
+
} catch (e) {
|
|
431
|
+
log().warn({ error: e, line }, 'Failed to parse Inworld chunk');
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// Flush remaining frames
|
|
438
|
+
for (const frame of bstream.flush()) {
|
|
439
|
+
this.queue.put({
|
|
440
|
+
requestId,
|
|
441
|
+
segmentId: requestId,
|
|
442
|
+
frame,
|
|
443
|
+
final: false,
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
class SynthesizeStream extends tts.SynthesizeStream {
|
|
450
|
+
#opts: TTSOptions;
|
|
451
|
+
#tts: TTS;
|
|
452
|
+
#contextId: string;
|
|
453
|
+
label = 'inworld.SynthesizeStream';
|
|
454
|
+
|
|
455
|
+
constructor(ttsInstance: TTS, opts: TTSOptions) {
|
|
456
|
+
super(ttsInstance);
|
|
457
|
+
this.#tts = ttsInstance;
|
|
458
|
+
this.#opts = opts;
|
|
459
|
+
this.#contextId = shortuuid();
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
protected async run() {
|
|
463
|
+
const ws = await this.#tts.pool.getConnection();
|
|
464
|
+
const bstream = new AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);
|
|
465
|
+
const tokenizerStream = this.#opts.tokenizer!.stream();
|
|
466
|
+
|
|
467
|
+
let resolveProcessing: () => void;
|
|
468
|
+
let rejectProcessing: (err: Error) => void;
|
|
469
|
+
const processing = new Promise<void>((resolve, reject) => {
|
|
470
|
+
resolveProcessing = resolve;
|
|
471
|
+
rejectProcessing = reject;
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
const handleMessage = (msg: InworldMessage) => {
|
|
475
|
+
const result = msg.result;
|
|
476
|
+
if (!result) return;
|
|
477
|
+
|
|
478
|
+
if (result.contextCreated) {
|
|
479
|
+
} else if (result.contextClosed) {
|
|
480
|
+
resolveProcessing();
|
|
481
|
+
} else if (result.audioChunk) {
|
|
482
|
+
if (result.audioChunk.timestampInfo) {
|
|
483
|
+
const tsInfo = result.audioChunk.timestampInfo;
|
|
484
|
+
if (tsInfo.wordAlignment) {
|
|
485
|
+
const words = tsInfo.wordAlignment.words || [];
|
|
486
|
+
const starts = tsInfo.wordAlignment.wordStartTimeSeconds || [];
|
|
487
|
+
const ends = tsInfo.wordAlignment.wordEndTimeSeconds || [];
|
|
488
|
+
|
|
489
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
490
|
+
(this.#tts as any).emit('alignment', {
|
|
491
|
+
requestId: this.#contextId,
|
|
492
|
+
segmentId: this.#contextId,
|
|
493
|
+
wordAlignment: { words, starts, ends },
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
if (tsInfo.characterAlignment) {
|
|
498
|
+
const chars = tsInfo.characterAlignment.characters || [];
|
|
499
|
+
const starts = tsInfo.characterAlignment.characterStartTimeSeconds || [];
|
|
500
|
+
const ends = tsInfo.characterAlignment.characterEndTimeSeconds || [];
|
|
501
|
+
|
|
502
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
503
|
+
(this.#tts as any).emit('alignment', {
|
|
504
|
+
requestId: this.#contextId,
|
|
505
|
+
segmentId: this.#contextId,
|
|
506
|
+
characterAlignment: { chars, starts, ends },
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
if (result.audioChunk.audioContent) {
|
|
512
|
+
const b64Content = result.audioChunk.audioContent || result.audioContent;
|
|
513
|
+
if (b64Content) {
|
|
514
|
+
const audio = Buffer.from(b64Content, 'base64');
|
|
515
|
+
let pcmData = audio;
|
|
516
|
+
if (audio.length > 44 && audio.subarray(0, 4).toString() === 'RIFF') {
|
|
517
|
+
// This is a WAV header, skip 44 bytes
|
|
518
|
+
pcmData = audio.subarray(44);
|
|
519
|
+
}
|
|
520
|
+
for (const frame of bstream.write(
|
|
521
|
+
pcmData.buffer.slice(pcmData.byteOffset, pcmData.byteOffset + pcmData.byteLength),
|
|
522
|
+
)) {
|
|
523
|
+
this.queue.put({
|
|
524
|
+
requestId: this.#contextId,
|
|
525
|
+
segmentId: this.#contextId,
|
|
526
|
+
frame,
|
|
527
|
+
final: false,
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
} else if (result.status && result.status.code !== 0) {
|
|
533
|
+
const error = new Error(`Inworld stream error: ${result.status.message}`);
|
|
534
|
+
rejectProcessing(error);
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
this.#tts.pool.registerListener(this.#contextId, handleMessage);
|
|
539
|
+
|
|
540
|
+
const sendLoop = async () => {
|
|
541
|
+
for await (const ev of tokenizerStream) {
|
|
542
|
+
await this.#sendText(ws, ev.token);
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
const sendPromise = sendLoop();
|
|
546
|
+
|
|
547
|
+
try {
|
|
548
|
+
await this.#createContext(ws);
|
|
549
|
+
|
|
550
|
+
for await (const text of this.input) {
|
|
551
|
+
if (text === tts.SynthesizeStream.FLUSH_SENTINEL) {
|
|
552
|
+
tokenizerStream.flush();
|
|
553
|
+
} else {
|
|
554
|
+
tokenizerStream.pushText(text);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
tokenizerStream.endInput();
|
|
558
|
+
await sendPromise;
|
|
559
|
+
|
|
560
|
+
await this.#flushContext(ws);
|
|
561
|
+
await this.#closeContext(ws);
|
|
562
|
+
await processing;
|
|
563
|
+
|
|
564
|
+
// Flush remaining frames
|
|
565
|
+
for (const frame of bstream.flush()) {
|
|
566
|
+
this.queue.put({
|
|
567
|
+
requestId: this.#contextId,
|
|
568
|
+
segmentId: this.#contextId,
|
|
569
|
+
frame,
|
|
570
|
+
final: false,
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
} catch (e) {
|
|
574
|
+
log().error({ error: e }, 'Error in SynthesizeStream run');
|
|
575
|
+
throw e;
|
|
576
|
+
} finally {
|
|
577
|
+
this.#tts.pool.unregisterListener(this.#contextId);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
#send(ws: WebSocket, data: object): Promise<void> {
|
|
582
|
+
return new Promise((resolve, reject) => {
|
|
583
|
+
if (ws.readyState !== WebSocket.OPEN) {
|
|
584
|
+
reject(new Error('WebSocket is not open'));
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
ws.send(JSON.stringify(data), (err) => {
|
|
588
|
+
if (err) {
|
|
589
|
+
reject(err);
|
|
590
|
+
} else {
|
|
591
|
+
resolve();
|
|
592
|
+
}
|
|
593
|
+
});
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
#createContext(ws: WebSocket): Promise<void> {
|
|
598
|
+
const config: CreateContextConfig = {
|
|
599
|
+
voiceId: this.#opts.voice,
|
|
600
|
+
modelId: this.#opts.model,
|
|
601
|
+
audioConfig: {
|
|
602
|
+
audioEncoding: this.#opts.encoding,
|
|
603
|
+
sampleRateHertz: this.#opts.sampleRate,
|
|
604
|
+
bitrate: this.#opts.bitRate,
|
|
605
|
+
speakingRate: this.#opts.speakingRate,
|
|
606
|
+
},
|
|
607
|
+
temperature: this.#opts.temperature,
|
|
608
|
+
bufferCharThreshold: this.#opts.bufferCharThreshold,
|
|
609
|
+
maxBufferDelayMs: this.#opts.maxBufferDelayMs,
|
|
610
|
+
timestampType: this.#opts.timestampType,
|
|
611
|
+
applyTextNormalization: this.#opts.textNormalization,
|
|
612
|
+
};
|
|
613
|
+
|
|
614
|
+
return this.#send(ws, { create: config, contextId: this.#contextId });
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
#sendText(ws: WebSocket, text: string): Promise<void> {
|
|
618
|
+
return this.#send(ws, {
|
|
619
|
+
send_text: { text },
|
|
620
|
+
contextId: this.#contextId,
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
#flushContext(ws: WebSocket): Promise<void> {
|
|
625
|
+
return this.#send(ws, {
|
|
626
|
+
flush_context: {},
|
|
627
|
+
contextId: this.#contextId,
|
|
628
|
+
});
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
#closeContext(ws: WebSocket): Promise<void> {
|
|
632
|
+
return this.#send(ws, {
|
|
633
|
+
close_context: {},
|
|
634
|
+
contextId: this.#contextId,
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
}
|