segmind 0.6.0 → 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.
@@ -1 +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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAoBxC,IAAM,kBAAA,YAAN,MAAwB;AAAA,EAW7B,WAAA,CAA6B,QAAA,EAA0B,CAAC,CAAA,EAAG;AAA9B,IAAA,IAAA,CAAA,QAAA,EAAA,OAAA;AAC3B,IAAA,IAAA,CAAK,WAAA,mBAAa,OAAA,CAAQ,UAAA,UAAc,uCAAA;AACxC,IAAA,IAAA,CAAK,aAAA,EAAe,IAAA,CAAK,KAAA,CAAO,IAAA,CAAK,WAAA,EAAA,kBAAc,OAAA,CAAQ,OAAA,UAAW,KAAA,EAAA,EAAQ,GAAI,CAAA;AAClF,IAAA,IAAA,CAAK,QAAA,mBAAU,OAAA,CAAQ,YAAA,UAAgB,MAAA;AACvC,IAAA,IAAA,CAAK,YAAA,EAAc,CAAC,OAAA,CAAQ,YAAA;AAAA,EAC9B;AAAA,EAL6B;AAAA,EAVpB;AAAA,EACA;AAAA,iBACD,QAAA,EAA+B,KAAA;AAAA,EACtB;AAAA,kBACT,OAAA,EAA6B,KAAA;AAAA,kBAC7B,OAAA,EAA4C,KAAA;AAAA,kBAC5C,KAAA,EAAgC,K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,sBAAA,OAAA,+BAAS,MAAA,qBAAO,GAAA;AAChB,MAAA,MAAM,QAAA,CAAS,OAAA,CAAQ,CAAA;AACvB,MAAA,MAAM,OAAA,CAAQ,OAAA,CAAQ,CAAA;AAAA,IACxB,CAAA,CAAA,CAAG,CAAA;AACH,IAAA,OAAO,OAAA;AAAA,EACT,CAAA;AAEA,EAAA,MAAM,SAAA,EAAW,OAAA,CAAQ,OAAA,CAAQ,CAAC,KAAA,EAAA,GAAU;AAC1C,IAAA,GAAA,CAAI,MAAA,IAAU,QAAA,EAAU;AACtB,MAAA,QAAA,CAAS,CAAA;AACT,MAAA,KAAK,IAAA,CAAK,CAAA;AAAA,IACZ;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO;AAAA,IACL,IAAI,KAAA,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"]}
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","../../../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"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACF,4DAAiC;AACjC;AACE;AACF,4DAAiC;AACjC;AACA;ACeA,IAAM,gBAAA,EAAkB,CAAC,YAAA,EAAA,GAAyB,CAAA;AAAA;AAAA;AAAA;AAAA,iCAAA,EAIf,YAAY,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAoBxC,IAAM,kBAAA,YAAN,MAAwB;AAAA,EAW7B,WAAA,CAA6B,QAAA,EAA0B,CAAC,CAAA,EAAG;AAA9B,IAAA,IAAA,CAAA,QAAA,EAAA,OAAA;AAC3B,IAAA,IAAA,CAAK,WAAA,mBAAa,OAAA,CAAQ,UAAA,UAAc,uCAAA;AACxC,IAAA,IAAA,CAAK,aAAA,EAAe,IAAA,CAAK,KAAA,CAAO,IAAA,CAAK,WAAA,EAAA,kBAAc,OAAA,CAAQ,OAAA,UAAW,KAAA,EAAA,EAAQ,GAAI,CAAA;AAClF,IAAA,IAAA,CAAK,QAAA,mBAAU,OAAA,CAAQ,YAAA,UAAgB,MAAA;AACvC,IAAA,IAAA,CAAK,YAAA,EAAc,CAAC,OAAA,CAAQ,YAAA;AAAA,EAC9B;AAAA,EAL6B;AAAA,EAVpB;AAAA,EACA;AAAA,iBACD,QAAA,EAA+B,KAAA;AAAA,EACtB;AAAA,kBACT,OAAA,EAA6B,KAAA;AAAA,kBAC7B,OAAA,EAA4C,KAAA;AAAA,kBAC5C,KAAA,EAAgC,KAAA;AAAA,kBACvB,UAAA,kBAAY,IAAI,GAAA,CAAmB,EAAA;AAAA,kBAC5C,UAAA,EA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C,IAAA;AACb,IAAA;AACT,EAAA;AAEgF,EAAA;AAC9D,IAAA;AACQ,IAAA;AACpB,IAAA;AACyB,MAAA;AACW,MAAA;AACxB,IAAA;AAC0B,MAAA;AACxC,MAAA;AACF,IAAA;AACmB,IAAA;AACU,IAAA;AAC/B,EAAA;AAEiD,EAAA;AAC9B,IAAA;AAGI,IAAA;AACR,IAAA;AAC6B,MAAA;AACxC,MAAA;AACF,IAAA;AAE4B,IAAA;AACf,IAAA;AACQ,IAAA;AACsB,IAAA;AAC7C,EAAA;AAE4D,EAAA;AACvB,IAAA;AAClB,IAAA;AACsB,IAAA;AACZ,IAAA;AACF,MAAA;AACE,MAAA;AACI,IAAA;AACI,MAAA;AAED,QAAA;AACP,QAAA;AACY,QAAA;AACb,UAAA;AACa,UAAA;AACrB,YAAA;AACZ,UAAA;AACiB,QAAA;AACd,MAAA;AACkC,QAAA;AACzC,MAAA;AACF,IAAA;AACF,EAAA;AAEkC,EAAA;AACA,IAAA;AACA,MAAA;AACV,MAAA;AACtB,IAAA;AACF,EAAA;AAAA;AAGoC,EAAA;AACF,IAAA;AAClB,IAAA;AACuB,IAAA;AACvB,IAAA;AAChB,EAAA;AAEyB,EAAA;AACN,IAAA;AACH,IAAA;AACS,IAAA;AACD,IAAA;AACqB,IAAA;AACZ,IAAA;AACD,IAAA;AACd,IAAA;AACN,IAAA;AACN,IAAA;AACQ,sBAAA;AACJ,IAAA;AAER,IAAA;AAC2B,IAAA;AACR,IAAA;AACrB,EAAA;AAAA;AAG8B,EAAA;AACK,IAAA;AACV,IAAA;AACzB,EAAA;AAE0C,EAAA;AACE,IAAA;AAC5B,IAAA;AACoB,IAAA;AACpC,EAAA;AAEsC,EAAA;AACG,IAAA;AACzC,EAAA;AACF;AAE+C;AACL,EAAA;AAC1C;AAE8C;AACN,EAAA;AACxC;APsS+C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","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","/**\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"]}
@@ -1,5 +1,5 @@
1
- import { VadOptions, RealtimeSession } from '../index.cjs';
2
- import '../../errors-CcHEuSmR.cjs';
1
+ import { VadOptions, RealtimeSession, SessionEnd } from '../index.cjs';
2
+ import { IceCandidateJson, IceServer, VideoControl } from '../index.cjs';
3
3
 
4
4
  /**
5
5
  * Microphone capture: `getUserMedia` with echo cancellation, an
@@ -118,5 +118,360 @@ interface Voice {
118
118
  */
119
119
  declare function startVoice(session: RealtimeSession, options?: VoiceOptions): Promise<Voice>;
120
120
 
121
- export { AudioPlayback, MicrophoneCapture, startVoice };
122
- export type { CaptureOptions, FrameListener, PlaybackOptions, Voice, VoiceOptions };
121
+ /**
122
+ * The subset of the WebRTC API the video module drives, so tests can fake a
123
+ * peer connection and a data channel without a browser.
124
+ */
125
+
126
+ interface SessionDescriptionLike {
127
+ type: string;
128
+ sdp?: string;
129
+ }
130
+ interface IceCandidateLike {
131
+ candidate: string;
132
+ toJSON(): IceCandidateJson;
133
+ }
134
+ interface IceCandidateEventLike {
135
+ candidate: IceCandidateLike | null;
136
+ }
137
+ interface TrackEventLike {
138
+ track: MediaStreamTrack;
139
+ streams: readonly MediaStream[];
140
+ }
141
+ interface DataChannelLike {
142
+ readonly readyState: string;
143
+ binaryType?: string;
144
+ send(data: string): void;
145
+ close(): void;
146
+ onopen: ((ev: unknown) => void) | null;
147
+ onclose: ((ev: unknown) => void) | null;
148
+ onerror: ((ev: unknown) => void) | null;
149
+ onmessage: ((ev: {
150
+ data: unknown;
151
+ }) => void) | null;
152
+ }
153
+ interface PeerConfiguration {
154
+ iceServers?: IceServer[];
155
+ }
156
+ interface PeerConnectionLike {
157
+ readonly localDescription: SessionDescriptionLike | null;
158
+ readonly iceGatheringState: string;
159
+ readonly connectionState: string;
160
+ addEventListener(type: 'icecandidate', listener: (ev: IceCandidateEventLike) => void): void;
161
+ addEventListener(type: 'icegatheringstatechange', listener: () => void): void;
162
+ addEventListener(type: 'connectionstatechange', listener: () => void): void;
163
+ addEventListener(type: 'track', listener: (ev: TrackEventLike) => void): void;
164
+ removeEventListener(type: string, listener: (...args: never[]) => void): void;
165
+ addTrack(track: MediaStreamTrack, ...streams: MediaStream[]): unknown;
166
+ addTransceiver(kind: 'audio' | 'video', init: {
167
+ direction: 'recvonly';
168
+ }): unknown;
169
+ createDataChannel(label: string): DataChannelLike;
170
+ createOffer(options?: {
171
+ iceRestart?: boolean;
172
+ }): Promise<SessionDescriptionLike>;
173
+ setLocalDescription(description?: SessionDescriptionLike): Promise<void>;
174
+ setRemoteDescription(description: {
175
+ type: 'answer';
176
+ sdp: string;
177
+ }): Promise<void>;
178
+ addIceCandidate(candidate: IceCandidateJson): Promise<void>;
179
+ getConfiguration(): PeerConfiguration;
180
+ setConfiguration(configuration: PeerConfiguration): void;
181
+ close(): void;
182
+ }
183
+
184
+ /**
185
+ * The WebRTC half of a realtime video session.
186
+ *
187
+ * A video session carries no media on the socket: `session.created.media`
188
+ * declares its streams with `transport: "webrtc"`, and the client negotiates
189
+ * a peer connection with the upstream through `webrtc.*` events on the
190
+ * session socket. `session.created.control` says how:
191
+ *
192
+ * - `session`: the camera goes up and the edited stream comes down (a
193
+ * camera-restyling model such as Decart Lucy). Trickle ICE both ways,
194
+ * `webrtc.answer`, and `webrtc.restart` (new ICE servers, a new offer with
195
+ * `iceRestart`). Steering is `video.prompt` / `video.image` on the socket,
196
+ * acknowledged in order with `video.prompt_ack`.
197
+ * - `datachannel`: receive-only video and audio (a prompt-driven model whose
198
+ * runner speaks over its own data channel, such as fal's Director). The
199
+ * service sends `webrtc.config`; the client gathers every candidate and
200
+ * sends ONE `webrtc.offer` (no trickle). Steering runs on the runner's
201
+ * `control` data channel (`configure` on open, then `prompt` with a rising
202
+ * `prompt_version`), and what the runner says there is mirrored to the
203
+ * socket as `video.report` for the record.
204
+ *
205
+ * Attach before `open()`: the service sends `webrtc.config` right after
206
+ * `session.created`, and a listener added later can miss it. Every ending of
207
+ * the session tears the peer down; on a `datachannel` session the runner's
208
+ * own `stop` goes first, so it stops generating at once rather than when its
209
+ * lease runs out. Any negotiation or transport failure ends the session, so
210
+ * nothing keeps billing for a stream nobody can see.
211
+ */
212
+
213
+ /** Runner data-channel events kept for the session's record (`video.report`). */
214
+ declare const REPORTED_CHANNEL_EVENTS: Set<string>;
215
+ /** How long a failed peer on a `session` stream waits for the upstream's ICE restart. */
216
+ declare const RESTART_GRACE_MS = 8000;
217
+ /**
218
+ * The ICE servers a `session` stream starts with: the service sends none for
219
+ * it (only a restart carries them). Without one a browser offers only its
220
+ * private `.local` addresses, which an upstream outside the network cannot
221
+ * reach, so the stream never connects.
222
+ */
223
+ declare const DEFAULT_ICE_SERVERS: readonly IceServer[];
224
+ type VideoPhase = 'waiting' | 'negotiating' | 'connected' | 'closed';
225
+ type VideoEvent = {
226
+ type: 'phase';
227
+ phase: VideoPhase;
228
+ }
229
+ /** The camera stream being sent (`session` control). */
230
+ | {
231
+ type: 'local_stream';
232
+ stream: MediaStream;
233
+ }
234
+ /** The upstream's video (and audio): put it on a `<video>`. */
235
+ | {
236
+ type: 'remote_stream';
237
+ stream: MediaStream;
238
+ } | {
239
+ type: 'connection';
240
+ state: string;
241
+ } | {
242
+ type: 'started';
243
+ }
244
+ /** Seconds of video generated so far, as billed. */
245
+ | {
246
+ type: 'progress';
247
+ seconds: number;
248
+ } | {
249
+ type: 'prompt_ack';
250
+ kind: 'prompt' | 'image';
251
+ applied: boolean;
252
+ reason?: string;
253
+ }
254
+ /** Anything the runner said on its data channel (`configured`, `chunk`, `prompt_applied`…). */
255
+ | {
256
+ type: 'channel';
257
+ event: Record<string, unknown>;
258
+ }
259
+ /** Negotiation or transport failed; the session is being closed. */
260
+ | {
261
+ type: 'failed';
262
+ message: string;
263
+ };
264
+ type VideoListener = (event: VideoEvent) => void;
265
+ interface VideoSessionOptions {
266
+ /**
267
+ * The opening prompt. `session` control sends it as `video.prompt` after the
268
+ * offer; `datachannel` puts it in `configure`.
269
+ */
270
+ prompt?: string;
271
+ /** Let the upstream rewrite prompts (`session` control). Server default: true. */
272
+ enhance?: boolean;
273
+ /**
274
+ * `configure.resolution` on a `datachannel` session. Default: the session's
275
+ * `resolution` param, else `768p` (the service's default). It must match
276
+ * what the session was opened with.
277
+ */
278
+ resolution?: string;
279
+ /** `configure.aspect_ratio` on a `datachannel` session. Default: the session's `aspect_ratio` param, else `16:9`. */
280
+ aspectRatio?: string;
281
+ /** The stream to send on a `session` stream. Default: the camera at the declared size. */
282
+ localStream?: MediaStream;
283
+ /** Capture the microphone with the camera. Default: when `media.audio` takes input. */
284
+ audio?: boolean;
285
+ /**
286
+ * ICE servers for a `session` stream, such as your own TURN servers for
287
+ * users behind a NAT that STUN cannot cross. Default: `DEFAULT_ICE_SERVERS`
288
+ * (one public STUN server). A `datachannel` session uses the servers in
289
+ * `webrtc.config` and ignores this.
290
+ */
291
+ iceServers?: IceServer[];
292
+ peerConnectionFactory?: (configuration: PeerConfiguration) => PeerConnectionLike;
293
+ getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;
294
+ /** A stream holding remote tracks the upstream sent without one. */
295
+ createMediaStream?: (tracks: MediaStreamTrack[]) => MediaStream | null;
296
+ /** Data-channel sends queued before it opens. Default 64. */
297
+ maxQueuedMessages?: number;
298
+ iceTimeoutMs?: number;
299
+ iceQuietPeriodMs?: number;
300
+ setTimeout?: typeof setTimeout;
301
+ clearTimeout?: typeof clearTimeout;
302
+ }
303
+ /** Hook a video negotiator onto `session`. Call before `session.open()`. */
304
+ declare function attachVideo(session: RealtimeSession, options?: VideoSessionOptions): VideoSession;
305
+ declare class VideoSession {
306
+ readonly session: RealtimeSession;
307
+ private readonly options;
308
+ private _phase;
309
+ private _control;
310
+ private _localStream;
311
+ private _remoteStream;
312
+ private pc;
313
+ private channel;
314
+ private readonly listeners;
315
+ private readonly unsubscribe;
316
+ private ownsLocalStream;
317
+ /** The upstream's answer is applied; remote candidates go straight in. */
318
+ private remoteReady;
319
+ private readonly remoteCandidates;
320
+ /** Local candidates wait until the offer they belong to has been sent. */
321
+ private offerSent;
322
+ private readonly localCandidates;
323
+ private sentVersion;
324
+ /** Data-channel prompts made before the channel exists; they go out right after `configure`. */
325
+ private readonly earlyPrompts;
326
+ /** The opening prompt has gone out on a `session` stream (or there is none). */
327
+ private openingSent;
328
+ private stopSent;
329
+ /** `end()` was called: the session is closing, so nothing new is opened. */
330
+ private ending;
331
+ private failed;
332
+ private restartTimer;
333
+ constructor(session: RealtimeSession, options?: VideoSessionOptions);
334
+ get phase(): VideoPhase;
335
+ /** `session` or `datachannel` once the session is live; null before, or for a non-video session. */
336
+ get control(): VideoControl | null;
337
+ /** The `prompt_version` of the latest prompt on a data channel (`configure` is 1). */
338
+ get promptVersion(): number;
339
+ /** Read through a getter so TypeScript does not narrow it across an await. */
340
+ private get closed();
341
+ get localStream(): MediaStream | null;
342
+ get remoteStream(): MediaStream | null;
343
+ onEvent(listener: VideoListener): () => void;
344
+ /**
345
+ * Steer the generation. On a `datachannel` session it goes on the runner's
346
+ * channel with the next `prompt_version` (queued until the channel opens).
347
+ * False when it could not be sent.
348
+ */
349
+ prompt(text: string, options?: {
350
+ enhance?: boolean;
351
+ }): boolean;
352
+ private sendOpeningPrompt;
353
+ private sendPrompt;
354
+ /**
355
+ * A reference image (base64, no `data:` prefix) with an optional prompt, or
356
+ * null to clear it. Only a `session` stream takes one.
357
+ */
358
+ setImage(image: string | null, text?: string, options?: {
359
+ enhance?: boolean;
360
+ }): boolean;
361
+ /**
362
+ * End the session: the runner's `stop` first (a `datachannel` session stops
363
+ * generating now, not when its lease lapses), then `session.close()`. The
364
+ * camera is released at once; the peer stays up until the session closes,
365
+ * so `stop` has a transport to leave on.
366
+ */
367
+ end(): Promise<SessionEnd>;
368
+ /** Stop listening and release the peer and the camera without closing the session. */
369
+ detach(): void;
370
+ private handleEvent;
371
+ private handleCreated;
372
+ private startCamera;
373
+ private openCamera;
374
+ private offer;
375
+ private sendLocalCandidate;
376
+ private addRemote;
377
+ private restart;
378
+ private startReceiveOnly;
379
+ private handleChannelMessage;
380
+ private sendStop;
381
+ private createPeer;
382
+ private applyAnswer;
383
+ private handleTrack;
384
+ private handleConnectionState;
385
+ private clearRestartTimer;
386
+ /** Report the failure and end the session: an uncontrollable stream should not keep billing. */
387
+ private fail;
388
+ private teardown;
389
+ /** Stop the camera this negotiator opened (a stream passed in stays the caller's). */
390
+ private releaseCamera;
391
+ private setPhase;
392
+ private emit;
393
+ }
394
+
395
+ /**
396
+ * The upstream's `control` data channel (a `datachannel` session), with the two traps
397
+ * `@fal-ai/client` `src/realtime/wma.js` (MIT, Copyright 2024 https://fal.ai)
398
+ * handles:
399
+ *
400
+ * - Messages sent before the channel opens are lost. The peer connection
401
+ * reports `connected` before the channel reports `open`, so sends made in
402
+ * between are queued (bounded, oldest dropped) and flushed on open, after
403
+ * the `first` message (`configure`), which is never dropped.
404
+ * - The channel can die while ICE still says `connected`: SCTP state is
405
+ * independent of the peer connection's. A close or error the owner did not
406
+ * ask for is reported through `onDied`, never laundered into a clean close.
407
+ */
408
+
409
+ declare const MAX_QUEUED_MESSAGES = 64;
410
+ interface ControlChannelOptions {
411
+ /** Sent first on open, ahead of anything queued. */
412
+ first?: Record<string, unknown>;
413
+ maxQueued?: number;
414
+ onMessage?: (message: Record<string, unknown>) => void;
415
+ onOpen?: () => void;
416
+ /** The channel closed or errored without `close()` being called. */
417
+ onDied?: (message: string) => void;
418
+ }
419
+ declare class ControlChannel {
420
+ private readonly channel;
421
+ private readonly options;
422
+ private readonly pending;
423
+ private closing;
424
+ private dead;
425
+ private readonly decoder;
426
+ constructor(channel: DataChannelLike, options?: ControlChannelOptions);
427
+ get readyState(): string;
428
+ /** Messages waiting for the channel to open. */
429
+ get queued(): number;
430
+ /** Sends now when open, queues while connecting, drops otherwise. Returns false when dropped. */
431
+ send(message: Record<string, unknown>): boolean;
432
+ /** Sends `last` if the channel is open, then closes it. Never reports a death. */
433
+ close(last?: Record<string, unknown>): void;
434
+ private handleOpen;
435
+ private handleDeath;
436
+ private handleMessage;
437
+ private rawSend;
438
+ }
439
+
440
+ /**
441
+ * ICE gathering for an upstream that takes one complete offer (no trickle).
442
+ *
443
+ * Adapted from `@fal-ai/client` `src/realtime/ice.js` (MIT, Copyright 2024
444
+ * https://fal.ai). The offer is sent once, so it must carry a usable candidate
445
+ * set that has stopped changing: resolve when the set is sufficient AND quiet,
446
+ * when gathering completes, or at a hard bound — whichever comes first. A
447
+ * configuration with a TURN server is not sufficient until a relay candidate
448
+ * exists; an offer without one would connect nowhere and say nothing about why.
449
+ */
450
+
451
+ declare const ICE_TIMEOUT_MS = 12000;
452
+ declare const ICE_QUIET_PERIOD_MS = 1250;
453
+ interface GatherOptions {
454
+ iceServers?: IceServer[];
455
+ timeoutMs?: number;
456
+ quietPeriodMs?: number;
457
+ setTimeout?: typeof setTimeout;
458
+ clearTimeout?: typeof clearTimeout;
459
+ }
460
+ interface GatherResult {
461
+ host: number;
462
+ srflx: number;
463
+ relay: number;
464
+ /** `complete`: the browser finished; `sufficient`: a usable set went quiet; `timeout`: the hard bound. */
465
+ state: 'complete' | 'sufficient' | 'timeout';
466
+ }
467
+ declare function countTurnServers(servers?: IceServer[]): number;
468
+ /** `host`, `srflx` or `relay` out of a candidate line, or null. */
469
+ declare function candidateType(candidate: string): 'host' | 'srflx' | 'relay' | null;
470
+ /**
471
+ * Call BEFORE `setLocalDescription`: fast host candidates otherwise fire
472
+ * before the listener exists and are never counted.
473
+ */
474
+ declare function gatherIceCandidates(pc: PeerConnectionLike, options?: GatherOptions): Promise<GatherResult>;
475
+
476
+ export { AudioPlayback, ControlChannel, DEFAULT_ICE_SERVERS, ICE_QUIET_PERIOD_MS, ICE_TIMEOUT_MS, MAX_QUEUED_MESSAGES, MicrophoneCapture, REPORTED_CHANNEL_EVENTS, RESTART_GRACE_MS, VideoSession, attachVideo, candidateType, countTurnServers, gatherIceCandidates, startVoice };
477
+ export type { CaptureOptions, ControlChannelOptions, DataChannelLike, FrameListener, GatherOptions, GatherResult, IceCandidateEventLike, IceCandidateLike, PeerConfiguration, PeerConnectionLike, PlaybackOptions, SessionDescriptionLike, TrackEventLike, VideoEvent, VideoListener, VideoPhase, VideoSessionOptions, Voice, VoiceOptions };