soma-voice 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/README.md +85 -0
- package/manifest.md +11 -0
- package/package.json +61 -0
- package/src/api/service/index.ts +5 -0
- package/src/api/service/voice/Synthesize.ts +15 -0
- package/src/api/service/voice/Transcribe.ts +16 -0
- package/src/api/service/voice/synthesize/Stream.ts +15 -0
- package/src/api/service/voice/transcribe/Raw.ts +15 -0
- package/src/client/audio-conversion.ts +127 -0
- package/src/client/audio-processing.ts +153 -0
- package/src/client/browser-codec.ts +73 -0
- package/src/client/capabilities.ts +72 -0
- package/src/client/errors.ts +10 -0
- package/src/client/http.ts +237 -0
- package/src/client/index.ts +15 -0
- package/src/client/indexeddb-storage.ts +109 -0
- package/src/client/offline.ts +139 -0
- package/src/client/player.ts +117 -0
- package/src/client/realtime-stt.ts +261 -0
- package/src/client/recorder.ts +280 -0
- package/src/client/storage.ts +89 -0
- package/src/client/streaming-tts.ts +156 -0
- package/src/client/transports.ts +221 -0
- package/src/client/wav.ts +58 -0
- package/src/index.ts +1 -0
- package/src/server/concurrency.ts +75 -0
- package/src/server/config.ts +173 -0
- package/src/server/errors.ts +49 -0
- package/src/server/index.ts +9 -0
- package/src/server/raw-transcription.ts +70 -0
- package/src/server/runtime.ts +425 -0
- package/src/server/speech-stream.ts +176 -0
- package/src/server/streaming.ts +160 -0
- package/src/server/upload.ts +94 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { VoiceError } from './errors';
|
|
2
|
+
|
|
3
|
+
export interface StreamingSpeechTransport {
|
|
4
|
+
stream(input: string, options: { signal: AbortSignal }): Promise<AsyncIterable<Uint8Array>>;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface StreamingPlaybackAdapter {
|
|
8
|
+
start(options?: { mimeType?: string }): Promise<void>;
|
|
9
|
+
append(chunk: Uint8Array): Promise<void>;
|
|
10
|
+
finish(): Promise<void>;
|
|
11
|
+
stop(reason?: unknown): Promise<void> | void;
|
|
12
|
+
destroy?(): Promise<void> | void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface StreamingSpeechSession {
|
|
16
|
+
speak(text: string, options?: { signal?: AbortSignal; mimeType?: string }): Promise<void>;
|
|
17
|
+
stop(reason?: unknown): Promise<void>;
|
|
18
|
+
destroy(): Promise<void>;
|
|
19
|
+
getState(): 'idle' | 'streaming' | 'destroyed';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function raceWithAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
23
|
+
if (signal.aborted) return Promise.reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
|
|
24
|
+
return new Promise<T>((resolve, reject) => {
|
|
25
|
+
const abort = () => reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
|
|
26
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
27
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function createStreamingSpeech(options: {
|
|
32
|
+
transport: StreamingSpeechTransport;
|
|
33
|
+
playback: StreamingPlaybackAdapter;
|
|
34
|
+
maxBytes?: number;
|
|
35
|
+
timeoutMs?: number;
|
|
36
|
+
onChunk?: (chunk: Uint8Array, totalBytes: number) => void;
|
|
37
|
+
}): StreamingSpeechSession {
|
|
38
|
+
let state: ReturnType<StreamingSpeechSession['getState']> = 'idle';
|
|
39
|
+
let destroyed = false;
|
|
40
|
+
let controller: AbortController | undefined;
|
|
41
|
+
let iterator: AsyncIterator<Uint8Array> | undefined;
|
|
42
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
43
|
+
let releasePromise: Promise<void> | undefined;
|
|
44
|
+
let timedOut = false;
|
|
45
|
+
let stopped = false;
|
|
46
|
+
const maximum = options.maxBytes ?? 25 * 1024 * 1024;
|
|
47
|
+
|
|
48
|
+
if (!Number.isSafeInteger(maximum) || maximum < 1) {
|
|
49
|
+
throw new TypeError('maxBytes must be a positive safe integer.');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const release = (reason?: unknown): Promise<void> => {
|
|
53
|
+
releasePromise ??= (async () => {
|
|
54
|
+
if (timer) clearTimeout(timer);
|
|
55
|
+
timer = undefined;
|
|
56
|
+
if (controller && !controller.signal.aborted) controller.abort(reason);
|
|
57
|
+
const activeIterator = iterator;
|
|
58
|
+
iterator = undefined;
|
|
59
|
+
if (activeIterator?.return) {
|
|
60
|
+
void Promise.resolve(activeIterator.return()).catch(() => undefined);
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
await options.playback.stop(reason);
|
|
64
|
+
} finally {
|
|
65
|
+
controller = undefined;
|
|
66
|
+
}
|
|
67
|
+
})();
|
|
68
|
+
return releasePromise;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const speak = async (
|
|
72
|
+
text: string,
|
|
73
|
+
speakOptions: { signal?: AbortSignal; mimeType?: string } = {},
|
|
74
|
+
) => {
|
|
75
|
+
if (destroyed || state !== 'idle') {
|
|
76
|
+
throw new VoiceError('INVALID_STATE', `Cannot stream speech in ${state} state.`);
|
|
77
|
+
}
|
|
78
|
+
if (!text.trim()) throw new TypeError('text must not be empty');
|
|
79
|
+
if (speakOptions.signal?.aborted) throw new VoiceError('ABORTED', 'Speech streaming aborted.');
|
|
80
|
+
|
|
81
|
+
state = 'streaming';
|
|
82
|
+
controller = new AbortController();
|
|
83
|
+
const sessionController = controller;
|
|
84
|
+
releasePromise = undefined;
|
|
85
|
+
timedOut = false;
|
|
86
|
+
stopped = false;
|
|
87
|
+
const abort = () => sessionController.abort(speakOptions.signal?.reason);
|
|
88
|
+
speakOptions.signal?.addEventListener('abort', abort, { once: true });
|
|
89
|
+
timer = setTimeout(() => {
|
|
90
|
+
timedOut = true;
|
|
91
|
+
sessionController.abort(new DOMException('Timed out', 'TimeoutError'));
|
|
92
|
+
}, options.timeoutMs ?? 120_000);
|
|
93
|
+
|
|
94
|
+
let total = 0;
|
|
95
|
+
try {
|
|
96
|
+
await raceWithAbort(
|
|
97
|
+
options.playback.start({ mimeType: speakOptions.mimeType }),
|
|
98
|
+
sessionController.signal,
|
|
99
|
+
);
|
|
100
|
+
const chunks = await raceWithAbort(
|
|
101
|
+
options.transport.stream(text, { signal: sessionController.signal }),
|
|
102
|
+
sessionController.signal,
|
|
103
|
+
);
|
|
104
|
+
iterator = chunks[Symbol.asyncIterator]();
|
|
105
|
+
while (true) {
|
|
106
|
+
const result = await raceWithAbort(iterator.next(), sessionController.signal);
|
|
107
|
+
if (result.done) break;
|
|
108
|
+
const chunk = result.value;
|
|
109
|
+
if (!(chunk instanceof Uint8Array)) {
|
|
110
|
+
throw new VoiceError('PLAYBACK_FAILED', 'Streaming transport returned an invalid chunk.');
|
|
111
|
+
}
|
|
112
|
+
total += chunk.byteLength;
|
|
113
|
+
if (total > maximum) {
|
|
114
|
+
throw new VoiceError('LIMIT_EXCEEDED', 'Streaming speech exceeds maxBytes.');
|
|
115
|
+
}
|
|
116
|
+
await raceWithAbort(options.playback.append(chunk), sessionController.signal);
|
|
117
|
+
options.onChunk?.(chunk, total);
|
|
118
|
+
}
|
|
119
|
+
await raceWithAbort(options.playback.finish(), sessionController.signal);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (error instanceof VoiceError) throw error;
|
|
122
|
+
if (timedOut) throw new VoiceError('TIMEOUT', 'Speech streaming timed out.', error);
|
|
123
|
+
if (stopped || speakOptions.signal?.aborted || sessionController.signal.aborted) {
|
|
124
|
+
throw new VoiceError('ABORTED', 'Speech streaming aborted.', error);
|
|
125
|
+
}
|
|
126
|
+
throw new VoiceError('PLAYBACK_FAILED', 'Streaming speech failed.', error);
|
|
127
|
+
} finally {
|
|
128
|
+
speakOptions.signal?.removeEventListener('abort', abort);
|
|
129
|
+
try {
|
|
130
|
+
await release();
|
|
131
|
+
} finally {
|
|
132
|
+
state = destroyed ? 'destroyed' : 'idle';
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const stop = async (reason?: unknown) => {
|
|
138
|
+
if (state !== 'streaming') return;
|
|
139
|
+
stopped = true;
|
|
140
|
+
await release(reason ?? new DOMException('Stopped', 'AbortError'));
|
|
141
|
+
state = destroyed ? 'destroyed' : 'idle';
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const destroy = async () => {
|
|
145
|
+
if (destroyed) return;
|
|
146
|
+
destroyed = true;
|
|
147
|
+
try {
|
|
148
|
+
await stop('destroyed');
|
|
149
|
+
await options.playback.destroy?.();
|
|
150
|
+
} finally {
|
|
151
|
+
state = 'destroyed';
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
return { speak, stop, destroy, getState: () => state };
|
|
156
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { VoiceError } from './errors';
|
|
2
|
+
import type { RealtimeSttTransport } from './realtime-stt';
|
|
3
|
+
import type { StreamingSpeechTransport } from './streaming-tts';
|
|
4
|
+
|
|
5
|
+
interface WebSocketLike {
|
|
6
|
+
binaryType: BinaryType;
|
|
7
|
+
readyState: number;
|
|
8
|
+
send(data: string | ArrayBuffer | ArrayBufferView | Blob): void;
|
|
9
|
+
close(code?: number, reason?: string): void;
|
|
10
|
+
addEventListener(type: string, listener: EventListener): void;
|
|
11
|
+
removeEventListener(type: string, listener: EventListener): void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function createWebSocketSttTransport(options: {
|
|
15
|
+
url: string;
|
|
16
|
+
protocols?: string | string[];
|
|
17
|
+
createSocket?: (url: string, protocols?: string | string[]) => WebSocketLike;
|
|
18
|
+
startMessage?: unknown;
|
|
19
|
+
finishMessage?: unknown;
|
|
20
|
+
isFinalEvent?: (event: unknown) => boolean;
|
|
21
|
+
finishTimeoutMs?: number;
|
|
22
|
+
}): RealtimeSttTransport {
|
|
23
|
+
let socket: WebSocketLike | undefined;
|
|
24
|
+
let eventListeners = new Set<(event: unknown) => void>();
|
|
25
|
+
let messageListener: EventListener | undefined;
|
|
26
|
+
let errorListener: EventListener | undefined;
|
|
27
|
+
let closeListener: EventListener | undefined;
|
|
28
|
+
let finishResolve: (() => void) | undefined;
|
|
29
|
+
let finishReject: ((error: unknown) => void) | undefined;
|
|
30
|
+
|
|
31
|
+
const factory = options.createSocket ?? ((url, protocols) => {
|
|
32
|
+
if (typeof WebSocket === 'undefined') {
|
|
33
|
+
throw new VoiceError('UNSUPPORTED', 'WebSocket is unavailable.');
|
|
34
|
+
}
|
|
35
|
+
return new WebSocket(url, protocols);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const detach = () => {
|
|
39
|
+
if (!socket) return;
|
|
40
|
+
if (messageListener) socket.removeEventListener('message', messageListener);
|
|
41
|
+
if (errorListener) socket.removeEventListener('error', errorListener);
|
|
42
|
+
if (closeListener) socket.removeEventListener('close', closeListener);
|
|
43
|
+
messageListener = undefined;
|
|
44
|
+
errorListener = undefined;
|
|
45
|
+
closeListener = undefined;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
async open({ signal }) {
|
|
50
|
+
if (signal.aborted) throw new VoiceError('ABORTED', 'WebSocket connection aborted.');
|
|
51
|
+
if (socket) throw new VoiceError('INVALID_STATE', 'WebSocket transport is already open.');
|
|
52
|
+
const active = factory(options.url, options.protocols);
|
|
53
|
+
socket = active;
|
|
54
|
+
active.binaryType = 'arraybuffer';
|
|
55
|
+
await new Promise<void>((resolve, reject) => {
|
|
56
|
+
const open = () => {
|
|
57
|
+
cleanup();
|
|
58
|
+
messageListener = ((event: MessageEvent) => {
|
|
59
|
+
let value: unknown = event.data;
|
|
60
|
+
if (typeof value === 'string') {
|
|
61
|
+
try {
|
|
62
|
+
value = JSON.parse(value) as unknown;
|
|
63
|
+
} catch {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
for (const listener of eventListeners) listener(value);
|
|
68
|
+
if (options.isFinalEvent?.(value)) {
|
|
69
|
+
finishResolve?.();
|
|
70
|
+
finishResolve = undefined;
|
|
71
|
+
finishReject = undefined;
|
|
72
|
+
}
|
|
73
|
+
}) as EventListener;
|
|
74
|
+
errorListener = ((event: Event) => {
|
|
75
|
+
finishReject?.(event);
|
|
76
|
+
finishResolve = undefined;
|
|
77
|
+
finishReject = undefined;
|
|
78
|
+
for (const listener of eventListeners) listener({
|
|
79
|
+
type: 'transport-error',
|
|
80
|
+
error: event,
|
|
81
|
+
});
|
|
82
|
+
}) as EventListener;
|
|
83
|
+
closeListener = ((event: CloseEvent) => {
|
|
84
|
+
if (event.code === 1000) {
|
|
85
|
+
finishResolve?.();
|
|
86
|
+
finishResolve = undefined;
|
|
87
|
+
finishReject = undefined;
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
finishReject?.(event);
|
|
91
|
+
finishResolve = undefined;
|
|
92
|
+
finishReject = undefined;
|
|
93
|
+
for (const listener of eventListeners) listener({
|
|
94
|
+
type: 'transport-close',
|
|
95
|
+
code: event.code,
|
|
96
|
+
reason: event.reason,
|
|
97
|
+
});
|
|
98
|
+
}) as EventListener;
|
|
99
|
+
active.addEventListener('message', messageListener);
|
|
100
|
+
active.addEventListener('error', errorListener);
|
|
101
|
+
active.addEventListener('close', closeListener);
|
|
102
|
+
if (options.startMessage !== undefined) active.send(JSON.stringify(options.startMessage));
|
|
103
|
+
resolve();
|
|
104
|
+
};
|
|
105
|
+
const fail = (event: Event) => {
|
|
106
|
+
cleanup();
|
|
107
|
+
reject(new VoiceError('NETWORK_ERROR', 'Unable to open realtime WebSocket.', event));
|
|
108
|
+
};
|
|
109
|
+
const abort = () => {
|
|
110
|
+
cleanup();
|
|
111
|
+
active.close(1000, 'aborted');
|
|
112
|
+
reject(new VoiceError('ABORTED', 'WebSocket connection aborted.'));
|
|
113
|
+
};
|
|
114
|
+
const cleanup = () => {
|
|
115
|
+
active.removeEventListener('open', open);
|
|
116
|
+
active.removeEventListener('error', fail);
|
|
117
|
+
signal.removeEventListener('abort', abort);
|
|
118
|
+
};
|
|
119
|
+
active.addEventListener('open', open);
|
|
120
|
+
active.addEventListener('error', fail);
|
|
121
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
122
|
+
});
|
|
123
|
+
},
|
|
124
|
+
async send(audio) {
|
|
125
|
+
if (!socket || socket.readyState !== 1) {
|
|
126
|
+
throw new VoiceError('INVALID_STATE', 'Realtime WebSocket is not open.');
|
|
127
|
+
}
|
|
128
|
+
socket.send(audio);
|
|
129
|
+
},
|
|
130
|
+
async finish() {
|
|
131
|
+
if (!socket || socket.readyState !== 1) return;
|
|
132
|
+
if (options.finishMessage !== undefined) socket.send(JSON.stringify(options.finishMessage));
|
|
133
|
+
if (!options.isFinalEvent) return;
|
|
134
|
+
await new Promise<void>((resolve, reject) => {
|
|
135
|
+
let settled = false;
|
|
136
|
+
const succeed = () => {
|
|
137
|
+
if (settled) return;
|
|
138
|
+
settled = true;
|
|
139
|
+
clearTimeout(timeout);
|
|
140
|
+
finishResolve = undefined;
|
|
141
|
+
finishReject = undefined;
|
|
142
|
+
resolve();
|
|
143
|
+
};
|
|
144
|
+
const fail = (error: unknown) => {
|
|
145
|
+
if (settled) return;
|
|
146
|
+
settled = true;
|
|
147
|
+
clearTimeout(timeout);
|
|
148
|
+
finishResolve = undefined;
|
|
149
|
+
finishReject = undefined;
|
|
150
|
+
reject(error);
|
|
151
|
+
};
|
|
152
|
+
const timeout = setTimeout(() => {
|
|
153
|
+
fail(new VoiceError('TIMEOUT', 'Realtime WebSocket final result timed out.'));
|
|
154
|
+
}, options.finishTimeoutMs ?? 10_000);
|
|
155
|
+
finishResolve = succeed;
|
|
156
|
+
finishReject = fail;
|
|
157
|
+
});
|
|
158
|
+
},
|
|
159
|
+
close(reason) {
|
|
160
|
+
if (!socket) return;
|
|
161
|
+
detach();
|
|
162
|
+
const active = socket;
|
|
163
|
+
socket = undefined;
|
|
164
|
+
active.close(1000, typeof reason === 'string' ? reason.slice(0, 123) : undefined);
|
|
165
|
+
},
|
|
166
|
+
subscribe(listener) {
|
|
167
|
+
eventListeners.add(listener);
|
|
168
|
+
return () => eventListeners.delete(listener);
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function createFetchStreamingSpeechTransport(options: {
|
|
174
|
+
endpoint?: string;
|
|
175
|
+
fetch?: typeof fetch;
|
|
176
|
+
headers?: HeadersInit | (() => HeadersInit);
|
|
177
|
+
body?: (text: string) => unknown;
|
|
178
|
+
} = {}): StreamingSpeechTransport {
|
|
179
|
+
return {
|
|
180
|
+
async stream(text, { signal }) {
|
|
181
|
+
const headers = new Headers(
|
|
182
|
+
typeof options.headers === 'function' ? options.headers() : options.headers,
|
|
183
|
+
);
|
|
184
|
+
if (!headers.has('content-type')) headers.set('content-type', 'application/json');
|
|
185
|
+
const response = await (options.fetch ?? globalThis.fetch)(
|
|
186
|
+
options.endpoint ?? '/api/voice/synthesize/stream',
|
|
187
|
+
{
|
|
188
|
+
method: 'POST',
|
|
189
|
+
headers,
|
|
190
|
+
body: JSON.stringify(options.body?.(text) ?? { text }),
|
|
191
|
+
signal,
|
|
192
|
+
},
|
|
193
|
+
);
|
|
194
|
+
const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';
|
|
195
|
+
if (!response.ok || !response.body || !contentType.startsWith('audio/')) {
|
|
196
|
+
await response.body?.cancel().catch(() => undefined);
|
|
197
|
+
throw new VoiceError(
|
|
198
|
+
'API_ERROR',
|
|
199
|
+
!response.ok
|
|
200
|
+
? `Streaming speech failed (${response.status}).`
|
|
201
|
+
: 'Streaming speech returned a non-audio response.',
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
const reader = response.body.getReader();
|
|
205
|
+
return {
|
|
206
|
+
async *[Symbol.asyncIterator]() {
|
|
207
|
+
try {
|
|
208
|
+
while (true) {
|
|
209
|
+
const result = await reader.read();
|
|
210
|
+
if (result.done) break;
|
|
211
|
+
yield result.value;
|
|
212
|
+
}
|
|
213
|
+
} finally {
|
|
214
|
+
await reader.cancel().catch(() => undefined);
|
|
215
|
+
reader.releaseLock();
|
|
216
|
+
}
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
export function encodePcm16Wav(
|
|
2
|
+
samples: Float32Array | readonly Float32Array[],
|
|
3
|
+
sampleRate: number,
|
|
4
|
+
channels = 1,
|
|
5
|
+
): Blob {
|
|
6
|
+
const planes = samples instanceof Float32Array ? [samples] : [...samples];
|
|
7
|
+
if (!Number.isSafeInteger(sampleRate)
|
|
8
|
+
|| sampleRate <= 0
|
|
9
|
+
|| sampleRate > 768_000
|
|
10
|
+
|| !Number.isSafeInteger(channels)
|
|
11
|
+
|| channels < 1
|
|
12
|
+
|| channels > 32
|
|
13
|
+
|| planes.length !== channels) {
|
|
14
|
+
throw new TypeError('Invalid PCM layout');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const frames = planes.reduce(
|
|
18
|
+
(count, plane) => Math.min(count, plane.length),
|
|
19
|
+
planes[0]?.length ?? 0,
|
|
20
|
+
);
|
|
21
|
+
const dataBytes = frames * channels * 2;
|
|
22
|
+
if (!Number.isSafeInteger(dataBytes) || dataBytes > 0xffff_ffff - 36) {
|
|
23
|
+
throw new RangeError('PCM data is too large for a WAV container.');
|
|
24
|
+
}
|
|
25
|
+
const buffer = new ArrayBuffer(44 + dataBytes);
|
|
26
|
+
const view = new DataView(buffer);
|
|
27
|
+
const writeText = (offset: number, value: string) => {
|
|
28
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
29
|
+
view.setUint8(offset + index, value.charCodeAt(index));
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
writeText(0, 'RIFF');
|
|
34
|
+
view.setUint32(4, buffer.byteLength - 8, true);
|
|
35
|
+
writeText(8, 'WAVE');
|
|
36
|
+
writeText(12, 'fmt ');
|
|
37
|
+
view.setUint32(16, 16, true);
|
|
38
|
+
view.setUint16(20, 1, true);
|
|
39
|
+
view.setUint16(22, channels, true);
|
|
40
|
+
view.setUint32(24, sampleRate, true);
|
|
41
|
+
view.setUint32(28, sampleRate * channels * 2, true);
|
|
42
|
+
view.setUint16(32, channels * 2, true);
|
|
43
|
+
view.setUint16(34, 16, true);
|
|
44
|
+
writeText(36, 'data');
|
|
45
|
+
view.setUint32(40, dataBytes, true);
|
|
46
|
+
|
|
47
|
+
let offset = 44;
|
|
48
|
+
for (let frame = 0; frame < frames; frame += 1) {
|
|
49
|
+
for (let channel = 0; channel < channels; channel += 1) {
|
|
50
|
+
const sample = Math.max(-1, Math.min(1, planes[channel]![frame]!));
|
|
51
|
+
const value = sample < 0 ? sample * 0x8000 : sample * 0x7fff;
|
|
52
|
+
view.setInt16(offset, value, true);
|
|
53
|
+
offset += 2;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return new Blob([buffer], { type: 'audio/wav' });
|
|
58
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './client/index';
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import 'server-only';
|
|
2
|
+
import type { VoiceConfig } from './config';
|
|
3
|
+
import { VoiceErrorCodes, VoiceServerError } from './errors';
|
|
4
|
+
|
|
5
|
+
interface Waiter {
|
|
6
|
+
resolve: () => void;
|
|
7
|
+
reject: (error: VoiceServerError) => void;
|
|
8
|
+
signal: AbortSignal;
|
|
9
|
+
abort: () => void;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface VoiceLimiter {
|
|
13
|
+
active: number;
|
|
14
|
+
queue: Waiter[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const limiters = new Map<string, VoiceLimiter>();
|
|
18
|
+
|
|
19
|
+
function limiterFor(config: VoiceConfig): VoiceLimiter {
|
|
20
|
+
const key = `${config.baseUrl}\0${config.maxConcurrency}\0${config.maxQueue}`;
|
|
21
|
+
let limiter = limiters.get(key);
|
|
22
|
+
if (!limiter) {
|
|
23
|
+
limiter = { active: 0, queue: [] };
|
|
24
|
+
limiters.set(key, limiter);
|
|
25
|
+
}
|
|
26
|
+
return limiter;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function createRelease(limiter: VoiceLimiter): () => void {
|
|
30
|
+
let released = false;
|
|
31
|
+
return () => {
|
|
32
|
+
if (released) return;
|
|
33
|
+
released = true;
|
|
34
|
+
while (limiter.queue.length) {
|
|
35
|
+
const next = limiter.queue.shift()!;
|
|
36
|
+
next.signal.removeEventListener('abort', next.abort);
|
|
37
|
+
if (next.signal.aborted) {
|
|
38
|
+
next.reject(new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Voice request was aborted.', 499));
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
// The active slot transfers directly to the waiter; its count does not pass through zero.
|
|
42
|
+
next.resolve();
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
limiter.active -= 1;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function acquireVoicePermit(
|
|
50
|
+
config: VoiceConfig,
|
|
51
|
+
signal: AbortSignal,
|
|
52
|
+
): Promise<() => void> {
|
|
53
|
+
const limiter = limiterFor(config);
|
|
54
|
+
if (signal.aborted) {
|
|
55
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Voice request was aborted.', 499);
|
|
56
|
+
}
|
|
57
|
+
if (limiter.active < config.maxConcurrency) {
|
|
58
|
+
limiter.active += 1;
|
|
59
|
+
return createRelease(limiter);
|
|
60
|
+
}
|
|
61
|
+
if (limiter.queue.length >= config.maxQueue) {
|
|
62
|
+
throw new VoiceServerError(VoiceErrorCodes.BUSY, 'Voice service queue is full.', 503);
|
|
63
|
+
}
|
|
64
|
+
await new Promise<void>((resolve, reject) => {
|
|
65
|
+
const waiter: Waiter = { resolve, reject, signal, abort: () => undefined };
|
|
66
|
+
waiter.abort = () => {
|
|
67
|
+
limiter.queue = limiter.queue.filter((item) => item !== waiter);
|
|
68
|
+
reject(new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Voice request was aborted.', 499));
|
|
69
|
+
};
|
|
70
|
+
limiter.queue.push(waiter);
|
|
71
|
+
signal.addEventListener('abort', waiter.abort, { once: true });
|
|
72
|
+
if (signal.aborted) waiter.abort();
|
|
73
|
+
});
|
|
74
|
+
return createRelease(limiter);
|
|
75
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import 'server-only';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import yaml from 'js-yaml';
|
|
5
|
+
import { VoiceServerError, VoiceErrorCodes } from './errors';
|
|
6
|
+
|
|
7
|
+
export interface VoiceConfig {
|
|
8
|
+
apiKey: string;
|
|
9
|
+
baseUrl: string;
|
|
10
|
+
transcriptionModel: string;
|
|
11
|
+
speechModel: string;
|
|
12
|
+
timeoutMs: number;
|
|
13
|
+
maxConcurrency: number;
|
|
14
|
+
maxQueue: number;
|
|
15
|
+
maxAudioBytes: number;
|
|
16
|
+
maxResponseBytes: number;
|
|
17
|
+
maxTextCodePoints: number;
|
|
18
|
+
voices: string[];
|
|
19
|
+
formats: string[];
|
|
20
|
+
speeds: number[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type SomaEnvironment = 'test' | 'prod';
|
|
24
|
+
|
|
25
|
+
export function readSomaEnv(env: NodeJS.ProcessEnv = process.env): SomaEnvironment {
|
|
26
|
+
const value = String(env.SOMA_ENV ?? env.APP_ENV ?? env.NODE_ENV ?? '').trim().toLowerCase();
|
|
27
|
+
return ['prod', 'production'].includes(value) ? 'prod' : 'test';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function resolveSafeChildRoot(parent: string, relativePath: string | undefined): string | undefined {
|
|
31
|
+
const trimmed = relativePath?.trim();
|
|
32
|
+
if (!trimmed) return undefined;
|
|
33
|
+
const normalizedParent = path.resolve(parent);
|
|
34
|
+
const resolved = path.resolve(normalizedParent, trimmed);
|
|
35
|
+
return resolved === normalizedParent || resolved.startsWith(`${normalizedParent}${path.sep}`)
|
|
36
|
+
? resolved
|
|
37
|
+
: undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function resolveHostConfigRoot(hostDir: string): string {
|
|
41
|
+
const normalizedHostDir = path.resolve(hostDir);
|
|
42
|
+
try {
|
|
43
|
+
const packageJson = JSON.parse(fs.readFileSync(path.join(normalizedHostDir, 'package.json'), 'utf8')) as {
|
|
44
|
+
soma?: { hostRoot?: string; configRoot?: string };
|
|
45
|
+
};
|
|
46
|
+
if (packageJson.soma?.configRoot !== undefined) {
|
|
47
|
+
return resolveSafeChildRoot(normalizedHostDir, packageJson.soma.configRoot)
|
|
48
|
+
?? path.join(normalizedHostDir, 'config');
|
|
49
|
+
}
|
|
50
|
+
const hostSourceRoot = resolveSafeChildRoot(normalizedHostDir, packageJson.soma?.hostRoot);
|
|
51
|
+
const candidates = [
|
|
52
|
+
path.join(normalizedHostDir, 'config'),
|
|
53
|
+
...(hostSourceRoot ? [path.join(hostSourceRoot, 'config')] : []),
|
|
54
|
+
];
|
|
55
|
+
return candidates.find(fs.existsSync) ?? candidates.at(-1)!;
|
|
56
|
+
} catch {
|
|
57
|
+
return path.join(normalizedHostDir, 'config');
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function validateVoiceConfig(
|
|
62
|
+
value: unknown,
|
|
63
|
+
environment: SomaEnvironment = readSomaEnv(),
|
|
64
|
+
): VoiceConfig {
|
|
65
|
+
if (!value || typeof value !== 'object') {
|
|
66
|
+
throw new VoiceServerError(VoiceErrorCodes.CONFIG, 'Voice config is missing.');
|
|
67
|
+
}
|
|
68
|
+
const config = value as Record<string, unknown>;
|
|
69
|
+
const string = (key: string) => {
|
|
70
|
+
if (typeof config[key] !== 'string' || !(config[key] as string).trim()) {
|
|
71
|
+
throw new VoiceServerError(VoiceErrorCodes.CONFIG, `Invalid voice config: ${key}`);
|
|
72
|
+
}
|
|
73
|
+
return (config[key] as string).trim();
|
|
74
|
+
};
|
|
75
|
+
const number = (key: string, fallback: number, min: number, max: number) => {
|
|
76
|
+
const candidate = config[key] ?? fallback;
|
|
77
|
+
if (typeof candidate !== 'number' || !Number.isFinite(candidate)
|
|
78
|
+
|| candidate < min || candidate > max) {
|
|
79
|
+
throw new VoiceServerError(VoiceErrorCodes.CONFIG, `Invalid voice config: ${key}`);
|
|
80
|
+
}
|
|
81
|
+
return candidate;
|
|
82
|
+
};
|
|
83
|
+
const list = (key: string, fallback: string[]) => {
|
|
84
|
+
const candidate = config[key] ?? fallback;
|
|
85
|
+
if (!Array.isArray(candidate) || !candidate.length
|
|
86
|
+
|| candidate.some((item) => typeof item !== 'string' || !item.trim())) {
|
|
87
|
+
throw new VoiceServerError(VoiceErrorCodes.CONFIG, `Invalid voice config: ${key}`);
|
|
88
|
+
}
|
|
89
|
+
return [...new Set(candidate.map((item) => item.trim()))];
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const rawBaseUrl = string('baseUrl').replace(/\/$/, '');
|
|
93
|
+
let url: URL;
|
|
94
|
+
try {
|
|
95
|
+
url = new URL(rawBaseUrl);
|
|
96
|
+
} catch {
|
|
97
|
+
throw new VoiceServerError(VoiceErrorCodes.CONFIG, 'Invalid voice config: baseUrl');
|
|
98
|
+
}
|
|
99
|
+
const loopback = ['localhost', '127.0.0.1', '::1'].includes(url.hostname);
|
|
100
|
+
const validProtocol = environment === 'prod'
|
|
101
|
+
? url.protocol === 'https:'
|
|
102
|
+
: url.protocol === 'https:' || (url.protocol === 'http:' && loopback);
|
|
103
|
+
if (!validProtocol || url.username || url.password || url.search || url.hash) {
|
|
104
|
+
throw new VoiceServerError(VoiceErrorCodes.CONFIG, 'Invalid voice config: baseUrl');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const speedsRaw = config.speeds ?? [0.75, 1, 1.25];
|
|
108
|
+
if (!Array.isArray(speedsRaw) || !speedsRaw.length
|
|
109
|
+
|| speedsRaw.some((speed) => typeof speed !== 'number' || !Number.isFinite(speed)
|
|
110
|
+
|| speed < 0.25 || speed > 4)) {
|
|
111
|
+
throw new VoiceServerError(VoiceErrorCodes.CONFIG, 'Invalid voice config: speeds');
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
apiKey: string('apiKey'),
|
|
115
|
+
baseUrl: rawBaseUrl,
|
|
116
|
+
transcriptionModel: string('transcriptionModel'),
|
|
117
|
+
speechModel: string('speechModel'),
|
|
118
|
+
timeoutMs: number('timeoutMs', 30_000, 100, 300_000),
|
|
119
|
+
maxConcurrency: number('maxConcurrency', 4, 1, 100),
|
|
120
|
+
maxQueue: number('maxQueue', 16, 0, 10_000),
|
|
121
|
+
maxAudioBytes: number('maxAudioBytes', 25 * 1024 * 1024, 1, 100 * 1024 * 1024),
|
|
122
|
+
maxResponseBytes: number('maxResponseBytes', 25 * 1024 * 1024, 1, 100 * 1024 * 1024),
|
|
123
|
+
maxTextCodePoints: number('maxTextCodePoints', 4096, 1, 100_000),
|
|
124
|
+
voices: list('voices', ['alloy']),
|
|
125
|
+
formats: list('formats', ['mp3', 'wav', 'opus', 'aac', 'flac']),
|
|
126
|
+
speeds: [...new Set(speedsRaw)],
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
interface CachedVoiceConfig {
|
|
131
|
+
file: string;
|
|
132
|
+
modifiedMs: number;
|
|
133
|
+
size: number;
|
|
134
|
+
config: VoiceConfig;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const configCache = new Map<string, CachedVoiceConfig>();
|
|
138
|
+
|
|
139
|
+
export function loadVoiceConfig(
|
|
140
|
+
hostDir = process.env.SOMA_HOST_DIR || process.cwd(),
|
|
141
|
+
environment = readSomaEnv(),
|
|
142
|
+
): VoiceConfig {
|
|
143
|
+
const normalizedHost = path.resolve(hostDir);
|
|
144
|
+
const root = resolveHostConfigRoot(normalizedHost);
|
|
145
|
+
const candidates = [
|
|
146
|
+
path.join(root, `voice.config.${environment}.yaml`),
|
|
147
|
+
path.join(root, 'voice.config.yaml'),
|
|
148
|
+
];
|
|
149
|
+
const file = candidates.find(fs.existsSync);
|
|
150
|
+
if (!file) throw new VoiceServerError(VoiceErrorCodes.CONFIG, 'Host voice config is missing.');
|
|
151
|
+
const cacheKey = `${normalizedHost}\0${environment}`;
|
|
152
|
+
try {
|
|
153
|
+
const stat = fs.statSync(file);
|
|
154
|
+
const cached = configCache.get(cacheKey);
|
|
155
|
+
if (cached
|
|
156
|
+
&& cached.file === file
|
|
157
|
+
&& cached.modifiedMs === stat.mtimeMs
|
|
158
|
+
&& cached.size === stat.size) {
|
|
159
|
+
return cached.config;
|
|
160
|
+
}
|
|
161
|
+
const config = validateVoiceConfig(yaml.load(fs.readFileSync(file, 'utf8')), environment);
|
|
162
|
+
configCache.set(cacheKey, {
|
|
163
|
+
file,
|
|
164
|
+
modifiedMs: stat.mtimeMs,
|
|
165
|
+
size: stat.size,
|
|
166
|
+
config,
|
|
167
|
+
});
|
|
168
|
+
return config;
|
|
169
|
+
} catch (error) {
|
|
170
|
+
if (error instanceof VoiceServerError) throw error;
|
|
171
|
+
throw new VoiceServerError(VoiceErrorCodes.CONFIG, 'Voice config cannot be parsed.');
|
|
172
|
+
}
|
|
173
|
+
}
|