segmind 0.5.1 → 0.6.1

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.
@@ -0,0 +1,307 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2;
2
+
3
+
4
+
5
+ var _chunkHWZJ36WCcjs = require('../../chunk-HWZJ36WC.cjs');
6
+
7
+
8
+ var _chunk74UKKBOOcjs = require('../../chunk-74UKKBOO.cjs');
9
+
10
+ // src/realtime/browser/capture.ts
11
+ var CAPTURE_WORKLET = (frameSamples) => `
12
+ class SegmindCapture extends AudioWorkletProcessor {
13
+ constructor() {
14
+ super();
15
+ this.buffer = new Int16Array(${frameSamples});
16
+ this.n = 0;
17
+ }
18
+ process(inputs) {
19
+ const channel = inputs[0] && inputs[0][0];
20
+ if (!channel) return true;
21
+ for (let i = 0; i < channel.length; i++) {
22
+ const s = Math.max(-1, Math.min(1, channel[i]));
23
+ this.buffer[this.n++] = s < 0 ? s * 0x8000 : s * 0x7fff;
24
+ if (this.n === this.buffer.length) {
25
+ this.port.postMessage(this.buffer.buffer.slice(0));
26
+ this.n = 0;
27
+ }
28
+ }
29
+ return true;
30
+ }
31
+ }
32
+ registerProcessor('segmind-capture', SegmindCapture);
33
+ `;
34
+ var MicrophoneCapture = (_class = class {
35
+ constructor(options = {}) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);_class.prototype.__init5.call(this);_class.prototype.__init6.call(this);
36
+ this.options = options;
37
+ this.sampleRate = _nullishCoalesce(options.sampleRate, () => ( _chunkHWZJ36WCcjs.SESSION_SAMPLE_RATE));
38
+ this.frameSamples = Math.round(this.sampleRate * (_nullishCoalesce(options.frameMs, () => ( 100))) / 1e3);
39
+ this.context = _nullishCoalesce(options.audioContext, () => ( null));
40
+ this.ownsContext = !options.audioContext;
41
+ }
42
+
43
+
44
+
45
+ __init() {this.context = null}
46
+
47
+ __init2() {this.stream = null}
48
+ __init3() {this.source = null}
49
+ __init4() {this.node = null}
50
+ __init5() {this.listeners = /* @__PURE__ */ new Set()}
51
+ __init6() {this.moduleUrl = null}
52
+ get running() {
53
+ return this.node !== null;
54
+ }
55
+ onFrame(listener) {
56
+ this.listeners.add(listener);
57
+ return () => this.listeners.delete(listener);
58
+ }
59
+ /** The context in use, for sharing with playback. */
60
+ getContext() {
61
+ if (!this.context) {
62
+ this.context = new AudioContext({ sampleRate: this.sampleRate });
63
+ }
64
+ return this.context;
65
+ }
66
+ async start() {
67
+ if (this.node) return;
68
+ const context = this.getContext();
69
+ if (context.state === "suspended") await context.resume();
70
+ this.stream = await navigator.mediaDevices.getUserMedia({
71
+ audio: {
72
+ echoCancellation: true,
73
+ noiseSuppression: true,
74
+ autoGainControl: true,
75
+ channelCount: 1,
76
+ ..._nullishCoalesce(this.options.constraints, () => ( {}))
77
+ }
78
+ });
79
+ if (!this.moduleUrl) {
80
+ this.moduleUrl = URL.createObjectURL(
81
+ new Blob([CAPTURE_WORKLET(this.frameSamples)], { type: "application/javascript" })
82
+ );
83
+ await context.audioWorklet.addModule(this.moduleUrl);
84
+ }
85
+ this.source = context.createMediaStreamSource(this.stream);
86
+ this.node = new AudioWorkletNode(context, "segmind-capture");
87
+ this.node.port.onmessage = (ev) => {
88
+ const frame = new Int16Array(ev.data);
89
+ for (const listener of this.listeners) listener(frame);
90
+ };
91
+ this.source.connect(this.node);
92
+ }
93
+ stop() {
94
+ _optionalChain([this, 'access', _ => _.source, 'optionalAccess', _2 => _2.disconnect, 'call', _3 => _3()]);
95
+ _optionalChain([this, 'access', _4 => _4.node, 'optionalAccess', _5 => _5.disconnect, 'call', _6 => _6()]);
96
+ if (this.node) this.node.port.onmessage = null;
97
+ _optionalChain([this, 'access', _7 => _7.stream, 'optionalAccess', _8 => _8.getTracks, 'call', _9 => _9(), 'access', _10 => _10.forEach, 'call', _11 => _11((track) => track.stop())]);
98
+ this.source = null;
99
+ this.node = null;
100
+ this.stream = null;
101
+ }
102
+ async dispose() {
103
+ this.stop();
104
+ if (this.moduleUrl) {
105
+ URL.revokeObjectURL(this.moduleUrl);
106
+ this.moduleUrl = null;
107
+ }
108
+ if (this.ownsContext && this.context) {
109
+ await this.context.close();
110
+ this.context = null;
111
+ }
112
+ }
113
+ }, _class);
114
+
115
+ // src/realtime/browser/playback.ts
116
+ var PLAYBACK_WORKLET = (primeSamples) => `
117
+ class SegmindPlayback extends AudioWorkletProcessor {
118
+ constructor() {
119
+ super();
120
+ this.queue = [];
121
+ this.offset = 0;
122
+ this.buffered = 0;
123
+ this.primed = false;
124
+ this.underruns = 0;
125
+ this.port.onmessage = (e) => {
126
+ if (e.data === 'flush') {
127
+ this.queue = []; this.offset = 0; this.buffered = 0; this.primed = false;
128
+ this.port.postMessage({ flushed: true });
129
+ return;
130
+ }
131
+ const pcm = new Int16Array(e.data);
132
+ this.queue.push(pcm);
133
+ this.buffered += pcm.length;
134
+ };
135
+ }
136
+ process(inputs, outputs) {
137
+ const out = outputs[0][0];
138
+ if (!out) return true;
139
+ if (!this.primed) {
140
+ if (this.buffered >= ${primeSamples}) this.primed = true;
141
+ else { out.fill(0); return true; }
142
+ }
143
+ for (let i = 0; i < out.length; i++) {
144
+ if (!this.queue.length) {
145
+ out.fill(0, i);
146
+ this.primed = false;
147
+ this.underruns++;
148
+ this.port.postMessage({ underruns: this.underruns, buffered: 0 });
149
+ return true;
150
+ }
151
+ const current = this.queue[0];
152
+ out[i] = current[this.offset++] / 0x8000;
153
+ this.buffered--;
154
+ if (this.offset >= current.length) { this.queue.shift(); this.offset = 0; }
155
+ }
156
+ return true;
157
+ }
158
+ }
159
+ registerProcessor('segmind-playback', SegmindPlayback);
160
+ `;
161
+ var AudioPlayback = (_class2 = class {
162
+ constructor(options = {}) {;_class2.prototype.__init7.call(this);_class2.prototype.__init8.call(this);_class2.prototype.__init9.call(this);_class2.prototype.__init10.call(this);_class2.prototype.__init11.call(this);
163
+ this.options = options;
164
+ this.sampleRate = _nullishCoalesce(options.sampleRate, () => ( _chunkHWZJ36WCcjs.SESSION_SAMPLE_RATE));
165
+ this.context = _nullishCoalesce(options.audioContext, () => ( null));
166
+ this.ownsContext = !options.audioContext;
167
+ }
168
+
169
+
170
+
171
+
172
+ __init7() {this.node = null}
173
+ __init8() {this.moduleUrl = null}
174
+ __init9() {this._underruns = 0}
175
+ __init10() {this.queuedSamples = 0}
176
+ __init11() {this.underrunListeners = /* @__PURE__ */ new Set()}
177
+ get underruns() {
178
+ return this._underruns;
179
+ }
180
+ /** Seconds of audio handed to the worklet and not yet flushed; an upper bound on what is still to play. */
181
+ get queuedSeconds() {
182
+ return this.queuedSamples / this.sampleRate;
183
+ }
184
+ onUnderrun(listener) {
185
+ this.underrunListeners.add(listener);
186
+ return () => this.underrunListeners.delete(listener);
187
+ }
188
+ getContext() {
189
+ if (!this.context) this.context = new AudioContext({ sampleRate: this.sampleRate });
190
+ return this.context;
191
+ }
192
+ async start() {
193
+ if (this.node) return;
194
+ const context = this.getContext();
195
+ if (context.state === "suspended") await context.resume();
196
+ const primeSamples = Math.round(this.sampleRate * (_nullishCoalesce(this.options.primeMs, () => ( 200))) / 1e3);
197
+ this.moduleUrl = URL.createObjectURL(
198
+ new Blob([PLAYBACK_WORKLET(primeSamples)], { type: "application/javascript" })
199
+ );
200
+ await context.audioWorklet.addModule(this.moduleUrl);
201
+ this.node = new AudioWorkletNode(context, "segmind-playback");
202
+ this.node.port.onmessage = (ev) => {
203
+ if (typeof ev.data.underruns === "number") {
204
+ this._underruns = ev.data.underruns;
205
+ this.queuedSamples = 0;
206
+ for (const listener of this.underrunListeners) listener(this._underruns);
207
+ }
208
+ };
209
+ this.node.connect(context.destination);
210
+ }
211
+ /** Queue one chunk. Accepts the `audio.delta` base64 payload or raw Int16 samples. */
212
+ enqueue(audio) {
213
+ if (!this.node) throw new Error("playback not started");
214
+ const pcm = typeof audio === "string" ? _chunkHWZJ36WCcjs.decodePcm.call(void 0, audio) : audio;
215
+ this.queuedSamples += pcm.length;
216
+ const copy = pcm.buffer.slice(pcm.byteOffset, pcm.byteOffset + pcm.byteLength);
217
+ this.node.port.postMessage(copy, [copy]);
218
+ }
219
+ /** Drop everything queued — the user interrupted. */
220
+ flush() {
221
+ this.queuedSamples = 0;
222
+ _optionalChain([this, 'access', _12 => _12.node, 'optionalAccess', _13 => _13.port, 'access', _14 => _14.postMessage, 'call', _15 => _15("flush")]);
223
+ }
224
+ async dispose() {
225
+ _optionalChain([this, 'access', _16 => _16.node, 'optionalAccess', _17 => _17.disconnect, 'call', _18 => _18()]);
226
+ if (this.node) this.node.port.onmessage = null;
227
+ this.node = null;
228
+ if (this.moduleUrl) {
229
+ URL.revokeObjectURL(this.moduleUrl);
230
+ this.moduleUrl = null;
231
+ }
232
+ if (this.ownsContext && this.context) {
233
+ await this.context.close();
234
+ this.context = null;
235
+ }
236
+ }
237
+ }, _class2);
238
+
239
+ // src/realtime/browser/voice.ts
240
+ async function startVoice(session, options = {}) {
241
+ const format = session.audio;
242
+ if (!format) {
243
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(
244
+ session.state === "live" ? "this session carries no 16-bit PCM audio" : "startVoice needs a live session: await connect() or session.open() first"
245
+ );
246
+ }
247
+ const capture = new MicrophoneCapture({ sampleRate: format.rate, constraints: options.constraints });
248
+ const playback = new AudioPlayback({
249
+ sampleRate: format.rate,
250
+ audioContext: capture.getContext(),
251
+ primeMs: options.primeMs
252
+ });
253
+ let muted = false;
254
+ let bargeIn = null;
255
+ try {
256
+ await playback.start();
257
+ await capture.start();
258
+ bargeIn = _chunkHWZJ36WCcjs.attachBargeIn.call(void 0, {
259
+ session,
260
+ capture,
261
+ playback,
262
+ localVad: options.localVad,
263
+ onLevel: options.onLevel,
264
+ onLocalSpeech: options.onLocalSpeech,
265
+ shouldSend: () => !muted
266
+ });
267
+ } catch (error) {
268
+ await playback.dispose();
269
+ await capture.dispose();
270
+ throw error;
271
+ }
272
+ let stopped = null;
273
+ const stop = () => {
274
+ stopped ??= (async () => {
275
+ _optionalChain([bargeIn, 'optionalAccess', _19 => _19.detach, 'call', _20 => _20()]);
276
+ await playback.dispose();
277
+ await capture.dispose();
278
+ })();
279
+ return stopped;
280
+ };
281
+ const offState = session.onState((state) => {
282
+ if (state === "closed") {
283
+ offState();
284
+ void stop();
285
+ }
286
+ });
287
+ return {
288
+ get muted() {
289
+ return muted;
290
+ },
291
+ set muted(value) {
292
+ muted = value;
293
+ },
294
+ get replying() {
295
+ return _nullishCoalesce(_optionalChain([bargeIn, 'optionalAccess', _21 => _21.replying]), () => ( false));
296
+ },
297
+ capture,
298
+ playback,
299
+ stop
300
+ };
301
+ }
302
+
303
+
304
+
305
+
306
+ exports.AudioPlayback = AudioPlayback; exports.MicrophoneCapture = MicrophoneCapture; exports.startVoice = startVoice;
307
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/segmind-js/segmind-js/packages/segmind/dist/realtime/browser/index.cjs","../../../src/realtime/browser/capture.ts","../../../src/realtime/browser/playback.ts","../../../src/realtime/browser/voice.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACF,4DAAiC;AACjC;AACE;AACF,4DAAiC;AACjC;AACA;ACiBA,IAAM,gBAAA,EAAkB,CAAC,YAAA,EAAA,GAAyB,CAAA;AAAA;AAAA;AAAA;AAAA,iCAAA,EAIf,YAAY,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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,CAAA,EAAQ;AACV,MAAA,OAAO,KAAA;AAAA,IACT,CAAA;AAAA,IACA,IAAI,KAAA,CAAM,KAAA,EAAgB;AACxB,MAAA,MAAA,EAAQ,KAAA;AAAA,IACV,CAAA;AAAA,IACA,IAAI,QAAA,CAAA,EAAW;AACb,MAAA,wCAAO,OAAA,+BAAS,UAAA,UAAY,OAAA;AAAA,IAC9B,CAAA;AAAA,IACA,OAAA;AAAA,IACA,QAAA;AAAA,IACA;AAAA,EACF,CAAA;AACF;AH8LA;AACE;AACA;AACA;AACF,sHAAC","file":"/home/runner/work/segmind-js/segmind-js/packages/segmind/dist/realtime/browser/index.cjs","sourcesContent":[null,"/**\n * Microphone capture: `getUserMedia` with echo cancellation, an\n * `AudioContext` at the session rate (the browser resamples), and an\n * `AudioWorklet` that hands out fixed-size s16le frames.\n *\n * The worklet source is inlined as a Blob URL so the package needs no\n * separate asset to serve. Browser-only; nothing here is imported by the\n * session itself.\n */\n\nimport { SESSION_SAMPLE_RATE } from '../pcm';\n\nexport interface CaptureOptions {\n sampleRate?: number;\n /** Frame length in milliseconds. Default 100. */\n frameMs?: number;\n /** Extra `getUserMedia` audio constraints. Echo cancellation, noise\n * suppression and auto gain are on by default: the model's own reply is\n * playing from the same device. */\n constraints?: MediaTrackConstraints;\n /** Reuse an existing context (one per page is the browser's preference). */\n audioContext?: AudioContext;\n}\n\nexport type FrameListener = (frame: Int16Array) => void;\n\nconst CAPTURE_WORKLET = (frameSamples: number) => `\nclass SegmindCapture extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Int16Array(${frameSamples});\n this.n = 0;\n }\n process(inputs) {\n const channel = inputs[0] && inputs[0][0];\n if (!channel) return true;\n for (let i = 0; i < channel.length; i++) {\n const s = Math.max(-1, Math.min(1, channel[i]));\n this.buffer[this.n++] = s < 0 ? s * 0x8000 : s * 0x7fff;\n if (this.n === this.buffer.length) {\n this.port.postMessage(this.buffer.buffer.slice(0));\n this.n = 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('segmind-capture', SegmindCapture);\n`;\n\nexport class MicrophoneCapture {\n readonly sampleRate: number;\n readonly frameSamples: number;\n private context: AudioContext | null = null;\n private readonly ownsContext: boolean;\n private stream: MediaStream | null = null;\n private source: MediaStreamAudioSourceNode | null = null;\n private node: AudioWorkletNode | null = null;\n private readonly listeners = new Set<FrameListener>();\n private moduleUrl: string | null = null;\n\n constructor(private readonly options: CaptureOptions = {}) {\n this.sampleRate = options.sampleRate ?? SESSION_SAMPLE_RATE;\n this.frameSamples = Math.round((this.sampleRate * (options.frameMs ?? 100)) / 1000);\n this.context = options.audioContext ?? null;\n this.ownsContext = !options.audioContext;\n }\n\n get running(): boolean {\n return this.node !== null;\n }\n\n onFrame(listener: FrameListener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /** The context in use, for sharing with playback. */\n getContext(): AudioContext {\n if (!this.context) {\n this.context = new AudioContext({ sampleRate: this.sampleRate });\n }\n return this.context;\n }\n\n async start(): Promise<void> {\n if (this.node) return;\n const context = this.getContext();\n if (context.state === 'suspended') await context.resume();\n this.stream = await navigator.mediaDevices.getUserMedia({\n audio: {\n echoCancellation: true,\n noiseSuppression: true,\n autoGainControl: true,\n channelCount: 1,\n ...(this.options.constraints ?? {}),\n },\n });\n if (!this.moduleUrl) {\n this.moduleUrl = URL.createObjectURL(\n new Blob([CAPTURE_WORKLET(this.frameSamples)], { type: 'application/javascript' }),\n );\n await context.audioWorklet.addModule(this.moduleUrl);\n }\n this.source = context.createMediaStreamSource(this.stream);\n this.node = new AudioWorkletNode(context, 'segmind-capture');\n this.node.port.onmessage = (ev: MessageEvent<ArrayBuffer>) => {\n const frame = new Int16Array(ev.data);\n for (const listener of this.listeners) listener(frame);\n };\n // Not connected to the destination: the user must not hear themselves.\n this.source.connect(this.node);\n }\n\n stop(): void {\n this.source?.disconnect();\n this.node?.disconnect();\n if (this.node) this.node.port.onmessage = null;\n this.stream?.getTracks().forEach((track) => track.stop());\n this.source = null;\n this.node = null;\n this.stream = null;\n }\n\n async dispose(): Promise<void> {\n this.stop();\n if (this.moduleUrl) {\n URL.revokeObjectURL(this.moduleUrl);\n this.moduleUrl = null;\n }\n if (this.ownsContext && this.context) {\n await this.context.close();\n this.context = null;\n }\n }\n}\n","/**\n * Gapless playback of `audio.delta` chunks through a jitter buffer in an\n * `AudioWorklet`.\n *\n * Chunks arrive in bursts (the upstream generates faster than real time), so\n * the worklet queues them and starts draining once `primeMs` of audio is\n * buffered. An underrun (the queue runs dry mid-reply) outputs silence,\n * counts, and re-primes. `flush()` drops everything queued — barge-in.\n */\n\nimport { SESSION_SAMPLE_RATE, decodePcm } from '../pcm';\n\nexport interface PlaybackOptions {\n sampleRate?: number;\n /** Audio buffered before playback starts. Default 200 ms. */\n primeMs?: number;\n audioContext?: AudioContext;\n}\n\nconst PLAYBACK_WORKLET = (primeSamples: number) => `\nclass SegmindPlayback extends AudioWorkletProcessor {\n constructor() {\n super();\n this.queue = [];\n this.offset = 0;\n this.buffered = 0;\n this.primed = false;\n this.underruns = 0;\n this.port.onmessage = (e) => {\n if (e.data === 'flush') {\n this.queue = []; this.offset = 0; this.buffered = 0; this.primed = false;\n this.port.postMessage({ flushed: true });\n return;\n }\n const pcm = new Int16Array(e.data);\n this.queue.push(pcm);\n this.buffered += pcm.length;\n };\n }\n process(inputs, outputs) {\n const out = outputs[0][0];\n if (!out) return true;\n if (!this.primed) {\n if (this.buffered >= ${primeSamples}) this.primed = true;\n else { out.fill(0); return true; }\n }\n for (let i = 0; i < out.length; i++) {\n if (!this.queue.length) {\n out.fill(0, i);\n this.primed = false;\n this.underruns++;\n this.port.postMessage({ underruns: this.underruns, buffered: 0 });\n return true;\n }\n const current = this.queue[0];\n out[i] = current[this.offset++] / 0x8000;\n this.buffered--;\n if (this.offset >= current.length) { this.queue.shift(); this.offset = 0; }\n }\n return true;\n }\n}\nregisterProcessor('segmind-playback', SegmindPlayback);\n`;\n\nexport class AudioPlayback {\n readonly sampleRate: number;\n private context: AudioContext | null;\n private readonly ownsContext: boolean;\n private node: AudioWorkletNode | null = null;\n private moduleUrl: string | null = null;\n private _underruns = 0;\n private queuedSamples = 0;\n private readonly underrunListeners = new Set<(count: number) => void>();\n\n constructor(private readonly options: PlaybackOptions = {}) {\n this.sampleRate = options.sampleRate ?? SESSION_SAMPLE_RATE;\n this.context = options.audioContext ?? null;\n this.ownsContext = !options.audioContext;\n }\n\n get underruns(): number {\n return this._underruns;\n }\n\n /** Seconds of audio handed to the worklet and not yet flushed; an upper bound on what is still to play. */\n get queuedSeconds(): number {\n return this.queuedSamples / this.sampleRate;\n }\n\n onUnderrun(listener: (count: number) => void): () => void {\n this.underrunListeners.add(listener);\n return () => this.underrunListeners.delete(listener);\n }\n\n getContext(): AudioContext {\n if (!this.context) this.context = new AudioContext({ sampleRate: this.sampleRate });\n return this.context;\n }\n\n async start(): Promise<void> {\n if (this.node) return;\n const context = this.getContext();\n if (context.state === 'suspended') await context.resume();\n const primeSamples = Math.round((this.sampleRate * (this.options.primeMs ?? 200)) / 1000);\n this.moduleUrl = URL.createObjectURL(\n new Blob([PLAYBACK_WORKLET(primeSamples)], { type: 'application/javascript' }),\n );\n await context.audioWorklet.addModule(this.moduleUrl);\n this.node = new AudioWorkletNode(context, 'segmind-playback');\n this.node.port.onmessage = (ev: MessageEvent<{ underruns?: number; flushed?: boolean }>) => {\n if (typeof ev.data.underruns === 'number') {\n this._underruns = ev.data.underruns;\n this.queuedSamples = 0;\n for (const listener of this.underrunListeners) listener(this._underruns);\n }\n };\n this.node.connect(context.destination);\n }\n\n /** Queue one chunk. Accepts the `audio.delta` base64 payload or raw Int16 samples. */\n enqueue(audio: string | Int16Array): void {\n if (!this.node) throw new Error('playback not started');\n const pcm = typeof audio === 'string' ? decodePcm(audio) : audio;\n this.queuedSamples += pcm.length;\n const copy = pcm.buffer.slice(pcm.byteOffset, pcm.byteOffset + pcm.byteLength);\n this.node.port.postMessage(copy, [copy]);\n }\n\n /** Drop everything queued — the user interrupted. */\n flush(): void {\n this.queuedSamples = 0;\n this.node?.port.postMessage('flush');\n }\n\n async dispose(): Promise<void> {\n this.node?.disconnect();\n if (this.node) this.node.port.onmessage = null;\n this.node = null;\n if (this.moduleUrl) {\n URL.revokeObjectURL(this.moduleUrl);\n this.moduleUrl = null;\n }\n if (this.ownsContext && this.context) {\n await this.context.close();\n this.context = null;\n }\n }\n}\n","/**\n * A voice conversation in one call: the microphone feeds the session, the\n * reply plays through a jitter buffer, and speaking over a reply cuts it.\n *\n * Call it from a user gesture (a click), because browsers allow microphone\n * access and audio output only after one.\n */\n\nimport { attachBargeIn, type BargeIn } from '../barge-in';\nimport { SegmindError } from '../../core/errors';\nimport type { RealtimeSession } from '../session';\nimport type { VadOptions } from '../vad';\nimport { MicrophoneCapture } from './capture';\nimport { AudioPlayback } from './playback';\n\nexport interface VoiceOptions {\n /** Extra `getUserMedia` audio constraints, such as a `deviceId`. */\n constraints?: MediaTrackConstraints;\n /** Milliseconds of reply audio to buffer before playing. Default 200. */\n primeMs?: number;\n /** Detect speech locally to cut a reply within a frame. Default on. */\n localVad?: boolean | VadOptions;\n /** The microphone level (RMS of each 100 ms frame), for a meter. */\n onLevel?: (rms: number) => void;\n /** True when the local detector hears the user start speaking, false when they stop. */\n onLocalSpeech?: (speaking: boolean) => void;\n}\n\nexport interface Voice {\n /** While muted, microphone frames are dropped: nothing is sent and nothing is billed as input. */\n muted: boolean;\n /** True while a reply is being delivered. */\n readonly replying: boolean;\n readonly capture: MicrophoneCapture;\n readonly playback: AudioPlayback;\n /** Stops the microphone and playback. It does not close the session. */\n stop(): Promise<void>;\n}\n\n/**\n * Starts microphone capture and reply playback for a live session, at the\n * rate the session declared (`session.audio.rate`).\n */\nexport async function startVoice(session: RealtimeSession, options: VoiceOptions = {}): Promise<Voice> {\n const format = session.audio;\n if (!format) {\n throw new SegmindError(\n session.state === 'live'\n ? 'this session carries no 16-bit PCM audio'\n : 'startVoice needs a live session: await connect() or session.open() first',\n );\n }\n const capture = new MicrophoneCapture({ sampleRate: format.rate, constraints: options.constraints });\n // One context for both: the browser's echo canceller needs the reply and the\n // microphone on the same device graph.\n const playback = new AudioPlayback({\n sampleRate: format.rate,\n audioContext: capture.getContext(),\n primeMs: options.primeMs,\n });\n let muted = false;\n let bargeIn: BargeIn | null = null;\n try {\n await playback.start();\n await capture.start();\n bargeIn = attachBargeIn({\n session,\n capture,\n playback,\n localVad: options.localVad,\n onLevel: options.onLevel,\n onLocalSpeech: options.onLocalSpeech,\n shouldSend: () => !muted,\n });\n } catch (error) {\n await playback.dispose();\n await capture.dispose();\n throw error;\n }\n\n let stopped: Promise<void> | null = null;\n const stop = () => {\n stopped ??= (async () => {\n bargeIn?.detach();\n await playback.dispose();\n await capture.dispose();\n })();\n return stopped;\n };\n // A session that ends on the server's side releases the microphone too.\n const offState = session.onState((state) => {\n if (state === 'closed') {\n offState();\n void stop();\n }\n });\n\n return {\n get muted() {\n return muted;\n },\n set muted(value: boolean) {\n muted = value;\n },\n get replying() {\n return bargeIn?.replying ?? false;\n },\n capture,\n playback,\n stop,\n };\n}\n"]}
@@ -0,0 +1,122 @@
1
+ import { VadOptions, RealtimeSession } from '../index.cjs';
2
+ import '../../errors-CcHEuSmR.cjs';
3
+
4
+ /**
5
+ * Microphone capture: `getUserMedia` with echo cancellation, an
6
+ * `AudioContext` at the session rate (the browser resamples), and an
7
+ * `AudioWorklet` that hands out fixed-size s16le frames.
8
+ *
9
+ * The worklet source is inlined as a Blob URL so the package needs no
10
+ * separate asset to serve. Browser-only; nothing here is imported by the
11
+ * session itself.
12
+ */
13
+ interface CaptureOptions {
14
+ sampleRate?: number;
15
+ /** Frame length in milliseconds. Default 100. */
16
+ frameMs?: number;
17
+ /** Extra `getUserMedia` audio constraints. Echo cancellation, noise
18
+ * suppression and auto gain are on by default: the model's own reply is
19
+ * playing from the same device. */
20
+ constraints?: MediaTrackConstraints;
21
+ /** Reuse an existing context (one per page is the browser's preference). */
22
+ audioContext?: AudioContext;
23
+ }
24
+ type FrameListener = (frame: Int16Array) => void;
25
+ declare class MicrophoneCapture {
26
+ private readonly options;
27
+ readonly sampleRate: number;
28
+ readonly frameSamples: number;
29
+ private context;
30
+ private readonly ownsContext;
31
+ private stream;
32
+ private source;
33
+ private node;
34
+ private readonly listeners;
35
+ private moduleUrl;
36
+ constructor(options?: CaptureOptions);
37
+ get running(): boolean;
38
+ onFrame(listener: FrameListener): () => void;
39
+ /** The context in use, for sharing with playback. */
40
+ getContext(): AudioContext;
41
+ start(): Promise<void>;
42
+ stop(): void;
43
+ dispose(): Promise<void>;
44
+ }
45
+
46
+ /**
47
+ * Gapless playback of `audio.delta` chunks through a jitter buffer in an
48
+ * `AudioWorklet`.
49
+ *
50
+ * Chunks arrive in bursts (the upstream generates faster than real time), so
51
+ * the worklet queues them and starts draining once `primeMs` of audio is
52
+ * buffered. An underrun (the queue runs dry mid-reply) outputs silence,
53
+ * counts, and re-primes. `flush()` drops everything queued — barge-in.
54
+ */
55
+ interface PlaybackOptions {
56
+ sampleRate?: number;
57
+ /** Audio buffered before playback starts. Default 200 ms. */
58
+ primeMs?: number;
59
+ audioContext?: AudioContext;
60
+ }
61
+ declare class AudioPlayback {
62
+ private readonly options;
63
+ readonly sampleRate: number;
64
+ private context;
65
+ private readonly ownsContext;
66
+ private node;
67
+ private moduleUrl;
68
+ private _underruns;
69
+ private queuedSamples;
70
+ private readonly underrunListeners;
71
+ constructor(options?: PlaybackOptions);
72
+ get underruns(): number;
73
+ /** Seconds of audio handed to the worklet and not yet flushed; an upper bound on what is still to play. */
74
+ get queuedSeconds(): number;
75
+ onUnderrun(listener: (count: number) => void): () => void;
76
+ getContext(): AudioContext;
77
+ start(): Promise<void>;
78
+ /** Queue one chunk. Accepts the `audio.delta` base64 payload or raw Int16 samples. */
79
+ enqueue(audio: string | Int16Array): void;
80
+ /** Drop everything queued — the user interrupted. */
81
+ flush(): void;
82
+ dispose(): Promise<void>;
83
+ }
84
+
85
+ /**
86
+ * A voice conversation in one call: the microphone feeds the session, the
87
+ * reply plays through a jitter buffer, and speaking over a reply cuts it.
88
+ *
89
+ * Call it from a user gesture (a click), because browsers allow microphone
90
+ * access and audio output only after one.
91
+ */
92
+
93
+ interface VoiceOptions {
94
+ /** Extra `getUserMedia` audio constraints, such as a `deviceId`. */
95
+ constraints?: MediaTrackConstraints;
96
+ /** Milliseconds of reply audio to buffer before playing. Default 200. */
97
+ primeMs?: number;
98
+ /** Detect speech locally to cut a reply within a frame. Default on. */
99
+ localVad?: boolean | VadOptions;
100
+ /** The microphone level (RMS of each 100 ms frame), for a meter. */
101
+ onLevel?: (rms: number) => void;
102
+ /** True when the local detector hears the user start speaking, false when they stop. */
103
+ onLocalSpeech?: (speaking: boolean) => void;
104
+ }
105
+ interface Voice {
106
+ /** While muted, microphone frames are dropped: nothing is sent and nothing is billed as input. */
107
+ muted: boolean;
108
+ /** True while a reply is being delivered. */
109
+ readonly replying: boolean;
110
+ readonly capture: MicrophoneCapture;
111
+ readonly playback: AudioPlayback;
112
+ /** Stops the microphone and playback. It does not close the session. */
113
+ stop(): Promise<void>;
114
+ }
115
+ /**
116
+ * Starts microphone capture and reply playback for a live session, at the
117
+ * rate the session declared (`session.audio.rate`).
118
+ */
119
+ declare function startVoice(session: RealtimeSession, options?: VoiceOptions): Promise<Voice>;
120
+
121
+ export { AudioPlayback, MicrophoneCapture, startVoice };
122
+ export type { CaptureOptions, FrameListener, PlaybackOptions, Voice, VoiceOptions };
@@ -0,0 +1,122 @@
1
+ import { VadOptions, RealtimeSession } from '../index.js';
2
+ import '../../errors-CcHEuSmR.js';
3
+
4
+ /**
5
+ * Microphone capture: `getUserMedia` with echo cancellation, an
6
+ * `AudioContext` at the session rate (the browser resamples), and an
7
+ * `AudioWorklet` that hands out fixed-size s16le frames.
8
+ *
9
+ * The worklet source is inlined as a Blob URL so the package needs no
10
+ * separate asset to serve. Browser-only; nothing here is imported by the
11
+ * session itself.
12
+ */
13
+ interface CaptureOptions {
14
+ sampleRate?: number;
15
+ /** Frame length in milliseconds. Default 100. */
16
+ frameMs?: number;
17
+ /** Extra `getUserMedia` audio constraints. Echo cancellation, noise
18
+ * suppression and auto gain are on by default: the model's own reply is
19
+ * playing from the same device. */
20
+ constraints?: MediaTrackConstraints;
21
+ /** Reuse an existing context (one per page is the browser's preference). */
22
+ audioContext?: AudioContext;
23
+ }
24
+ type FrameListener = (frame: Int16Array) => void;
25
+ declare class MicrophoneCapture {
26
+ private readonly options;
27
+ readonly sampleRate: number;
28
+ readonly frameSamples: number;
29
+ private context;
30
+ private readonly ownsContext;
31
+ private stream;
32
+ private source;
33
+ private node;
34
+ private readonly listeners;
35
+ private moduleUrl;
36
+ constructor(options?: CaptureOptions);
37
+ get running(): boolean;
38
+ onFrame(listener: FrameListener): () => void;
39
+ /** The context in use, for sharing with playback. */
40
+ getContext(): AudioContext;
41
+ start(): Promise<void>;
42
+ stop(): void;
43
+ dispose(): Promise<void>;
44
+ }
45
+
46
+ /**
47
+ * Gapless playback of `audio.delta` chunks through a jitter buffer in an
48
+ * `AudioWorklet`.
49
+ *
50
+ * Chunks arrive in bursts (the upstream generates faster than real time), so
51
+ * the worklet queues them and starts draining once `primeMs` of audio is
52
+ * buffered. An underrun (the queue runs dry mid-reply) outputs silence,
53
+ * counts, and re-primes. `flush()` drops everything queued — barge-in.
54
+ */
55
+ interface PlaybackOptions {
56
+ sampleRate?: number;
57
+ /** Audio buffered before playback starts. Default 200 ms. */
58
+ primeMs?: number;
59
+ audioContext?: AudioContext;
60
+ }
61
+ declare class AudioPlayback {
62
+ private readonly options;
63
+ readonly sampleRate: number;
64
+ private context;
65
+ private readonly ownsContext;
66
+ private node;
67
+ private moduleUrl;
68
+ private _underruns;
69
+ private queuedSamples;
70
+ private readonly underrunListeners;
71
+ constructor(options?: PlaybackOptions);
72
+ get underruns(): number;
73
+ /** Seconds of audio handed to the worklet and not yet flushed; an upper bound on what is still to play. */
74
+ get queuedSeconds(): number;
75
+ onUnderrun(listener: (count: number) => void): () => void;
76
+ getContext(): AudioContext;
77
+ start(): Promise<void>;
78
+ /** Queue one chunk. Accepts the `audio.delta` base64 payload or raw Int16 samples. */
79
+ enqueue(audio: string | Int16Array): void;
80
+ /** Drop everything queued — the user interrupted. */
81
+ flush(): void;
82
+ dispose(): Promise<void>;
83
+ }
84
+
85
+ /**
86
+ * A voice conversation in one call: the microphone feeds the session, the
87
+ * reply plays through a jitter buffer, and speaking over a reply cuts it.
88
+ *
89
+ * Call it from a user gesture (a click), because browsers allow microphone
90
+ * access and audio output only after one.
91
+ */
92
+
93
+ interface VoiceOptions {
94
+ /** Extra `getUserMedia` audio constraints, such as a `deviceId`. */
95
+ constraints?: MediaTrackConstraints;
96
+ /** Milliseconds of reply audio to buffer before playing. Default 200. */
97
+ primeMs?: number;
98
+ /** Detect speech locally to cut a reply within a frame. Default on. */
99
+ localVad?: boolean | VadOptions;
100
+ /** The microphone level (RMS of each 100 ms frame), for a meter. */
101
+ onLevel?: (rms: number) => void;
102
+ /** True when the local detector hears the user start speaking, false when they stop. */
103
+ onLocalSpeech?: (speaking: boolean) => void;
104
+ }
105
+ interface Voice {
106
+ /** While muted, microphone frames are dropped: nothing is sent and nothing is billed as input. */
107
+ muted: boolean;
108
+ /** True while a reply is being delivered. */
109
+ readonly replying: boolean;
110
+ readonly capture: MicrophoneCapture;
111
+ readonly playback: AudioPlayback;
112
+ /** Stops the microphone and playback. It does not close the session. */
113
+ stop(): Promise<void>;
114
+ }
115
+ /**
116
+ * Starts microphone capture and reply playback for a live session, at the
117
+ * rate the session declared (`session.audio.rate`).
118
+ */
119
+ declare function startVoice(session: RealtimeSession, options?: VoiceOptions): Promise<Voice>;
120
+
121
+ export { AudioPlayback, MicrophoneCapture, startVoice };
122
+ export type { CaptureOptions, FrameListener, PlaybackOptions, Voice, VoiceOptions };