@dimchansky/meshpost 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/voice.js ADDED
@@ -0,0 +1,838 @@
1
+ import { getRoomRemoteStreams, isRoomClosed, onRoomClose } from './room.js';
2
+ const defaultAudioConstraints = Object.freeze({
3
+ echoCancellation: true,
4
+ noiseSuppression: true,
5
+ autoGainControl: true
6
+ });
7
+ const gestureEvents = ['pointerdown', 'pointerup', 'touchend', 'click', 'keydown'];
8
+ const captureOpts = { capture: true };
9
+ const maxRemoteStreamsPerPeer = 4;
10
+ const minSpeakingIntervalMs = 50;
11
+ const maxSpeakingIntervalMs = 60_000;
12
+ const defaultSpeakingThreshold = 0.03;
13
+ const defaultSpeakingIntervalMs = 180;
14
+ function isAudioCtxPaused(ctx) {
15
+ return ctx !== null && ctx.state !== 'running' && ctx.state !== 'closed';
16
+ }
17
+ function getIosAudioSession() {
18
+ if (typeof navigator === 'undefined')
19
+ return null;
20
+ const session = navigator.audioSession;
21
+ return session && typeof session === 'object' && typeof session.type === 'string' ? session : null;
22
+ }
23
+ function classifyMicError(err) {
24
+ const name = err && typeof err === 'object' && 'name' in err ? String(err.name) : '';
25
+ if (name === 'NotAllowedError' || name === 'PermissionDeniedError') {
26
+ return Object.freeze({
27
+ code: 'permission-denied',
28
+ message: 'Microphone permission denied'
29
+ });
30
+ }
31
+ if (name === 'NotFoundError' || name === 'DevicesNotFoundError') {
32
+ return Object.freeze({
33
+ code: 'not-found',
34
+ message: 'No microphone device found'
35
+ });
36
+ }
37
+ if (name === 'NotReadableError' || name === 'TrackStartError') {
38
+ return Object.freeze({
39
+ code: 'in-use',
40
+ message: 'Microphone is already in use by another application'
41
+ });
42
+ }
43
+ if (name === 'SecurityError') {
44
+ return Object.freeze({
45
+ code: 'insecure-context',
46
+ message: 'Microphone access requires HTTPS or localhost'
47
+ });
48
+ }
49
+ return Object.freeze({
50
+ code: 'unknown',
51
+ message: 'Could not access microphone'
52
+ });
53
+ }
54
+ function listeners() {
55
+ const entries = new Set();
56
+ let closed = false;
57
+ return {
58
+ add(fn, options) {
59
+ const signal = options?.signal;
60
+ if (closed || signal?.aborted)
61
+ return () => { };
62
+ const entry = {
63
+ fn,
64
+ once: Boolean(options?.once),
65
+ off() {
66
+ if (!entries.delete(entry))
67
+ return;
68
+ signal?.removeEventListener('abort', entry.off);
69
+ }
70
+ };
71
+ entries.add(entry);
72
+ signal?.addEventListener('abort', entry.off, { once: true });
73
+ return entry.off;
74
+ },
75
+ fire(...args) {
76
+ for (const entry of [...entries]) {
77
+ if (!entries.has(entry))
78
+ continue;
79
+ if (entry.once)
80
+ entry.off();
81
+ try {
82
+ entry.fn(...args);
83
+ }
84
+ catch (error) {
85
+ globalThis.reportError?.(error);
86
+ }
87
+ }
88
+ },
89
+ clear() {
90
+ closed = true;
91
+ for (const entry of [...entries])
92
+ entry.off();
93
+ }
94
+ };
95
+ }
96
+ function applyAudioVolume(audio, volume) {
97
+ try {
98
+ audio.volume = volume;
99
+ }
100
+ catch {
101
+ // Ignore read-only volume property on certain iOS WebKit builds.
102
+ }
103
+ }
104
+ /**
105
+ * Create a headless P2P voice chat controller attached to a `Room`.
106
+ *
107
+ * Automatically plays incoming peer audio streams, manages local microphone capture with instant
108
+ * soft-mute (`track.enabled`) vs full hardware release, tracks speaking peers via a shared lazy
109
+ * `AudioContext`, and handles browser Autoplay Policy & iOS Safari audio unlocking.
110
+ */
111
+ export function createVoice(room, options) {
112
+ if (!room ||
113
+ typeof room !== 'object' ||
114
+ typeof room.onPeerStream !== 'function' ||
115
+ typeof room.onPeerStreamEnd !== 'function' ||
116
+ typeof room.addStream !== 'function' ||
117
+ typeof room.removeStream !== 'function') {
118
+ throw new TypeError('Expected a valid Room instance');
119
+ }
120
+ const initialVolume = options?.volume ?? 1;
121
+ if (typeof initialVolume !== 'number' ||
122
+ !Number.isFinite(initialVolume) ||
123
+ initialVolume < 0 ||
124
+ initialVolume > 1) {
125
+ throw new RangeError('Expected volume between 0 and 1');
126
+ }
127
+ const speakingThreshold = options?.speakingThreshold ?? defaultSpeakingThreshold;
128
+ if (typeof speakingThreshold !== 'number' ||
129
+ !Number.isFinite(speakingThreshold) ||
130
+ speakingThreshold < 0 ||
131
+ speakingThreshold > 1) {
132
+ throw new RangeError('Expected speakingThreshold between 0 and 1');
133
+ }
134
+ const speakingIntervalMs = options?.speakingIntervalMs ?? defaultSpeakingIntervalMs;
135
+ if (!Number.isSafeInteger(speakingIntervalMs) ||
136
+ speakingIntervalMs < minSpeakingIntervalMs ||
137
+ speakingIntervalMs > maxSpeakingIntervalMs) {
138
+ throw new RangeError('Expected a safe integer speakingIntervalMs between 50 and 60000');
139
+ }
140
+ const rawConstraints = options?.audioConstraints;
141
+ if (rawConstraints !== undefined &&
142
+ rawConstraints !== true &&
143
+ (typeof rawConstraints !== 'object' || rawConstraints === null || Array.isArray(rawConstraints))) {
144
+ throw new TypeError('Expected audioConstraints to be true or a MediaTrackConstraints object');
145
+ }
146
+ const resolvedConstraints = rawConstraints === undefined
147
+ ? { ...defaultAudioConstraints }
148
+ : rawConstraints === true
149
+ ? true
150
+ : { ...rawConstraints };
151
+ const targetPeer = options?.to;
152
+ if (targetPeer !== undefined && typeof targetPeer !== 'string') {
153
+ throw new TypeError('Expected target peer ID to be a string');
154
+ }
155
+ const autoUnlock = options?.autoUnlock !== false;
156
+ const speakingDetection = options?.speakingDetection !== false;
157
+ let volume = initialVolume;
158
+ let deafened = Boolean(options?.deafened);
159
+ let micStatus = 'off';
160
+ let micError = null;
161
+ let autoplayBlocked = false;
162
+ let selfSpeaking = false;
163
+ let closed = false;
164
+ let localStream = null;
165
+ let localMeter = null;
166
+ let localTrackCleanups = [];
167
+ let micEpoch = 0;
168
+ let inFlightMic = null;
169
+ let audioSessionSwitched = false;
170
+ let prevAudioSessionType = null;
171
+ let audioCtx = null;
172
+ let silentSink = null;
173
+ let meterTimer;
174
+ let gestureListenersAttached = false;
175
+ let visibilityListenerAttached = false;
176
+ const remotePeers = new Map();
177
+ const speakingPeers = new Set();
178
+ const changes = listeners();
179
+ function buildSnapshot() {
180
+ return Object.freeze({
181
+ micStatus,
182
+ micError,
183
+ autoplayBlocked,
184
+ deafened,
185
+ volume,
186
+ selfSpeaking,
187
+ remotePeers: Object.freeze([...remotePeers.keys()]),
188
+ speakingPeers: Object.freeze([...speakingPeers])
189
+ });
190
+ }
191
+ function emitChange() {
192
+ if (closed)
193
+ return;
194
+ changes.fire(buildSnapshot());
195
+ }
196
+ function restoreAudioSession() {
197
+ if (!audioSessionSwitched)
198
+ return;
199
+ audioSessionSwitched = false;
200
+ const prev = prevAudioSessionType;
201
+ prevAudioSessionType = null;
202
+ if (prev === null)
203
+ return;
204
+ const session = getIosAudioSession();
205
+ if (session && session.type === 'play-and-record') {
206
+ try {
207
+ session.type = prev;
208
+ }
209
+ catch {
210
+ // Ignore restricted audioSession writes.
211
+ }
212
+ }
213
+ }
214
+ function switchAudioSessionForMic() {
215
+ const session = getIosAudioSession();
216
+ if (!session || session.type === 'play-and-record')
217
+ return;
218
+ const prev = session.type;
219
+ try {
220
+ session.type = 'play-and-record';
221
+ if (session.type === 'play-and-record') {
222
+ audioSessionSwitched = true;
223
+ prevAudioSessionType = prev;
224
+ }
225
+ }
226
+ catch {
227
+ // Ignore unsupported audioSession writes.
228
+ }
229
+ }
230
+ function hasBlockedRemoteAudio() {
231
+ for (const streams of remotePeers.values()) {
232
+ for (const entry of streams.values()) {
233
+ if (entry.blocked || entry.audio.paused)
234
+ return true;
235
+ }
236
+ }
237
+ return false;
238
+ }
239
+ function attachGestureListeners() {
240
+ if (!autoUnlock || closed || gestureListenersAttached || typeof window === 'undefined')
241
+ return;
242
+ gestureListenersAttached = true;
243
+ for (const type of gestureEvents) {
244
+ window.addEventListener(type, unlockAudio, captureOpts);
245
+ }
246
+ }
247
+ function detachGestureListeners() {
248
+ if (!gestureListenersAttached || typeof window === 'undefined')
249
+ return;
250
+ gestureListenersAttached = false;
251
+ for (const type of gestureEvents) {
252
+ window.removeEventListener(type, unlockAudio, captureOpts);
253
+ }
254
+ }
255
+ function markAutoplayBlocked() {
256
+ if (closed)
257
+ return;
258
+ const changed = !autoplayBlocked;
259
+ autoplayBlocked = true;
260
+ attachGestureListeners();
261
+ if (changed)
262
+ emitChange();
263
+ }
264
+ function reconcileUnlockState() {
265
+ if (closed)
266
+ return;
267
+ let changed = false;
268
+ if (autoplayBlocked && !hasBlockedRemoteAudio()) {
269
+ autoplayBlocked = false;
270
+ changed = true;
271
+ }
272
+ if (!autoplayBlocked && !isAudioCtxPaused(audioCtx)) {
273
+ detachGestureListeners();
274
+ }
275
+ if (changed)
276
+ emitChange();
277
+ }
278
+ function tryPlayEntry(peerId, streamId, entry) {
279
+ let playPromise;
280
+ try {
281
+ playPromise = entry.audio.play();
282
+ }
283
+ catch {
284
+ return;
285
+ }
286
+ if (!playPromise || typeof playPromise.then !== 'function')
287
+ return;
288
+ void playPromise
289
+ .then(() => {
290
+ if (closed || remotePeers.get(peerId)?.get(streamId) !== entry)
291
+ return;
292
+ entry.blocked = false;
293
+ reconcileUnlockState();
294
+ })
295
+ .catch((err) => {
296
+ if (closed || remotePeers.get(peerId)?.get(streamId) !== entry)
297
+ return;
298
+ const name = err && typeof err === 'object' && 'name' in err
299
+ ? String(err.name)
300
+ : '';
301
+ if (name !== 'NotAllowedError')
302
+ return;
303
+ entry.blocked = true;
304
+ markAutoplayBlocked();
305
+ });
306
+ }
307
+ // Never gate on an in-flight boolean or await audioCtx.resume(): on iOS Safari,
308
+ // pointerdown is not a media activation gesture and leaves audioCtx.resume()
309
+ // pending forever until a subsequent touchend/pointerup/click calls resume() again.
310
+ function unlockAudio() {
311
+ if (closed)
312
+ return;
313
+ if (isAudioCtxPaused(audioCtx)) {
314
+ void audioCtx
315
+ .resume()
316
+ .then(() => reconcileUnlockState())
317
+ .catch(() => { });
318
+ }
319
+ let attemptedPlay = false;
320
+ for (const [peerId, streams] of remotePeers) {
321
+ for (const [streamId, entry] of streams) {
322
+ if (entry.audio.paused) {
323
+ attemptedPlay = true;
324
+ tryPlayEntry(peerId, streamId, entry);
325
+ }
326
+ }
327
+ }
328
+ if (!attemptedPlay) {
329
+ reconcileUnlockState();
330
+ }
331
+ }
332
+ function isAnalyserActive(entry) {
333
+ if (!entry?.analyser || !entry.data)
334
+ return false;
335
+ entry.analyser.getByteTimeDomainData(entry.data);
336
+ let sum = 0;
337
+ for (let i = 0; i < entry.data.length; i++) {
338
+ const d = (entry.data[i] - 128) / 128;
339
+ sum += d * d;
340
+ }
341
+ return Math.sqrt(sum / entry.data.length) > speakingThreshold;
342
+ }
343
+ function ensureMeter() {
344
+ if (!speakingDetection || closed || meterTimer !== undefined)
345
+ return;
346
+ if (remotePeers.size === 0 && !localMeter)
347
+ return;
348
+ meterTimer = setInterval(() => {
349
+ if (closed)
350
+ return;
351
+ let changed = false;
352
+ for (const [peerId, streams] of remotePeers) {
353
+ let active = false;
354
+ for (const entry of streams.values()) {
355
+ if (isAnalyserActive(entry)) {
356
+ active = true;
357
+ break;
358
+ }
359
+ }
360
+ const was = speakingPeers.has(peerId);
361
+ if (active && !was) {
362
+ speakingPeers.add(peerId);
363
+ changed = true;
364
+ }
365
+ else if (!active && was) {
366
+ speakingPeers.delete(peerId);
367
+ changed = true;
368
+ }
369
+ }
370
+ const nextSelf = micStatus === 'live' && isAnalyserActive(localMeter);
371
+ if (nextSelf !== selfSpeaking) {
372
+ selfSpeaking = nextSelf;
373
+ changed = true;
374
+ }
375
+ if (changed)
376
+ emitChange();
377
+ }, speakingIntervalMs);
378
+ }
379
+ function stopMeterIfEmpty() {
380
+ if (remotePeers.size === 0) {
381
+ speakingPeers.clear();
382
+ autoplayBlocked = false;
383
+ if (!isAudioCtxPaused(audioCtx)) {
384
+ detachGestureListeners();
385
+ }
386
+ }
387
+ if (remotePeers.size > 0 || localMeter)
388
+ return;
389
+ if (meterTimer !== undefined) {
390
+ clearInterval(meterTimer);
391
+ meterTimer = undefined;
392
+ }
393
+ if (audioCtx) {
394
+ const ctx = audioCtx;
395
+ audioCtx = null;
396
+ silentSink?.disconnect();
397
+ silentSink = null;
398
+ ctx.onstatechange = null;
399
+ void ctx.close().catch(() => { });
400
+ }
401
+ detachGestureListeners();
402
+ }
403
+ function createAnalyser(stream) {
404
+ if (!speakingDetection || typeof AudioContext !== 'function')
405
+ return {};
406
+ try {
407
+ if (!audioCtx) {
408
+ const rawCtx = new AudioContext();
409
+ const ctx = rawCtx;
410
+ rawCtx.onstatechange = () => {
411
+ if (closed || audioCtx !== ctx)
412
+ return;
413
+ if (isAudioCtxPaused(ctx))
414
+ attachGestureListeners();
415
+ else
416
+ reconcileUnlockState();
417
+ };
418
+ const gain = rawCtx.createGain();
419
+ gain.gain.value = 0;
420
+ gain.connect(rawCtx.destination);
421
+ audioCtx = ctx;
422
+ silentSink = gain;
423
+ }
424
+ if (isAudioCtxPaused(audioCtx)) {
425
+ void audioCtx.resume().catch(() => { });
426
+ attachGestureListeners();
427
+ }
428
+ const rawCtx = audioCtx;
429
+ const source = rawCtx.createMediaStreamSource(stream);
430
+ const analyser = rawCtx.createAnalyser();
431
+ analyser.fftSize = 256;
432
+ source.connect(analyser);
433
+ if (silentSink)
434
+ analyser.connect(silentSink);
435
+ return { source, analyser, data: new Uint8Array(analyser.fftSize) };
436
+ }
437
+ catch {
438
+ return {};
439
+ }
440
+ }
441
+ function teardownLocalStream(detachFromRoom) {
442
+ let changed = false;
443
+ for (const cleanup of localTrackCleanups)
444
+ cleanup();
445
+ localTrackCleanups = [];
446
+ if (localMeter) {
447
+ localMeter.source?.disconnect();
448
+ localMeter.analyser?.disconnect();
449
+ localMeter = null;
450
+ }
451
+ if (selfSpeaking) {
452
+ selfSpeaking = false;
453
+ changed = true;
454
+ }
455
+ if (localStream) {
456
+ const stream = localStream;
457
+ localStream = null;
458
+ if (detachFromRoom && !isRoomClosed(room)) {
459
+ try {
460
+ room.removeStream(stream, targetPeer);
461
+ }
462
+ catch {
463
+ // Ignore if room closed concurrently.
464
+ }
465
+ }
466
+ for (const track of stream.getTracks())
467
+ track.stop();
468
+ changed = true;
469
+ }
470
+ if (micStatus !== 'off') {
471
+ micStatus = 'off';
472
+ changed = true;
473
+ }
474
+ if (micError !== null) {
475
+ micError = null;
476
+ changed = true;
477
+ }
478
+ restoreAudioSession();
479
+ stopMeterIfEmpty();
480
+ return changed;
481
+ }
482
+ function acquireMic() {
483
+ if (closed)
484
+ return Promise.resolve('off');
485
+ if (inFlightMic)
486
+ return inFlightMic;
487
+ if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia) {
488
+ micStatus = 'error';
489
+ micError = Object.freeze({
490
+ code: 'insecure-context',
491
+ message: 'Microphone access requires HTTPS or localhost'
492
+ });
493
+ emitChange();
494
+ return Promise.resolve('error');
495
+ }
496
+ const epoch = ++micEpoch;
497
+ micStatus = 'requesting';
498
+ micError = null;
499
+ emitChange();
500
+ if (closed || epoch !== micEpoch)
501
+ return Promise.resolve('off');
502
+ switchAudioSessionForMic();
503
+ const promise = (async () => {
504
+ let stream;
505
+ try {
506
+ stream = await navigator.mediaDevices.getUserMedia({ audio: resolvedConstraints });
507
+ }
508
+ catch (err) {
509
+ if (closed || epoch !== micEpoch)
510
+ return 'off';
511
+ restoreAudioSession();
512
+ micStatus = 'error';
513
+ micError = classifyMicError(err);
514
+ emitChange();
515
+ return 'error';
516
+ }
517
+ if (closed || epoch !== micEpoch || isRoomClosed(room)) {
518
+ for (const track of stream.getTracks())
519
+ track.stop();
520
+ if (!closed && epoch === micEpoch) {
521
+ restoreAudioSession();
522
+ micStatus = 'error';
523
+ micError = Object.freeze({
524
+ code: 'room-closed',
525
+ message: 'Room is closed'
526
+ });
527
+ emitChange();
528
+ return 'error';
529
+ }
530
+ return 'off';
531
+ }
532
+ try {
533
+ room.addStream(stream, targetPeer);
534
+ }
535
+ catch {
536
+ restoreAudioSession();
537
+ for (const track of stream.getTracks())
538
+ track.stop();
539
+ micStatus = 'error';
540
+ micError = Object.freeze({
541
+ code: 'room-closed',
542
+ message: 'Room is closed'
543
+ });
544
+ emitChange();
545
+ return 'error';
546
+ }
547
+ localStream = stream;
548
+ micStatus = 'live';
549
+ micError = null;
550
+ const onTrackEnded = () => {
551
+ if (closed || localStream !== stream)
552
+ return;
553
+ const changed = teardownLocalStream(true);
554
+ if (changed)
555
+ emitChange();
556
+ };
557
+ localTrackCleanups = [];
558
+ for (const track of stream.getAudioTracks()) {
559
+ track.addEventListener('ended', onTrackEnded, { once: true });
560
+ localTrackCleanups.push(() => track.removeEventListener('ended', onTrackEnded));
561
+ }
562
+ const meter = createAnalyser(stream);
563
+ localMeter = meter.analyser ? meter : null;
564
+ ensureMeter();
565
+ unlockAudio();
566
+ emitChange();
567
+ return 'live';
568
+ })();
569
+ inFlightMic = promise;
570
+ void promise.finally(() => {
571
+ if (inFlightMic === promise) {
572
+ inFlightMic = null;
573
+ }
574
+ });
575
+ return promise;
576
+ }
577
+ function teardownRemoteEntry(entry) {
578
+ entry.source?.disconnect();
579
+ entry.analyser?.disconnect();
580
+ try {
581
+ entry.audio.pause();
582
+ }
583
+ catch {
584
+ // Ignore non-standard audio element implementations.
585
+ }
586
+ entry.audio.srcObject = null;
587
+ entry.audio.remove();
588
+ }
589
+ function addRemoteStream(peerId, stream) {
590
+ if (closed || typeof document === 'undefined' || !document.body)
591
+ return;
592
+ if (!stream || typeof stream.getAudioTracks !== 'function')
593
+ return;
594
+ if (stream.getAudioTracks().length === 0)
595
+ return;
596
+ let byPeer = remotePeers.get(peerId);
597
+ if (!byPeer) {
598
+ byPeer = new Map();
599
+ remotePeers.set(peerId, byPeer);
600
+ }
601
+ if (byPeer.has(stream.id))
602
+ return;
603
+ if (byPeer.size >= maxRemoteStreamsPerPeer)
604
+ return;
605
+ const audio = document.createElement('audio');
606
+ audio.autoplay = true;
607
+ audio.setAttribute('playsinline', '');
608
+ audio.hidden = true;
609
+ audio.muted = deafened;
610
+ applyAudioVolume(audio, volume);
611
+ audio.srcObject = stream;
612
+ document.body.append(audio);
613
+ const meter = createAnalyser(stream);
614
+ const entry = { audio, blocked: false, ...meter };
615
+ byPeer.set(stream.id, entry);
616
+ const onPlaybackAccepted = () => {
617
+ if (closed || remotePeers.get(peerId)?.get(stream.id) !== entry || entry.audio.paused)
618
+ return;
619
+ entry.blocked = false;
620
+ reconcileUnlockState();
621
+ };
622
+ audio.addEventListener('play', onPlaybackAccepted);
623
+ audio.addEventListener('playing', onPlaybackAccepted);
624
+ tryPlayEntry(peerId, stream.id, entry);
625
+ ensureMeter();
626
+ emitChange();
627
+ }
628
+ function removeRemoteStream(peerId, stream) {
629
+ if (closed)
630
+ return;
631
+ const byPeer = remotePeers.get(peerId);
632
+ const entry = byPeer?.get(stream.id);
633
+ if (!entry || !byPeer)
634
+ return;
635
+ teardownRemoteEntry(entry);
636
+ byPeer.delete(stream.id);
637
+ if (byPeer.size === 0) {
638
+ remotePeers.delete(peerId);
639
+ speakingPeers.delete(peerId);
640
+ }
641
+ stopMeterIfEmpty();
642
+ reconcileUnlockState();
643
+ emitChange();
644
+ }
645
+ const onVisibilityChange = () => {
646
+ if (closed || typeof document === 'undefined' || document.visibilityState !== 'visible')
647
+ return;
648
+ if (isAudioCtxPaused(audioCtx)) {
649
+ void audioCtx
650
+ .resume()
651
+ .then(() => reconcileUnlockState())
652
+ .catch(() => { });
653
+ attachGestureListeners();
654
+ }
655
+ for (const [peerId, streams] of remotePeers) {
656
+ for (const [streamId, entry] of streams) {
657
+ if (entry.audio.paused) {
658
+ tryPlayEntry(peerId, streamId, entry);
659
+ }
660
+ }
661
+ }
662
+ };
663
+ function closeInternal(roomClosing) {
664
+ if (closed)
665
+ return;
666
+ closed = true;
667
+ micEpoch++;
668
+ inFlightMic = null;
669
+ offStream();
670
+ offStreamEnd();
671
+ offRoomClose();
672
+ if (visibilityListenerAttached && typeof document !== 'undefined') {
673
+ visibilityListenerAttached = false;
674
+ document.removeEventListener('visibilitychange', onVisibilityChange);
675
+ }
676
+ detachGestureListeners();
677
+ teardownLocalStream(!roomClosing);
678
+ for (const byPeer of remotePeers.values()) {
679
+ for (const entry of byPeer.values()) {
680
+ teardownRemoteEntry(entry);
681
+ }
682
+ }
683
+ remotePeers.clear();
684
+ speakingPeers.clear();
685
+ autoplayBlocked = false;
686
+ stopMeterIfEmpty();
687
+ changes.clear();
688
+ }
689
+ let offStream = () => { };
690
+ let offStreamEnd = () => { };
691
+ let offRoomClose = () => { };
692
+ if (isRoomClosed(room)) {
693
+ closed = true;
694
+ changes.clear();
695
+ }
696
+ else {
697
+ offStream = room.onPeerStream(addRemoteStream);
698
+ offStreamEnd = room.onPeerStreamEnd(removeRemoteStream);
699
+ offRoomClose = onRoomClose(room, () => closeInternal(true));
700
+ if (autoUnlock && typeof document !== 'undefined') {
701
+ visibilityListenerAttached = true;
702
+ document.addEventListener('visibilitychange', onVisibilityChange);
703
+ }
704
+ for (const [peerId, stream] of getRoomRemoteStreams(room)) {
705
+ addRemoteStream(peerId, stream);
706
+ }
707
+ }
708
+ return {
709
+ get micStatus() {
710
+ return micStatus;
711
+ },
712
+ get micError() {
713
+ return micError;
714
+ },
715
+ get autoplayBlocked() {
716
+ return autoplayBlocked;
717
+ },
718
+ get deafened() {
719
+ return deafened;
720
+ },
721
+ get volume() {
722
+ return volume;
723
+ },
724
+ get selfSpeaking() {
725
+ return selfSpeaking;
726
+ },
727
+ get remotePeers() {
728
+ return Object.freeze([...remotePeers.keys()]);
729
+ },
730
+ get speakingPeers() {
731
+ return Object.freeze([...speakingPeers]);
732
+ },
733
+ getSnapshot: buildSnapshot,
734
+ toggleMic() {
735
+ if (closed)
736
+ return Promise.resolve('off');
737
+ if (inFlightMic)
738
+ return inFlightMic;
739
+ if (localStream) {
740
+ const nextMuted = micStatus === 'live';
741
+ for (const track of localStream.getAudioTracks()) {
742
+ track.enabled = !nextMuted;
743
+ }
744
+ micStatus = nextMuted ? 'muted' : 'live';
745
+ micError = null;
746
+ if (nextMuted)
747
+ selfSpeaking = false;
748
+ emitChange();
749
+ return Promise.resolve(micStatus);
750
+ }
751
+ return acquireMic();
752
+ },
753
+ startMic() {
754
+ if (closed)
755
+ return Promise.resolve('off');
756
+ if (inFlightMic)
757
+ return inFlightMic;
758
+ if (localStream) {
759
+ if (micStatus === 'muted') {
760
+ for (const track of localStream.getAudioTracks()) {
761
+ track.enabled = true;
762
+ }
763
+ micStatus = 'live';
764
+ micError = null;
765
+ emitChange();
766
+ }
767
+ return Promise.resolve('live');
768
+ }
769
+ return acquireMic();
770
+ },
771
+ setMuted(muted) {
772
+ if (closed || !localStream)
773
+ return;
774
+ const next = Boolean(muted);
775
+ const nextStatus = next ? 'muted' : 'live';
776
+ if (micStatus === nextStatus)
777
+ return;
778
+ for (const track of localStream.getAudioTracks()) {
779
+ track.enabled = !next;
780
+ }
781
+ micStatus = nextStatus;
782
+ micError = null;
783
+ if (next)
784
+ selfSpeaking = false;
785
+ emitChange();
786
+ },
787
+ stopMic() {
788
+ if (closed)
789
+ return;
790
+ const wasRequesting = inFlightMic !== null;
791
+ micEpoch++;
792
+ inFlightMic = null;
793
+ const changed = teardownLocalStream(true);
794
+ if (changed || wasRequesting)
795
+ emitChange();
796
+ },
797
+ setVolume(nextVolume) {
798
+ if (typeof nextVolume !== 'number' || !Number.isFinite(nextVolume)) {
799
+ throw new RangeError('Expected a finite volume');
800
+ }
801
+ if (closed)
802
+ return;
803
+ const clamped = Math.max(0, Math.min(1, nextVolume));
804
+ if (clamped === volume)
805
+ return;
806
+ volume = clamped;
807
+ for (const byPeer of remotePeers.values()) {
808
+ for (const entry of byPeer.values()) {
809
+ applyAudioVolume(entry.audio, clamped);
810
+ }
811
+ }
812
+ emitChange();
813
+ },
814
+ setDeafened(nextDeafened) {
815
+ if (closed)
816
+ return;
817
+ const next = Boolean(nextDeafened);
818
+ if (next === deafened)
819
+ return;
820
+ deafened = next;
821
+ for (const byPeer of remotePeers.values()) {
822
+ for (const entry of byPeer.values()) {
823
+ entry.audio.muted = next;
824
+ }
825
+ }
826
+ if (!next)
827
+ unlockAudio();
828
+ emitChange();
829
+ },
830
+ unlockAudio,
831
+ onChange(fn, listenOpts) {
832
+ return changes.add(fn, listenOpts);
833
+ },
834
+ close() {
835
+ closeInternal(false);
836
+ }
837
+ };
838
+ }