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,261 @@
|
|
|
1
|
+
import { VoiceError } from './errors';
|
|
2
|
+
|
|
3
|
+
export interface RealtimeTranscriptWord {
|
|
4
|
+
text: string;
|
|
5
|
+
startMs?: number;
|
|
6
|
+
endMs?: number;
|
|
7
|
+
speaker?: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface RealtimeTranscript {
|
|
11
|
+
text: string;
|
|
12
|
+
final: boolean;
|
|
13
|
+
startMs?: number;
|
|
14
|
+
endMs?: number;
|
|
15
|
+
speaker?: string;
|
|
16
|
+
words?: RealtimeTranscriptWord[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface RealtimeSttTransport {
|
|
20
|
+
open(options: { signal: AbortSignal }): Promise<void>;
|
|
21
|
+
send(audio: Blob | ArrayBuffer | Uint8Array): Promise<void>;
|
|
22
|
+
finish(): Promise<void>;
|
|
23
|
+
close(reason?: unknown): Promise<void> | void;
|
|
24
|
+
subscribe(listener: (event: unknown) => void): () => void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface RealtimeSttSession {
|
|
28
|
+
start(options?: { signal?: AbortSignal }): Promise<void>;
|
|
29
|
+
sendAudio(audio: Blob | ArrayBuffer | Uint8Array): Promise<void>;
|
|
30
|
+
stop(): Promise<RealtimeTranscript[]>;
|
|
31
|
+
cancel(reason?: unknown): Promise<void>;
|
|
32
|
+
destroy(): Promise<void>;
|
|
33
|
+
getState(): 'idle' | 'starting' | 'streaming' | 'stopping' | 'destroyed';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function optionalFiniteNumber(value: unknown): number | undefined {
|
|
37
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function parseTranscript(value: unknown): RealtimeTranscript | undefined {
|
|
41
|
+
if (!value || typeof value !== 'object') return undefined;
|
|
42
|
+
const source = value as Record<string, unknown>;
|
|
43
|
+
if (typeof source.text !== 'string' || typeof source.final !== 'boolean') return undefined;
|
|
44
|
+
const startMs = optionalFiniteNumber(source.startMs);
|
|
45
|
+
const endMs = optionalFiniteNumber(source.endMs);
|
|
46
|
+
const words = Array.isArray(source.words)
|
|
47
|
+
? source.words.flatMap((word) => {
|
|
48
|
+
if (!word || typeof word !== 'object') return [];
|
|
49
|
+
const item = word as Record<string, unknown>;
|
|
50
|
+
if (typeof item.text !== 'string') return [];
|
|
51
|
+
const wordStartMs = optionalFiniteNumber(item.startMs);
|
|
52
|
+
const wordEndMs = optionalFiniteNumber(item.endMs);
|
|
53
|
+
return [{
|
|
54
|
+
text: item.text,
|
|
55
|
+
...(wordStartMs !== undefined ? { startMs: wordStartMs } : {}),
|
|
56
|
+
...(wordEndMs !== undefined ? { endMs: wordEndMs } : {}),
|
|
57
|
+
...(typeof item.speaker === 'string' ? { speaker: item.speaker } : {}),
|
|
58
|
+
}];
|
|
59
|
+
})
|
|
60
|
+
: undefined;
|
|
61
|
+
return {
|
|
62
|
+
text: source.text,
|
|
63
|
+
final: source.final,
|
|
64
|
+
...(startMs !== undefined ? { startMs } : {}),
|
|
65
|
+
...(endMs !== undefined ? { endMs } : {}),
|
|
66
|
+
...(typeof source.speaker === 'string' ? { speaker: source.speaker } : {}),
|
|
67
|
+
...(words ? { words } : {}),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function createRealtimeTranscriber(options: {
|
|
72
|
+
transport: RealtimeSttTransport;
|
|
73
|
+
onTranscript?: (transcript: RealtimeTranscript) => void;
|
|
74
|
+
maxBufferedBytes?: number;
|
|
75
|
+
timeoutMs?: number;
|
|
76
|
+
}): RealtimeSttSession {
|
|
77
|
+
let state: ReturnType<RealtimeSttSession['getState']> = 'idle';
|
|
78
|
+
let controller: AbortController | undefined;
|
|
79
|
+
let unsubscribe: (() => void) | undefined;
|
|
80
|
+
let externalSignal: AbortSignal | undefined;
|
|
81
|
+
let externalAbort: (() => void) | undefined;
|
|
82
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
83
|
+
let closePromise: Promise<void> | undefined;
|
|
84
|
+
let terminalError: VoiceError | undefined;
|
|
85
|
+
let bufferedBytes = 0;
|
|
86
|
+
let transcripts: RealtimeTranscript[] = [];
|
|
87
|
+
const maximum = options.maxBufferedBytes ?? 25 * 1024 * 1024;
|
|
88
|
+
|
|
89
|
+
if (!Number.isSafeInteger(maximum) || maximum < 1) {
|
|
90
|
+
throw new TypeError('maxBufferedBytes must be a positive safe integer.');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const closeTransport = (reason?: unknown): Promise<void> => {
|
|
94
|
+
closePromise ??= Promise.resolve(options.transport.close(reason));
|
|
95
|
+
return closePromise;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const cleanup = async (reason?: unknown) => {
|
|
99
|
+
if (timeout) clearTimeout(timeout);
|
|
100
|
+
timeout = undefined;
|
|
101
|
+
if (externalSignal && externalAbort) externalSignal.removeEventListener('abort', externalAbort);
|
|
102
|
+
externalSignal = undefined;
|
|
103
|
+
externalAbort = undefined;
|
|
104
|
+
unsubscribe?.();
|
|
105
|
+
unsubscribe = undefined;
|
|
106
|
+
if (controller && !controller.signal.aborted) controller.abort(reason);
|
|
107
|
+
await closeTransport(reason);
|
|
108
|
+
controller = undefined;
|
|
109
|
+
bufferedBytes = 0;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const terminate = (error: VoiceError, reason?: unknown) => {
|
|
113
|
+
if (state !== 'starting' && state !== 'streaming') return;
|
|
114
|
+
terminalError = error;
|
|
115
|
+
state = 'stopping';
|
|
116
|
+
if (controller && !controller.signal.aborted) controller.abort(reason ?? error);
|
|
117
|
+
void cleanup(reason ?? error).catch(() => undefined);
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const consumeTerminalError = async (): Promise<never> => {
|
|
121
|
+
const error = terminalError ?? new VoiceError('ABORTED', 'Realtime transcription stopped.');
|
|
122
|
+
terminalError = undefined;
|
|
123
|
+
try {
|
|
124
|
+
await cleanup(error).catch(() => undefined);
|
|
125
|
+
} finally {
|
|
126
|
+
state = 'idle';
|
|
127
|
+
}
|
|
128
|
+
throw error;
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const start = async (startOptions: { signal?: AbortSignal } = {}) => {
|
|
132
|
+
if (state === 'destroyed' || state !== 'idle') {
|
|
133
|
+
throw new VoiceError('INVALID_STATE', `Cannot start realtime transcription in ${state} state.`);
|
|
134
|
+
}
|
|
135
|
+
if (startOptions.signal?.aborted) throw new VoiceError('ABORTED', 'Realtime transcription aborted.');
|
|
136
|
+
state = 'starting';
|
|
137
|
+
controller = new AbortController();
|
|
138
|
+
externalSignal = startOptions.signal;
|
|
139
|
+
closePromise = undefined;
|
|
140
|
+
terminalError = undefined;
|
|
141
|
+
transcripts = [];
|
|
142
|
+
bufferedBytes = 0;
|
|
143
|
+
externalAbort = () => terminate(
|
|
144
|
+
new VoiceError('ABORTED', 'Realtime transcription aborted.'),
|
|
145
|
+
externalSignal?.reason,
|
|
146
|
+
);
|
|
147
|
+
externalSignal?.addEventListener('abort', externalAbort, { once: true });
|
|
148
|
+
unsubscribe = options.transport.subscribe((event) => {
|
|
149
|
+
if (event && typeof event === 'object') {
|
|
150
|
+
const transportEvent = event as Record<string, unknown>;
|
|
151
|
+
if (transportEvent.type === 'transport-error'
|
|
152
|
+
|| transportEvent.type === 'transport-close') {
|
|
153
|
+
terminate(
|
|
154
|
+
new VoiceError(
|
|
155
|
+
'NETWORK_ERROR',
|
|
156
|
+
transportEvent.type === 'transport-close'
|
|
157
|
+
? 'Realtime transport closed unexpectedly.'
|
|
158
|
+
: 'Realtime transport failed.',
|
|
159
|
+
transportEvent.error ?? transportEvent.reason,
|
|
160
|
+
),
|
|
161
|
+
event,
|
|
162
|
+
);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const transcript = parseTranscript(event);
|
|
167
|
+
if (!transcript) return;
|
|
168
|
+
transcripts.push(transcript);
|
|
169
|
+
options.onTranscript?.(transcript);
|
|
170
|
+
});
|
|
171
|
+
timeout = setTimeout(() => terminate(
|
|
172
|
+
new VoiceError('TIMEOUT', 'Realtime transcription timed out.'),
|
|
173
|
+
'timeout',
|
|
174
|
+
), options.timeoutMs ?? 120_000);
|
|
175
|
+
try {
|
|
176
|
+
await options.transport.open({ signal: controller.signal });
|
|
177
|
+
if (terminalError) return consumeTerminalError();
|
|
178
|
+
state = 'streaming';
|
|
179
|
+
} catch (error) {
|
|
180
|
+
const mapped = terminalError ?? new VoiceError(
|
|
181
|
+
controller.signal.aborted ? 'ABORTED' : 'NETWORK_ERROR',
|
|
182
|
+
'Unable to start realtime transcription.',
|
|
183
|
+
error,
|
|
184
|
+
);
|
|
185
|
+
terminalError = undefined;
|
|
186
|
+
try {
|
|
187
|
+
await cleanup(error).catch(() => undefined);
|
|
188
|
+
} finally {
|
|
189
|
+
state = 'idle';
|
|
190
|
+
}
|
|
191
|
+
throw mapped;
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
const sendAudio = async (audio: Blob | ArrayBuffer | Uint8Array) => {
|
|
196
|
+
if (terminalError && state === 'stopping') return consumeTerminalError();
|
|
197
|
+
if (state !== 'streaming') {
|
|
198
|
+
throw new VoiceError('INVALID_STATE', 'Realtime transcription is not streaming.');
|
|
199
|
+
}
|
|
200
|
+
const size = audio instanceof Blob ? audio.size : audio.byteLength;
|
|
201
|
+
bufferedBytes += size;
|
|
202
|
+
if (bufferedBytes > maximum) {
|
|
203
|
+
const error = new VoiceError('LIMIT_EXCEEDED', 'Realtime audio exceeds maxBufferedBytes.');
|
|
204
|
+
terminalError = error;
|
|
205
|
+
state = 'stopping';
|
|
206
|
+
await cleanup('buffer limit');
|
|
207
|
+
return consumeTerminalError();
|
|
208
|
+
}
|
|
209
|
+
try {
|
|
210
|
+
await options.transport.send(audio);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
const mapped = new VoiceError('NETWORK_ERROR', 'Unable to send realtime audio.', error);
|
|
213
|
+
terminalError = mapped;
|
|
214
|
+
state = 'stopping';
|
|
215
|
+
await cleanup(error).catch(() => undefined);
|
|
216
|
+
return consumeTerminalError();
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
const stop = async () => {
|
|
221
|
+
if (terminalError && state === 'stopping') return consumeTerminalError();
|
|
222
|
+
if (state !== 'streaming') {
|
|
223
|
+
throw new VoiceError('INVALID_STATE', 'Realtime transcription is not streaming.');
|
|
224
|
+
}
|
|
225
|
+
state = 'stopping';
|
|
226
|
+
try {
|
|
227
|
+
await options.transport.finish();
|
|
228
|
+
return [...transcripts];
|
|
229
|
+
} catch (error) {
|
|
230
|
+
throw new VoiceError('NETWORK_ERROR', 'Unable to finish realtime transcription.', error);
|
|
231
|
+
} finally {
|
|
232
|
+
try {
|
|
233
|
+
await cleanup().catch(() => undefined);
|
|
234
|
+
} finally {
|
|
235
|
+
state = 'idle';
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
const cancel = async (reason?: unknown) => {
|
|
241
|
+
if (state === 'idle' || state === 'destroyed') return;
|
|
242
|
+
state = 'stopping';
|
|
243
|
+
terminalError = undefined;
|
|
244
|
+
try {
|
|
245
|
+
await cleanup(reason);
|
|
246
|
+
} finally {
|
|
247
|
+
state = 'idle';
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
const destroy = async () => {
|
|
252
|
+
if (state === 'destroyed') return;
|
|
253
|
+
try {
|
|
254
|
+
await cancel('destroyed');
|
|
255
|
+
} finally {
|
|
256
|
+
state = 'destroyed';
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
return { start, sendAudio, stop, cancel, destroy, getState: () => state };
|
|
261
|
+
}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import {
|
|
2
|
+
VOICE_RECORDING_MIME_TYPES,
|
|
3
|
+
type VoiceCaptureAdapter,
|
|
4
|
+
} from './capabilities';
|
|
5
|
+
import { VoiceError } from './errors';
|
|
6
|
+
import { encodePcm16Wav } from './wav';
|
|
7
|
+
|
|
8
|
+
export interface VoiceRecording {
|
|
9
|
+
blob: Blob;
|
|
10
|
+
mimeType: string;
|
|
11
|
+
durationMs: number;
|
|
12
|
+
bytes: number;
|
|
13
|
+
}
|
|
14
|
+
export const DEFAULT_VOICE_MEDIA_CONSTRAINTS: MediaStreamConstraints = {
|
|
15
|
+
audio: {
|
|
16
|
+
channelCount: 1,
|
|
17
|
+
echoCancellation: true,
|
|
18
|
+
noiseSuppression: true,
|
|
19
|
+
autoGainControl: true,
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export interface VoiceRecorderOptions {
|
|
24
|
+
adapter?: VoiceCaptureAdapter;
|
|
25
|
+
mimeTypes?: string[];
|
|
26
|
+
maxDurationMs?: number;
|
|
27
|
+
maxBytes?: number;
|
|
28
|
+
mediaConstraints?: MediaStreamConstraints;
|
|
29
|
+
}
|
|
30
|
+
export interface VoiceRecorder {
|
|
31
|
+
start(): Promise<void>;
|
|
32
|
+
stop(): Promise<VoiceRecording>;
|
|
33
|
+
cancel(): Promise<void>;
|
|
34
|
+
destroy(): Promise<void>;
|
|
35
|
+
getState(): 'idle' | 'starting' | 'recording' | 'stopping' | 'destroyed';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function createVoiceRecorder(options: VoiceRecorderOptions = {}): VoiceRecorder {
|
|
39
|
+
let state: ReturnType<VoiceRecorder['getState']> = 'idle';
|
|
40
|
+
let stream: MediaStream | undefined;
|
|
41
|
+
let recorder: MediaRecorder | undefined;
|
|
42
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
43
|
+
let chunks: Blob[] = [];
|
|
44
|
+
let bytes = 0;
|
|
45
|
+
let started = 0;
|
|
46
|
+
let adapterActive = false;
|
|
47
|
+
let context: AudioContext | undefined;
|
|
48
|
+
let source: MediaStreamAudioSourceNode | undefined;
|
|
49
|
+
let processor: ScriptProcessorNode | undefined;
|
|
50
|
+
let pcm: Float32Array[] = [];
|
|
51
|
+
let terminalError: VoiceError | undefined;
|
|
52
|
+
let operation = 0;
|
|
53
|
+
const maxDuration = options.maxDurationMs ?? 120_000;
|
|
54
|
+
const maxBytes = options.maxBytes ?? 25 * 1024 * 1024;
|
|
55
|
+
|
|
56
|
+
const cleanup = async () => {
|
|
57
|
+
if (timer) clearTimeout(timer);
|
|
58
|
+
timer = undefined;
|
|
59
|
+
recorder = undefined;
|
|
60
|
+
processor?.disconnect();
|
|
61
|
+
source?.disconnect();
|
|
62
|
+
processor = undefined;
|
|
63
|
+
source = undefined;
|
|
64
|
+
if (context) await context.close().catch(() => undefined);
|
|
65
|
+
context = undefined;
|
|
66
|
+
stream?.getTracks().forEach((track) => track.stop());
|
|
67
|
+
stream = undefined;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const bestEffortAdapterCancel = async () => {
|
|
71
|
+
if (!adapterActive) return;
|
|
72
|
+
try {
|
|
73
|
+
await options.adapter?.cancel?.();
|
|
74
|
+
} catch {
|
|
75
|
+
// Cleanup and the original terminal result take precedence.
|
|
76
|
+
} finally {
|
|
77
|
+
adapterActive = false;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const exceedLimit = async (message: string) => {
|
|
82
|
+
if (state !== 'recording') return;
|
|
83
|
+
terminalError = new VoiceError('LIMIT_EXCEEDED', message);
|
|
84
|
+
state = 'stopping';
|
|
85
|
+
if (recorder?.state === 'recording') recorder.stop();
|
|
86
|
+
await bestEffortAdapterCancel();
|
|
87
|
+
await cleanup();
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const start = async () => {
|
|
91
|
+
if (state === 'destroyed' || state !== 'idle') {
|
|
92
|
+
throw new VoiceError('INVALID_STATE', `Cannot start recorder in ${state} state`);
|
|
93
|
+
}
|
|
94
|
+
state = 'starting';
|
|
95
|
+
operation += 1;
|
|
96
|
+
const startOperation = operation;
|
|
97
|
+
chunks = [];
|
|
98
|
+
bytes = 0;
|
|
99
|
+
pcm = [];
|
|
100
|
+
terminalError = undefined;
|
|
101
|
+
started = Date.now();
|
|
102
|
+
try {
|
|
103
|
+
if (options.adapter) {
|
|
104
|
+
await options.adapter.start();
|
|
105
|
+
if (operation !== startOperation || state !== 'starting') {
|
|
106
|
+
await options.adapter.cancel?.();
|
|
107
|
+
throw new VoiceError('ABORTED', 'Recorder start was canceled.');
|
|
108
|
+
}
|
|
109
|
+
adapterActive = true;
|
|
110
|
+
state = 'recording';
|
|
111
|
+
} else {
|
|
112
|
+
if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia) {
|
|
113
|
+
throw new VoiceError(
|
|
114
|
+
'UNSUPPORTED',
|
|
115
|
+
'Microphone capture is unavailable; inject a VoiceCaptureAdapter.',
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
stream = await navigator.mediaDevices.getUserMedia(
|
|
119
|
+
options.mediaConstraints ?? DEFAULT_VOICE_MEDIA_CONSTRAINTS,
|
|
120
|
+
);
|
|
121
|
+
if (operation !== startOperation || state !== 'starting') {
|
|
122
|
+
stream.getTracks().forEach((track) => track.stop());
|
|
123
|
+
stream = undefined;
|
|
124
|
+
throw new VoiceError('ABORTED', 'Recorder start was canceled.');
|
|
125
|
+
}
|
|
126
|
+
if (typeof MediaRecorder !== 'undefined') {
|
|
127
|
+
const candidates = [...new Set(options.mimeTypes ?? VOICE_RECORDING_MIME_TYPES)];
|
|
128
|
+
const mimeType = candidates.find((candidate) => (
|
|
129
|
+
typeof MediaRecorder.isTypeSupported !== 'function'
|
|
130
|
+
|| MediaRecorder.isTypeSupported(candidate)
|
|
131
|
+
));
|
|
132
|
+
try {
|
|
133
|
+
recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (!mimeType) throw error;
|
|
136
|
+
recorder = new MediaRecorder(stream);
|
|
137
|
+
}
|
|
138
|
+
recorder.ondataavailable = (event) => {
|
|
139
|
+
if (!event.data.size) return;
|
|
140
|
+
chunks.push(event.data);
|
|
141
|
+
bytes += event.data.size;
|
|
142
|
+
if (bytes > maxBytes) void exceedLimit('Recording exceeds maxBytes.');
|
|
143
|
+
};
|
|
144
|
+
recorder.start(250);
|
|
145
|
+
state = 'recording';
|
|
146
|
+
} else {
|
|
147
|
+
const AC = globalThis.AudioContext
|
|
148
|
+
?? (globalThis as typeof globalThis & {
|
|
149
|
+
webkitAudioContext?: typeof AudioContext;
|
|
150
|
+
}).webkitAudioContext;
|
|
151
|
+
if (!AC) throw new VoiceError('UNSUPPORTED', 'MediaRecorder and Web Audio are unavailable.');
|
|
152
|
+
context = new AC();
|
|
153
|
+
if (context.state === 'suspended') await context.resume();
|
|
154
|
+
if (context.state !== 'running') {
|
|
155
|
+
throw new VoiceError(
|
|
156
|
+
'CAPTURE_FAILED',
|
|
157
|
+
'Web Audio could not start; call start() from a user gesture.',
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
source = context.createMediaStreamSource(stream);
|
|
161
|
+
processor = context.createScriptProcessor(4096, 1, 1);
|
|
162
|
+
processor.onaudioprocess = (event) => {
|
|
163
|
+
const part = new Float32Array(event.inputBuffer.getChannelData(0));
|
|
164
|
+
pcm.push(part);
|
|
165
|
+
bytes += part.byteLength / 2;
|
|
166
|
+
if (bytes > maxBytes) void exceedLimit('Recording exceeds maxBytes.');
|
|
167
|
+
};
|
|
168
|
+
source.connect(processor);
|
|
169
|
+
processor.connect(context.destination);
|
|
170
|
+
state = 'recording';
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
timer = setTimeout(() => {
|
|
174
|
+
void exceedLimit('Recording exceeds maxDurationMs.');
|
|
175
|
+
}, maxDuration);
|
|
176
|
+
} catch (error) {
|
|
177
|
+
const canceled = operation !== startOperation;
|
|
178
|
+
if (!canceled) state = 'idle';
|
|
179
|
+
await bestEffortAdapterCancel();
|
|
180
|
+
await cleanup();
|
|
181
|
+
if (error instanceof VoiceError) throw error;
|
|
182
|
+
const denied = error instanceof DOMException
|
|
183
|
+
&& ['NotAllowedError', 'SecurityError'].includes(error.name);
|
|
184
|
+
throw new VoiceError(
|
|
185
|
+
denied ? 'PERMISSION_DENIED' : 'CAPTURE_FAILED',
|
|
186
|
+
denied ? 'Microphone permission denied.' : 'Unable to start voice capture.',
|
|
187
|
+
error,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
const stop = async (): Promise<VoiceRecording> => {
|
|
193
|
+
if (terminalError && state === 'stopping') {
|
|
194
|
+
const error = terminalError;
|
|
195
|
+
terminalError = undefined;
|
|
196
|
+
await cleanup();
|
|
197
|
+
state = 'idle';
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
if (state !== 'recording') {
|
|
201
|
+
throw new VoiceError('INVALID_STATE', `Cannot stop recorder in ${state} state`);
|
|
202
|
+
}
|
|
203
|
+
state = 'stopping';
|
|
204
|
+
try {
|
|
205
|
+
let blob: Blob;
|
|
206
|
+
if (options.adapter) {
|
|
207
|
+
try {
|
|
208
|
+
blob = await options.adapter.stop();
|
|
209
|
+
adapterActive = false;
|
|
210
|
+
} catch (error) {
|
|
211
|
+
await bestEffortAdapterCancel();
|
|
212
|
+
throw new VoiceError('CAPTURE_FAILED', 'Unable to stop voice capture.', error);
|
|
213
|
+
}
|
|
214
|
+
} else if (recorder) {
|
|
215
|
+
const active = recorder;
|
|
216
|
+
blob = await new Promise<Blob>((resolve, reject) => {
|
|
217
|
+
active.onerror = () => reject(new VoiceError('CAPTURE_FAILED', 'MediaRecorder failed.'));
|
|
218
|
+
active.onstop = () => resolve(new Blob(chunks, {
|
|
219
|
+
type: active.mimeType || chunks[0]?.type || 'application/octet-stream',
|
|
220
|
+
}));
|
|
221
|
+
active.stop();
|
|
222
|
+
});
|
|
223
|
+
} else {
|
|
224
|
+
const sampleCount = pcm.reduce((count, part) => count + part.length, 0);
|
|
225
|
+
if (!sampleCount) throw new VoiceError('CAPTURE_FAILED', 'No audio frames were captured.');
|
|
226
|
+
const all = new Float32Array(sampleCount);
|
|
227
|
+
let offset = 0;
|
|
228
|
+
for (const part of pcm) {
|
|
229
|
+
all.set(part, offset);
|
|
230
|
+
offset += part.length;
|
|
231
|
+
}
|
|
232
|
+
blob = encodePcm16Wav(all, context!.sampleRate);
|
|
233
|
+
}
|
|
234
|
+
if (blob.size > maxBytes) {
|
|
235
|
+
throw new VoiceError('LIMIT_EXCEEDED', 'Recording exceeds maxBytes.');
|
|
236
|
+
}
|
|
237
|
+
return {
|
|
238
|
+
blob,
|
|
239
|
+
mimeType: blob.type,
|
|
240
|
+
durationMs: Date.now() - started,
|
|
241
|
+
bytes: blob.size,
|
|
242
|
+
};
|
|
243
|
+
} finally {
|
|
244
|
+
await cleanup();
|
|
245
|
+
state = 'idle';
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
const cancel = async () => {
|
|
250
|
+
if (state !== 'starting' && state !== 'recording' && state !== 'stopping') return;
|
|
251
|
+
operation += 1;
|
|
252
|
+
state = 'stopping';
|
|
253
|
+
terminalError = undefined;
|
|
254
|
+
let cancelError: unknown;
|
|
255
|
+
try {
|
|
256
|
+
if (recorder?.state === 'recording') recorder.stop();
|
|
257
|
+
if (adapterActive) await options.adapter?.cancel?.();
|
|
258
|
+
} catch (error) {
|
|
259
|
+
cancelError = error;
|
|
260
|
+
} finally {
|
|
261
|
+
adapterActive = false;
|
|
262
|
+
await cleanup();
|
|
263
|
+
state = 'idle';
|
|
264
|
+
}
|
|
265
|
+
if (cancelError) throw new VoiceError('CAPTURE_FAILED', 'Unable to cancel voice capture.', cancelError);
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
const destroy = async () => {
|
|
269
|
+
if (state === 'destroyed') return;
|
|
270
|
+
operation += 1;
|
|
271
|
+
try {
|
|
272
|
+
await cancel().catch(() => undefined);
|
|
273
|
+
await options.adapter?.destroy?.();
|
|
274
|
+
} finally {
|
|
275
|
+
await cleanup();
|
|
276
|
+
state = 'destroyed';
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
return { start, stop, cancel, destroy, getState: () => state };
|
|
280
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
export type VoiceStoredKind = 'recording' | 'transcript' | 'speech';
|
|
2
|
+
|
|
3
|
+
export interface VoiceStoredItem {
|
|
4
|
+
id: string;
|
|
5
|
+
kind: VoiceStoredKind;
|
|
6
|
+
createdAt: number;
|
|
7
|
+
bytes: number;
|
|
8
|
+
metadata?: Record<string, string | number | boolean>;
|
|
9
|
+
value: Blob | string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface VoiceStorageAdapter {
|
|
13
|
+
save(item: VoiceStoredItem, options?: { signal?: AbortSignal }): Promise<void>;
|
|
14
|
+
load(id: string, options?: { signal?: AbortSignal }): Promise<VoiceStoredItem | undefined>;
|
|
15
|
+
list(options?: { signal?: AbortSignal }): Promise<VoiceStoredItem[]>;
|
|
16
|
+
delete(id: string, options?: { signal?: AbortSignal }): Promise<boolean>;
|
|
17
|
+
clear(options?: { signal?: AbortSignal }): Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function throwIfAborted(signal?: AbortSignal): void {
|
|
21
|
+
if (signal?.aborted) throw new DOMException('Aborted', 'AbortError');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function cloneItem(item: VoiceStoredItem): VoiceStoredItem {
|
|
25
|
+
return { ...item, metadata: item.metadata ? { ...item.metadata } : undefined };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function createMemoryVoiceStorage(options: { maxBytes?: number } = {}): VoiceStorageAdapter {
|
|
29
|
+
const items = new Map<string, VoiceStoredItem>();
|
|
30
|
+
const maximum = options.maxBytes ?? 50 * 1024 * 1024;
|
|
31
|
+
if (!Number.isSafeInteger(maximum) || maximum < 0) {
|
|
32
|
+
throw new TypeError('maxBytes must be a non-negative safe integer.');
|
|
33
|
+
}
|
|
34
|
+
let used = 0;
|
|
35
|
+
|
|
36
|
+
const save: VoiceStorageAdapter['save'] = async (item, saveOptions) => {
|
|
37
|
+
throwIfAborted(saveOptions?.signal);
|
|
38
|
+
const actualBytes = typeof item.value === 'string'
|
|
39
|
+
? new TextEncoder().encode(item.value).byteLength
|
|
40
|
+
: item.value.size;
|
|
41
|
+
if (!item.id
|
|
42
|
+
|| !Number.isSafeInteger(item.bytes)
|
|
43
|
+
|| item.bytes < 0
|
|
44
|
+
|| item.bytes !== actualBytes
|
|
45
|
+
|| item.bytes > maximum) {
|
|
46
|
+
throw new TypeError('Invalid stored voice item.');
|
|
47
|
+
}
|
|
48
|
+
const existing = items.get(item.id);
|
|
49
|
+
if (existing) used -= existing.bytes;
|
|
50
|
+
const ordered = [...items.values()]
|
|
51
|
+
.filter((candidate) => candidate.id !== item.id)
|
|
52
|
+
.sort((left, right) => left.createdAt - right.createdAt || left.id.localeCompare(right.id));
|
|
53
|
+
for (const candidate of ordered) {
|
|
54
|
+
if (used + item.bytes <= maximum) break;
|
|
55
|
+
items.delete(candidate.id);
|
|
56
|
+
used -= candidate.bytes;
|
|
57
|
+
}
|
|
58
|
+
if (used + item.bytes > maximum) throw new RangeError('Voice storage quota exceeded.');
|
|
59
|
+
items.set(item.id, cloneItem(item));
|
|
60
|
+
used += item.bytes;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
return {
|
|
64
|
+
save,
|
|
65
|
+
async load(id, loadOptions) {
|
|
66
|
+
throwIfAborted(loadOptions?.signal);
|
|
67
|
+
const item = items.get(id);
|
|
68
|
+
return item ? cloneItem(item) : undefined;
|
|
69
|
+
},
|
|
70
|
+
async list(listOptions) {
|
|
71
|
+
throwIfAborted(listOptions?.signal);
|
|
72
|
+
return [...items.values()]
|
|
73
|
+
.sort((left, right) => right.createdAt - left.createdAt || left.id.localeCompare(right.id))
|
|
74
|
+
.map(cloneItem);
|
|
75
|
+
},
|
|
76
|
+
async delete(id, deleteOptions) {
|
|
77
|
+
throwIfAborted(deleteOptions?.signal);
|
|
78
|
+
const item = items.get(id);
|
|
79
|
+
if (!item) return false;
|
|
80
|
+
used -= item.bytes;
|
|
81
|
+
return items.delete(id);
|
|
82
|
+
},
|
|
83
|
+
async clear(clearOptions) {
|
|
84
|
+
throwIfAborted(clearOptions?.signal);
|
|
85
|
+
items.clear();
|
|
86
|
+
used = 0;
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|