@dimchansky/meshpost 0.5.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.
- package/README.md +66 -544
- package/dist/bip340.d.ts +1 -0
- package/dist/bip340.js +346 -0
- package/dist/blob.d.ts +1 -1
- package/dist/blob.js +44 -45
- package/dist/channel.d.ts +4 -0
- package/dist/channel.js +19 -44
- package/dist/combine.d.ts +9 -2
- package/dist/combine.js +40 -57
- package/dist/crypto.js +10 -9
- package/dist/identity.d.ts +2 -0
- package/dist/identity.js +39 -71
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/listeners.js +18 -3
- package/dist/mqtt.js +211 -476
- package/dist/nostr.js +194 -836
- package/dist/peer-link.d.ts +1 -0
- package/dist/peer-link.js +983 -0
- package/dist/presence.d.ts +1 -0
- package/dist/presence.js +74 -0
- package/dist/public.d.ts +1 -1
- package/dist/public.js +25 -77
- package/dist/relay-core.d.ts +1 -0
- package/dist/relay-core.js +399 -0
- package/dist/room-reclaim.d.ts +1 -0
- package/dist/room-reclaim.js +115 -0
- package/dist/room-stats.d.ts +1 -0
- package/dist/room-stats.js +75 -0
- package/dist/room.js +245 -1218
- package/dist/rpc.js +25 -28
- package/dist/signaling.d.ts +8 -0
- package/dist/signaling.js +55 -0
- package/dist/state.js +23 -33
- package/dist/tabs.js +6 -50
- package/dist/voice-mic.d.ts +1 -0
- package/dist/voice-mic.js +496 -0
- package/dist/voice-remote.d.ts +1 -0
- package/dist/voice-remote.js +568 -0
- package/dist/voice.d.ts +19 -1
- package/dist/voice.js +95 -1036
- package/dist/ws.js +56 -197
- package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
- package/docs/api.md +219 -0
- package/docs/behavior.md +14 -8
- package/docs/guide.md +404 -0
- package/docs/signaling-and-production.md +312 -0
- package/docs/voice-and-media.md +193 -0
- package/package.json +6 -3
package/dist/voice.js
CHANGED
|
@@ -1,71 +1,13 @@
|
|
|
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
|
-
|
|
4
|
-
|
|
5
|
-
noiseSuppression: true,
|
|
6
|
-
autoGainControl: true
|
|
7
|
-
});
|
|
8
|
-
const gestureEvents = ['pointerdown', 'pointerup', 'touchend', 'click', 'keydown'];
|
|
9
|
-
const captureOpts = { capture: true };
|
|
10
|
-
const maxRemoteStreamsPerPeer = 4;
|
|
11
|
-
const maxPeerAudioPrefs = 128;
|
|
3
|
+
import { createLocalMic, defaultAudioConstraints, normalizeDeviceIdArg } from './voice-mic.js';
|
|
4
|
+
import { createRemoteAudio } from './voice-remote.js';
|
|
12
5
|
const minSpeakingIntervalMs = 50;
|
|
13
6
|
const maxSpeakingIntervalMs = 60_000;
|
|
14
7
|
const defaultSpeakingThreshold = 0.03;
|
|
15
8
|
const defaultSpeakingIntervalMs = 180;
|
|
16
9
|
const defaultStreamTag = 'voice';
|
|
17
10
|
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
11
|
/**
|
|
70
12
|
* List available audio input (microphone) devices safely across browser and non-DOM runtimes.
|
|
71
13
|
* Returns an empty frozen array if `navigator.mediaDevices.enumerateDevices()` is unavailable or rejects.
|
|
@@ -104,19 +46,24 @@ export async function listAudioInputs() {
|
|
|
104
46
|
/**
|
|
105
47
|
* Subscribe to `navigator.mediaDevices` `'devicechange'` events and receive the updated
|
|
106
48
|
* `listAudioInputs()` array (guarded against out-of-order async enumerations and supporting `ListenOptions`).
|
|
49
|
+
* Pass `{ immediate: true }` to also deliver the initial device list through the same race guard.
|
|
107
50
|
* Returns an idempotent unsubscribe function.
|
|
108
51
|
*/
|
|
109
52
|
export function onAudioInputsChange(fn, options) {
|
|
110
53
|
if (typeof fn !== 'function')
|
|
111
54
|
throw new TypeError('Expected a listener function');
|
|
55
|
+
if (options?.immediate !== undefined && typeof options.immediate !== 'boolean') {
|
|
56
|
+
throw new TypeError('Expected immediate option to be a boolean');
|
|
57
|
+
}
|
|
112
58
|
const signal = options?.signal;
|
|
113
59
|
if (signal?.aborted)
|
|
114
60
|
return () => { };
|
|
115
|
-
|
|
116
|
-
|
|
61
|
+
const immediate = options?.immediate ?? false;
|
|
62
|
+
const mediaDevices = typeof navigator !== 'undefined' ? navigator.mediaDevices : undefined;
|
|
63
|
+
const canListen = typeof mediaDevices?.addEventListener === 'function';
|
|
64
|
+
if (!canListen && !immediate) {
|
|
117
65
|
return () => { };
|
|
118
66
|
}
|
|
119
|
-
const mediaDevices = navigator.mediaDevices;
|
|
120
67
|
const once = Boolean(options?.once);
|
|
121
68
|
let active = true;
|
|
122
69
|
let epoch = 0;
|
|
@@ -127,11 +74,13 @@ export function onAudioInputsChange(fn, options) {
|
|
|
127
74
|
active = false;
|
|
128
75
|
epoch++;
|
|
129
76
|
unbindAbort?.();
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
77
|
+
if (canListen) {
|
|
78
|
+
try {
|
|
79
|
+
mediaDevices.removeEventListener('devicechange', handleChange);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
// Ignore cleanup errors on restricted runtimes.
|
|
83
|
+
}
|
|
135
84
|
}
|
|
136
85
|
};
|
|
137
86
|
const handleChange = () => {
|
|
@@ -141,29 +90,24 @@ export function onAudioInputsChange(fn, options) {
|
|
|
141
90
|
void listAudioInputs().then((devices) => {
|
|
142
91
|
if (!active || myEpoch !== epoch)
|
|
143
92
|
return;
|
|
144
|
-
if (once)
|
|
93
|
+
if (once || !canListen)
|
|
145
94
|
off();
|
|
146
95
|
try {
|
|
147
96
|
fn(devices);
|
|
148
97
|
}
|
|
149
98
|
catch (error) {
|
|
150
|
-
|
|
99
|
+
reportAsyncError(error);
|
|
151
100
|
}
|
|
152
101
|
});
|
|
153
102
|
};
|
|
154
|
-
|
|
103
|
+
if (canListen) {
|
|
104
|
+
mediaDevices.addEventListener('devicechange', handleChange);
|
|
105
|
+
}
|
|
155
106
|
unbindAbort = bindAbort(signal, off);
|
|
107
|
+
if (immediate)
|
|
108
|
+
handleChange();
|
|
156
109
|
return off;
|
|
157
110
|
}
|
|
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
111
|
/**
|
|
168
112
|
* Create a headless P2P voice chat controller attached to a `Room`.
|
|
169
113
|
*
|
|
@@ -253,73 +197,22 @@ export function createVoice(room, options) {
|
|
|
253
197
|
}
|
|
254
198
|
}
|
|
255
199
|
}
|
|
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
|
-
let volume = initialVolume;
|
|
271
|
-
let deafened = Boolean(options?.deafened);
|
|
272
|
-
let micStatus = 'off';
|
|
273
|
-
let micError = null;
|
|
274
|
-
let autoplayBlocked = false;
|
|
275
|
-
let selfSpeaking = false;
|
|
276
200
|
let closed = false;
|
|
277
|
-
|
|
278
|
-
let localMeter = null;
|
|
279
|
-
let localTrackCleanups = [];
|
|
280
|
-
let micEpoch = 0;
|
|
281
|
-
let switchEpoch = 0;
|
|
282
|
-
let inFlightMic = null;
|
|
283
|
-
let swapQueue = Promise.resolve();
|
|
284
|
-
let audioSessionSwitched = false;
|
|
285
|
-
let prevAudioSessionType = null;
|
|
286
|
-
let audioCtx = null;
|
|
287
|
-
let silentSink = null;
|
|
288
|
-
let meterTimer;
|
|
289
|
-
let gestureListenersAttached = false;
|
|
290
|
-
let visibilityListenerAttached = false;
|
|
291
|
-
const remotePeers = new Map();
|
|
292
|
-
const speakingPeers = new Set();
|
|
293
|
-
const peerVolumes = new Map();
|
|
294
|
-
const mutedPeers = new Set();
|
|
295
|
-
const changes = listeners();
|
|
296
|
-
function effectiveVolumeFor(peerId) {
|
|
297
|
-
return Math.max(0, Math.min(1, volume * (peerVolumes.get(peerId) ?? 1)));
|
|
298
|
-
}
|
|
299
|
-
function effectiveMutedFor(peerId) {
|
|
300
|
-
return deafened || mutedPeers.has(peerId);
|
|
301
|
-
}
|
|
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
|
-
function buildPeerVolumes() {
|
|
308
|
-
return Object.freeze(Object.fromEntries(peerVolumes));
|
|
309
|
-
}
|
|
201
|
+
const changes = createListeners();
|
|
310
202
|
function buildSnapshot() {
|
|
311
203
|
return Object.freeze({
|
|
312
|
-
micStatus,
|
|
313
|
-
micError,
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
204
|
+
micStatus: mic.status,
|
|
205
|
+
micError: mic.error,
|
|
206
|
+
micStopReason: mic.stopReason,
|
|
207
|
+
deviceId: mic.deviceId,
|
|
208
|
+
autoplayBlocked: remote.autoplayBlocked,
|
|
209
|
+
deafened: remote.deafened,
|
|
210
|
+
volume: remote.volume,
|
|
211
|
+
selfSpeaking: remote.selfSpeaking,
|
|
212
|
+
remotePeers: remote.remotePeers,
|
|
213
|
+
speakingPeers: remote.speakingPeers,
|
|
214
|
+
mutedPeers: remote.mutedPeers,
|
|
215
|
+
peerVolumes: remote.peerVolumes
|
|
323
216
|
});
|
|
324
217
|
}
|
|
325
218
|
function emitChange() {
|
|
@@ -327,937 +220,103 @@ export function createVoice(room, options) {
|
|
|
327
220
|
return;
|
|
328
221
|
changes.fire(buildSnapshot());
|
|
329
222
|
}
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
if (session.type === 'play-and-record') {
|
|
356
|
-
audioSessionSwitched = true;
|
|
357
|
-
prevAudioSessionType = prev;
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
catch {
|
|
361
|
-
// Ignore unsupported audioSession writes.
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
function hasBlockedRemoteAudio() {
|
|
365
|
-
for (const streams of remotePeers.values()) {
|
|
366
|
-
for (const entry of streams.values()) {
|
|
367
|
-
if (entry.blocked || entry.audio.paused)
|
|
368
|
-
return true;
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
return false;
|
|
372
|
-
}
|
|
373
|
-
function attachGestureListeners() {
|
|
374
|
-
if (!autoUnlock || closed || gestureListenersAttached || typeof window === 'undefined')
|
|
375
|
-
return;
|
|
376
|
-
gestureListenersAttached = true;
|
|
377
|
-
for (const type of gestureEvents) {
|
|
378
|
-
window.addEventListener(type, unlockAudio, captureOpts);
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
function detachGestureListeners() {
|
|
382
|
-
if (!gestureListenersAttached || typeof window === 'undefined')
|
|
383
|
-
return;
|
|
384
|
-
gestureListenersAttached = false;
|
|
385
|
-
for (const type of gestureEvents) {
|
|
386
|
-
window.removeEventListener(type, unlockAudio, captureOpts);
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
function markAutoplayBlocked() {
|
|
390
|
-
if (closed)
|
|
391
|
-
return;
|
|
392
|
-
const changed = !autoplayBlocked;
|
|
393
|
-
autoplayBlocked = true;
|
|
394
|
-
attachGestureListeners();
|
|
395
|
-
if (changed)
|
|
396
|
-
emitChange();
|
|
397
|
-
}
|
|
398
|
-
function reconcileUnlockState() {
|
|
399
|
-
if (closed)
|
|
400
|
-
return;
|
|
401
|
-
let changed = false;
|
|
402
|
-
if (autoplayBlocked && !hasBlockedRemoteAudio()) {
|
|
403
|
-
autoplayBlocked = false;
|
|
404
|
-
changed = true;
|
|
405
|
-
}
|
|
406
|
-
if (!autoplayBlocked && !isAudioCtxPaused(audioCtx)) {
|
|
407
|
-
detachGestureListeners();
|
|
408
|
-
}
|
|
409
|
-
if (changed)
|
|
410
|
-
emitChange();
|
|
411
|
-
}
|
|
412
|
-
function tryPlayEntry(peerId, streamId, entry) {
|
|
413
|
-
let playPromise;
|
|
414
|
-
try {
|
|
415
|
-
playPromise = entry.audio.play();
|
|
416
|
-
}
|
|
417
|
-
catch {
|
|
418
|
-
return;
|
|
419
|
-
}
|
|
420
|
-
if (!playPromise || typeof playPromise.then !== 'function')
|
|
421
|
-
return;
|
|
422
|
-
void playPromise
|
|
423
|
-
.then(() => {
|
|
424
|
-
if (closed || remotePeers.get(peerId)?.get(streamId) !== entry)
|
|
425
|
-
return;
|
|
426
|
-
entry.blocked = false;
|
|
427
|
-
reconcileUnlockState();
|
|
428
|
-
})
|
|
429
|
-
.catch((err) => {
|
|
430
|
-
if (closed || remotePeers.get(peerId)?.get(streamId) !== entry)
|
|
431
|
-
return;
|
|
432
|
-
const name = err && typeof err === 'object' && 'name' in err
|
|
433
|
-
? String(err.name)
|
|
434
|
-
: '';
|
|
435
|
-
if (name !== 'NotAllowedError')
|
|
436
|
-
return;
|
|
437
|
-
entry.blocked = true;
|
|
438
|
-
markAutoplayBlocked();
|
|
439
|
-
});
|
|
440
|
-
}
|
|
441
|
-
// Never gate on an in-flight boolean or await audioCtx.resume(): on iOS Safari,
|
|
442
|
-
// pointerdown is not a media activation gesture and leaves audioCtx.resume()
|
|
443
|
-
// pending forever until a subsequent touchend/pointerup/click calls resume() again.
|
|
444
|
-
function unlockAudio() {
|
|
445
|
-
if (closed)
|
|
446
|
-
return;
|
|
447
|
-
if (isAudioCtxPaused(audioCtx)) {
|
|
448
|
-
void audioCtx
|
|
449
|
-
.resume()
|
|
450
|
-
.then(() => reconcileUnlockState())
|
|
451
|
-
.catch(() => { });
|
|
452
|
-
}
|
|
453
|
-
let attemptedPlay = false;
|
|
454
|
-
for (const [peerId, streams] of remotePeers) {
|
|
455
|
-
for (const [streamId, entry] of streams) {
|
|
456
|
-
if (entry.audio.paused) {
|
|
457
|
-
attemptedPlay = true;
|
|
458
|
-
tryPlayEntry(peerId, streamId, entry);
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
if (!attemptedPlay) {
|
|
463
|
-
reconcileUnlockState();
|
|
464
|
-
}
|
|
465
|
-
}
|
|
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;
|
|
476
|
-
}
|
|
477
|
-
function ensureMeter() {
|
|
478
|
-
if (!speakingDetection || closed || meterTimer !== undefined)
|
|
479
|
-
return;
|
|
480
|
-
if (remotePeers.size === 0 && !localMeter)
|
|
481
|
-
return;
|
|
482
|
-
meterTimer = setInterval(() => {
|
|
483
|
-
if (closed)
|
|
484
|
-
return;
|
|
485
|
-
let changed = false;
|
|
486
|
-
for (const [peerId, streams] of remotePeers) {
|
|
487
|
-
let active = false;
|
|
488
|
-
for (const entry of streams.values()) {
|
|
489
|
-
if (isAnalyserActive(entry)) {
|
|
490
|
-
active = true;
|
|
491
|
-
break;
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
const was = speakingPeers.has(peerId);
|
|
495
|
-
if (active && !was) {
|
|
496
|
-
speakingPeers.add(peerId);
|
|
497
|
-
changed = true;
|
|
498
|
-
}
|
|
499
|
-
else if (!active && was) {
|
|
500
|
-
speakingPeers.delete(peerId);
|
|
501
|
-
changed = true;
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
const nextSelf = micStatus === 'live' && isAnalyserActive(localMeter);
|
|
505
|
-
if (nextSelf !== selfSpeaking) {
|
|
506
|
-
selfSpeaking = nextSelf;
|
|
507
|
-
changed = true;
|
|
508
|
-
}
|
|
509
|
-
if (changed)
|
|
510
|
-
emitChange();
|
|
511
|
-
}, speakingIntervalMs);
|
|
512
|
-
}
|
|
513
|
-
function stopMeterIfEmpty() {
|
|
514
|
-
if (remotePeers.size === 0) {
|
|
515
|
-
speakingPeers.clear();
|
|
516
|
-
autoplayBlocked = false;
|
|
517
|
-
if (!isAudioCtxPaused(audioCtx)) {
|
|
518
|
-
detachGestureListeners();
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
if (remotePeers.size > 0 || localMeter)
|
|
522
|
-
return;
|
|
523
|
-
if (meterTimer !== undefined) {
|
|
524
|
-
clearInterval(meterTimer);
|
|
525
|
-
meterTimer = undefined;
|
|
526
|
-
}
|
|
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
|
-
}
|
|
535
|
-
detachGestureListeners();
|
|
536
|
-
}
|
|
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
|
-
function teardownLocalStream(detachFromRoom) {
|
|
576
|
-
let changed = false;
|
|
577
|
-
for (const cleanup of localTrackCleanups)
|
|
578
|
-
cleanup();
|
|
579
|
-
localTrackCleanups = [];
|
|
580
|
-
if (localMeter) {
|
|
581
|
-
localMeter.source?.disconnect();
|
|
582
|
-
localMeter.analyser?.disconnect();
|
|
583
|
-
localMeter = null;
|
|
584
|
-
}
|
|
585
|
-
if (selfSpeaking) {
|
|
586
|
-
selfSpeaking = false;
|
|
587
|
-
changed = true;
|
|
588
|
-
}
|
|
589
|
-
if (localStream) {
|
|
590
|
-
const stream = localStream;
|
|
591
|
-
localStream = null;
|
|
592
|
-
if (detachFromRoom && !isRoomClosed(room)) {
|
|
593
|
-
try {
|
|
594
|
-
room.removeStream(stream, targetPeer);
|
|
595
|
-
}
|
|
596
|
-
catch {
|
|
597
|
-
// Ignore if room closed concurrently.
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
for (const track of stream.getTracks())
|
|
601
|
-
track.stop();
|
|
602
|
-
changed = true;
|
|
603
|
-
}
|
|
604
|
-
if (micStatus !== 'off') {
|
|
605
|
-
micStatus = 'off';
|
|
606
|
-
changed = true;
|
|
607
|
-
}
|
|
608
|
-
if (micError !== null) {
|
|
609
|
-
micError = null;
|
|
610
|
-
changed = true;
|
|
611
|
-
}
|
|
612
|
-
restoreAudioSession();
|
|
613
|
-
stopMeterIfEmpty();
|
|
614
|
-
return changed;
|
|
615
|
-
}
|
|
616
|
-
function bindLocalTrackEnded(stream) {
|
|
617
|
-
for (const cleanup of localTrackCleanups)
|
|
618
|
-
cleanup();
|
|
619
|
-
localTrackCleanups = [];
|
|
620
|
-
const onTrackEnded = () => {
|
|
621
|
-
if (closed || localStream !== stream)
|
|
622
|
-
return;
|
|
623
|
-
const changed = teardownLocalStream(true);
|
|
624
|
-
if (changed)
|
|
625
|
-
emitChange();
|
|
626
|
-
};
|
|
627
|
-
for (const track of stream.getAudioTracks()) {
|
|
628
|
-
track.addEventListener('ended', onTrackEnded, { once: true });
|
|
629
|
-
localTrackCleanups.push(() => track.removeEventListener('ended', onTrackEnded));
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
function acquireMic() {
|
|
633
|
-
if (closed)
|
|
634
|
-
return Promise.resolve('off');
|
|
635
|
-
if (inFlightMic)
|
|
636
|
-
return inFlightMic;
|
|
637
|
-
if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia) {
|
|
638
|
-
micStatus = 'error';
|
|
639
|
-
micError = Object.freeze({
|
|
640
|
-
code: 'insecure-context',
|
|
641
|
-
message: 'Microphone access requires HTTPS or localhost'
|
|
642
|
-
});
|
|
643
|
-
emitChange();
|
|
644
|
-
return Promise.resolve('error');
|
|
645
|
-
}
|
|
646
|
-
const epoch = ++micEpoch;
|
|
647
|
-
const requestedDeviceId = selectedDeviceId;
|
|
648
|
-
const requestedDeviceExact = selectedDeviceExact;
|
|
649
|
-
micStatus = 'requesting';
|
|
650
|
-
micError = null;
|
|
651
|
-
emitChange();
|
|
652
|
-
if (closed || epoch !== micEpoch)
|
|
653
|
-
return Promise.resolve('off');
|
|
654
|
-
switchAudioSessionForMic();
|
|
655
|
-
const promise = (async () => {
|
|
656
|
-
let stream;
|
|
657
|
-
let fellBackToDefault = false;
|
|
658
|
-
try {
|
|
659
|
-
stream = await navigator.mediaDevices.getUserMedia({
|
|
660
|
-
audio: buildAudioConstraints(requestedDeviceId, requestedDeviceExact)
|
|
661
|
-
});
|
|
662
|
-
}
|
|
663
|
-
catch (err) {
|
|
664
|
-
if (closed || epoch !== micEpoch)
|
|
665
|
-
return 'off';
|
|
666
|
-
const classified = classifyMicError(err);
|
|
667
|
-
if (fallbackToDefaultOnNotFound &&
|
|
668
|
-
requestedDeviceId !== null &&
|
|
669
|
-
classified.code === 'not-found') {
|
|
670
|
-
try {
|
|
671
|
-
stream = await navigator.mediaDevices.getUserMedia({
|
|
672
|
-
audio: buildAudioConstraints(null, false)
|
|
673
|
-
});
|
|
674
|
-
fellBackToDefault = true;
|
|
675
|
-
}
|
|
676
|
-
catch (fallbackErr) {
|
|
677
|
-
if (closed || epoch !== micEpoch)
|
|
678
|
-
return 'off';
|
|
679
|
-
restoreAudioSession();
|
|
680
|
-
micStatus = 'error';
|
|
681
|
-
micError = classifyMicError(fallbackErr);
|
|
682
|
-
emitChange();
|
|
683
|
-
return 'error';
|
|
684
|
-
}
|
|
685
|
-
}
|
|
686
|
-
else {
|
|
687
|
-
restoreAudioSession();
|
|
688
|
-
micStatus = 'error';
|
|
689
|
-
micError = classified;
|
|
690
|
-
emitChange();
|
|
691
|
-
return 'error';
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
if (closed || epoch !== micEpoch || isRoomClosed(room)) {
|
|
695
|
-
for (const track of stream.getTracks())
|
|
696
|
-
track.stop();
|
|
697
|
-
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';
|
|
706
|
-
}
|
|
707
|
-
return 'off';
|
|
708
|
-
}
|
|
709
|
-
try {
|
|
710
|
-
room.addStream(stream, {
|
|
711
|
-
...(targetPeer !== undefined ? { to: targetPeer } : {}),
|
|
712
|
-
tag: streamTag
|
|
713
|
-
});
|
|
714
|
-
}
|
|
715
|
-
catch {
|
|
716
|
-
restoreAudioSession();
|
|
717
|
-
for (const track of stream.getTracks())
|
|
718
|
-
track.stop();
|
|
719
|
-
micStatus = 'error';
|
|
720
|
-
micError = Object.freeze({
|
|
721
|
-
code: 'room-closed',
|
|
722
|
-
message: 'Room is closed'
|
|
723
|
-
});
|
|
724
|
-
emitChange();
|
|
725
|
-
return 'error';
|
|
726
|
-
}
|
|
727
|
-
localStream = stream;
|
|
728
|
-
const actualDeviceId = stream.getAudioTracks()[0]?.getSettings?.().deviceId;
|
|
729
|
-
const resolvedActual = typeof actualDeviceId === 'string' && actualDeviceId.length > 0 ? actualDeviceId : null;
|
|
730
|
-
if (fellBackToDefault) {
|
|
731
|
-
selectedDeviceId = resolvedActual;
|
|
732
|
-
selectedDeviceExact = false;
|
|
733
|
-
}
|
|
734
|
-
else {
|
|
735
|
-
selectedDeviceId = requestedDeviceId ?? resolvedActual;
|
|
736
|
-
}
|
|
737
|
-
micStatus = 'live';
|
|
738
|
-
micError = null;
|
|
739
|
-
bindLocalTrackEnded(stream);
|
|
740
|
-
const meter = createAnalyser(stream);
|
|
741
|
-
localMeter = meter.analyser ? meter : null;
|
|
742
|
-
ensureMeter();
|
|
743
|
-
unlockAudio();
|
|
744
|
-
emitChange();
|
|
745
|
-
return 'live';
|
|
746
|
-
})();
|
|
747
|
-
inFlightMic = promise;
|
|
748
|
-
void promise.finally(() => {
|
|
749
|
-
if (inFlightMic === promise) {
|
|
750
|
-
inFlightMic = null;
|
|
751
|
-
}
|
|
752
|
-
});
|
|
753
|
-
return promise;
|
|
754
|
-
}
|
|
755
|
-
function teardownRemoteEntry(entry) {
|
|
756
|
-
entry.source?.disconnect();
|
|
757
|
-
entry.analyser?.disconnect();
|
|
758
|
-
try {
|
|
759
|
-
entry.audio.pause();
|
|
760
|
-
}
|
|
761
|
-
catch {
|
|
762
|
-
// Ignore non-standard audio element implementations.
|
|
763
|
-
}
|
|
764
|
-
entry.audio.srcObject = null;
|
|
765
|
-
entry.audio.remove();
|
|
766
|
-
}
|
|
767
|
-
function addRemoteStream(peerId, stream, meta) {
|
|
768
|
-
if (closed || typeof document === 'undefined' || !document.body)
|
|
769
|
-
return;
|
|
770
|
-
if (!stream || typeof stream.getAudioTracks !== 'function')
|
|
771
|
-
return;
|
|
772
|
-
if (stream.getAudioTracks().length === 0)
|
|
773
|
-
return;
|
|
774
|
-
const incomingTag = meta?.tag;
|
|
775
|
-
if (incomingTag === undefined ? strictStreamTag : incomingTag !== streamTag)
|
|
776
|
-
return;
|
|
777
|
-
let byPeer = remotePeers.get(peerId);
|
|
778
|
-
if (!byPeer) {
|
|
779
|
-
byPeer = new Map();
|
|
780
|
-
remotePeers.set(peerId, byPeer);
|
|
781
|
-
}
|
|
782
|
-
if (byPeer.has(stream.id))
|
|
783
|
-
return;
|
|
784
|
-
if (byPeer.size >= maxRemoteStreamsPerPeer)
|
|
785
|
-
return;
|
|
786
|
-
const audio = document.createElement('audio');
|
|
787
|
-
audio.autoplay = true;
|
|
788
|
-
audio.setAttribute('playsinline', '');
|
|
789
|
-
audio.hidden = true;
|
|
790
|
-
audio.muted = effectiveMutedFor(peerId);
|
|
791
|
-
applyAudioVolume(audio, effectiveVolumeFor(peerId));
|
|
792
|
-
audio.srcObject = stream;
|
|
793
|
-
document.body.append(audio);
|
|
794
|
-
const meter = createAnalyser(stream);
|
|
795
|
-
const entry = { audio, blocked: false, ...meter };
|
|
796
|
-
byPeer.set(stream.id, entry);
|
|
797
|
-
const onPlaybackAccepted = () => {
|
|
798
|
-
if (closed || remotePeers.get(peerId)?.get(stream.id) !== entry || entry.audio.paused)
|
|
799
|
-
return;
|
|
800
|
-
entry.blocked = false;
|
|
801
|
-
reconcileUnlockState();
|
|
802
|
-
};
|
|
803
|
-
audio.addEventListener('play', onPlaybackAccepted);
|
|
804
|
-
audio.addEventListener('playing', onPlaybackAccepted);
|
|
805
|
-
tryPlayEntry(peerId, stream.id, entry);
|
|
806
|
-
ensureMeter();
|
|
807
|
-
emitChange();
|
|
808
|
-
}
|
|
809
|
-
function removeRemoteStream(peerId, stream) {
|
|
810
|
-
if (closed)
|
|
811
|
-
return;
|
|
812
|
-
const byPeer = remotePeers.get(peerId);
|
|
813
|
-
const entry = byPeer?.get(stream.id);
|
|
814
|
-
if (!entry || !byPeer)
|
|
815
|
-
return;
|
|
816
|
-
teardownRemoteEntry(entry);
|
|
817
|
-
byPeer.delete(stream.id);
|
|
818
|
-
if (byPeer.size === 0) {
|
|
819
|
-
remotePeers.delete(peerId);
|
|
820
|
-
speakingPeers.delete(peerId);
|
|
821
|
-
}
|
|
822
|
-
stopMeterIfEmpty();
|
|
823
|
-
reconcileUnlockState();
|
|
824
|
-
emitChange();
|
|
825
|
-
}
|
|
826
|
-
const onVisibilityChange = () => {
|
|
827
|
-
if (closed || typeof document === 'undefined' || document.visibilityState !== 'visible')
|
|
828
|
-
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
|
-
}
|
|
843
|
-
};
|
|
223
|
+
const remote = createRemoteAudio({
|
|
224
|
+
initialVolume,
|
|
225
|
+
initialDeafened: Boolean(options?.deafened),
|
|
226
|
+
autoUnlock,
|
|
227
|
+
speakingDetection,
|
|
228
|
+
speakingThreshold,
|
|
229
|
+
speakingIntervalMs,
|
|
230
|
+
streamTag,
|
|
231
|
+
strictStreamTag,
|
|
232
|
+
onChange: emitChange
|
|
233
|
+
});
|
|
234
|
+
const mic = createLocalMic({
|
|
235
|
+
room,
|
|
236
|
+
baseConstraints,
|
|
237
|
+
initialDeviceId: selectedDeviceId,
|
|
238
|
+
initialDeviceExact: selectedDeviceExact,
|
|
239
|
+
fallbackToDefaultOnNotFound,
|
|
240
|
+
targetPeer,
|
|
241
|
+
streamTag,
|
|
242
|
+
onLocalStream: remote.setLocalStream,
|
|
243
|
+
onChange: emitChange
|
|
244
|
+
});
|
|
245
|
+
let offStream = () => { };
|
|
246
|
+
let offStreamEnd = () => { };
|
|
247
|
+
let offRoomClose = () => { };
|
|
844
248
|
function closeInternal(roomClosing) {
|
|
845
249
|
if (closed)
|
|
846
250
|
return;
|
|
847
251
|
closed = true;
|
|
848
|
-
micEpoch++;
|
|
849
|
-
switchEpoch++;
|
|
850
|
-
inFlightMic = null;
|
|
851
252
|
offStream();
|
|
852
253
|
offStreamEnd();
|
|
853
254
|
offRoomClose();
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
document.removeEventListener('visibilitychange', onVisibilityChange);
|
|
857
|
-
}
|
|
858
|
-
detachGestureListeners();
|
|
859
|
-
teardownLocalStream(!roomClosing);
|
|
860
|
-
for (const byPeer of remotePeers.values()) {
|
|
861
|
-
for (const entry of byPeer.values()) {
|
|
862
|
-
teardownRemoteEntry(entry);
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
remotePeers.clear();
|
|
866
|
-
speakingPeers.clear();
|
|
867
|
-
peerVolumes.clear();
|
|
868
|
-
mutedPeers.clear();
|
|
869
|
-
autoplayBlocked = false;
|
|
870
|
-
stopMeterIfEmpty();
|
|
255
|
+
mic.close(roomClosing);
|
|
256
|
+
remote.close();
|
|
871
257
|
changes.clear();
|
|
872
258
|
}
|
|
873
|
-
let offStream = () => { };
|
|
874
|
-
let offStreamEnd = () => { };
|
|
875
|
-
let offRoomClose = () => { };
|
|
876
259
|
if (isRoomClosed(room)) {
|
|
877
|
-
|
|
878
|
-
changes.clear();
|
|
260
|
+
closeInternal(true);
|
|
879
261
|
}
|
|
880
262
|
else {
|
|
881
|
-
offStream = room.onPeerStream(addRemoteStream);
|
|
882
|
-
offStreamEnd = room.onPeerStreamEnd(removeRemoteStream);
|
|
263
|
+
offStream = room.onPeerStream(remote.addRemoteStream);
|
|
264
|
+
offStreamEnd = room.onPeerStreamEnd(remote.removeRemoteStream);
|
|
883
265
|
offRoomClose = onRoomClose(room, () => closeInternal(true));
|
|
884
|
-
if (autoUnlock && typeof document !== 'undefined') {
|
|
885
|
-
visibilityListenerAttached = true;
|
|
886
|
-
document.addEventListener('visibilitychange', onVisibilityChange);
|
|
887
|
-
}
|
|
888
266
|
for (const [peerId, stream, meta] of getRoomRemoteStreams(room)) {
|
|
889
|
-
addRemoteStream(peerId, stream, meta);
|
|
267
|
+
remote.addRemoteStream(peerId, stream, meta);
|
|
890
268
|
}
|
|
891
269
|
}
|
|
892
270
|
return {
|
|
893
271
|
get micStatus() {
|
|
894
|
-
return
|
|
272
|
+
return mic.status;
|
|
895
273
|
},
|
|
896
274
|
get micError() {
|
|
897
|
-
return
|
|
275
|
+
return mic.error;
|
|
276
|
+
},
|
|
277
|
+
get micStopReason() {
|
|
278
|
+
return mic.stopReason;
|
|
898
279
|
},
|
|
899
280
|
get deviceId() {
|
|
900
|
-
return
|
|
281
|
+
return mic.deviceId;
|
|
901
282
|
},
|
|
902
283
|
get autoplayBlocked() {
|
|
903
|
-
return autoplayBlocked;
|
|
284
|
+
return remote.autoplayBlocked;
|
|
904
285
|
},
|
|
905
286
|
get deafened() {
|
|
906
|
-
return deafened;
|
|
287
|
+
return remote.deafened;
|
|
907
288
|
},
|
|
908
289
|
get volume() {
|
|
909
|
-
return volume;
|
|
290
|
+
return remote.volume;
|
|
910
291
|
},
|
|
911
292
|
get selfSpeaking() {
|
|
912
|
-
return selfSpeaking;
|
|
293
|
+
return remote.selfSpeaking;
|
|
913
294
|
},
|
|
914
295
|
get remotePeers() {
|
|
915
|
-
return
|
|
296
|
+
return remote.remotePeers;
|
|
916
297
|
},
|
|
917
298
|
get speakingPeers() {
|
|
918
|
-
return
|
|
299
|
+
return remote.speakingPeers;
|
|
919
300
|
},
|
|
920
301
|
get mutedPeers() {
|
|
921
|
-
return
|
|
302
|
+
return remote.mutedPeers;
|
|
922
303
|
},
|
|
923
304
|
get peerVolumes() {
|
|
924
|
-
return
|
|
305
|
+
return remote.peerVolumes;
|
|
925
306
|
},
|
|
926
307
|
getSnapshot: buildSnapshot,
|
|
927
|
-
toggleMic
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
if (nextMuted)
|
|
940
|
-
selfSpeaking = false;
|
|
941
|
-
emitChange();
|
|
942
|
-
return Promise.resolve(micStatus);
|
|
943
|
-
}
|
|
944
|
-
return acquireMic();
|
|
945
|
-
},
|
|
946
|
-
startMic() {
|
|
947
|
-
if (closed)
|
|
948
|
-
return Promise.resolve('off');
|
|
949
|
-
if (inFlightMic)
|
|
950
|
-
return inFlightMic;
|
|
951
|
-
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
|
-
}
|
|
960
|
-
return Promise.resolve('live');
|
|
961
|
-
}
|
|
962
|
-
return acquireMic();
|
|
963
|
-
},
|
|
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
|
-
},
|
|
980
|
-
stopMic() {
|
|
981
|
-
if (closed)
|
|
982
|
-
return;
|
|
983
|
-
const wasRequesting = inFlightMic !== null;
|
|
984
|
-
micEpoch++;
|
|
985
|
-
switchEpoch++;
|
|
986
|
-
inFlightMic = null;
|
|
987
|
-
const changed = teardownLocalStream(true);
|
|
988
|
-
if (changed || wasRequesting)
|
|
989
|
-
emitChange();
|
|
990
|
-
},
|
|
991
|
-
async switchDevice(deviceId) {
|
|
992
|
-
const nextDeviceId = normalizeDeviceIdArg(deviceId);
|
|
993
|
-
if (closed)
|
|
994
|
-
return 'off';
|
|
995
|
-
if (inFlightMic !== null) {
|
|
996
|
-
micEpoch++;
|
|
997
|
-
switchEpoch++;
|
|
998
|
-
inFlightMic = null;
|
|
999
|
-
selectedDeviceId = nextDeviceId;
|
|
1000
|
-
selectedDeviceExact = nextDeviceId !== null;
|
|
1001
|
-
return acquireMic();
|
|
1002
|
-
}
|
|
1003
|
-
if (!localStream || (micStatus !== 'live' && micStatus !== 'muted')) {
|
|
1004
|
-
const hadError = micStatus === 'error' || micError !== null;
|
|
1005
|
-
const deviceChanged = selectedDeviceId !== nextDeviceId;
|
|
1006
|
-
selectedDeviceId = nextDeviceId;
|
|
1007
|
-
selectedDeviceExact = nextDeviceId !== null;
|
|
1008
|
-
if (hadError) {
|
|
1009
|
-
micStatus = 'off';
|
|
1010
|
-
micError = null;
|
|
1011
|
-
}
|
|
1012
|
-
if (hadError || deviceChanged) {
|
|
1013
|
-
emitChange();
|
|
1014
|
-
}
|
|
1015
|
-
return micStatus;
|
|
1016
|
-
}
|
|
1017
|
-
if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia) {
|
|
1018
|
-
micError = Object.freeze({
|
|
1019
|
-
code: 'insecure-context',
|
|
1020
|
-
message: 'Microphone access requires HTTPS or localhost'
|
|
1021
|
-
});
|
|
1022
|
-
emitChange();
|
|
1023
|
-
return micStatus;
|
|
1024
|
-
}
|
|
1025
|
-
if (typeof room.replaceStreamTrack !== 'function') {
|
|
1026
|
-
throw new TypeError('Room instance does not support replaceStreamTrack');
|
|
1027
|
-
}
|
|
1028
|
-
const epoch = micEpoch;
|
|
1029
|
-
const sEpoch = ++switchEpoch;
|
|
1030
|
-
let newStream;
|
|
1031
|
-
try {
|
|
1032
|
-
newStream = await navigator.mediaDevices.getUserMedia({
|
|
1033
|
-
audio: buildAudioConstraints(nextDeviceId, nextDeviceId !== null)
|
|
1034
|
-
});
|
|
1035
|
-
}
|
|
1036
|
-
catch (err) {
|
|
1037
|
-
if (closed)
|
|
1038
|
-
return 'off';
|
|
1039
|
-
if (epoch !== micEpoch || sEpoch !== switchEpoch)
|
|
1040
|
-
return micStatus;
|
|
1041
|
-
micError = classifyMicError(err);
|
|
1042
|
-
emitChange();
|
|
1043
|
-
return micStatus;
|
|
1044
|
-
}
|
|
1045
|
-
if (closed ||
|
|
1046
|
-
epoch !== micEpoch ||
|
|
1047
|
-
sEpoch !== switchEpoch ||
|
|
1048
|
-
!localStream ||
|
|
1049
|
-
isRoomClosed(room)) {
|
|
1050
|
-
for (const t of newStream.getTracks())
|
|
1051
|
-
t.stop();
|
|
1052
|
-
return closed ? 'off' : micStatus;
|
|
1053
|
-
}
|
|
1054
|
-
let resultStatus = micStatus;
|
|
1055
|
-
const runSwap = swapQueue.then(async () => {
|
|
1056
|
-
if (closed ||
|
|
1057
|
-
epoch !== micEpoch ||
|
|
1058
|
-
sEpoch !== switchEpoch ||
|
|
1059
|
-
!localStream ||
|
|
1060
|
-
isRoomClosed(room)) {
|
|
1061
|
-
for (const t of newStream.getTracks())
|
|
1062
|
-
t.stop();
|
|
1063
|
-
resultStatus = closed ? 'off' : micStatus;
|
|
1064
|
-
return;
|
|
1065
|
-
}
|
|
1066
|
-
const audioTracks = newStream.getAudioTracks();
|
|
1067
|
-
const newTrack = audioTracks[0];
|
|
1068
|
-
for (const extra of newStream.getTracks()) {
|
|
1069
|
-
if (extra !== newTrack)
|
|
1070
|
-
extra.stop();
|
|
1071
|
-
}
|
|
1072
|
-
const targetStream = localStream;
|
|
1073
|
-
const oldTrack = targetStream.getAudioTracks()[0];
|
|
1074
|
-
if (!newTrack || !oldTrack) {
|
|
1075
|
-
newTrack?.stop();
|
|
1076
|
-
resultStatus = micStatus;
|
|
1077
|
-
return;
|
|
1078
|
-
}
|
|
1079
|
-
newTrack.enabled = micStatus === 'live';
|
|
1080
|
-
for (const cleanup of localTrackCleanups)
|
|
1081
|
-
cleanup();
|
|
1082
|
-
localTrackCleanups = [];
|
|
1083
|
-
let replaceInvoked = false;
|
|
1084
|
-
try {
|
|
1085
|
-
replaceInvoked = true;
|
|
1086
|
-
await room.replaceStreamTrack(targetStream, oldTrack, newTrack);
|
|
1087
|
-
}
|
|
1088
|
-
catch (err) {
|
|
1089
|
-
if (replaceInvoked && !targetStream.getTracks().includes(oldTrack)) {
|
|
1090
|
-
oldTrack.stop();
|
|
1091
|
-
}
|
|
1092
|
-
newTrack.stop();
|
|
1093
|
-
if (!closed && epoch === micEpoch && localStream === targetStream) {
|
|
1094
|
-
if (!targetStream.getAudioTracks().length) {
|
|
1095
|
-
teardownLocalStream(true);
|
|
1096
|
-
}
|
|
1097
|
-
else {
|
|
1098
|
-
bindLocalTrackEnded(targetStream);
|
|
1099
|
-
}
|
|
1100
|
-
micError = classifyMicError(err);
|
|
1101
|
-
emitChange();
|
|
1102
|
-
}
|
|
1103
|
-
resultStatus = closed ? 'off' : micStatus;
|
|
1104
|
-
return;
|
|
1105
|
-
}
|
|
1106
|
-
// oldTrack has been removed from targetStream; always release hardware even if cancelled mid-await.
|
|
1107
|
-
oldTrack.stop();
|
|
1108
|
-
if (closed || epoch !== micEpoch || localStream !== targetStream) {
|
|
1109
|
-
newTrack.stop();
|
|
1110
|
-
resultStatus = closed ? 'off' : micStatus;
|
|
1111
|
-
return;
|
|
1112
|
-
}
|
|
1113
|
-
if (sEpoch !== switchEpoch) {
|
|
1114
|
-
// A newer switchDevice() is queued next in swapQueue and will replace newTrack!
|
|
1115
|
-
bindLocalTrackEnded(targetStream);
|
|
1116
|
-
resultStatus = micStatus;
|
|
1117
|
-
return;
|
|
1118
|
-
}
|
|
1119
|
-
bindLocalTrackEnded(targetStream);
|
|
1120
|
-
if (localMeter) {
|
|
1121
|
-
localMeter.source?.disconnect();
|
|
1122
|
-
localMeter.analyser?.disconnect();
|
|
1123
|
-
localMeter = null;
|
|
1124
|
-
}
|
|
1125
|
-
const meter = createAnalyser(targetStream);
|
|
1126
|
-
localMeter = meter.analyser ? meter : null;
|
|
1127
|
-
ensureMeter();
|
|
1128
|
-
const actualDeviceId = newTrack.getSettings?.().deviceId;
|
|
1129
|
-
selectedDeviceId =
|
|
1130
|
-
nextDeviceId ??
|
|
1131
|
-
(typeof actualDeviceId === 'string' && actualDeviceId.length > 0 ? actualDeviceId : null);
|
|
1132
|
-
selectedDeviceExact = nextDeviceId !== null;
|
|
1133
|
-
micError = null;
|
|
1134
|
-
emitChange();
|
|
1135
|
-
resultStatus = micStatus;
|
|
1136
|
-
});
|
|
1137
|
-
swapQueue = runSwap.catch(() => { });
|
|
1138
|
-
await runSwap;
|
|
1139
|
-
return resultStatus;
|
|
1140
|
-
},
|
|
1141
|
-
setVolume(nextVolume) {
|
|
1142
|
-
if (typeof nextVolume !== 'number' || !Number.isFinite(nextVolume)) {
|
|
1143
|
-
throw new RangeError('Expected a finite volume');
|
|
1144
|
-
}
|
|
1145
|
-
if (closed)
|
|
1146
|
-
return;
|
|
1147
|
-
const clamped = Math.max(0, Math.min(1, nextVolume));
|
|
1148
|
-
if (clamped === volume)
|
|
1149
|
-
return;
|
|
1150
|
-
volume = clamped;
|
|
1151
|
-
for (const [peerId, byPeer] of remotePeers) {
|
|
1152
|
-
const eff = effectiveVolumeFor(peerId);
|
|
1153
|
-
for (const entry of byPeer.values()) {
|
|
1154
|
-
applyAudioVolume(entry.audio, eff);
|
|
1155
|
-
}
|
|
1156
|
-
}
|
|
1157
|
-
emitChange();
|
|
1158
|
-
},
|
|
1159
|
-
setPeerVolume(peerId, nextPeerVolume) {
|
|
1160
|
-
validatePeerIdArg(peerId);
|
|
1161
|
-
if (typeof nextPeerVolume !== 'number' || !Number.isFinite(nextPeerVolume)) {
|
|
1162
|
-
throw new RangeError('Expected a finite volume');
|
|
1163
|
-
}
|
|
1164
|
-
if (closed)
|
|
1165
|
-
return;
|
|
1166
|
-
const clamped = Math.max(0, Math.min(1, nextPeerVolume));
|
|
1167
|
-
const prev = peerVolumes.get(peerId) ?? 1;
|
|
1168
|
-
if (clamped === prev)
|
|
1169
|
-
return;
|
|
1170
|
-
if (clamped === 1) {
|
|
1171
|
-
peerVolumes.delete(peerId);
|
|
1172
|
-
}
|
|
1173
|
-
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);
|
|
1185
|
-
}
|
|
1186
|
-
peerVolumes.delete(peerId);
|
|
1187
|
-
peerVolumes.set(peerId, clamped);
|
|
1188
|
-
}
|
|
1189
|
-
const byPeer = remotePeers.get(peerId);
|
|
1190
|
-
if (byPeer) {
|
|
1191
|
-
const eff = effectiveVolumeFor(peerId);
|
|
1192
|
-
for (const entry of byPeer.values()) {
|
|
1193
|
-
applyAudioVolume(entry.audio, eff);
|
|
1194
|
-
}
|
|
1195
|
-
}
|
|
1196
|
-
emitChange();
|
|
1197
|
-
},
|
|
1198
|
-
getPeerVolume(peerId) {
|
|
1199
|
-
if (typeof peerId !== 'string' || peerId.length === 0)
|
|
1200
|
-
return 1;
|
|
1201
|
-
return peerVolumes.get(peerId) ?? 1;
|
|
1202
|
-
},
|
|
1203
|
-
setDeafened(nextDeafened) {
|
|
1204
|
-
if (closed)
|
|
1205
|
-
return;
|
|
1206
|
-
const next = Boolean(nextDeafened);
|
|
1207
|
-
if (next === deafened)
|
|
1208
|
-
return;
|
|
1209
|
-
deafened = next;
|
|
1210
|
-
for (const [peerId, byPeer] of remotePeers) {
|
|
1211
|
-
const effMuted = effectiveMutedFor(peerId);
|
|
1212
|
-
for (const entry of byPeer.values()) {
|
|
1213
|
-
entry.audio.muted = effMuted;
|
|
1214
|
-
}
|
|
1215
|
-
}
|
|
1216
|
-
if (!next)
|
|
1217
|
-
unlockAudio();
|
|
1218
|
-
emitChange();
|
|
1219
|
-
},
|
|
1220
|
-
setPeerMuted(peerId, muted) {
|
|
1221
|
-
validatePeerIdArg(peerId);
|
|
1222
|
-
if (closed)
|
|
1223
|
-
return;
|
|
1224
|
-
const next = Boolean(muted);
|
|
1225
|
-
const was = mutedPeers.has(peerId);
|
|
1226
|
-
if (next === was)
|
|
1227
|
-
return;
|
|
1228
|
-
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
|
-
}
|
|
1241
|
-
mutedPeers.add(peerId);
|
|
1242
|
-
}
|
|
1243
|
-
else {
|
|
1244
|
-
mutedPeers.delete(peerId);
|
|
1245
|
-
}
|
|
1246
|
-
const byPeer = remotePeers.get(peerId);
|
|
1247
|
-
if (byPeer) {
|
|
1248
|
-
const effMuted = effectiveMutedFor(peerId);
|
|
1249
|
-
for (const entry of byPeer.values()) {
|
|
1250
|
-
entry.audio.muted = effMuted;
|
|
1251
|
-
}
|
|
1252
|
-
}
|
|
1253
|
-
if (!next && !deafened)
|
|
1254
|
-
unlockAudio();
|
|
1255
|
-
emitChange();
|
|
1256
|
-
},
|
|
1257
|
-
isPeerMuted(peerId) {
|
|
1258
|
-
return typeof peerId === 'string' && mutedPeers.has(peerId);
|
|
1259
|
-
},
|
|
1260
|
-
unlockAudio,
|
|
308
|
+
toggleMic: mic.toggleMic,
|
|
309
|
+
startMic: mic.startMic,
|
|
310
|
+
setMuted: mic.setMuted,
|
|
311
|
+
stopMic: mic.stopMic,
|
|
312
|
+
switchDevice: mic.switchDevice,
|
|
313
|
+
setVolume: remote.setVolume,
|
|
314
|
+
setPeerVolume: remote.setPeerVolume,
|
|
315
|
+
getPeerVolume: remote.getPeerVolume,
|
|
316
|
+
setDeafened: remote.setDeafened,
|
|
317
|
+
setPeerMuted: remote.setPeerMuted,
|
|
318
|
+
isPeerMuted: remote.isPeerMuted,
|
|
319
|
+
unlockAudio: remote.unlockAudio,
|
|
1261
320
|
onChange(fn, listenOpts) {
|
|
1262
321
|
return changes.add(fn, listenOpts);
|
|
1263
322
|
},
|