@dimchansky/meshpost 0.4.2 → 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 -550
  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 +25 -39
  8. package/dist/crypto.js +10 -9
  9. package/dist/identity.d.ts +45 -0
  10. package/dist/identity.js +188 -28
  11. package/dist/index.d.ts +6 -6
  12. package/dist/index.js +3 -3
  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 +19 -1
  17. package/dist/public.js +26 -9
  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 +41 -0
  39. package/dist/voice.js +205 -273
  40. package/dist/ws.js +60 -146
  41. package/docs/api.md +217 -0
  42. package/docs/behavior.md +16 -9
  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 { 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,105 @@ 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
- });
15
+ /**
16
+ * List available audio input (microphone) devices safely across browser and non-DOM runtimes.
17
+ * Returns an empty frozen array if `navigator.mediaDevices.enumerateDevices()` is unavailable or rejects.
18
+ * Entries are deduplicated by non-empty `deviceId` and returned with trimmed labels (may be `''` before first `getUserMedia`).
19
+ */
20
+ export async function listAudioInputs() {
21
+ if (typeof navigator === 'undefined' ||
22
+ typeof navigator.mediaDevices?.enumerateDevices !== 'function') {
23
+ return Object.freeze([]);
34
24
  }
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
- });
25
+ let raw;
26
+ try {
27
+ raw = await navigator.mediaDevices.enumerateDevices();
43
28
  }
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
- });
29
+ catch {
30
+ return Object.freeze([]);
49
31
  }
50
- if (name === 'SecurityError') {
51
- return Object.freeze({
52
- code: 'insecure-context',
53
- message: 'Microphone access requires HTTPS or localhost'
54
- });
32
+ const seen = new Set();
33
+ const result = [];
34
+ for (const dev of raw) {
35
+ if (!dev || dev.kind !== 'audioinput')
36
+ continue;
37
+ if (typeof dev.deviceId !== 'string' || dev.deviceId.length === 0)
38
+ continue;
39
+ if (seen.has(dev.deviceId))
40
+ continue;
41
+ seen.add(dev.deviceId);
42
+ result.push(Object.freeze({
43
+ deviceId: dev.deviceId,
44
+ label: typeof dev.label === 'string' ? dev.label.trim() : '',
45
+ groupId: typeof dev.groupId === 'string' ? dev.groupId : ''
46
+ }));
55
47
  }
56
- return Object.freeze({
57
- code: 'unknown',
58
- message: 'Could not access microphone'
59
- });
48
+ return Object.freeze(result);
60
49
  }
61
- const listeners = createListeners;
62
- function applyAudioVolume(audio, volume) {
63
- try {
64
- audio.volume = volume;
50
+ /**
51
+ * Subscribe to `navigator.mediaDevices` `'devicechange'` events and receive the updated
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.
54
+ * Returns an idempotent unsubscribe function.
55
+ */
56
+ export function onAudioInputsChange(fn, options) {
57
+ if (typeof fn !== 'function')
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');
65
61
  }
66
- catch {
67
- // Ignore read-only volume property on certain iOS WebKit builds.
62
+ const signal = options?.signal;
63
+ if (signal?.aborted)
64
+ return () => { };
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) {
69
+ return () => { };
68
70
  }
71
+ const once = Boolean(options?.once);
72
+ let active = true;
73
+ let epoch = 0;
74
+ let unbindAbort;
75
+ const off = () => {
76
+ if (!active)
77
+ return;
78
+ active = false;
79
+ epoch++;
80
+ unbindAbort?.();
81
+ if (canListen) {
82
+ try {
83
+ mediaDevices.removeEventListener('devicechange', handleChange);
84
+ }
85
+ catch {
86
+ // Ignore cleanup errors on restricted runtimes.
87
+ }
88
+ }
89
+ };
90
+ const handleChange = () => {
91
+ if (!active)
92
+ return;
93
+ const myEpoch = ++epoch;
94
+ void listAudioInputs().then((devices) => {
95
+ if (!active || myEpoch !== epoch)
96
+ return;
97
+ if (once || !canListen)
98
+ off();
99
+ try {
100
+ fn(devices);
101
+ }
102
+ catch (error) {
103
+ reportAsyncError(error);
104
+ }
105
+ });
106
+ };
107
+ if (canListen) {
108
+ mediaDevices.addEventListener('devicechange', handleChange);
109
+ }
110
+ unbindAbort = bindAbort(signal, off);
111
+ if (immediate)
112
+ handleChange();
113
+ return off;
69
114
  }
70
115
  /**
71
116
  * Create a headless P2P voice chat controller attached to a `Room`.
@@ -126,11 +171,20 @@ export function createVoice(room, options) {
126
171
  throw new TypeError('Expected strictStreamTag to be a boolean');
127
172
  }
128
173
  const strictStreamTag = options?.strictStreamTag ?? false;
174
+ if (options?.fallbackToDefaultOnNotFound !== undefined &&
175
+ typeof options.fallbackToDefaultOnNotFound !== 'boolean') {
176
+ throw new TypeError('Expected fallbackToDefaultOnNotFound to be a boolean');
177
+ }
178
+ const fallbackToDefaultOnNotFound = options?.fallbackToDefaultOnNotFound ?? false;
129
179
  const autoUnlock = options?.autoUnlock !== false;
130
180
  const speakingDetection = options?.speakingDetection !== false;
131
181
  let selectedDeviceId = null;
132
182
  let selectedDeviceExact = false;
133
- if (typeof baseConstraints === 'object' && baseConstraints.deviceId !== undefined) {
183
+ if (options?.deviceId !== undefined) {
184
+ selectedDeviceId = normalizeDeviceIdArg(options.deviceId);
185
+ selectedDeviceExact = selectedDeviceId !== null;
186
+ }
187
+ else if (typeof baseConstraints === 'object' && baseConstraints.deviceId !== undefined) {
134
188
  const rawDev = baseConstraints.deviceId;
135
189
  if (typeof rawDev === 'string' && rawDev.trim().length > 0) {
136
190
  selectedDeviceId = rawDev;
@@ -147,20 +201,6 @@ export function createVoice(room, options) {
147
201
  }
148
202
  }
149
203
  }
150
- function buildAudioConstraints(deviceOverride, exact) {
151
- if (deviceOverride !== null) {
152
- const base = typeof baseConstraints === 'object'
153
- ? { ...baseConstraints }
154
- : { ...defaultAudioConstraints };
155
- base.deviceId = exact ? { exact: deviceOverride } : { ideal: deviceOverride };
156
- return base;
157
- }
158
- if (baseConstraints === true)
159
- return true;
160
- const copy = { ...baseConstraints };
161
- delete copy.deviceId;
162
- return copy;
163
- }
164
204
  let volume = initialVolume;
165
205
  let deafened = Boolean(options?.deafened);
166
206
  let micStatus = 'off';
@@ -177,8 +217,6 @@ export function createVoice(room, options) {
177
217
  let swapQueue = Promise.resolve();
178
218
  let audioSessionSwitched = false;
179
219
  let prevAudioSessionType = null;
180
- let audioCtx = null;
181
- let silentSink = null;
182
220
  let meterTimer;
183
221
  let gestureListenersAttached = false;
184
222
  let visibilityListenerAttached = false;
@@ -186,18 +224,21 @@ export function createVoice(room, options) {
186
224
  const speakingPeers = new Set();
187
225
  const peerVolumes = new Map();
188
226
  const mutedPeers = new Set();
189
- 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);
190
236
  function effectiveVolumeFor(peerId) {
191
237
  return Math.max(0, Math.min(1, volume * (peerVolumes.get(peerId) ?? 1)));
192
238
  }
193
239
  function effectiveMutedFor(peerId) {
194
240
  return deafened || mutedPeers.has(peerId);
195
241
  }
196
- function validatePeerIdArg(peerId) {
197
- if (typeof peerId !== 'string' || peerId.length === 0 || peerId.length > 128) {
198
- throw new TypeError('Expected a non-empty peerId string');
199
- }
200
- }
201
242
  function buildPeerVolumes() {
202
243
  return Object.freeze(Object.fromEntries(peerVolumes));
203
244
  }
@@ -297,7 +338,7 @@ export function createVoice(room, options) {
297
338
  autoplayBlocked = false;
298
339
  changed = true;
299
340
  }
300
- if (!autoplayBlocked && !isAudioCtxPaused(audioCtx)) {
341
+ if (!autoplayBlocked && !meter.isPaused()) {
301
342
  detachGestureListeners();
302
343
  }
303
344
  if (changed)
@@ -335,14 +376,13 @@ export function createVoice(room, options) {
335
376
  // Never gate on an in-flight boolean or await audioCtx.resume(): on iOS Safari,
336
377
  // pointerdown is not a media activation gesture and leaves audioCtx.resume()
337
378
  // pending forever until a subsequent touchend/pointerup/click calls resume() again.
338
- function unlockAudio() {
379
+ function unlockRemoteAudio(reattachOnPausedCtx = false) {
339
380
  if (closed)
340
381
  return;
341
- if (isAudioCtxPaused(audioCtx)) {
342
- void audioCtx
343
- .resume()
344
- .then(() => reconcileUnlockState())
345
- .catch(() => { });
382
+ if (meter.isPaused()) {
383
+ meter.resume(reconcileUnlockState);
384
+ if (reattachOnPausedCtx)
385
+ attachGestureListeners();
346
386
  }
347
387
  let attemptedPlay = false;
348
388
  for (const [peerId, streams] of remotePeers) {
@@ -353,20 +393,12 @@ export function createVoice(room, options) {
353
393
  }
354
394
  }
355
395
  }
356
- if (!attemptedPlay) {
396
+ if (!attemptedPlay && !reattachOnPausedCtx) {
357
397
  reconcileUnlockState();
358
398
  }
359
399
  }
360
- function isAnalyserActive(entry) {
361
- if (!entry?.analyser || !entry.data)
362
- return false;
363
- entry.analyser.getByteTimeDomainData(entry.data);
364
- let sum = 0;
365
- for (let i = 0; i < entry.data.length; i++) {
366
- const d = (entry.data[i] - 128) / 128;
367
- sum += d * d;
368
- }
369
- return Math.sqrt(sum / entry.data.length) > speakingThreshold;
400
+ function unlockAudio() {
401
+ unlockRemoteAudio(false);
370
402
  }
371
403
  function ensureMeter() {
372
404
  if (!speakingDetection || closed || meterTimer !== undefined)
@@ -380,7 +412,7 @@ export function createVoice(room, options) {
380
412
  for (const [peerId, streams] of remotePeers) {
381
413
  let active = false;
382
414
  for (const entry of streams.values()) {
383
- if (isAnalyserActive(entry)) {
415
+ if (meter.isActive(entry)) {
384
416
  active = true;
385
417
  break;
386
418
  }
@@ -395,7 +427,7 @@ export function createVoice(room, options) {
395
427
  changed = true;
396
428
  }
397
429
  }
398
- const nextSelf = micStatus === 'live' && isAnalyserActive(localMeter);
430
+ const nextSelf = micStatus === 'live' && meter.isActive(localMeter);
399
431
  if (nextSelf !== selfSpeaking) {
400
432
  selfSpeaking = nextSelf;
401
433
  changed = true;
@@ -408,7 +440,7 @@ export function createVoice(room, options) {
408
440
  if (remotePeers.size === 0) {
409
441
  speakingPeers.clear();
410
442
  autoplayBlocked = false;
411
- if (!isAudioCtxPaused(audioCtx)) {
443
+ if (!meter.isPaused()) {
412
444
  detachGestureListeners();
413
445
  }
414
446
  }
@@ -418,62 +450,16 @@ export function createVoice(room, options) {
418
450
  clearInterval(meterTimer);
419
451
  meterTimer = undefined;
420
452
  }
421
- if (audioCtx) {
422
- const ctx = audioCtx;
423
- audioCtx = null;
424
- silentSink?.disconnect();
425
- silentSink = null;
426
- ctx.onstatechange = null;
427
- void ctx.close().catch(() => { });
428
- }
453
+ meter.closeContext();
429
454
  detachGestureListeners();
430
455
  }
431
- function createAnalyser(stream) {
432
- if (!speakingDetection || typeof AudioContext !== 'function')
433
- return {};
434
- try {
435
- if (!audioCtx) {
436
- const rawCtx = new AudioContext();
437
- const ctx = rawCtx;
438
- rawCtx.onstatechange = () => {
439
- if (closed || audioCtx !== ctx)
440
- return;
441
- if (isAudioCtxPaused(ctx))
442
- attachGestureListeners();
443
- else
444
- reconcileUnlockState();
445
- };
446
- const gain = rawCtx.createGain();
447
- gain.gain.value = 0;
448
- gain.connect(rawCtx.destination);
449
- audioCtx = ctx;
450
- silentSink = gain;
451
- }
452
- if (isAudioCtxPaused(audioCtx)) {
453
- void audioCtx.resume().catch(() => { });
454
- attachGestureListeners();
455
- }
456
- const rawCtx = audioCtx;
457
- const source = rawCtx.createMediaStreamSource(stream);
458
- const analyser = rawCtx.createAnalyser();
459
- analyser.fftSize = 256;
460
- source.connect(analyser);
461
- if (silentSink)
462
- analyser.connect(silentSink);
463
- return { source, analyser, data: new Uint8Array(analyser.fftSize) };
464
- }
465
- catch {
466
- return {};
467
- }
468
- }
469
456
  function teardownLocalStream(detachFromRoom) {
470
457
  let changed = false;
471
458
  for (const cleanup of localTrackCleanups)
472
459
  cleanup();
473
460
  localTrackCleanups = [];
474
461
  if (localMeter) {
475
- localMeter.source?.disconnect();
476
- localMeter.analyser?.disconnect();
462
+ meter.disconnect(localMeter);
477
463
  localMeter = null;
478
464
  }
479
465
  if (selfSpeaking) {
@@ -523,19 +509,39 @@ export function createVoice(room, options) {
523
509
  localTrackCleanups.push(() => track.removeEventListener('ended', onTrackEnded));
524
510
  }
525
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
+ }
526
535
  function acquireMic() {
527
536
  if (closed)
528
537
  return Promise.resolve('off');
529
538
  if (inFlightMic)
530
539
  return inFlightMic;
531
540
  if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia) {
532
- micStatus = 'error';
533
- micError = Object.freeze({
541
+ return Promise.resolve(failMic(Object.freeze({
534
542
  code: 'insecure-context',
535
543
  message: 'Microphone access requires HTTPS or localhost'
536
- });
537
- emitChange();
538
- return Promise.resolve('error');
544
+ })));
539
545
  }
540
546
  const epoch = ++micEpoch;
541
547
  const requestedDeviceId = selectedDeviceId;
@@ -548,32 +554,40 @@ export function createVoice(room, options) {
548
554
  switchAudioSessionForMic();
549
555
  const promise = (async () => {
550
556
  let stream;
557
+ let fellBackToDefault = false;
551
558
  try {
552
559
  stream = await navigator.mediaDevices.getUserMedia({
553
- audio: buildAudioConstraints(requestedDeviceId, requestedDeviceExact)
560
+ audio: buildConstraints(requestedDeviceId, requestedDeviceExact)
554
561
  });
555
562
  }
556
563
  catch (err) {
557
564
  if (closed || epoch !== micEpoch)
558
565
  return 'off';
559
- restoreAudioSession();
560
- micStatus = 'error';
561
- micError = classifyMicError(err);
562
- emitChange();
563
- return 'error';
566
+ const classified = classifyMicError(err);
567
+ if (fallbackToDefaultOnNotFound &&
568
+ requestedDeviceId !== null &&
569
+ classified.code === 'not-found') {
570
+ try {
571
+ stream = await navigator.mediaDevices.getUserMedia({
572
+ audio: buildConstraints(null, false)
573
+ });
574
+ fellBackToDefault = true;
575
+ }
576
+ catch (fallbackErr) {
577
+ if (closed || epoch !== micEpoch)
578
+ return 'off';
579
+ return failMic(classifyMicError(fallbackErr));
580
+ }
581
+ }
582
+ else {
583
+ return failMic(classified);
584
+ }
564
585
  }
565
586
  if (closed || epoch !== micEpoch || isRoomClosed(room)) {
566
587
  for (const track of stream.getTracks())
567
588
  track.stop();
568
589
  if (!closed && epoch === micEpoch) {
569
- restoreAudioSession();
570
- micStatus = 'error';
571
- micError = Object.freeze({
572
- code: 'room-closed',
573
- message: 'Room is closed'
574
- });
575
- emitChange();
576
- return 'error';
590
+ return failMic(Object.freeze({ code: 'room-closed', message: 'Room is closed' }));
577
591
  }
578
592
  return 'off';
579
593
  }
@@ -584,27 +598,25 @@ export function createVoice(room, options) {
584
598
  });
585
599
  }
586
600
  catch {
587
- restoreAudioSession();
588
601
  for (const track of stream.getTracks())
589
602
  track.stop();
590
- micStatus = 'error';
591
- micError = Object.freeze({
592
- code: 'room-closed',
593
- message: 'Room is closed'
594
- });
595
- emitChange();
596
- return 'error';
603
+ return failMic(Object.freeze({ code: 'room-closed', message: 'Room is closed' }));
597
604
  }
598
605
  localStream = stream;
599
606
  const actualDeviceId = stream.getAudioTracks()[0]?.getSettings?.().deviceId;
600
- selectedDeviceId =
601
- requestedDeviceId ??
602
- (typeof actualDeviceId === 'string' && actualDeviceId.length > 0 ? actualDeviceId : null);
607
+ const resolvedActual = typeof actualDeviceId === 'string' && actualDeviceId.length > 0 ? actualDeviceId : null;
608
+ if (fellBackToDefault) {
609
+ selectedDeviceId = resolvedActual;
610
+ selectedDeviceExact = false;
611
+ }
612
+ else {
613
+ selectedDeviceId = requestedDeviceId ?? resolvedActual;
614
+ }
603
615
  micStatus = 'live';
604
616
  micError = null;
605
617
  bindLocalTrackEnded(stream);
606
- const meter = createAnalyser(stream);
607
- localMeter = meter.analyser ? meter : null;
618
+ const m = meter.createAnalyser(stream);
619
+ localMeter = m.analyser ? m : null;
608
620
  ensureMeter();
609
621
  unlockAudio();
610
622
  emitChange();
@@ -619,8 +631,7 @@ export function createVoice(room, options) {
619
631
  return promise;
620
632
  }
621
633
  function teardownRemoteEntry(entry) {
622
- entry.source?.disconnect();
623
- entry.analyser?.disconnect();
634
+ meter.disconnect(entry);
624
635
  try {
625
636
  entry.audio.pause();
626
637
  }
@@ -657,8 +668,8 @@ export function createVoice(room, options) {
657
668
  applyAudioVolume(audio, effectiveVolumeFor(peerId));
658
669
  audio.srcObject = stream;
659
670
  document.body.append(audio);
660
- const meter = createAnalyser(stream);
661
- const entry = { audio, blocked: false, ...meter };
671
+ const m = meter.createAnalyser(stream);
672
+ const entry = { audio, blocked: false, ...m };
662
673
  byPeer.set(stream.id, entry);
663
674
  const onPlaybackAccepted = () => {
664
675
  if (closed || remotePeers.get(peerId)?.get(stream.id) !== entry || entry.audio.paused)
@@ -692,20 +703,7 @@ export function createVoice(room, options) {
692
703
  const onVisibilityChange = () => {
693
704
  if (closed || typeof document === 'undefined' || document.visibilityState !== 'visible')
694
705
  return;
695
- if (isAudioCtxPaused(audioCtx)) {
696
- void audioCtx
697
- .resume()
698
- .then(() => reconcileUnlockState())
699
- .catch(() => { });
700
- attachGestureListeners();
701
- }
702
- for (const [peerId, streams] of remotePeers) {
703
- for (const [streamId, entry] of streams) {
704
- if (entry.audio.paused) {
705
- tryPlayEntry(peerId, streamId, entry);
706
- }
707
- }
708
- }
706
+ unlockRemoteAudio(true);
709
707
  };
710
708
  function closeInternal(roomClosing) {
711
709
  if (closed)
@@ -796,15 +794,7 @@ export function createVoice(room, options) {
796
794
  if (inFlightMic)
797
795
  return inFlightMic;
798
796
  if (localStream) {
799
- const nextMuted = micStatus === 'live';
800
- for (const track of localStream.getAudioTracks()) {
801
- track.enabled = !nextMuted;
802
- }
803
- micStatus = nextMuted ? 'muted' : 'live';
804
- micError = null;
805
- if (nextMuted)
806
- selfSpeaking = false;
807
- emitChange();
797
+ applySoftMute(micStatus === 'live');
808
798
  return Promise.resolve(micStatus);
809
799
  }
810
800
  return acquireMic();
@@ -815,34 +805,12 @@ export function createVoice(room, options) {
815
805
  if (inFlightMic)
816
806
  return inFlightMic;
817
807
  if (localStream) {
818
- if (micStatus === 'muted') {
819
- for (const track of localStream.getAudioTracks()) {
820
- track.enabled = true;
821
- }
822
- micStatus = 'live';
823
- micError = null;
824
- emitChange();
825
- }
808
+ applySoftMute(false);
826
809
  return Promise.resolve('live');
827
810
  }
828
811
  return acquireMic();
829
812
  },
830
- setMuted(muted) {
831
- if (closed || !localStream)
832
- return;
833
- const next = Boolean(muted);
834
- const nextStatus = next ? 'muted' : 'live';
835
- if (micStatus === nextStatus)
836
- return;
837
- for (const track of localStream.getAudioTracks()) {
838
- track.enabled = !next;
839
- }
840
- micStatus = nextStatus;
841
- micError = null;
842
- if (next)
843
- selfSpeaking = false;
844
- emitChange();
845
- },
813
+ setMuted: applySoftMute,
846
814
  stopMic() {
847
815
  if (closed)
848
816
  return;
@@ -855,13 +823,7 @@ export function createVoice(room, options) {
855
823
  emitChange();
856
824
  },
857
825
  async switchDevice(deviceId) {
858
- let nextDeviceId = null;
859
- if (deviceId !== undefined && deviceId !== null && deviceId !== '') {
860
- if (typeof deviceId !== 'string' || deviceId.trim().length === 0) {
861
- throw new TypeError('Expected deviceId to be a non-empty string, null, or undefined');
862
- }
863
- nextDeviceId = deviceId;
864
- }
826
+ const nextDeviceId = normalizeDeviceIdArg(deviceId);
865
827
  if (closed)
866
828
  return 'off';
867
829
  if (inFlightMic !== null) {
@@ -899,10 +861,11 @@ export function createVoice(room, options) {
899
861
  }
900
862
  const epoch = micEpoch;
901
863
  const sEpoch = ++switchEpoch;
864
+ const isStale = () => closed || epoch !== micEpoch || sEpoch !== switchEpoch || !localStream || isRoomClosed(room);
902
865
  let newStream;
903
866
  try {
904
867
  newStream = await navigator.mediaDevices.getUserMedia({
905
- audio: buildAudioConstraints(nextDeviceId, nextDeviceId !== null)
868
+ audio: buildConstraints(nextDeviceId, nextDeviceId !== null)
906
869
  });
907
870
  }
908
871
  catch (err) {
@@ -914,22 +877,14 @@ export function createVoice(room, options) {
914
877
  emitChange();
915
878
  return micStatus;
916
879
  }
917
- if (closed ||
918
- epoch !== micEpoch ||
919
- sEpoch !== switchEpoch ||
920
- !localStream ||
921
- isRoomClosed(room)) {
880
+ if (isStale()) {
922
881
  for (const t of newStream.getTracks())
923
882
  t.stop();
924
883
  return closed ? 'off' : micStatus;
925
884
  }
926
885
  let resultStatus = micStatus;
927
886
  const runSwap = swapQueue.then(async () => {
928
- if (closed ||
929
- epoch !== micEpoch ||
930
- sEpoch !== switchEpoch ||
931
- !localStream ||
932
- isRoomClosed(room)) {
887
+ if (isStale()) {
933
888
  for (const t of newStream.getTracks())
934
889
  t.stop();
935
890
  resultStatus = closed ? 'off' : micStatus;
@@ -952,13 +907,11 @@ export function createVoice(room, options) {
952
907
  for (const cleanup of localTrackCleanups)
953
908
  cleanup();
954
909
  localTrackCleanups = [];
955
- let replaceInvoked = false;
956
910
  try {
957
- replaceInvoked = true;
958
911
  await room.replaceStreamTrack(targetStream, oldTrack, newTrack);
959
912
  }
960
913
  catch (err) {
961
- if (replaceInvoked && !targetStream.getTracks().includes(oldTrack)) {
914
+ if (!targetStream.getTracks().includes(oldTrack)) {
962
915
  oldTrack.stop();
963
916
  }
964
917
  newTrack.stop();
@@ -990,12 +943,11 @@ export function createVoice(room, options) {
990
943
  }
991
944
  bindLocalTrackEnded(targetStream);
992
945
  if (localMeter) {
993
- localMeter.source?.disconnect();
994
- localMeter.analyser?.disconnect();
946
+ meter.disconnect(localMeter);
995
947
  localMeter = null;
996
948
  }
997
- const meter = createAnalyser(targetStream);
998
- localMeter = meter.analyser ? meter : null;
949
+ const m = meter.createAnalyser(targetStream);
950
+ localMeter = m.analyser ? m : null;
999
951
  ensureMeter();
1000
952
  const actualDeviceId = newTrack.getSettings?.().deviceId;
1001
953
  selectedDeviceId =
@@ -1043,17 +995,8 @@ export function createVoice(room, options) {
1043
995
  peerVolumes.delete(peerId);
1044
996
  }
1045
997
  else {
1046
- if (!peerVolumes.has(peerId) && peerVolumes.size >= maxPeerAudioPrefs) {
1047
- let victim;
1048
- for (const k of peerVolumes.keys()) {
1049
- if (!remotePeers.has(k)) {
1050
- victim = k;
1051
- break;
1052
- }
1053
- }
1054
- victim ??= peerVolumes.keys().next().value;
1055
- if (victim !== undefined)
1056
- peerVolumes.delete(victim);
998
+ if (!peerVolumes.has(peerId)) {
999
+ evictPeerPref(peerVolumes, remotePeers, maxPeerAudioPrefs);
1057
1000
  }
1058
1001
  peerVolumes.delete(peerId);
1059
1002
  peerVolumes.set(peerId, clamped);
@@ -1098,18 +1041,7 @@ export function createVoice(room, options) {
1098
1041
  if (next === was)
1099
1042
  return;
1100
1043
  if (next) {
1101
- if (mutedPeers.size >= maxPeerAudioPrefs) {
1102
- let victim;
1103
- for (const k of mutedPeers) {
1104
- if (!remotePeers.has(k)) {
1105
- victim = k;
1106
- break;
1107
- }
1108
- }
1109
- victim ??= mutedPeers.values().next().value;
1110
- if (victim !== undefined)
1111
- mutedPeers.delete(victim);
1112
- }
1044
+ evictPeerPref(mutedPeers, remotePeers, maxPeerAudioPrefs);
1113
1045
  mutedPeers.add(peerId);
1114
1046
  }
1115
1047
  else {