@dimchansky/meshpost 0.5.0 → 0.6.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.
Files changed (46) hide show
  1. package/README.md +66 -544
  2. package/dist/bip340.d.ts +1 -0
  3. package/dist/bip340.js +346 -0
  4. package/dist/blob.d.ts +1 -1
  5. package/dist/blob.js +15 -16
  6. package/dist/channel.js +15 -44
  7. package/dist/combine.js +5 -24
  8. package/dist/crypto.js +10 -9
  9. package/dist/identity.d.ts +2 -0
  10. package/dist/identity.js +39 -71
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.js +1 -1
  13. package/dist/listeners.js +18 -3
  14. package/dist/mqtt.js +193 -408
  15. package/dist/nostr.js +163 -745
  16. package/dist/public.d.ts +1 -1
  17. package/dist/public.js +9 -54
  18. package/dist/relay-core.d.ts +1 -0
  19. package/dist/relay-core.js +323 -0
  20. package/dist/room-hello.d.ts +1 -0
  21. package/dist/room-hello.js +129 -0
  22. package/dist/room-ice.d.ts +1 -0
  23. package/dist/room-ice.js +115 -0
  24. package/dist/room-media.d.ts +1 -0
  25. package/dist/room-media.js +477 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +111 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +109 -919
  31. package/dist/signaling.d.ts +8 -0
  32. package/dist/signaling.js +64 -0
  33. package/dist/state.js +1 -2
  34. package/dist/voice-helpers.d.ts +1 -0
  35. package/dist/voice-helpers.js +100 -0
  36. package/dist/voice-meter.d.ts +1 -0
  37. package/dist/voice-meter.js +79 -0
  38. package/dist/voice.d.ts +11 -1
  39. package/dist/voice.js +99 -295
  40. package/dist/ws.js +39 -142
  41. package/docs/api.md +217 -0
  42. package/docs/behavior.md +10 -4
  43. package/docs/guide.md +404 -0
  44. package/docs/signaling-and-production.md +312 -0
  45. package/docs/voice-and-media.md +193 -0
  46. package/package.json +3 -2
package/dist/voice.js CHANGED
@@ -1,10 +1,7 @@
1
- import { bindAbort, createListeners } from './listeners.js';
1
+ import { bindAbort, createListeners, reportAsyncError } from './listeners.js';
2
2
  import { getRoomRemoteStreams, isRoomClosed, onRoomClose } from './room.js';
3
- const defaultAudioConstraints = Object.freeze({
4
- echoCancellation: true,
5
- noiseSuppression: true,
6
- autoGainControl: true
7
- });
3
+ import { applyAudioVolume, buildAudioConstraints, classifyMicError, defaultAudioConstraints, evictPeerPref, getIosAudioSession, normalizeDeviceIdArg, validatePeerIdArg } from './voice-helpers.js';
4
+ import { createVoiceMeter } from './voice-meter.js';
8
5
  const gestureEvents = ['pointerdown', 'pointerup', 'touchend', 'click', 'keydown'];
9
6
  const captureOpts = { capture: true };
10
7
  const maxRemoteStreamsPerPeer = 4;
@@ -15,57 +12,6 @@ const defaultSpeakingThreshold = 0.03;
15
12
  const defaultSpeakingIntervalMs = 180;
16
13
  const defaultStreamTag = 'voice';
17
14
  const streamTagPattern = /^[a-zA-Z0-9._-]{1,32}$/;
18
- function isAudioCtxPaused(ctx) {
19
- return ctx !== null && ctx.state !== 'running' && ctx.state !== 'closed';
20
- }
21
- function getIosAudioSession() {
22
- if (typeof navigator === 'undefined')
23
- return null;
24
- const session = navigator.audioSession;
25
- return session && typeof session === 'object' && typeof session.type === 'string' ? session : null;
26
- }
27
- function classifyMicError(err) {
28
- const name = err && typeof err === 'object' && 'name' in err ? String(err.name) : '';
29
- if (name === 'NotAllowedError' || name === 'PermissionDeniedError') {
30
- return Object.freeze({
31
- code: 'permission-denied',
32
- message: 'Microphone permission denied'
33
- });
34
- }
35
- if (name === 'NotFoundError' ||
36
- name === 'DevicesNotFoundError' ||
37
- name === 'OverconstrainedError' ||
38
- name === 'ConstraintNotSatisfiedError') {
39
- return Object.freeze({
40
- code: 'not-found',
41
- message: 'No matching microphone device found'
42
- });
43
- }
44
- if (name === 'NotReadableError' || name === 'TrackStartError') {
45
- return Object.freeze({
46
- code: 'in-use',
47
- message: 'Microphone is already in use by another application'
48
- });
49
- }
50
- if (name === 'SecurityError') {
51
- return Object.freeze({
52
- code: 'insecure-context',
53
- message: 'Microphone access requires HTTPS or localhost'
54
- });
55
- }
56
- return Object.freeze({
57
- code: 'unknown',
58
- message: 'Could not access microphone'
59
- });
60
- }
61
- function normalizeDeviceIdArg(deviceId) {
62
- if (deviceId === undefined || deviceId === null || deviceId === '')
63
- return null;
64
- if (typeof deviceId !== 'string' || deviceId.trim().length === 0) {
65
- throw new TypeError('Expected deviceId to be a non-empty string, null, or undefined');
66
- }
67
- return deviceId;
68
- }
69
15
  /**
70
16
  * List available audio input (microphone) devices safely across browser and non-DOM runtimes.
71
17
  * Returns an empty frozen array if `navigator.mediaDevices.enumerateDevices()` is unavailable or rejects.
@@ -104,19 +50,24 @@ export async function listAudioInputs() {
104
50
  /**
105
51
  * Subscribe to `navigator.mediaDevices` `'devicechange'` events and receive the updated
106
52
  * `listAudioInputs()` array (guarded against out-of-order async enumerations and supporting `ListenOptions`).
53
+ * Pass `{ immediate: true }` to also deliver the initial device list through the same race guard.
107
54
  * Returns an idempotent unsubscribe function.
108
55
  */
109
56
  export function onAudioInputsChange(fn, options) {
110
57
  if (typeof fn !== 'function')
111
58
  throw new TypeError('Expected a listener function');
59
+ if (options?.immediate !== undefined && typeof options.immediate !== 'boolean') {
60
+ throw new TypeError('Expected immediate option to be a boolean');
61
+ }
112
62
  const signal = options?.signal;
113
63
  if (signal?.aborted)
114
64
  return () => { };
115
- if (typeof navigator === 'undefined' ||
116
- typeof navigator.mediaDevices?.addEventListener !== 'function') {
65
+ const immediate = options?.immediate ?? false;
66
+ const mediaDevices = typeof navigator !== 'undefined' ? navigator.mediaDevices : undefined;
67
+ const canListen = typeof mediaDevices?.addEventListener === 'function';
68
+ if (!canListen && !immediate) {
117
69
  return () => { };
118
70
  }
119
- const mediaDevices = navigator.mediaDevices;
120
71
  const once = Boolean(options?.once);
121
72
  let active = true;
122
73
  let epoch = 0;
@@ -127,11 +78,13 @@ export function onAudioInputsChange(fn, options) {
127
78
  active = false;
128
79
  epoch++;
129
80
  unbindAbort?.();
130
- try {
131
- mediaDevices.removeEventListener('devicechange', handleChange);
132
- }
133
- catch {
134
- // Ignore cleanup errors on restricted runtimes.
81
+ if (canListen) {
82
+ try {
83
+ mediaDevices.removeEventListener('devicechange', handleChange);
84
+ }
85
+ catch {
86
+ // Ignore cleanup errors on restricted runtimes.
87
+ }
135
88
  }
136
89
  };
137
90
  const handleChange = () => {
@@ -141,29 +94,24 @@ export function onAudioInputsChange(fn, options) {
141
94
  void listAudioInputs().then((devices) => {
142
95
  if (!active || myEpoch !== epoch)
143
96
  return;
144
- if (once)
97
+ if (once || !canListen)
145
98
  off();
146
99
  try {
147
100
  fn(devices);
148
101
  }
149
102
  catch (error) {
150
- globalThis.reportError?.(error);
103
+ reportAsyncError(error);
151
104
  }
152
105
  });
153
106
  };
154
- mediaDevices.addEventListener('devicechange', handleChange);
107
+ if (canListen) {
108
+ mediaDevices.addEventListener('devicechange', handleChange);
109
+ }
155
110
  unbindAbort = bindAbort(signal, off);
111
+ if (immediate)
112
+ handleChange();
156
113
  return off;
157
114
  }
158
- const listeners = createListeners;
159
- function applyAudioVolume(audio, volume) {
160
- try {
161
- audio.volume = volume;
162
- }
163
- catch {
164
- // Ignore read-only volume property on certain iOS WebKit builds.
165
- }
166
- }
167
115
  /**
168
116
  * Create a headless P2P voice chat controller attached to a `Room`.
169
117
  *
@@ -253,20 +201,6 @@ export function createVoice(room, options) {
253
201
  }
254
202
  }
255
203
  }
256
- function buildAudioConstraints(deviceOverride, exact) {
257
- if (deviceOverride !== null) {
258
- const base = typeof baseConstraints === 'object'
259
- ? { ...baseConstraints }
260
- : { ...defaultAudioConstraints };
261
- base.deviceId = exact ? { exact: deviceOverride } : { ideal: deviceOverride };
262
- return base;
263
- }
264
- if (baseConstraints === true)
265
- return true;
266
- const copy = { ...baseConstraints };
267
- delete copy.deviceId;
268
- return copy;
269
- }
270
204
  let volume = initialVolume;
271
205
  let deafened = Boolean(options?.deafened);
272
206
  let micStatus = 'off';
@@ -283,8 +217,6 @@ export function createVoice(room, options) {
283
217
  let swapQueue = Promise.resolve();
284
218
  let audioSessionSwitched = false;
285
219
  let prevAudioSessionType = null;
286
- let audioCtx = null;
287
- let silentSink = null;
288
220
  let meterTimer;
289
221
  let gestureListenersAttached = false;
290
222
  let visibilityListenerAttached = false;
@@ -292,18 +224,21 @@ export function createVoice(room, options) {
292
224
  const speakingPeers = new Set();
293
225
  const peerVolumes = new Map();
294
226
  const mutedPeers = new Set();
295
- const changes = listeners();
227
+ const changes = createListeners();
228
+ const meter = createVoiceMeter({
229
+ enabled: speakingDetection,
230
+ threshold: speakingThreshold,
231
+ isClosed: () => closed,
232
+ onContextPaused: attachGestureListeners,
233
+ onContextRunning: reconcileUnlockState
234
+ });
235
+ const buildConstraints = (deviceOverride, exact) => buildAudioConstraints(baseConstraints, deviceOverride, exact);
296
236
  function effectiveVolumeFor(peerId) {
297
237
  return Math.max(0, Math.min(1, volume * (peerVolumes.get(peerId) ?? 1)));
298
238
  }
299
239
  function effectiveMutedFor(peerId) {
300
240
  return deafened || mutedPeers.has(peerId);
301
241
  }
302
- function validatePeerIdArg(peerId) {
303
- if (typeof peerId !== 'string' || peerId.length === 0 || peerId.length > 128) {
304
- throw new TypeError('Expected a non-empty peerId string');
305
- }
306
- }
307
242
  function buildPeerVolumes() {
308
243
  return Object.freeze(Object.fromEntries(peerVolumes));
309
244
  }
@@ -403,7 +338,7 @@ export function createVoice(room, options) {
403
338
  autoplayBlocked = false;
404
339
  changed = true;
405
340
  }
406
- if (!autoplayBlocked && !isAudioCtxPaused(audioCtx)) {
341
+ if (!autoplayBlocked && !meter.isPaused()) {
407
342
  detachGestureListeners();
408
343
  }
409
344
  if (changed)
@@ -441,14 +376,13 @@ export function createVoice(room, options) {
441
376
  // Never gate on an in-flight boolean or await audioCtx.resume(): on iOS Safari,
442
377
  // pointerdown is not a media activation gesture and leaves audioCtx.resume()
443
378
  // pending forever until a subsequent touchend/pointerup/click calls resume() again.
444
- function unlockAudio() {
379
+ function unlockRemoteAudio(reattachOnPausedCtx = false) {
445
380
  if (closed)
446
381
  return;
447
- if (isAudioCtxPaused(audioCtx)) {
448
- void audioCtx
449
- .resume()
450
- .then(() => reconcileUnlockState())
451
- .catch(() => { });
382
+ if (meter.isPaused()) {
383
+ meter.resume(reconcileUnlockState);
384
+ if (reattachOnPausedCtx)
385
+ attachGestureListeners();
452
386
  }
453
387
  let attemptedPlay = false;
454
388
  for (const [peerId, streams] of remotePeers) {
@@ -459,20 +393,12 @@ export function createVoice(room, options) {
459
393
  }
460
394
  }
461
395
  }
462
- if (!attemptedPlay) {
396
+ if (!attemptedPlay && !reattachOnPausedCtx) {
463
397
  reconcileUnlockState();
464
398
  }
465
399
  }
466
- function isAnalyserActive(entry) {
467
- if (!entry?.analyser || !entry.data)
468
- return false;
469
- entry.analyser.getByteTimeDomainData(entry.data);
470
- let sum = 0;
471
- for (let i = 0; i < entry.data.length; i++) {
472
- const d = (entry.data[i] - 128) / 128;
473
- sum += d * d;
474
- }
475
- return Math.sqrt(sum / entry.data.length) > speakingThreshold;
400
+ function unlockAudio() {
401
+ unlockRemoteAudio(false);
476
402
  }
477
403
  function ensureMeter() {
478
404
  if (!speakingDetection || closed || meterTimer !== undefined)
@@ -486,7 +412,7 @@ export function createVoice(room, options) {
486
412
  for (const [peerId, streams] of remotePeers) {
487
413
  let active = false;
488
414
  for (const entry of streams.values()) {
489
- if (isAnalyserActive(entry)) {
415
+ if (meter.isActive(entry)) {
490
416
  active = true;
491
417
  break;
492
418
  }
@@ -501,7 +427,7 @@ export function createVoice(room, options) {
501
427
  changed = true;
502
428
  }
503
429
  }
504
- const nextSelf = micStatus === 'live' && isAnalyserActive(localMeter);
430
+ const nextSelf = micStatus === 'live' && meter.isActive(localMeter);
505
431
  if (nextSelf !== selfSpeaking) {
506
432
  selfSpeaking = nextSelf;
507
433
  changed = true;
@@ -514,7 +440,7 @@ export function createVoice(room, options) {
514
440
  if (remotePeers.size === 0) {
515
441
  speakingPeers.clear();
516
442
  autoplayBlocked = false;
517
- if (!isAudioCtxPaused(audioCtx)) {
443
+ if (!meter.isPaused()) {
518
444
  detachGestureListeners();
519
445
  }
520
446
  }
@@ -524,62 +450,16 @@ export function createVoice(room, options) {
524
450
  clearInterval(meterTimer);
525
451
  meterTimer = undefined;
526
452
  }
527
- if (audioCtx) {
528
- const ctx = audioCtx;
529
- audioCtx = null;
530
- silentSink?.disconnect();
531
- silentSink = null;
532
- ctx.onstatechange = null;
533
- void ctx.close().catch(() => { });
534
- }
453
+ meter.closeContext();
535
454
  detachGestureListeners();
536
455
  }
537
- function createAnalyser(stream) {
538
- if (!speakingDetection || typeof AudioContext !== 'function')
539
- return {};
540
- try {
541
- if (!audioCtx) {
542
- const rawCtx = new AudioContext();
543
- const ctx = rawCtx;
544
- rawCtx.onstatechange = () => {
545
- if (closed || audioCtx !== ctx)
546
- return;
547
- if (isAudioCtxPaused(ctx))
548
- attachGestureListeners();
549
- else
550
- reconcileUnlockState();
551
- };
552
- const gain = rawCtx.createGain();
553
- gain.gain.value = 0;
554
- gain.connect(rawCtx.destination);
555
- audioCtx = ctx;
556
- silentSink = gain;
557
- }
558
- if (isAudioCtxPaused(audioCtx)) {
559
- void audioCtx.resume().catch(() => { });
560
- attachGestureListeners();
561
- }
562
- const rawCtx = audioCtx;
563
- const source = rawCtx.createMediaStreamSource(stream);
564
- const analyser = rawCtx.createAnalyser();
565
- analyser.fftSize = 256;
566
- source.connect(analyser);
567
- if (silentSink)
568
- analyser.connect(silentSink);
569
- return { source, analyser, data: new Uint8Array(analyser.fftSize) };
570
- }
571
- catch {
572
- return {};
573
- }
574
- }
575
456
  function teardownLocalStream(detachFromRoom) {
576
457
  let changed = false;
577
458
  for (const cleanup of localTrackCleanups)
578
459
  cleanup();
579
460
  localTrackCleanups = [];
580
461
  if (localMeter) {
581
- localMeter.source?.disconnect();
582
- localMeter.analyser?.disconnect();
462
+ meter.disconnect(localMeter);
583
463
  localMeter = null;
584
464
  }
585
465
  if (selfSpeaking) {
@@ -629,19 +509,39 @@ export function createVoice(room, options) {
629
509
  localTrackCleanups.push(() => track.removeEventListener('ended', onTrackEnded));
630
510
  }
631
511
  }
512
+ function failMic(error) {
513
+ restoreAudioSession();
514
+ micStatus = 'error';
515
+ micError = error;
516
+ emitChange();
517
+ return 'error';
518
+ }
519
+ function applySoftMute(muted) {
520
+ if (closed || !localStream)
521
+ return;
522
+ const next = Boolean(muted);
523
+ const nextStatus = next ? 'muted' : 'live';
524
+ if (micStatus === nextStatus)
525
+ return;
526
+ for (const track of localStream.getAudioTracks()) {
527
+ track.enabled = !next;
528
+ }
529
+ micStatus = nextStatus;
530
+ micError = null;
531
+ if (next)
532
+ selfSpeaking = false;
533
+ emitChange();
534
+ }
632
535
  function acquireMic() {
633
536
  if (closed)
634
537
  return Promise.resolve('off');
635
538
  if (inFlightMic)
636
539
  return inFlightMic;
637
540
  if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia) {
638
- micStatus = 'error';
639
- micError = Object.freeze({
541
+ return Promise.resolve(failMic(Object.freeze({
640
542
  code: 'insecure-context',
641
543
  message: 'Microphone access requires HTTPS or localhost'
642
- });
643
- emitChange();
644
- return Promise.resolve('error');
544
+ })));
645
545
  }
646
546
  const epoch = ++micEpoch;
647
547
  const requestedDeviceId = selectedDeviceId;
@@ -657,7 +557,7 @@ export function createVoice(room, options) {
657
557
  let fellBackToDefault = false;
658
558
  try {
659
559
  stream = await navigator.mediaDevices.getUserMedia({
660
- audio: buildAudioConstraints(requestedDeviceId, requestedDeviceExact)
560
+ audio: buildConstraints(requestedDeviceId, requestedDeviceExact)
661
561
  });
662
562
  }
663
563
  catch (err) {
@@ -669,40 +569,25 @@ export function createVoice(room, options) {
669
569
  classified.code === 'not-found') {
670
570
  try {
671
571
  stream = await navigator.mediaDevices.getUserMedia({
672
- audio: buildAudioConstraints(null, false)
572
+ audio: buildConstraints(null, false)
673
573
  });
674
574
  fellBackToDefault = true;
675
575
  }
676
576
  catch (fallbackErr) {
677
577
  if (closed || epoch !== micEpoch)
678
578
  return 'off';
679
- restoreAudioSession();
680
- micStatus = 'error';
681
- micError = classifyMicError(fallbackErr);
682
- emitChange();
683
- return 'error';
579
+ return failMic(classifyMicError(fallbackErr));
684
580
  }
685
581
  }
686
582
  else {
687
- restoreAudioSession();
688
- micStatus = 'error';
689
- micError = classified;
690
- emitChange();
691
- return 'error';
583
+ return failMic(classified);
692
584
  }
693
585
  }
694
586
  if (closed || epoch !== micEpoch || isRoomClosed(room)) {
695
587
  for (const track of stream.getTracks())
696
588
  track.stop();
697
589
  if (!closed && epoch === micEpoch) {
698
- restoreAudioSession();
699
- micStatus = 'error';
700
- micError = Object.freeze({
701
- code: 'room-closed',
702
- message: 'Room is closed'
703
- });
704
- emitChange();
705
- return 'error';
590
+ return failMic(Object.freeze({ code: 'room-closed', message: 'Room is closed' }));
706
591
  }
707
592
  return 'off';
708
593
  }
@@ -713,16 +598,9 @@ export function createVoice(room, options) {
713
598
  });
714
599
  }
715
600
  catch {
716
- restoreAudioSession();
717
601
  for (const track of stream.getTracks())
718
602
  track.stop();
719
- micStatus = 'error';
720
- micError = Object.freeze({
721
- code: 'room-closed',
722
- message: 'Room is closed'
723
- });
724
- emitChange();
725
- return 'error';
603
+ return failMic(Object.freeze({ code: 'room-closed', message: 'Room is closed' }));
726
604
  }
727
605
  localStream = stream;
728
606
  const actualDeviceId = stream.getAudioTracks()[0]?.getSettings?.().deviceId;
@@ -737,8 +615,8 @@ export function createVoice(room, options) {
737
615
  micStatus = 'live';
738
616
  micError = null;
739
617
  bindLocalTrackEnded(stream);
740
- const meter = createAnalyser(stream);
741
- localMeter = meter.analyser ? meter : null;
618
+ const m = meter.createAnalyser(stream);
619
+ localMeter = m.analyser ? m : null;
742
620
  ensureMeter();
743
621
  unlockAudio();
744
622
  emitChange();
@@ -753,8 +631,7 @@ export function createVoice(room, options) {
753
631
  return promise;
754
632
  }
755
633
  function teardownRemoteEntry(entry) {
756
- entry.source?.disconnect();
757
- entry.analyser?.disconnect();
634
+ meter.disconnect(entry);
758
635
  try {
759
636
  entry.audio.pause();
760
637
  }
@@ -791,8 +668,8 @@ export function createVoice(room, options) {
791
668
  applyAudioVolume(audio, effectiveVolumeFor(peerId));
792
669
  audio.srcObject = stream;
793
670
  document.body.append(audio);
794
- const meter = createAnalyser(stream);
795
- const entry = { audio, blocked: false, ...meter };
671
+ const m = meter.createAnalyser(stream);
672
+ const entry = { audio, blocked: false, ...m };
796
673
  byPeer.set(stream.id, entry);
797
674
  const onPlaybackAccepted = () => {
798
675
  if (closed || remotePeers.get(peerId)?.get(stream.id) !== entry || entry.audio.paused)
@@ -826,20 +703,7 @@ export function createVoice(room, options) {
826
703
  const onVisibilityChange = () => {
827
704
  if (closed || typeof document === 'undefined' || document.visibilityState !== 'visible')
828
705
  return;
829
- if (isAudioCtxPaused(audioCtx)) {
830
- void audioCtx
831
- .resume()
832
- .then(() => reconcileUnlockState())
833
- .catch(() => { });
834
- attachGestureListeners();
835
- }
836
- for (const [peerId, streams] of remotePeers) {
837
- for (const [streamId, entry] of streams) {
838
- if (entry.audio.paused) {
839
- tryPlayEntry(peerId, streamId, entry);
840
- }
841
- }
842
- }
706
+ unlockRemoteAudio(true);
843
707
  };
844
708
  function closeInternal(roomClosing) {
845
709
  if (closed)
@@ -930,15 +794,7 @@ export function createVoice(room, options) {
930
794
  if (inFlightMic)
931
795
  return inFlightMic;
932
796
  if (localStream) {
933
- const nextMuted = micStatus === 'live';
934
- for (const track of localStream.getAudioTracks()) {
935
- track.enabled = !nextMuted;
936
- }
937
- micStatus = nextMuted ? 'muted' : 'live';
938
- micError = null;
939
- if (nextMuted)
940
- selfSpeaking = false;
941
- emitChange();
797
+ applySoftMute(micStatus === 'live');
942
798
  return Promise.resolve(micStatus);
943
799
  }
944
800
  return acquireMic();
@@ -949,34 +805,12 @@ export function createVoice(room, options) {
949
805
  if (inFlightMic)
950
806
  return inFlightMic;
951
807
  if (localStream) {
952
- if (micStatus === 'muted') {
953
- for (const track of localStream.getAudioTracks()) {
954
- track.enabled = true;
955
- }
956
- micStatus = 'live';
957
- micError = null;
958
- emitChange();
959
- }
808
+ applySoftMute(false);
960
809
  return Promise.resolve('live');
961
810
  }
962
811
  return acquireMic();
963
812
  },
964
- setMuted(muted) {
965
- if (closed || !localStream)
966
- return;
967
- const next = Boolean(muted);
968
- const nextStatus = next ? 'muted' : 'live';
969
- if (micStatus === nextStatus)
970
- return;
971
- for (const track of localStream.getAudioTracks()) {
972
- track.enabled = !next;
973
- }
974
- micStatus = nextStatus;
975
- micError = null;
976
- if (next)
977
- selfSpeaking = false;
978
- emitChange();
979
- },
813
+ setMuted: applySoftMute,
980
814
  stopMic() {
981
815
  if (closed)
982
816
  return;
@@ -1027,10 +861,11 @@ export function createVoice(room, options) {
1027
861
  }
1028
862
  const epoch = micEpoch;
1029
863
  const sEpoch = ++switchEpoch;
864
+ const isStale = () => closed || epoch !== micEpoch || sEpoch !== switchEpoch || !localStream || isRoomClosed(room);
1030
865
  let newStream;
1031
866
  try {
1032
867
  newStream = await navigator.mediaDevices.getUserMedia({
1033
- audio: buildAudioConstraints(nextDeviceId, nextDeviceId !== null)
868
+ audio: buildConstraints(nextDeviceId, nextDeviceId !== null)
1034
869
  });
1035
870
  }
1036
871
  catch (err) {
@@ -1042,22 +877,14 @@ export function createVoice(room, options) {
1042
877
  emitChange();
1043
878
  return micStatus;
1044
879
  }
1045
- if (closed ||
1046
- epoch !== micEpoch ||
1047
- sEpoch !== switchEpoch ||
1048
- !localStream ||
1049
- isRoomClosed(room)) {
880
+ if (isStale()) {
1050
881
  for (const t of newStream.getTracks())
1051
882
  t.stop();
1052
883
  return closed ? 'off' : micStatus;
1053
884
  }
1054
885
  let resultStatus = micStatus;
1055
886
  const runSwap = swapQueue.then(async () => {
1056
- if (closed ||
1057
- epoch !== micEpoch ||
1058
- sEpoch !== switchEpoch ||
1059
- !localStream ||
1060
- isRoomClosed(room)) {
887
+ if (isStale()) {
1061
888
  for (const t of newStream.getTracks())
1062
889
  t.stop();
1063
890
  resultStatus = closed ? 'off' : micStatus;
@@ -1080,13 +907,11 @@ export function createVoice(room, options) {
1080
907
  for (const cleanup of localTrackCleanups)
1081
908
  cleanup();
1082
909
  localTrackCleanups = [];
1083
- let replaceInvoked = false;
1084
910
  try {
1085
- replaceInvoked = true;
1086
911
  await room.replaceStreamTrack(targetStream, oldTrack, newTrack);
1087
912
  }
1088
913
  catch (err) {
1089
- if (replaceInvoked && !targetStream.getTracks().includes(oldTrack)) {
914
+ if (!targetStream.getTracks().includes(oldTrack)) {
1090
915
  oldTrack.stop();
1091
916
  }
1092
917
  newTrack.stop();
@@ -1118,12 +943,11 @@ export function createVoice(room, options) {
1118
943
  }
1119
944
  bindLocalTrackEnded(targetStream);
1120
945
  if (localMeter) {
1121
- localMeter.source?.disconnect();
1122
- localMeter.analyser?.disconnect();
946
+ meter.disconnect(localMeter);
1123
947
  localMeter = null;
1124
948
  }
1125
- const meter = createAnalyser(targetStream);
1126
- localMeter = meter.analyser ? meter : null;
949
+ const m = meter.createAnalyser(targetStream);
950
+ localMeter = m.analyser ? m : null;
1127
951
  ensureMeter();
1128
952
  const actualDeviceId = newTrack.getSettings?.().deviceId;
1129
953
  selectedDeviceId =
@@ -1171,17 +995,8 @@ export function createVoice(room, options) {
1171
995
  peerVolumes.delete(peerId);
1172
996
  }
1173
997
  else {
1174
- if (!peerVolumes.has(peerId) && peerVolumes.size >= maxPeerAudioPrefs) {
1175
- let victim;
1176
- for (const k of peerVolumes.keys()) {
1177
- if (!remotePeers.has(k)) {
1178
- victim = k;
1179
- break;
1180
- }
1181
- }
1182
- victim ??= peerVolumes.keys().next().value;
1183
- if (victim !== undefined)
1184
- peerVolumes.delete(victim);
998
+ if (!peerVolumes.has(peerId)) {
999
+ evictPeerPref(peerVolumes, remotePeers, maxPeerAudioPrefs);
1185
1000
  }
1186
1001
  peerVolumes.delete(peerId);
1187
1002
  peerVolumes.set(peerId, clamped);
@@ -1226,18 +1041,7 @@ export function createVoice(room, options) {
1226
1041
  if (next === was)
1227
1042
  return;
1228
1043
  if (next) {
1229
- if (mutedPeers.size >= maxPeerAudioPrefs) {
1230
- let victim;
1231
- for (const k of mutedPeers) {
1232
- if (!remotePeers.has(k)) {
1233
- victim = k;
1234
- break;
1235
- }
1236
- }
1237
- victim ??= mutedPeers.values().next().value;
1238
- if (victim !== undefined)
1239
- mutedPeers.delete(victim);
1240
- }
1044
+ evictPeerPref(mutedPeers, remotePeers, maxPeerAudioPrefs);
1241
1045
  mutedPeers.add(peerId);
1242
1046
  }
1243
1047
  else {