segmind 0.6.1 → 0.7.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 +69 -1
- package/dist/chunk-B7VAGG2U.cjs +342 -0
- package/dist/chunk-B7VAGG2U.cjs.map +1 -0
- package/dist/{chunk-USGY6G4C.js → chunk-YSAOJ3YL.js} +157 -1
- package/dist/chunk-YSAOJ3YL.js.map +1 -0
- package/dist/{errors-CcHEuSmR.d.cts → errors-DsVQfts3.d.cts} +114 -9
- package/dist/{errors-CcHEuSmR.d.ts → errors-DsVQfts3.d.ts} +114 -9
- package/dist/index.cjs +114 -23
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +167 -8
- package/dist/index.d.ts +167 -8
- package/dist/index.js +92 -1
- package/dist/index.js.map +1 -1
- package/dist/realtime/browser/index.cjs +632 -7
- package/dist/realtime/browser/index.cjs.map +1 -1
- package/dist/realtime/browser/index.d.cts +359 -4
- package/dist/realtime/browser/index.d.ts +359 -4
- package/dist/realtime/browser/index.js +627 -2
- package/dist/realtime/browser/index.js.map +1 -1
- package/dist/realtime/index.cjs +41 -141
- package/dist/realtime/index.cjs.map +1 -1
- package/dist/realtime/index.d.cts +12 -5
- package/dist/realtime/index.d.ts +12 -5
- package/dist/realtime/index.js +24 -124
- package/dist/realtime/index.js.map +1 -1
- package/dist/{vad-BcBkqh2p.d.ts → vad-dy0g4f3R.d.ts} +3 -1
- package/dist/{vad-B-BeifvT.d.cts → vad-xeCHdSHo.d.cts} +3 -1
- package/package.json +1 -1
- package/dist/chunk-HWZJ36WC.cjs +0 -186
- package/dist/chunk-HWZJ36WC.cjs.map +0 -1
- package/dist/chunk-USGY6G4C.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/realtime/browser/capture.ts","../../../src/realtime/browser/playback.ts","../../../src/realtime/browser/voice.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;;;;;AA0BA,IAAM,kBAAkB,CAAC,iBAAyB;AAAA;AAAA;AAAA;AAAA,mCAIf,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBxC,IAAM,oBAAN,MAAwB;AAAA,EAW7B,YAA6B,UAA0B,CAAC,GAAG;AAA9B;AAC3B,SAAK,aAAa,QAAQ,cAAc;AACxC,SAAK,eAAe,KAAK,MAAO,KAAK,cAAc,QAAQ,WAAW,OAAQ,GAAI;AAClF,SAAK,UAAU,QAAQ,gBAAgB;AACvC,SAAK,cAAc,CAAC,QAAQ;AAAA,EAC9B;AAAA,EAL6B;AAAA,EAVpB;AAAA,EACA;AAAA,EACD,UAA+B;AAAA,EACtB;AAAA,EACT,SAA6B;AAAA,EAC7B,SAA4C;AAAA,EAC5C,OAAgC;AAAA,EACvB,YAAY,oBAAI,IAAmB;AAAA,EAC5C,YAA2B;AAAA,EASnC,IAAI,UAAmB;AACrB,WAAO,KAAK,SAAS;AAAA,EACvB;AAAA,EAEA,QAAQ,UAAqC;AAC3C,SAAK,UAAU,IAAI,QAAQ;AAC3B,WAAO,MAAM,KAAK,UAAU,OAAO,QAAQ;AAAA,EAC7C;AAAA;AAAA,EAGA,aAA2B;AACzB,QAAI,CAAC,KAAK,SAAS;AACjB,WAAK,UAAU,IAAI,aAAa,EAAE,YAAY,KAAK,WAAW,CAAC;AAAA,IACjE;AACA,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,QAAuB;AAC3B,QAAI,KAAK,KA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AY;AAAA,IAC9B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/realtime/browser/capture.ts","../../../src/realtime/browser/playback.ts","../../../src/realtime/browser/voice.ts","../../../src/realtime/browser/video/control-channel.ts","../../../src/realtime/browser/video/ice.ts","../../../src/realtime/browser/video/peer.ts","../../../src/realtime/browser/video/video-session.ts"],"sourcesContent":["/**\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","/**\n * The upstream's `control` data channel (a `datachannel` session), with the two traps\n * `@fal-ai/client` `src/realtime/wma.js` (MIT, Copyright 2024 https://fal.ai)\n * handles:\n *\n * - Messages sent before the channel opens are lost. The peer connection\n * reports `connected` before the channel reports `open`, so sends made in\n * between are queued (bounded, oldest dropped) and flushed on open, after\n * the `first` message (`configure`), which is never dropped.\n * - The channel can die while ICE still says `connected`: SCTP state is\n * independent of the peer connection's. A close or error the owner did not\n * ask for is reported through `onDied`, never laundered into a clean close.\n */\n\nimport type { DataChannelLike } from './peer';\n\nexport const MAX_QUEUED_MESSAGES = 64;\n\nexport interface ControlChannelOptions {\n /** Sent first on open, ahead of anything queued. */\n first?: Record<string, unknown>;\n maxQueued?: number;\n onMessage?: (message: Record<string, unknown>) => void;\n onOpen?: () => void;\n /** The channel closed or errored without `close()` being called. */\n onDied?: (message: string) => void;\n}\n\nexport class ControlChannel {\n private readonly pending: string[] = [];\n private closing = false;\n private dead = false;\n private readonly decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder() : null;\n\n constructor(\n private readonly channel: DataChannelLike,\n private readonly options: ControlChannelOptions = {},\n ) {\n channel.binaryType = 'arraybuffer';\n channel.onopen = () => this.handleOpen();\n channel.onclose = () => this.handleDeath('the control channel closed');\n channel.onerror = () => this.handleDeath('the control channel failed');\n channel.onmessage = (event) => this.handleMessage(event.data);\n }\n\n get readyState(): string {\n return this.channel.readyState;\n }\n\n /** Messages waiting for the channel to open. */\n get queued(): number {\n return this.pending.length;\n }\n\n /** Sends now when open, queues while connecting, drops otherwise. Returns false when dropped. */\n send(message: Record<string, unknown>): boolean {\n if (this.closing || this.dead) return false;\n const payload = JSON.stringify(message);\n const state = this.channel.readyState;\n if (state === 'open') return this.rawSend(payload);\n if (state !== 'connecting') return false;\n const limit = this.options.maxQueued ?? MAX_QUEUED_MESSAGES;\n if (this.pending.length >= limit) this.pending.shift();\n this.pending.push(payload);\n return true;\n }\n\n /** Sends `last` if the channel is open, then closes it. Never reports a death. */\n close(last?: Record<string, unknown>): void {\n if (this.closing) return;\n if (last && this.channel.readyState === 'open' && !this.dead) {\n this.rawSend(JSON.stringify(last));\n }\n this.closing = true;\n this.pending.length = 0;\n try {\n this.channel.close();\n } catch {\n /* already closed */\n }\n }\n\n private handleOpen(): void {\n if (this.closing || this.dead) return;\n const queued = this.pending.splice(0);\n if (this.options.first) queued.unshift(JSON.stringify(this.options.first));\n // A channel can die between the open event and this handler: one failed\n // send ends the flush rather than throwing out of an event handler.\n for (const payload of queued) {\n if (!this.rawSend(payload)) break;\n }\n this.options.onOpen?.();\n }\n\n private handleDeath(message: string): void {\n if (this.closing || this.dead) return;\n this.dead = true;\n this.pending.length = 0;\n this.options.onDied?.(message);\n }\n\n private handleMessage(data: unknown): void {\n let text: string | null = null;\n if (typeof data === 'string') text = data;\n else if (this.decoder && (data instanceof ArrayBuffer || ArrayBuffer.isView(data))) {\n text = this.decoder.decode(data as ArrayBuffer | ArrayBufferView);\n }\n if (text === null) return;\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return; // not a control event\n }\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n this.options.onMessage?.(parsed as Record<string, unknown>);\n }\n }\n\n private rawSend(payload: string): boolean {\n try {\n this.channel.send(payload);\n return true;\n } catch {\n return false;\n }\n }\n}\n","/**\n * ICE gathering for an upstream that takes one complete offer (no trickle).\n *\n * Adapted from `@fal-ai/client` `src/realtime/ice.js` (MIT, Copyright 2024\n * https://fal.ai). The offer is sent once, so it must carry a usable candidate\n * set that has stopped changing: resolve when the set is sufficient AND quiet,\n * when gathering completes, or at a hard bound — whichever comes first. A\n * configuration with a TURN server is not sufficient until a relay candidate\n * exists; an offer without one would connect nowhere and say nothing about why.\n */\n\nimport type { IceServer } from '../../types';\nimport type { IceCandidateEventLike, PeerConnectionLike } from './peer';\n\nexport const ICE_TIMEOUT_MS = 12000;\nexport const ICE_QUIET_PERIOD_MS = 1250;\n\nexport interface GatherOptions {\n iceServers?: IceServer[];\n timeoutMs?: number;\n quietPeriodMs?: number;\n setTimeout?: typeof setTimeout;\n clearTimeout?: typeof clearTimeout;\n}\n\nexport interface GatherResult {\n host: number;\n srflx: number;\n relay: number;\n /** `complete`: the browser finished; `sufficient`: a usable set went quiet; `timeout`: the hard bound. */\n state: 'complete' | 'sufficient' | 'timeout';\n}\n\nexport function countTurnServers(servers: IceServer[] = []): number {\n return servers.filter((server) => {\n const urls = Array.isArray(server.urls) ? server.urls : [server.urls];\n return urls.some((url) => /^turns?:/i.test(url));\n }).length;\n}\n\n/** `host`, `srflx` or `relay` out of a candidate line, or null. */\nexport function candidateType(candidate: string): 'host' | 'srflx' | 'relay' | null {\n const match = candidate.match(/(?:^|\\s)typ\\s+(host|srflx|relay)(?:\\s|$)/);\n return (match?.[1] as 'host' | 'srflx' | 'relay' | undefined) ?? null;\n}\n\n/**\n * Call BEFORE `setLocalDescription`: fast host candidates otherwise fire\n * before the listener exists and are never counted.\n */\nexport function gatherIceCandidates(\n pc: PeerConnectionLike,\n options: GatherOptions = {},\n): Promise<GatherResult> {\n const {\n iceServers = [],\n timeoutMs = ICE_TIMEOUT_MS,\n quietPeriodMs = ICE_QUIET_PERIOD_MS,\n setTimeout: schedule = setTimeout,\n clearTimeout: cancel = clearTimeout,\n } = options;\n const counts = { host: 0, srflx: 0, relay: 0 };\n // Candidates already in the local description never fire again.\n for (const line of (pc.localDescription?.sdp ?? '').split(/\\r?\\n/)) {\n if (!line.startsWith('a=candidate:')) continue;\n const type = candidateType(line.slice(2));\n if (type) counts[type] += 1;\n }\n if (pc.iceGatheringState === 'complete') {\n return Promise.resolve({ ...counts, state: 'complete' });\n }\n const requireRelay = countTurnServers(iceServers) > 0;\n const sufficient = () => (requireRelay ? counts.relay > 0 : counts.srflx > 0);\n\n return new Promise<GatherResult>((resolve) => {\n let settled = false;\n let quiet: ReturnType<typeof setTimeout> | null = null;\n const finish = (state: GatherResult['state']) => {\n if (settled) return;\n settled = true;\n cancel(hardBound);\n if (quiet !== null) cancel(quiet);\n pc.removeEventListener('icegatheringstatechange', onState);\n pc.removeEventListener('icecandidate', onCandidate);\n resolve({ ...counts, state });\n };\n const onState = () => {\n if (pc.iceGatheringState === 'complete') finish('complete');\n };\n // Every candidate restarts the quiet period: the goal is a settled set,\n // not the first usable address.\n const onCandidate = (event: IceCandidateEventLike) => {\n const type = event.candidate ? candidateType(event.candidate.candidate) : null;\n if (type) counts[type] += 1;\n if (quiet !== null) cancel(quiet);\n quiet = sufficient() ? schedule(() => finish('sufficient'), quietPeriodMs) : null;\n };\n const hardBound = schedule(() => finish('timeout'), timeoutMs);\n pc.addEventListener('icegatheringstatechange', onState);\n pc.addEventListener('icecandidate', onCandidate);\n if (sufficient()) quiet = schedule(() => finish('sufficient'), quietPeriodMs);\n });\n}\n","/**\n * The subset of the WebRTC API the video module drives, so tests can fake a\n * peer connection and a data channel without a browser.\n */\n\nimport type { IceCandidateJson, IceServer } from '../../types';\n\nexport interface SessionDescriptionLike {\n type: string;\n sdp?: string;\n}\n\nexport interface IceCandidateLike {\n candidate: string;\n toJSON(): IceCandidateJson;\n}\n\nexport interface IceCandidateEventLike {\n candidate: IceCandidateLike | null;\n}\n\nexport interface TrackEventLike {\n track: MediaStreamTrack;\n streams: readonly MediaStream[];\n}\n\nexport interface DataChannelLike {\n readonly readyState: string;\n binaryType?: string;\n send(data: string): void;\n close(): void;\n onopen: ((ev: unknown) => void) | null;\n onclose: ((ev: unknown) => void) | null;\n onerror: ((ev: unknown) => void) | null;\n onmessage: ((ev: { data: unknown }) => void) | null;\n}\n\nexport interface PeerConfiguration {\n iceServers?: IceServer[];\n}\n\nexport interface PeerConnectionLike {\n readonly localDescription: SessionDescriptionLike | null;\n readonly iceGatheringState: string;\n readonly connectionState: string;\n addEventListener(type: 'icecandidate', listener: (ev: IceCandidateEventLike) => void): void;\n addEventListener(type: 'icegatheringstatechange', listener: () => void): void;\n addEventListener(type: 'connectionstatechange', listener: () => void): void;\n addEventListener(type: 'track', listener: (ev: TrackEventLike) => void): void;\n removeEventListener(type: string, listener: (...args: never[]) => void): void;\n addTrack(track: MediaStreamTrack, ...streams: MediaStream[]): unknown;\n addTransceiver(kind: 'audio' | 'video', init: { direction: 'recvonly' }): unknown;\n createDataChannel(label: string): DataChannelLike;\n createOffer(options?: { iceRestart?: boolean }): Promise<SessionDescriptionLike>;\n setLocalDescription(description?: SessionDescriptionLike): Promise<void>;\n setRemoteDescription(description: { type: 'answer'; sdp: string }): Promise<void>;\n addIceCandidate(candidate: IceCandidateJson): Promise<void>;\n getConfiguration(): PeerConfiguration;\n setConfiguration(configuration: PeerConfiguration): void;\n close(): void;\n}\n\nexport function defaultPeerConnection(configuration: PeerConfiguration): PeerConnectionLike {\n const Ctor = (globalThis as { RTCPeerConnection?: new (c: PeerConfiguration) => unknown })\n .RTCPeerConnection;\n if (!Ctor) throw new Error('no RTCPeerConnection in this runtime: pass peerConnectionFactory');\n return new Ctor(configuration) as PeerConnectionLike;\n}\n\nexport function defaultGetUserMedia(constraints: MediaStreamConstraints): Promise<MediaStream> {\n const devices = (globalThis as { navigator?: { mediaDevices?: MediaDevices } }).navigator\n ?.mediaDevices;\n if (!devices?.getUserMedia) {\n return Promise.reject(new Error('no camera access in this runtime: pass getUserMedia'));\n }\n return devices.getUserMedia(constraints);\n}\n\n/** A stream holding `tracks`, or null in a runtime without `MediaStream`. */\nexport function defaultMediaStream(tracks: MediaStreamTrack[]): MediaStream | null {\n const Ctor = (globalThis as { MediaStream?: new (tracks: MediaStreamTrack[]) => MediaStream })\n .MediaStream;\n return Ctor ? new Ctor(tracks) : null;\n}\n","/**\n * The WebRTC half of a realtime video session.\n *\n * A video session carries no media on the socket: `session.created.media`\n * declares its streams with `transport: \"webrtc\"`, and the client negotiates\n * a peer connection with the upstream through `webrtc.*` events on the\n * session socket. `session.created.control` says how:\n *\n * - `session`: the camera goes up and the edited stream comes down (a\n * camera-restyling model such as Decart Lucy). Trickle ICE both ways,\n * `webrtc.answer`, and `webrtc.restart` (new ICE servers, a new offer with\n * `iceRestart`). Steering is `video.prompt` / `video.image` on the socket,\n * acknowledged in order with `video.prompt_ack`.\n * - `datachannel`: receive-only video and audio (a prompt-driven model whose\n * runner speaks over its own data channel, such as fal's Director). The\n * service sends `webrtc.config`; the client gathers every candidate and\n * sends ONE `webrtc.offer` (no trickle). Steering runs on the runner's\n * `control` data channel (`configure` on open, then `prompt` with a rising\n * `prompt_version`), and what the runner says there is mirrored to the\n * socket as `video.report` for the record.\n *\n * Attach before `open()`: the service sends `webrtc.config` right after\n * `session.created`, and a listener added later can miss it. Every ending of\n * the session tears the peer down; on a `datachannel` session the runner's\n * own `stop` goes first, so it stops generating at once rather than when its\n * lease runs out. Any negotiation or transport failure ends the session, so\n * nothing keeps billing for a stream nobody can see.\n */\n\nimport { videoControl, webrtcVideo } from '../../protocol';\nimport type { RealtimeSession, SessionEnd } from '../../session';\nimport type {\n IceCandidateJson,\n IceServer,\n ServerEvent,\n SessionCreatedEvent,\n VideoControl,\n WebrtcConfigEvent,\n} from '../../types';\nimport { ControlChannel, MAX_QUEUED_MESSAGES } from './control-channel';\nimport { gatherIceCandidates, type GatherResult } from './ice';\nimport {\n defaultGetUserMedia,\n defaultMediaStream,\n defaultPeerConnection,\n type IceCandidateEventLike,\n type PeerConfiguration,\n type PeerConnectionLike,\n type TrackEventLike,\n} from './peer';\n\n/** Runner data-channel events kept for the session's record (`video.report`). */\nexport const REPORTED_CHANNEL_EVENTS = new Set([\n 'configured',\n 'prompt_applied',\n 'prompt_rejected',\n 'deadline_missed',\n 'stream_exhausted',\n 'error',\n]);\n\n/** What the service opens a `datachannel` session at when its params name no `resolution` / `aspect_ratio`. */\nconst DEFAULT_RESOLUTION = '768p';\nconst DEFAULT_ASPECT_RATIO = '16:9';\n\n/** How long a failed peer on a `session` stream waits for the upstream's ICE restart. */\nexport const RESTART_GRACE_MS = 8000;\n\n/**\n * The ICE servers a `session` stream starts with: the service sends none for\n * it (only a restart carries them). Without one a browser offers only its\n * private `.local` addresses, which an upstream outside the network cannot\n * reach, so the stream never connects.\n */\nexport const DEFAULT_ICE_SERVERS: readonly IceServer[] = [{ urls: 'stun:stun.cloudflare.com:3478' }];\n\nexport type VideoPhase = 'waiting' | 'negotiating' | 'connected' | 'closed';\n\nexport type VideoEvent =\n | { type: 'phase'; phase: VideoPhase }\n /** The camera stream being sent (`session` control). */\n | { type: 'local_stream'; stream: MediaStream }\n /** The upstream's video (and audio): put it on a `<video>`. */\n | { type: 'remote_stream'; stream: MediaStream }\n | { type: 'connection'; state: string }\n | { type: 'started' }\n /** Seconds of video generated so far, as billed. */\n | { type: 'progress'; seconds: number }\n | { type: 'prompt_ack'; kind: 'prompt' | 'image'; applied: boolean; reason?: string }\n /** Anything the runner said on its data channel (`configured`, `chunk`, `prompt_applied`…). */\n | { type: 'channel'; event: Record<string, unknown> }\n /** Negotiation or transport failed; the session is being closed. */\n | { type: 'failed'; message: string };\n\nexport type VideoListener = (event: VideoEvent) => void;\n\nexport interface VideoSessionOptions {\n /**\n * The opening prompt. `session` control sends it as `video.prompt` after the\n * offer; `datachannel` puts it in `configure`.\n */\n prompt?: string;\n /** Let the upstream rewrite prompts (`session` control). Server default: true. */\n enhance?: boolean;\n /**\n * `configure.resolution` on a `datachannel` session. Default: the session's\n * `resolution` param, else `768p` (the service's default). It must match\n * what the session was opened with.\n */\n resolution?: string;\n /** `configure.aspect_ratio` on a `datachannel` session. Default: the session's `aspect_ratio` param, else `16:9`. */\n aspectRatio?: string;\n /** The stream to send on a `session` stream. Default: the camera at the declared size. */\n localStream?: MediaStream;\n /** Capture the microphone with the camera. Default: when `media.audio` takes input. */\n audio?: boolean;\n /**\n * ICE servers for a `session` stream, such as your own TURN servers for\n * users behind a NAT that STUN cannot cross. Default: `DEFAULT_ICE_SERVERS`\n * (one public STUN server). A `datachannel` session uses the servers in\n * `webrtc.config` and ignores this.\n */\n iceServers?: IceServer[];\n peerConnectionFactory?: (configuration: PeerConfiguration) => PeerConnectionLike;\n getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;\n /** A stream holding remote tracks the upstream sent without one. */\n createMediaStream?: (tracks: MediaStreamTrack[]) => MediaStream | null;\n /** Data-channel sends queued before it opens. Default 64. */\n maxQueuedMessages?: number;\n iceTimeoutMs?: number;\n iceQuietPeriodMs?: number;\n setTimeout?: typeof setTimeout;\n clearTimeout?: typeof clearTimeout;\n}\n\n/** Hook a video negotiator onto `session`. Call before `session.open()`. */\nexport function attachVideo(session: RealtimeSession, options?: VideoSessionOptions): VideoSession {\n return new VideoSession(session, options);\n}\n\nexport class VideoSession {\n private _phase: VideoPhase = 'waiting';\n private _control: VideoControl | null = null;\n private _localStream: MediaStream | null = null;\n private _remoteStream: MediaStream | null = null;\n private pc: PeerConnectionLike | null = null;\n private channel: ControlChannel | null = null;\n private readonly listeners = new Set<VideoListener>();\n private readonly unsubscribe: (() => void)[] = [];\n private ownsLocalStream = false;\n /** The upstream's answer is applied; remote candidates go straight in. */\n private remoteReady = false;\n private readonly remoteCandidates: IceCandidateJson[] = [];\n /** Local candidates wait until the offer they belong to has been sent. */\n private offerSent = false;\n private readonly localCandidates: (IceCandidateJson | null)[] = [];\n private sentVersion = 1;\n /** Data-channel prompts made before the channel exists; they go out right after `configure`. */\n private readonly earlyPrompts: Record<string, unknown>[] = [];\n /** The opening prompt has gone out on a `session` stream (or there is none). */\n private openingSent = false;\n private stopSent = false;\n /** `end()` was called: the session is closing, so nothing new is opened. */\n private ending = false;\n private failed = false;\n private restartTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n public readonly session: RealtimeSession,\n private readonly options: VideoSessionOptions = {},\n ) {\n if (session.state === 'closed') throw new Error('the session has already closed');\n this.unsubscribe.push(session.onEvent((event) => this.handleEvent(event)));\n this.unsubscribe.push(\n session.onState((state) => {\n if (state === 'closed') this.teardown();\n }),\n );\n if (session.created) this.handleCreated(session.created);\n }\n\n get phase(): VideoPhase {\n return this._phase;\n }\n\n /** `session` or `datachannel` once the session is live; null before, or for a non-video session. */\n get control(): VideoControl | null {\n return this._control;\n }\n\n /** The `prompt_version` of the latest prompt on a data channel (`configure` is 1). */\n get promptVersion(): number {\n return this.sentVersion;\n }\n\n /** Read through a getter so TypeScript does not narrow it across an await. */\n private get closed(): boolean {\n return this._phase === 'closed';\n }\n\n get localStream(): MediaStream | null {\n return this._localStream;\n }\n\n get remoteStream(): MediaStream | null {\n return this._remoteStream;\n }\n\n onEvent(listener: VideoListener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Steer the generation. On a `datachannel` session it goes on the runner's\n * channel with the next `prompt_version` (queued until the channel opens).\n * False when it could not be sent.\n */\n prompt(text: string, options: { enhance?: boolean } = {}): boolean {\n const value = text.trim();\n if (!value || this.closed) return false;\n if (this._control === 'datachannel') {\n const message = { type: 'prompt', prompt_version: this.sentVersion + 1, prompt: value };\n if (!this.channel) {\n // Before `webrtc.config`: held, and sent behind `configure` once the channel exists.\n const limit = this.options.maxQueuedMessages ?? MAX_QUEUED_MESSAGES;\n if (this.earlyPrompts.length >= limit) this.earlyPrompts.shift();\n this.earlyPrompts.push(message);\n this.sentVersion += 1;\n return true;\n }\n const sent = this.channel.send(message);\n if (sent) this.sentVersion += 1;\n return sent;\n }\n if (this._control !== 'session') return false;\n // The opening prompt goes first, so acks (which come in send order) match and\n // a steer made while the camera opens is not overridden by it.\n this.sendOpeningPrompt();\n return this.sendPrompt(value, options);\n }\n\n private sendOpeningPrompt(): void {\n if (this.openingSent) return;\n this.openingSent = true;\n const opening = this.options.prompt?.trim();\n if (opening) this.sendPrompt(opening);\n }\n\n private sendPrompt(value: string, options: { enhance?: boolean } = {}): boolean {\n const enhance = options.enhance ?? this.options.enhance;\n return this.session.send({\n type: 'video.prompt',\n text: value,\n ...(enhance === undefined ? {} : { enhance }),\n });\n }\n\n /**\n * A reference image (base64, no `data:` prefix) with an optional prompt, or\n * null to clear it. Only a `session` stream takes one.\n */\n setImage(image: string | null, text?: string, options: { enhance?: boolean } = {}): boolean {\n if (this._control !== 'session' || this.closed) return false;\n const enhance = options.enhance ?? this.options.enhance;\n return this.session.send({\n type: 'video.image',\n image,\n ...(text?.trim() ? { text: text.trim() } : {}),\n ...(enhance === undefined ? {} : { enhance }),\n });\n }\n\n /**\n * End the session: the runner's `stop` first (a `datachannel` session stops\n * generating now, not when its lease lapses), then `session.close()`. The\n * camera is released at once; the peer stays up until the session closes,\n * so `stop` has a transport to leave on.\n */\n end(): Promise<SessionEnd> {\n this.ending = true;\n this.sendStop();\n this.releaseCamera();\n return this.session.close();\n }\n\n /** Stop listening and release the peer and the camera without closing the session. */\n detach(): void {\n this.teardown();\n }\n\n // --- server events ------------------------------------------------------------\n\n private handleEvent(event: ServerEvent): void {\n switch (event.type) {\n case 'session.created':\n this.handleCreated(event);\n break;\n case 'webrtc.config':\n if (this._control === 'datachannel' && !this.pc && !this.ending) void this.startReceiveOnly(event);\n break;\n case 'webrtc.answer':\n void this.applyAnswer(event.sdp, event.ice_servers);\n break;\n case 'webrtc.candidate':\n // A complete-offer upstream never trickles.\n if (this._control === 'session' && event.candidate) void this.addRemote(event.candidate);\n break;\n case 'webrtc.restart':\n if (this._control === 'session') void this.restart(event.ice_servers);\n break;\n case 'video.started':\n this.emit({ type: 'started' });\n break;\n case 'video.progress':\n this.emit({ type: 'progress', seconds: event.seconds });\n break;\n case 'video.prompt_ack':\n this.emit({\n type: 'prompt_ack',\n kind: event.kind,\n applied: event.applied,\n ...(event.reason ? { reason: event.reason } : {}),\n });\n break;\n default:\n break;\n }\n }\n\n private handleCreated(created: SessionCreatedEvent): void {\n if (this._control || this.closed) return;\n this._control = videoControl(created);\n if (this._control === 'session') void this.startCamera(created);\n // `datachannel` waits for `webrtc.config`.\n }\n\n // --- session control: the camera up, the edited stream down ------------------\n\n private async startCamera(created: SessionCreatedEvent): Promise<void> {\n this.setPhase('negotiating');\n let stream: MediaStream;\n try {\n stream = this.options.localStream ?? (await this.openCamera(created));\n } catch (error) {\n this.fail(`camera: ${errorMessage(error)}`);\n return;\n }\n if (this.closed || this.ending) {\n if (!this.options.localStream) stopTracks(stream);\n return;\n }\n this.ownsLocalStream = !this.options.localStream;\n this._localStream = stream;\n this.emit({ type: 'local_stream', stream });\n try {\n const pc = this.createPeer({ iceServers: [...(this.options.iceServers ?? DEFAULT_ICE_SERVERS)] });\n pc.addEventListener('icecandidate', (event: IceCandidateEventLike) => {\n this.sendLocalCandidate(event.candidate ? event.candidate.toJSON() : null);\n });\n for (const track of stream.getTracks()) pc.addTrack(track, stream);\n await this.offer(pc);\n } catch (error) {\n this.fail(`negotiation: ${errorMessage(error)}`);\n return;\n }\n if (this.closed) return;\n this.sendOpeningPrompt();\n }\n\n private async openCamera(created: SessionCreatedEvent): Promise<MediaStream> {\n const getUserMedia = this.options.getUserMedia ?? defaultGetUserMedia;\n const video = webrtcVideo(created);\n const constraints: MediaTrackConstraints = {};\n if (video?.width) constraints.width = { ideal: video.width };\n if (video?.height) constraints.height = { ideal: video.height };\n if (video?.fps) constraints.frameRate = { ideal: video.fps };\n const audioSpec = created.media?.audio;\n const wantAudio =\n this.options.audio ??\n (audioSpec?.transport === 'webrtc' &&\n (audioSpec.direction === 'in' || audioSpec.direction === 'duplex'));\n const videoConstraint = Object.keys(constraints).length ? constraints : true;\n try {\n return await getUserMedia({ video: videoConstraint, audio: wantAudio });\n } catch (error) {\n // A refused microphone should not cost the camera.\n if (!wantAudio) throw error;\n return getUserMedia({ video: videoConstraint, audio: false });\n }\n }\n\n private async offer(pc: PeerConnectionLike, iceRestart = false): Promise<void> {\n const offer = await pc.createOffer(iceRestart ? { iceRestart: true } : undefined);\n await pc.setLocalDescription(offer);\n if (this.closed || pc !== this.pc) return;\n const sdp = pc.localDescription?.sdp ?? offer.sdp;\n if (!sdp) throw new Error('the browser produced no SDP offer');\n this.session.send({ type: 'webrtc.offer', sdp });\n this.offerSent = true;\n for (const candidate of this.localCandidates.splice(0)) {\n this.session.send({ type: 'webrtc.candidate', candidate });\n }\n }\n\n private sendLocalCandidate(candidate: IceCandidateJson | null): void {\n if (this.closed) return;\n if (!this.offerSent) {\n this.localCandidates.push(candidate);\n return;\n }\n this.session.send({ type: 'webrtc.candidate', candidate });\n }\n\n private async addRemote(candidate: IceCandidateJson): Promise<void> {\n if (!this.pc || !this.remoteReady) {\n this.remoteCandidates.push(candidate);\n return;\n }\n try {\n await this.pc.addIceCandidate(candidate);\n } catch {\n /* a candidate the browser cannot use is not fatal */\n }\n }\n\n private async restart(iceServers: IceServer[]): Promise<void> {\n const pc = this.pc;\n if (!pc || this.closed) return;\n this.clearRestartTimer();\n try {\n pc.setConfiguration({ ...pc.getConfiguration(), iceServers });\n this.remoteReady = false;\n this.offerSent = false;\n await this.offer(pc, true);\n } catch (error) {\n this.fail(`ICE restart: ${errorMessage(error)}`);\n }\n }\n\n // --- datachannel control: receive-only, one complete offer -------------------\n\n private async startReceiveOnly(config: WebrtcConfigEvent): Promise<void> {\n this.setPhase('negotiating');\n try {\n const pc = this.createPeer({ iceServers: config.ice_servers });\n pc.addTransceiver('video', { direction: 'recvonly' });\n pc.addTransceiver('audio', { direction: 'recvonly' });\n // The channel must exist before the offer, or the SDP has no m=application.\n this.channel = new ControlChannel(pc.createDataChannel('control'), {\n first: {\n type: 'configure',\n protocol_version: 1,\n prompt_version: 1,\n prompt: this.options.prompt?.trim() ?? '',\n resolution: this.options.resolution ?? this.session.params.resolution ?? DEFAULT_RESOLUTION,\n aspect_ratio: this.options.aspectRatio ?? this.session.params.aspect_ratio ?? DEFAULT_ASPECT_RATIO,\n },\n maxQueued: this.options.maxQueuedMessages ?? MAX_QUEUED_MESSAGES,\n onMessage: (message) => this.handleChannelMessage(message),\n onDied: (message) => this.fail(message),\n });\n for (const message of this.earlyPrompts.splice(0)) this.channel.send(message);\n const offer = await pc.createOffer();\n // Listen before setLocalDescription starts gathering.\n const gathering: Promise<GatherResult> = gatherIceCandidates(pc, {\n iceServers: config.ice_servers,\n timeoutMs: this.options.iceTimeoutMs,\n quietPeriodMs: this.options.iceQuietPeriodMs,\n setTimeout: this.options.setTimeout,\n clearTimeout: this.options.clearTimeout,\n });\n const [gathered] = await Promise.all([gathering, pc.setLocalDescription(offer)]);\n if (this.closed || pc !== this.pc) return;\n if (gathered.relay === 0 && gathered.srflx === 0 && gathered.host === 0) {\n throw new Error('ICE gathering produced no candidate');\n }\n const sdp = pc.localDescription?.sdp;\n if (!sdp) throw new Error('the browser produced no SDP offer');\n this.session.send({ type: 'webrtc.offer', sdp });\n this.offerSent = true;\n } catch (error) {\n this.fail(`negotiation: ${errorMessage(error)}`);\n }\n }\n\n private handleChannelMessage(message: Record<string, unknown>): void {\n this.emit({ type: 'channel', event: message });\n if (typeof message.type === 'string' && REPORTED_CHANNEL_EVENTS.has(message.type)) {\n this.session.send({ type: 'video.report', event: message });\n }\n }\n\n private sendStop(): void {\n if (this.stopSent || !this.channel) return;\n this.stopSent = true;\n this.channel.close({ type: 'stop' });\n }\n\n // --- both -------------------------------------------------------------------\n\n private createPeer(configuration: PeerConfiguration): PeerConnectionLike {\n const pc = (this.options.peerConnectionFactory ?? defaultPeerConnection)(configuration);\n this.pc = pc;\n pc.addEventListener('track', (event: TrackEventLike) => this.handleTrack(event));\n pc.addEventListener('connectionstatechange', () => this.handleConnectionState(pc));\n return pc;\n }\n\n private async applyAnswer(sdp: string, iceServers?: IceServer[]): Promise<void> {\n const pc = this.pc;\n if (!pc || this.closed) return;\n try {\n if (iceServers?.length) pc.setConfiguration({ ...pc.getConfiguration(), iceServers });\n await pc.setRemoteDescription({ type: 'answer', sdp });\n } catch (error) {\n this.fail(`answer: ${errorMessage(error)}`);\n return;\n }\n this.remoteReady = true;\n for (const candidate of this.remoteCandidates.splice(0)) await this.addRemote(candidate);\n }\n\n private handleTrack(event: TrackEventLike): void {\n if (this.closed) return;\n // One remote stream for the session: a track that arrives in another\n // stream (or in none) joins the first, so one <video> plays both.\n const current = this._remoteStream;\n if (current) {\n if (!current.getTracks().includes(event.track)) current.addTrack(event.track);\n return;\n }\n const stream =\n event.streams[0] ?? (this.options.createMediaStream ?? defaultMediaStream)([event.track]);\n if (!stream) return;\n this._remoteStream = stream;\n this.emit({ type: 'remote_stream', stream });\n }\n\n private handleConnectionState(pc: PeerConnectionLike): void {\n if (pc !== this.pc || this.closed) return;\n const state = pc.connectionState;\n this.emit({ type: 'connection', state });\n if (state === 'connected') {\n this.clearRestartTimer();\n this.setPhase('connected');\n } else if (state === 'failed') {\n if (this._control === 'session') {\n // The upstream may move the session to TURN with a restart.\n const schedule = this.options.setTimeout ?? setTimeout;\n this.clearRestartTimer();\n this.restartTimer = schedule(() => {\n this.restartTimer = null;\n if (this.pc?.connectionState === 'failed') {\n this.fail('the video connection failed');\n }\n }, RESTART_GRACE_MS);\n } else {\n this.fail('the video connection failed');\n }\n }\n }\n\n private clearRestartTimer(): void {\n if (this.restartTimer !== null) {\n (this.options.clearTimeout ?? clearTimeout)(this.restartTimer);\n this.restartTimer = null;\n }\n }\n\n /** Report the failure and end the session: an uncontrollable stream should not keep billing. */\n private fail(message: string): void {\n if (this.failed || this.closed) return;\n this.failed = true;\n this.emit({ type: 'failed', message });\n void this.end();\n }\n\n private teardown(): void {\n if (this.closed) return;\n this.sendStop();\n this.clearRestartTimer();\n this.setPhase('closed');\n for (const off of this.unsubscribe.splice(0)) off();\n this.remoteCandidates.length = 0;\n this.localCandidates.length = 0;\n const pc = this.pc;\n this.pc = null;\n try {\n pc?.close();\n } catch {\n /* already closed */\n }\n this.earlyPrompts.length = 0;\n this.releaseCamera();\n }\n\n /** Stop the camera this negotiator opened (a stream passed in stays the caller's). */\n private releaseCamera(): void {\n if (this.ownsLocalStream && this._localStream) stopTracks(this._localStream);\n this.ownsLocalStream = false;\n }\n\n private setPhase(phase: VideoPhase): void {\n if (this._phase === phase || this.closed) return;\n this._phase = phase;\n this.emit({ type: 'phase', phase });\n }\n\n private emit(event: VideoEvent): void {\n for (const listener of this.listeners) listener(event);\n }\n}\n\nfunction stopTracks(stream: MediaStream): void {\n for (const track of stream.getTracks()) track.stop();\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;;;;;;;;AA0BA,IAAM,kBAAkB,CAAC,iBAAyB;AAAA;AAAA;AAAA;AAAA,mCAIf,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBxC,IAAM,oBAAN,MAAwB;AAAA,EAW7B,YAA6B,UAA0B,CAAC,GAAG;AAA9B;AAC3B,SAAK,aAAa,QAAQ,cAAc;AACxC,SAAK,eAAe,KAAK,MAAO,KAAK,cAAc,QAAQ,WAAW,OAAQ,GAAI;AAClF,SAAK,UAAU,QAAQ,gBAAgB;AACvC,SAAK,cAAc,CAAC,QAAQ;AAAA,EAC9B;AAAA,EAL6B;AAAA,EAVpB;AAAA,EACA;AAAA,EACD,UAA+B;AAAA,EACtB;AAAA,EACT,SAA6B;AAAA,EAC7B,SAA4C;AAAA,EAC5C,OAAgC;AAAA,EACvB,YAAY,oBAAI,IAAmB;AA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WZJ36WC.cjs');
|
|
11
10
|
|
|
12
11
|
|
|
13
|
-
var _chunk74UKKBOOcjs = require('../chunk-74UKKBOO.cjs');
|
|
14
12
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
"error",
|
|
32
|
-
"upstream.event",
|
|
33
|
-
"pong"
|
|
34
|
-
]);
|
|
35
|
-
var ProtocolError = class extends _chunk74UKKBOOcjs.SegmindError {
|
|
36
|
-
constructor(message, raw) {
|
|
37
|
-
super(message, { body: raw });
|
|
38
|
-
this.raw = raw;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
};
|
|
42
|
-
function decodeServerEvent(text) {
|
|
43
|
-
let parsed;
|
|
44
|
-
try {
|
|
45
|
-
parsed = JSON.parse(text);
|
|
46
|
-
} catch (e) {
|
|
47
|
-
throw new ProtocolError("server frame is not JSON", text);
|
|
48
|
-
}
|
|
49
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
50
|
-
throw new ProtocolError("server frame is not an object", parsed);
|
|
51
|
-
}
|
|
52
|
-
const type = parsed.type;
|
|
53
|
-
if (typeof type !== "string" || !SERVER_EVENT_TYPES.has(type)) {
|
|
54
|
-
throw new ProtocolError(`unknown server event type: ${String(type)}`, parsed);
|
|
55
|
-
}
|
|
56
|
-
return parsed;
|
|
57
|
-
}
|
|
58
|
-
function encodeClientEvent(event) {
|
|
59
|
-
return JSON.stringify(event);
|
|
60
|
-
}
|
|
61
|
-
var SERVER_ENDINGS = /* @__PURE__ */ new Set([
|
|
62
|
-
"client",
|
|
63
|
-
"ceiling",
|
|
64
|
-
"idle",
|
|
65
|
-
"max_length",
|
|
66
|
-
"balance_exhausted",
|
|
67
|
-
"upstream_error",
|
|
68
|
-
"server_shutdown",
|
|
69
|
-
"internal_error",
|
|
70
|
-
"metering_failed"
|
|
71
|
-
]);
|
|
72
|
-
var REFUSAL_CLOSE_CODES = {
|
|
73
|
-
bad_request: 4e3,
|
|
74
|
-
unauthorized: 4001,
|
|
75
|
-
insufficient_credits: 4002,
|
|
76
|
-
unknown_model: 4004,
|
|
77
|
-
capacity: 4029,
|
|
78
|
-
/** A dependency (Redis, Spot) is unreachable, or the server is draining; retry shortly. */
|
|
79
|
-
try_again: 1013
|
|
80
|
-
};
|
|
81
|
-
var REFUSAL_CODES = new Set(Object.values(REFUSAL_CLOSE_CODES));
|
|
82
|
-
function reasonFromCloseCode(code, closeReason) {
|
|
83
|
-
if (REFUSAL_CODES.has(code)) return "refused";
|
|
84
|
-
if (closeReason && SERVER_ENDINGS.has(closeReason)) return closeReason;
|
|
85
|
-
switch (code) {
|
|
86
|
-
case 1e3:
|
|
87
|
-
return "client";
|
|
88
|
-
case 4008:
|
|
89
|
-
return "limit";
|
|
90
|
-
case 1012:
|
|
91
|
-
return "server_shutdown";
|
|
92
|
-
case 1011:
|
|
93
|
-
return "internal_error";
|
|
94
|
-
default:
|
|
95
|
-
return "connection_lost";
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
function isRetryableRefusal(closeCode) {
|
|
99
|
-
return closeCode === REFUSAL_CLOSE_CODES.try_again;
|
|
100
|
-
}
|
|
101
|
-
function unsupportedSession(created) {
|
|
102
|
-
if (created.protocol !== PROTOCOL_VERSION) {
|
|
103
|
-
return `server speaks protocol ${String(created.protocol)}; this client speaks ${PROTOCOL_VERSION}`;
|
|
104
|
-
}
|
|
105
|
-
return null;
|
|
106
|
-
}
|
|
107
|
-
function audioFormat(created) {
|
|
108
|
-
const spec = _optionalChain([created, 'optionalAccess', _ => _.media, 'optionalAccess', _2 => _2.audio]);
|
|
109
|
-
if (!spec || spec.encoding !== "pcm_s16le" || typeof spec.rate !== "number") return null;
|
|
110
|
-
return {
|
|
111
|
-
...spec,
|
|
112
|
-
encoding: "pcm_s16le",
|
|
113
|
-
rate: spec.rate,
|
|
114
|
-
channels: _nullishCoalesce(spec.channels, () => ( 1)),
|
|
115
|
-
tag: _nullishCoalesce(spec.tag, () => ( STREAM_TAGS.audio))
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
function acceptsInput(format) {
|
|
119
|
-
return format !== null && (format.direction === "in" || format.direction === "duplex");
|
|
120
|
-
}
|
|
121
|
-
function mediaFrame(tag, payload) {
|
|
122
|
-
const bytes = payload instanceof ArrayBuffer ? new Uint8Array(payload) : new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength);
|
|
123
|
-
const frame = new Uint8Array(bytes.byteLength + 1);
|
|
124
|
-
frame[0] = tag;
|
|
125
|
-
frame.set(bytes, 1);
|
|
126
|
-
return frame.buffer;
|
|
127
|
-
}
|
|
128
|
-
function sessionUrl(root, slug, token, query, path) {
|
|
129
|
-
const base = root.replace(/\/+$/, "");
|
|
130
|
-
const segments = (_nullishCoalesce(path, () => ( slug))).split("/").filter(Boolean);
|
|
131
|
-
const encoded = (segments.length ? segments : [slug]).map(encodeURIComponent).join("/");
|
|
132
|
-
const params = new URLSearchParams({ token, ..._nullishCoalesce(query, () => ( {})) });
|
|
133
|
-
return `${base}/${encoded}?${params.toString()}`;
|
|
134
|
-
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
var _chunkB7VAGG2Ucjs = require('../chunk-B7VAGG2U.cjs');
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
var _chunk74UKKBOOcjs = require('../chunk-74UKKBOO.cjs');
|
|
135
29
|
|
|
136
30
|
// src/realtime/session.ts
|
|
137
31
|
var DEFAULT_REALTIME_URL = "wss://rt.segmind.com";
|
|
@@ -202,6 +96,10 @@ var RealtimeSession = (_class = class {
|
|
|
202
96
|
get end() {
|
|
203
97
|
return this._end;
|
|
204
98
|
}
|
|
99
|
+
/** The session options sent on the URL at open (`SessionOptions.params`). */
|
|
100
|
+
get params() {
|
|
101
|
+
return _nullishCoalesce(this.options.params, () => ( {}));
|
|
102
|
+
}
|
|
205
103
|
/** The `session.created` frame, once live. */
|
|
206
104
|
get created() {
|
|
207
105
|
return this._created;
|
|
@@ -212,7 +110,7 @@ var RealtimeSession = (_class = class {
|
|
|
212
110
|
* 16-bit PCM audio. Size capture and playback from it.
|
|
213
111
|
*/
|
|
214
112
|
get audio() {
|
|
215
|
-
return audioFormat(this._created);
|
|
113
|
+
return _chunkB7VAGG2Ucjs.audioFormat.call(void 0, this._created);
|
|
216
114
|
}
|
|
217
115
|
/** Every server event. Returns a function that removes the listener. */
|
|
218
116
|
onEvent(listener) {
|
|
@@ -236,12 +134,12 @@ var RealtimeSession = (_class = class {
|
|
|
236
134
|
let done = this._state === "closed";
|
|
237
135
|
const unsubscribe = this.onEvent((event) => {
|
|
238
136
|
buffer.push(event);
|
|
239
|
-
_optionalChain([wake, 'optionalCall',
|
|
137
|
+
_optionalChain([wake, 'optionalCall', _ => _()]);
|
|
240
138
|
});
|
|
241
139
|
const unsubscribeState = this.onState((state) => {
|
|
242
140
|
if (state === "closed") {
|
|
243
141
|
done = true;
|
|
244
|
-
_optionalChain([wake, 'optionalCall',
|
|
142
|
+
_optionalChain([wake, 'optionalCall', _2 => _2()]);
|
|
245
143
|
}
|
|
246
144
|
});
|
|
247
145
|
return {
|
|
@@ -301,7 +199,7 @@ var RealtimeSession = (_class = class {
|
|
|
301
199
|
if (this._state === "closed") {
|
|
302
200
|
throw new SessionOpenError(_nullishCoalesce(this._end, () => ( { reason: "client", usage: null })));
|
|
303
201
|
}
|
|
304
|
-
const url = sessionUrl(
|
|
202
|
+
const url = _chunkB7VAGG2Ucjs.sessionUrl.call(void 0,
|
|
305
203
|
_nullishCoalesce(this.client.realtimeRoot, () => ( DEFAULT_REALTIME_URL)),
|
|
306
204
|
this.slug,
|
|
307
205
|
token,
|
|
@@ -345,7 +243,7 @@ var RealtimeSession = (_class = class {
|
|
|
345
243
|
if (this._state === "closed") return this.ended;
|
|
346
244
|
this.closeRequested = true;
|
|
347
245
|
if (this._state === "live" && this.socket && this.socket.readyState === WS_OPEN) {
|
|
348
|
-
this.rawSend(encodeClientEvent({ type: "close" }));
|
|
246
|
+
this.rawSend(_chunkB7VAGG2Ucjs.encodeClientEvent.call(void 0, { type: "close" }));
|
|
349
247
|
} else if (this.socket) {
|
|
350
248
|
this.socket.close(1e3, "client");
|
|
351
249
|
} else {
|
|
@@ -364,8 +262,8 @@ var RealtimeSession = (_class = class {
|
|
|
364
262
|
if (this._state === "closed") return false;
|
|
365
263
|
if (this._state === "opening") return this.enqueue({ pcm: pcmBytes(pcm) });
|
|
366
264
|
const format = this.audio;
|
|
367
|
-
if (!acceptsInput(format)) return false;
|
|
368
|
-
return this.rawSend(mediaFrame(format.tag, pcmBytes(pcm)));
|
|
265
|
+
if (!_chunkB7VAGG2Ucjs.acceptsInput.call(void 0, format)) return false;
|
|
266
|
+
return this.rawSend(_chunkB7VAGG2Ucjs.mediaFrame.call(void 0, format.tag, pcmBytes(pcm)));
|
|
369
267
|
}
|
|
370
268
|
commitAudio() {
|
|
371
269
|
return this.send({ type: "audio.commit" });
|
|
@@ -381,7 +279,7 @@ var RealtimeSession = (_class = class {
|
|
|
381
279
|
}
|
|
382
280
|
send(event) {
|
|
383
281
|
if (this._state === "closed") return false;
|
|
384
|
-
const frame = encodeClientEvent(event);
|
|
282
|
+
const frame = _chunkB7VAGG2Ucjs.encodeClientEvent.call(void 0, event);
|
|
385
283
|
if (this._state === "opening") return this.enqueue({ text: frame });
|
|
386
284
|
return this.rawSend(frame);
|
|
387
285
|
}
|
|
@@ -395,7 +293,7 @@ var RealtimeSession = (_class = class {
|
|
|
395
293
|
const format = this.audio;
|
|
396
294
|
for (const item of this.queue.splice(0)) {
|
|
397
295
|
if ("text" in item) this.rawSend(item.text);
|
|
398
|
-
else if (acceptsInput(format)) this.rawSend(mediaFrame(format.tag, item.pcm));
|
|
296
|
+
else if (_chunkB7VAGG2Ucjs.acceptsInput.call(void 0, format)) this.rawSend(_chunkB7VAGG2Ucjs.mediaFrame.call(void 0, format.tag, item.pcm));
|
|
399
297
|
}
|
|
400
298
|
}
|
|
401
299
|
rawSend(frame) {
|
|
@@ -404,7 +302,7 @@ var RealtimeSession = (_class = class {
|
|
|
404
302
|
try {
|
|
405
303
|
socket.send(frame);
|
|
406
304
|
return true;
|
|
407
|
-
} catch (
|
|
305
|
+
} catch (e) {
|
|
408
306
|
return false;
|
|
409
307
|
}
|
|
410
308
|
}
|
|
@@ -413,14 +311,14 @@ var RealtimeSession = (_class = class {
|
|
|
413
311
|
if (typeof data !== "string") return;
|
|
414
312
|
let event;
|
|
415
313
|
try {
|
|
416
|
-
event = decodeServerEvent(data);
|
|
417
|
-
} catch (
|
|
314
|
+
event = _chunkB7VAGG2Ucjs.decodeServerEvent.call(void 0, data);
|
|
315
|
+
} catch (e2) {
|
|
418
316
|
return;
|
|
419
317
|
}
|
|
420
318
|
if (event.type === "session.created") {
|
|
421
|
-
const unsupported = unsupportedSession(event);
|
|
319
|
+
const unsupported = _chunkB7VAGG2Ucjs.unsupportedSession.call(void 0, event);
|
|
422
320
|
if (unsupported) {
|
|
423
|
-
this.rawSend(encodeClientEvent({ type: "close" }));
|
|
321
|
+
this.rawSend(_chunkB7VAGG2Ucjs.encodeClientEvent.call(void 0, { type: "close" }));
|
|
424
322
|
this.finish("refused", null, unsupported, { code: "unsupported_protocol" });
|
|
425
323
|
return;
|
|
426
324
|
}
|
|
@@ -447,7 +345,7 @@ var RealtimeSession = (_class = class {
|
|
|
447
345
|
});
|
|
448
346
|
return;
|
|
449
347
|
}
|
|
450
|
-
const inferred = this.closeRequested && code === 1e3 ? "client" : reasonFromCloseCode(code, reason);
|
|
348
|
+
const inferred = this.closeRequested && code === 1e3 ? "client" : _chunkB7VAGG2Ucjs.reasonFromCloseCode.call(void 0, code, reason);
|
|
451
349
|
this.finish(inferred, null, reason || void 0, {
|
|
452
350
|
// A refusal without its frame still names its code in the close reason.
|
|
453
351
|
code: inferred === "refused" && reason ? reason : void 0,
|
|
@@ -465,7 +363,7 @@ var RealtimeSession = (_class = class {
|
|
|
465
363
|
if (socket && socket.readyState === WS_OPEN) {
|
|
466
364
|
try {
|
|
467
365
|
socket.close(1e3, "client");
|
|
468
|
-
} catch (
|
|
366
|
+
} catch (e3) {
|
|
469
367
|
}
|
|
470
368
|
}
|
|
471
369
|
const end = { reason, usage, message };
|
|
@@ -480,7 +378,7 @@ var RealtimeSession = (_class = class {
|
|
|
480
378
|
if (ms <= 0) return;
|
|
481
379
|
const schedule = _nullishCoalesce(this.client.setInterval, () => ( setInterval));
|
|
482
380
|
this.heartbeat = schedule(() => {
|
|
483
|
-
this.rawSend(encodeClientEvent({ type: "ping" }));
|
|
381
|
+
this.rawSend(_chunkB7VAGG2Ucjs.encodeClientEvent.call(void 0, { type: "ping" }));
|
|
484
382
|
}, ms);
|
|
485
383
|
}
|
|
486
384
|
stopHeartbeat() {
|
|
@@ -500,7 +398,7 @@ var RealtimeSession = (_class = class {
|
|
|
500
398
|
var RealtimeClient = class {
|
|
501
399
|
constructor(options) {
|
|
502
400
|
this.options = options;
|
|
503
|
-
if (typeof _optionalChain([options, 'optionalAccess',
|
|
401
|
+
if (typeof _optionalChain([options, 'optionalAccess', _3 => _3.tokenProvider]) !== "function") throw new (0, _chunk74UKKBOOcjs.SegmindError)("realtime: tokenProvider is required");
|
|
504
402
|
}
|
|
505
403
|
|
|
506
404
|
/** A session handle in `opening`; call `open()` to connect. */
|
|
@@ -545,5 +443,7 @@ function connect(slug, options) {
|
|
|
545
443
|
|
|
546
444
|
|
|
547
445
|
|
|
548
|
-
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
exports.DEFAULT_REALTIME_URL = DEFAULT_REALTIME_URL; exports.EnergyVad = _chunkB7VAGG2Ucjs.EnergyVad; exports.PROTOCOL_VERSION = _chunkB7VAGG2Ucjs.PROTOCOL_VERSION; exports.ProtocolError = _chunkB7VAGG2Ucjs.ProtocolError; exports.REFUSAL_CLOSE_CODES = _chunkB7VAGG2Ucjs.REFUSAL_CLOSE_CODES; exports.RealtimeClient = RealtimeClient; exports.RealtimeSession = RealtimeSession; exports.SESSION_SAMPLE_RATE = _chunkB7VAGG2Ucjs.SESSION_SAMPLE_RATE; exports.STREAM_TAGS = _chunkB7VAGG2Ucjs.STREAM_TAGS; exports.SessionOpenError = SessionOpenError; exports.acceptsInput = _chunkB7VAGG2Ucjs.acceptsInput; exports.attachBargeIn = _chunkB7VAGG2Ucjs.attachBargeIn; exports.audioFormat = _chunkB7VAGG2Ucjs.audioFormat; exports.connect = connect; exports.decodePcm = _chunkB7VAGG2Ucjs.decodePcm; exports.decodeServerEvent = _chunkB7VAGG2Ucjs.decodeServerEvent; exports.encodeClientEvent = _chunkB7VAGG2Ucjs.encodeClientEvent; exports.encodePcm = _chunkB7VAGG2Ucjs.encodePcm; exports.floatToInt16 = _chunkB7VAGG2Ucjs.floatToInt16; exports.isRetryableRefusal = _chunkB7VAGG2Ucjs.isRetryableRefusal; exports.mediaFrame = _chunkB7VAGG2Ucjs.mediaFrame; exports.pcmSeconds = _chunkB7VAGG2Ucjs.pcmSeconds; exports.reasonFromCloseCode = _chunkB7VAGG2Ucjs.reasonFromCloseCode; exports.rms = _chunkB7VAGG2Ucjs.rms; exports.sessionUrl = _chunkB7VAGG2Ucjs.sessionUrl; exports.unsupportedSession = _chunkB7VAGG2Ucjs.unsupportedSession; exports.videoControl = _chunkB7VAGG2Ucjs.videoControl; exports.webrtcVideo = _chunkB7VAGG2Ucjs.webrtcVideo;
|
|
549
449
|
//# sourceMappingURL=index.cjs.map
|