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,8 +1,10 @@
1
1
  import {
2
2
  SESSION_SAMPLE_RATE,
3
3
  attachBargeIn,
4
- decodePcm
5
- } from "../../chunk-USGY6G4C.js";
4
+ decodePcm,
5
+ videoControl,
6
+ webrtcVideo
7
+ } from "../../chunk-YSAOJ3YL.js";
6
8
  import {
7
9
  SegmindError
8
10
  } from "../../chunk-PS5KUT7P.js";
@@ -299,9 +301,632 @@ async function startVoice(session, options = {}) {
299
301
  stop
300
302
  };
301
303
  }
304
+
305
+ // src/realtime/browser/video/control-channel.ts
306
+ var MAX_QUEUED_MESSAGES = 64;
307
+ var ControlChannel = class {
308
+ constructor(channel, options = {}) {
309
+ this.channel = channel;
310
+ this.options = options;
311
+ channel.binaryType = "arraybuffer";
312
+ channel.onopen = () => this.handleOpen();
313
+ channel.onclose = () => this.handleDeath("the control channel closed");
314
+ channel.onerror = () => this.handleDeath("the control channel failed");
315
+ channel.onmessage = (event) => this.handleMessage(event.data);
316
+ }
317
+ channel;
318
+ options;
319
+ pending = [];
320
+ closing = false;
321
+ dead = false;
322
+ decoder = typeof TextDecoder !== "undefined" ? new TextDecoder() : null;
323
+ get readyState() {
324
+ return this.channel.readyState;
325
+ }
326
+ /** Messages waiting for the channel to open. */
327
+ get queued() {
328
+ return this.pending.length;
329
+ }
330
+ /** Sends now when open, queues while connecting, drops otherwise. Returns false when dropped. */
331
+ send(message) {
332
+ if (this.closing || this.dead) return false;
333
+ const payload = JSON.stringify(message);
334
+ const state = this.channel.readyState;
335
+ if (state === "open") return this.rawSend(payload);
336
+ if (state !== "connecting") return false;
337
+ const limit = this.options.maxQueued ?? MAX_QUEUED_MESSAGES;
338
+ if (this.pending.length >= limit) this.pending.shift();
339
+ this.pending.push(payload);
340
+ return true;
341
+ }
342
+ /** Sends `last` if the channel is open, then closes it. Never reports a death. */
343
+ close(last) {
344
+ if (this.closing) return;
345
+ if (last && this.channel.readyState === "open" && !this.dead) {
346
+ this.rawSend(JSON.stringify(last));
347
+ }
348
+ this.closing = true;
349
+ this.pending.length = 0;
350
+ try {
351
+ this.channel.close();
352
+ } catch {
353
+ }
354
+ }
355
+ handleOpen() {
356
+ if (this.closing || this.dead) return;
357
+ const queued = this.pending.splice(0);
358
+ if (this.options.first) queued.unshift(JSON.stringify(this.options.first));
359
+ for (const payload of queued) {
360
+ if (!this.rawSend(payload)) break;
361
+ }
362
+ this.options.onOpen?.();
363
+ }
364
+ handleDeath(message) {
365
+ if (this.closing || this.dead) return;
366
+ this.dead = true;
367
+ this.pending.length = 0;
368
+ this.options.onDied?.(message);
369
+ }
370
+ handleMessage(data) {
371
+ let text = null;
372
+ if (typeof data === "string") text = data;
373
+ else if (this.decoder && (data instanceof ArrayBuffer || ArrayBuffer.isView(data))) {
374
+ text = this.decoder.decode(data);
375
+ }
376
+ if (text === null) return;
377
+ let parsed;
378
+ try {
379
+ parsed = JSON.parse(text);
380
+ } catch {
381
+ return;
382
+ }
383
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
384
+ this.options.onMessage?.(parsed);
385
+ }
386
+ }
387
+ rawSend(payload) {
388
+ try {
389
+ this.channel.send(payload);
390
+ return true;
391
+ } catch {
392
+ return false;
393
+ }
394
+ }
395
+ };
396
+
397
+ // src/realtime/browser/video/ice.ts
398
+ var ICE_TIMEOUT_MS = 12e3;
399
+ var ICE_QUIET_PERIOD_MS = 1250;
400
+ function countTurnServers(servers = []) {
401
+ return servers.filter((server) => {
402
+ const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
403
+ return urls.some((url) => /^turns?:/i.test(url));
404
+ }).length;
405
+ }
406
+ function candidateType(candidate) {
407
+ const match = candidate.match(/(?:^|\s)typ\s+(host|srflx|relay)(?:\s|$)/);
408
+ return match?.[1] ?? null;
409
+ }
410
+ function gatherIceCandidates(pc, options = {}) {
411
+ const {
412
+ iceServers = [],
413
+ timeoutMs = ICE_TIMEOUT_MS,
414
+ quietPeriodMs = ICE_QUIET_PERIOD_MS,
415
+ setTimeout: schedule = setTimeout,
416
+ clearTimeout: cancel = clearTimeout
417
+ } = options;
418
+ const counts = { host: 0, srflx: 0, relay: 0 };
419
+ for (const line of (pc.localDescription?.sdp ?? "").split(/\r?\n/)) {
420
+ if (!line.startsWith("a=candidate:")) continue;
421
+ const type = candidateType(line.slice(2));
422
+ if (type) counts[type] += 1;
423
+ }
424
+ if (pc.iceGatheringState === "complete") {
425
+ return Promise.resolve({ ...counts, state: "complete" });
426
+ }
427
+ const requireRelay = countTurnServers(iceServers) > 0;
428
+ const sufficient = () => requireRelay ? counts.relay > 0 : counts.srflx > 0;
429
+ return new Promise((resolve) => {
430
+ let settled = false;
431
+ let quiet = null;
432
+ const finish = (state) => {
433
+ if (settled) return;
434
+ settled = true;
435
+ cancel(hardBound);
436
+ if (quiet !== null) cancel(quiet);
437
+ pc.removeEventListener("icegatheringstatechange", onState);
438
+ pc.removeEventListener("icecandidate", onCandidate);
439
+ resolve({ ...counts, state });
440
+ };
441
+ const onState = () => {
442
+ if (pc.iceGatheringState === "complete") finish("complete");
443
+ };
444
+ const onCandidate = (event) => {
445
+ const type = event.candidate ? candidateType(event.candidate.candidate) : null;
446
+ if (type) counts[type] += 1;
447
+ if (quiet !== null) cancel(quiet);
448
+ quiet = sufficient() ? schedule(() => finish("sufficient"), quietPeriodMs) : null;
449
+ };
450
+ const hardBound = schedule(() => finish("timeout"), timeoutMs);
451
+ pc.addEventListener("icegatheringstatechange", onState);
452
+ pc.addEventListener("icecandidate", onCandidate);
453
+ if (sufficient()) quiet = schedule(() => finish("sufficient"), quietPeriodMs);
454
+ });
455
+ }
456
+
457
+ // src/realtime/browser/video/peer.ts
458
+ function defaultPeerConnection(configuration) {
459
+ const Ctor = globalThis.RTCPeerConnection;
460
+ if (!Ctor) throw new Error("no RTCPeerConnection in this runtime: pass peerConnectionFactory");
461
+ return new Ctor(configuration);
462
+ }
463
+ function defaultGetUserMedia(constraints) {
464
+ const devices = globalThis.navigator?.mediaDevices;
465
+ if (!devices?.getUserMedia) {
466
+ return Promise.reject(new Error("no camera access in this runtime: pass getUserMedia"));
467
+ }
468
+ return devices.getUserMedia(constraints);
469
+ }
470
+ function defaultMediaStream(tracks) {
471
+ const Ctor = globalThis.MediaStream;
472
+ return Ctor ? new Ctor(tracks) : null;
473
+ }
474
+
475
+ // src/realtime/browser/video/video-session.ts
476
+ var REPORTED_CHANNEL_EVENTS = /* @__PURE__ */ new Set([
477
+ "configured",
478
+ "prompt_applied",
479
+ "prompt_rejected",
480
+ "deadline_missed",
481
+ "stream_exhausted",
482
+ "error"
483
+ ]);
484
+ var DEFAULT_RESOLUTION = "768p";
485
+ var DEFAULT_ASPECT_RATIO = "16:9";
486
+ var RESTART_GRACE_MS = 8e3;
487
+ var DEFAULT_ICE_SERVERS = [{ urls: "stun:stun.cloudflare.com:3478" }];
488
+ function attachVideo(session, options) {
489
+ return new VideoSession(session, options);
490
+ }
491
+ var VideoSession = class {
492
+ constructor(session, options = {}) {
493
+ this.session = session;
494
+ this.options = options;
495
+ if (session.state === "closed") throw new Error("the session has already closed");
496
+ this.unsubscribe.push(session.onEvent((event) => this.handleEvent(event)));
497
+ this.unsubscribe.push(
498
+ session.onState((state) => {
499
+ if (state === "closed") this.teardown();
500
+ })
501
+ );
502
+ if (session.created) this.handleCreated(session.created);
503
+ }
504
+ session;
505
+ options;
506
+ _phase = "waiting";
507
+ _control = null;
508
+ _localStream = null;
509
+ _remoteStream = null;
510
+ pc = null;
511
+ channel = null;
512
+ listeners = /* @__PURE__ */ new Set();
513
+ unsubscribe = [];
514
+ ownsLocalStream = false;
515
+ /** The upstream's answer is applied; remote candidates go straight in. */
516
+ remoteReady = false;
517
+ remoteCandidates = [];
518
+ /** Local candidates wait until the offer they belong to has been sent. */
519
+ offerSent = false;
520
+ localCandidates = [];
521
+ sentVersion = 1;
522
+ /** Data-channel prompts made before the channel exists; they go out right after `configure`. */
523
+ earlyPrompts = [];
524
+ /** The opening prompt has gone out on a `session` stream (or there is none). */
525
+ openingSent = false;
526
+ stopSent = false;
527
+ /** `end()` was called: the session is closing, so nothing new is opened. */
528
+ ending = false;
529
+ failed = false;
530
+ restartTimer = null;
531
+ get phase() {
532
+ return this._phase;
533
+ }
534
+ /** `session` or `datachannel` once the session is live; null before, or for a non-video session. */
535
+ get control() {
536
+ return this._control;
537
+ }
538
+ /** The `prompt_version` of the latest prompt on a data channel (`configure` is 1). */
539
+ get promptVersion() {
540
+ return this.sentVersion;
541
+ }
542
+ /** Read through a getter so TypeScript does not narrow it across an await. */
543
+ get closed() {
544
+ return this._phase === "closed";
545
+ }
546
+ get localStream() {
547
+ return this._localStream;
548
+ }
549
+ get remoteStream() {
550
+ return this._remoteStream;
551
+ }
552
+ onEvent(listener) {
553
+ this.listeners.add(listener);
554
+ return () => this.listeners.delete(listener);
555
+ }
556
+ /**
557
+ * Steer the generation. On a `datachannel` session it goes on the runner's
558
+ * channel with the next `prompt_version` (queued until the channel opens).
559
+ * False when it could not be sent.
560
+ */
561
+ prompt(text, options = {}) {
562
+ const value = text.trim();
563
+ if (!value || this.closed) return false;
564
+ if (this._control === "datachannel") {
565
+ const message = { type: "prompt", prompt_version: this.sentVersion + 1, prompt: value };
566
+ if (!this.channel) {
567
+ const limit = this.options.maxQueuedMessages ?? MAX_QUEUED_MESSAGES;
568
+ if (this.earlyPrompts.length >= limit) this.earlyPrompts.shift();
569
+ this.earlyPrompts.push(message);
570
+ this.sentVersion += 1;
571
+ return true;
572
+ }
573
+ const sent = this.channel.send(message);
574
+ if (sent) this.sentVersion += 1;
575
+ return sent;
576
+ }
577
+ if (this._control !== "session") return false;
578
+ this.sendOpeningPrompt();
579
+ return this.sendPrompt(value, options);
580
+ }
581
+ sendOpeningPrompt() {
582
+ if (this.openingSent) return;
583
+ this.openingSent = true;
584
+ const opening = this.options.prompt?.trim();
585
+ if (opening) this.sendPrompt(opening);
586
+ }
587
+ sendPrompt(value, options = {}) {
588
+ const enhance = options.enhance ?? this.options.enhance;
589
+ return this.session.send({
590
+ type: "video.prompt",
591
+ text: value,
592
+ ...enhance === void 0 ? {} : { enhance }
593
+ });
594
+ }
595
+ /**
596
+ * A reference image (base64, no `data:` prefix) with an optional prompt, or
597
+ * null to clear it. Only a `session` stream takes one.
598
+ */
599
+ setImage(image, text, options = {}) {
600
+ if (this._control !== "session" || this.closed) return false;
601
+ const enhance = options.enhance ?? this.options.enhance;
602
+ return this.session.send({
603
+ type: "video.image",
604
+ image,
605
+ ...text?.trim() ? { text: text.trim() } : {},
606
+ ...enhance === void 0 ? {} : { enhance }
607
+ });
608
+ }
609
+ /**
610
+ * End the session: the runner's `stop` first (a `datachannel` session stops
611
+ * generating now, not when its lease lapses), then `session.close()`. The
612
+ * camera is released at once; the peer stays up until the session closes,
613
+ * so `stop` has a transport to leave on.
614
+ */
615
+ end() {
616
+ this.ending = true;
617
+ this.sendStop();
618
+ this.releaseCamera();
619
+ return this.session.close();
620
+ }
621
+ /** Stop listening and release the peer and the camera without closing the session. */
622
+ detach() {
623
+ this.teardown();
624
+ }
625
+ // --- server events ------------------------------------------------------------
626
+ handleEvent(event) {
627
+ switch (event.type) {
628
+ case "session.created":
629
+ this.handleCreated(event);
630
+ break;
631
+ case "webrtc.config":
632
+ if (this._control === "datachannel" && !this.pc && !this.ending) void this.startReceiveOnly(event);
633
+ break;
634
+ case "webrtc.answer":
635
+ void this.applyAnswer(event.sdp, event.ice_servers);
636
+ break;
637
+ case "webrtc.candidate":
638
+ if (this._control === "session" && event.candidate) void this.addRemote(event.candidate);
639
+ break;
640
+ case "webrtc.restart":
641
+ if (this._control === "session") void this.restart(event.ice_servers);
642
+ break;
643
+ case "video.started":
644
+ this.emit({ type: "started" });
645
+ break;
646
+ case "video.progress":
647
+ this.emit({ type: "progress", seconds: event.seconds });
648
+ break;
649
+ case "video.prompt_ack":
650
+ this.emit({
651
+ type: "prompt_ack",
652
+ kind: event.kind,
653
+ applied: event.applied,
654
+ ...event.reason ? { reason: event.reason } : {}
655
+ });
656
+ break;
657
+ default:
658
+ break;
659
+ }
660
+ }
661
+ handleCreated(created) {
662
+ if (this._control || this.closed) return;
663
+ this._control = videoControl(created);
664
+ if (this._control === "session") void this.startCamera(created);
665
+ }
666
+ // --- session control: the camera up, the edited stream down ------------------
667
+ async startCamera(created) {
668
+ this.setPhase("negotiating");
669
+ let stream;
670
+ try {
671
+ stream = this.options.localStream ?? await this.openCamera(created);
672
+ } catch (error) {
673
+ this.fail(`camera: ${errorMessage(error)}`);
674
+ return;
675
+ }
676
+ if (this.closed || this.ending) {
677
+ if (!this.options.localStream) stopTracks(stream);
678
+ return;
679
+ }
680
+ this.ownsLocalStream = !this.options.localStream;
681
+ this._localStream = stream;
682
+ this.emit({ type: "local_stream", stream });
683
+ try {
684
+ const pc = this.createPeer({ iceServers: [...this.options.iceServers ?? DEFAULT_ICE_SERVERS] });
685
+ pc.addEventListener("icecandidate", (event) => {
686
+ this.sendLocalCandidate(event.candidate ? event.candidate.toJSON() : null);
687
+ });
688
+ for (const track of stream.getTracks()) pc.addTrack(track, stream);
689
+ await this.offer(pc);
690
+ } catch (error) {
691
+ this.fail(`negotiation: ${errorMessage(error)}`);
692
+ return;
693
+ }
694
+ if (this.closed) return;
695
+ this.sendOpeningPrompt();
696
+ }
697
+ async openCamera(created) {
698
+ const getUserMedia = this.options.getUserMedia ?? defaultGetUserMedia;
699
+ const video = webrtcVideo(created);
700
+ const constraints = {};
701
+ if (video?.width) constraints.width = { ideal: video.width };
702
+ if (video?.height) constraints.height = { ideal: video.height };
703
+ if (video?.fps) constraints.frameRate = { ideal: video.fps };
704
+ const audioSpec = created.media?.audio;
705
+ const wantAudio = this.options.audio ?? (audioSpec?.transport === "webrtc" && (audioSpec.direction === "in" || audioSpec.direction === "duplex"));
706
+ const videoConstraint = Object.keys(constraints).length ? constraints : true;
707
+ try {
708
+ return await getUserMedia({ video: videoConstraint, audio: wantAudio });
709
+ } catch (error) {
710
+ if (!wantAudio) throw error;
711
+ return getUserMedia({ video: videoConstraint, audio: false });
712
+ }
713
+ }
714
+ async offer(pc, iceRestart = false) {
715
+ const offer = await pc.createOffer(iceRestart ? { iceRestart: true } : void 0);
716
+ await pc.setLocalDescription(offer);
717
+ if (this.closed || pc !== this.pc) return;
718
+ const sdp = pc.localDescription?.sdp ?? offer.sdp;
719
+ if (!sdp) throw new Error("the browser produced no SDP offer");
720
+ this.session.send({ type: "webrtc.offer", sdp });
721
+ this.offerSent = true;
722
+ for (const candidate of this.localCandidates.splice(0)) {
723
+ this.session.send({ type: "webrtc.candidate", candidate });
724
+ }
725
+ }
726
+ sendLocalCandidate(candidate) {
727
+ if (this.closed) return;
728
+ if (!this.offerSent) {
729
+ this.localCandidates.push(candidate);
730
+ return;
731
+ }
732
+ this.session.send({ type: "webrtc.candidate", candidate });
733
+ }
734
+ async addRemote(candidate) {
735
+ if (!this.pc || !this.remoteReady) {
736
+ this.remoteCandidates.push(candidate);
737
+ return;
738
+ }
739
+ try {
740
+ await this.pc.addIceCandidate(candidate);
741
+ } catch {
742
+ }
743
+ }
744
+ async restart(iceServers) {
745
+ const pc = this.pc;
746
+ if (!pc || this.closed) return;
747
+ this.clearRestartTimer();
748
+ try {
749
+ pc.setConfiguration({ ...pc.getConfiguration(), iceServers });
750
+ this.remoteReady = false;
751
+ this.offerSent = false;
752
+ await this.offer(pc, true);
753
+ } catch (error) {
754
+ this.fail(`ICE restart: ${errorMessage(error)}`);
755
+ }
756
+ }
757
+ // --- datachannel control: receive-only, one complete offer -------------------
758
+ async startReceiveOnly(config) {
759
+ this.setPhase("negotiating");
760
+ try {
761
+ const pc = this.createPeer({ iceServers: config.ice_servers });
762
+ pc.addTransceiver("video", { direction: "recvonly" });
763
+ pc.addTransceiver("audio", { direction: "recvonly" });
764
+ this.channel = new ControlChannel(pc.createDataChannel("control"), {
765
+ first: {
766
+ type: "configure",
767
+ protocol_version: 1,
768
+ prompt_version: 1,
769
+ prompt: this.options.prompt?.trim() ?? "",
770
+ resolution: this.options.resolution ?? this.session.params.resolution ?? DEFAULT_RESOLUTION,
771
+ aspect_ratio: this.options.aspectRatio ?? this.session.params.aspect_ratio ?? DEFAULT_ASPECT_RATIO
772
+ },
773
+ maxQueued: this.options.maxQueuedMessages ?? MAX_QUEUED_MESSAGES,
774
+ onMessage: (message) => this.handleChannelMessage(message),
775
+ onDied: (message) => this.fail(message)
776
+ });
777
+ for (const message of this.earlyPrompts.splice(0)) this.channel.send(message);
778
+ const offer = await pc.createOffer();
779
+ const gathering = gatherIceCandidates(pc, {
780
+ iceServers: config.ice_servers,
781
+ timeoutMs: this.options.iceTimeoutMs,
782
+ quietPeriodMs: this.options.iceQuietPeriodMs,
783
+ setTimeout: this.options.setTimeout,
784
+ clearTimeout: this.options.clearTimeout
785
+ });
786
+ const [gathered] = await Promise.all([gathering, pc.setLocalDescription(offer)]);
787
+ if (this.closed || pc !== this.pc) return;
788
+ if (gathered.relay === 0 && gathered.srflx === 0 && gathered.host === 0) {
789
+ throw new Error("ICE gathering produced no candidate");
790
+ }
791
+ const sdp = pc.localDescription?.sdp;
792
+ if (!sdp) throw new Error("the browser produced no SDP offer");
793
+ this.session.send({ type: "webrtc.offer", sdp });
794
+ this.offerSent = true;
795
+ } catch (error) {
796
+ this.fail(`negotiation: ${errorMessage(error)}`);
797
+ }
798
+ }
799
+ handleChannelMessage(message) {
800
+ this.emit({ type: "channel", event: message });
801
+ if (typeof message.type === "string" && REPORTED_CHANNEL_EVENTS.has(message.type)) {
802
+ this.session.send({ type: "video.report", event: message });
803
+ }
804
+ }
805
+ sendStop() {
806
+ if (this.stopSent || !this.channel) return;
807
+ this.stopSent = true;
808
+ this.channel.close({ type: "stop" });
809
+ }
810
+ // --- both -------------------------------------------------------------------
811
+ createPeer(configuration) {
812
+ const pc = (this.options.peerConnectionFactory ?? defaultPeerConnection)(configuration);
813
+ this.pc = pc;
814
+ pc.addEventListener("track", (event) => this.handleTrack(event));
815
+ pc.addEventListener("connectionstatechange", () => this.handleConnectionState(pc));
816
+ return pc;
817
+ }
818
+ async applyAnswer(sdp, iceServers) {
819
+ const pc = this.pc;
820
+ if (!pc || this.closed) return;
821
+ try {
822
+ if (iceServers?.length) pc.setConfiguration({ ...pc.getConfiguration(), iceServers });
823
+ await pc.setRemoteDescription({ type: "answer", sdp });
824
+ } catch (error) {
825
+ this.fail(`answer: ${errorMessage(error)}`);
826
+ return;
827
+ }
828
+ this.remoteReady = true;
829
+ for (const candidate of this.remoteCandidates.splice(0)) await this.addRemote(candidate);
830
+ }
831
+ handleTrack(event) {
832
+ if (this.closed) return;
833
+ const current = this._remoteStream;
834
+ if (current) {
835
+ if (!current.getTracks().includes(event.track)) current.addTrack(event.track);
836
+ return;
837
+ }
838
+ const stream = event.streams[0] ?? (this.options.createMediaStream ?? defaultMediaStream)([event.track]);
839
+ if (!stream) return;
840
+ this._remoteStream = stream;
841
+ this.emit({ type: "remote_stream", stream });
842
+ }
843
+ handleConnectionState(pc) {
844
+ if (pc !== this.pc || this.closed) return;
845
+ const state = pc.connectionState;
846
+ this.emit({ type: "connection", state });
847
+ if (state === "connected") {
848
+ this.clearRestartTimer();
849
+ this.setPhase("connected");
850
+ } else if (state === "failed") {
851
+ if (this._control === "session") {
852
+ const schedule = this.options.setTimeout ?? setTimeout;
853
+ this.clearRestartTimer();
854
+ this.restartTimer = schedule(() => {
855
+ this.restartTimer = null;
856
+ if (this.pc?.connectionState === "failed") {
857
+ this.fail("the video connection failed");
858
+ }
859
+ }, RESTART_GRACE_MS);
860
+ } else {
861
+ this.fail("the video connection failed");
862
+ }
863
+ }
864
+ }
865
+ clearRestartTimer() {
866
+ if (this.restartTimer !== null) {
867
+ (this.options.clearTimeout ?? clearTimeout)(this.restartTimer);
868
+ this.restartTimer = null;
869
+ }
870
+ }
871
+ /** Report the failure and end the session: an uncontrollable stream should not keep billing. */
872
+ fail(message) {
873
+ if (this.failed || this.closed) return;
874
+ this.failed = true;
875
+ this.emit({ type: "failed", message });
876
+ void this.end();
877
+ }
878
+ teardown() {
879
+ if (this.closed) return;
880
+ this.sendStop();
881
+ this.clearRestartTimer();
882
+ this.setPhase("closed");
883
+ for (const off of this.unsubscribe.splice(0)) off();
884
+ this.remoteCandidates.length = 0;
885
+ this.localCandidates.length = 0;
886
+ const pc = this.pc;
887
+ this.pc = null;
888
+ try {
889
+ pc?.close();
890
+ } catch {
891
+ }
892
+ this.earlyPrompts.length = 0;
893
+ this.releaseCamera();
894
+ }
895
+ /** Stop the camera this negotiator opened (a stream passed in stays the caller's). */
896
+ releaseCamera() {
897
+ if (this.ownsLocalStream && this._localStream) stopTracks(this._localStream);
898
+ this.ownsLocalStream = false;
899
+ }
900
+ setPhase(phase) {
901
+ if (this._phase === phase || this.closed) return;
902
+ this._phase = phase;
903
+ this.emit({ type: "phase", phase });
904
+ }
905
+ emit(event) {
906
+ for (const listener of this.listeners) listener(event);
907
+ }
908
+ };
909
+ function stopTracks(stream) {
910
+ for (const track of stream.getTracks()) track.stop();
911
+ }
912
+ function errorMessage(error) {
913
+ return error instanceof Error ? error.message : String(error);
914
+ }
302
915
  export {
303
916
  AudioPlayback,
917
+ ControlChannel,
918
+ DEFAULT_ICE_SERVERS,
919
+ ICE_QUIET_PERIOD_MS,
920
+ ICE_TIMEOUT_MS,
921
+ MAX_QUEUED_MESSAGES,
304
922
  MicrophoneCapture,
923
+ REPORTED_CHANNEL_EVENTS,
924
+ RESTART_GRACE_MS,
925
+ VideoSession,
926
+ attachVideo,
927
+ candidateType,
928
+ countTurnServers,
929
+ gatherIceCandidates,
305
930
  startVoice
306
931
  };
307
932
  //# sourceMappingURL=index.js.map