@dimchansky/meshpost 0.2.0 → 0.4.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 +330 -96
- package/dist/channel.d.ts +37 -2
- package/dist/channel.js +226 -12
- package/dist/combine.d.ts +12 -1
- package/dist/combine.js +304 -213
- package/dist/crypto.d.ts +34 -0
- package/dist/crypto.js +158 -0
- package/dist/identity.d.ts +45 -0
- package/dist/identity.js +264 -0
- package/dist/index.d.ts +17 -5
- package/dist/index.js +8 -2
- package/dist/mqtt.d.ts +9 -1
- package/dist/mqtt.js +95 -87
- package/dist/nostr.d.ts +27 -0
- package/dist/nostr.js +1008 -0
- package/dist/room.d.ts +37 -7
- package/dist/room.js +656 -65
- package/dist/rpc.d.ts +48 -0
- package/dist/rpc.js +382 -0
- package/dist/signaling.d.ts +9 -8
- package/dist/signaling.js +10 -2
- package/dist/state.d.ts +56 -0
- package/dist/state.js +305 -0
- package/dist/tabs.js +8 -1
- package/dist/turn.d.ts +13 -0
- package/dist/turn.js +213 -0
- package/dist/voice.d.ts +108 -0
- package/dist/voice.js +1160 -0
- package/dist/ws.d.ts +17 -2
- package/dist/ws.js +248 -33
- package/docs/behavior.md +107 -54
- package/package.json +67 -2
package/dist/voice.js
ADDED
|
@@ -0,0 +1,1160 @@
|
|
|
1
|
+
import { getRoomRemoteStreams, isRoomClosed, onRoomClose } from './room.js';
|
|
2
|
+
const defaultAudioConstraints = Object.freeze({
|
|
3
|
+
echoCancellation: true,
|
|
4
|
+
noiseSuppression: true,
|
|
5
|
+
autoGainControl: true
|
|
6
|
+
});
|
|
7
|
+
const gestureEvents = ['pointerdown', 'pointerup', 'touchend', 'click', 'keydown'];
|
|
8
|
+
const captureOpts = { capture: true };
|
|
9
|
+
const maxRemoteStreamsPerPeer = 4;
|
|
10
|
+
const maxPeerAudioPrefs = 128;
|
|
11
|
+
const minSpeakingIntervalMs = 50;
|
|
12
|
+
const maxSpeakingIntervalMs = 60_000;
|
|
13
|
+
const defaultSpeakingThreshold = 0.03;
|
|
14
|
+
const defaultSpeakingIntervalMs = 180;
|
|
15
|
+
const defaultStreamTag = 'voice';
|
|
16
|
+
const streamTagPattern = /^[a-zA-Z0-9._-]{1,32}$/;
|
|
17
|
+
function isAudioCtxPaused(ctx) {
|
|
18
|
+
return ctx !== null && ctx.state !== 'running' && ctx.state !== 'closed';
|
|
19
|
+
}
|
|
20
|
+
function getIosAudioSession() {
|
|
21
|
+
if (typeof navigator === 'undefined')
|
|
22
|
+
return null;
|
|
23
|
+
const session = navigator.audioSession;
|
|
24
|
+
return session && typeof session === 'object' && typeof session.type === 'string' ? session : null;
|
|
25
|
+
}
|
|
26
|
+
function classifyMicError(err) {
|
|
27
|
+
const name = err && typeof err === 'object' && 'name' in err ? String(err.name) : '';
|
|
28
|
+
if (name === 'NotAllowedError' || name === 'PermissionDeniedError') {
|
|
29
|
+
return Object.freeze({
|
|
30
|
+
code: 'permission-denied',
|
|
31
|
+
message: 'Microphone permission denied'
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
if (name === 'NotFoundError' ||
|
|
35
|
+
name === 'DevicesNotFoundError' ||
|
|
36
|
+
name === 'OverconstrainedError' ||
|
|
37
|
+
name === 'ConstraintNotSatisfiedError') {
|
|
38
|
+
return Object.freeze({
|
|
39
|
+
code: 'not-found',
|
|
40
|
+
message: 'No matching microphone device found'
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
if (name === 'NotReadableError' || name === 'TrackStartError') {
|
|
44
|
+
return Object.freeze({
|
|
45
|
+
code: 'in-use',
|
|
46
|
+
message: 'Microphone is already in use by another application'
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
if (name === 'SecurityError') {
|
|
50
|
+
return Object.freeze({
|
|
51
|
+
code: 'insecure-context',
|
|
52
|
+
message: 'Microphone access requires HTTPS or localhost'
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
return Object.freeze({
|
|
56
|
+
code: 'unknown',
|
|
57
|
+
message: 'Could not access microphone'
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
function listeners() {
|
|
61
|
+
const entries = new Set();
|
|
62
|
+
let closed = false;
|
|
63
|
+
return {
|
|
64
|
+
add(fn, options) {
|
|
65
|
+
const signal = options?.signal;
|
|
66
|
+
if (closed || signal?.aborted)
|
|
67
|
+
return () => { };
|
|
68
|
+
const entry = {
|
|
69
|
+
fn,
|
|
70
|
+
once: Boolean(options?.once),
|
|
71
|
+
off() {
|
|
72
|
+
if (!entries.delete(entry))
|
|
73
|
+
return;
|
|
74
|
+
signal?.removeEventListener('abort', entry.off);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
entries.add(entry);
|
|
78
|
+
signal?.addEventListener('abort', entry.off, { once: true });
|
|
79
|
+
return entry.off;
|
|
80
|
+
},
|
|
81
|
+
fire(...args) {
|
|
82
|
+
for (const entry of [...entries]) {
|
|
83
|
+
if (!entries.has(entry))
|
|
84
|
+
continue;
|
|
85
|
+
if (entry.once)
|
|
86
|
+
entry.off();
|
|
87
|
+
try {
|
|
88
|
+
entry.fn(...args);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
globalThis.reportError?.(error);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
clear() {
|
|
96
|
+
closed = true;
|
|
97
|
+
for (const entry of [...entries])
|
|
98
|
+
entry.off();
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function applyAudioVolume(audio, volume) {
|
|
103
|
+
try {
|
|
104
|
+
audio.volume = volume;
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
// Ignore read-only volume property on certain iOS WebKit builds.
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Create a headless P2P voice chat controller attached to a `Room`.
|
|
112
|
+
*
|
|
113
|
+
* Automatically plays incoming peer audio streams, manages local microphone capture with instant
|
|
114
|
+
* soft-mute (`track.enabled`) vs full hardware release, tracks speaking peers via a shared lazy
|
|
115
|
+
* `AudioContext`, and handles browser Autoplay Policy & iOS Safari audio unlocking.
|
|
116
|
+
*/
|
|
117
|
+
export function createVoice(room, options) {
|
|
118
|
+
if (!room ||
|
|
119
|
+
typeof room !== 'object' ||
|
|
120
|
+
typeof room.onPeerStream !== 'function' ||
|
|
121
|
+
typeof room.onPeerStreamEnd !== 'function' ||
|
|
122
|
+
typeof room.addStream !== 'function' ||
|
|
123
|
+
typeof room.removeStream !== 'function') {
|
|
124
|
+
throw new TypeError('Expected a valid Room instance');
|
|
125
|
+
}
|
|
126
|
+
const initialVolume = options?.volume ?? 1;
|
|
127
|
+
if (typeof initialVolume !== 'number' ||
|
|
128
|
+
!Number.isFinite(initialVolume) ||
|
|
129
|
+
initialVolume < 0 ||
|
|
130
|
+
initialVolume > 1) {
|
|
131
|
+
throw new RangeError('Expected volume between 0 and 1');
|
|
132
|
+
}
|
|
133
|
+
const speakingThreshold = options?.speakingThreshold ?? defaultSpeakingThreshold;
|
|
134
|
+
if (typeof speakingThreshold !== 'number' ||
|
|
135
|
+
!Number.isFinite(speakingThreshold) ||
|
|
136
|
+
speakingThreshold < 0 ||
|
|
137
|
+
speakingThreshold > 1) {
|
|
138
|
+
throw new RangeError('Expected speakingThreshold between 0 and 1');
|
|
139
|
+
}
|
|
140
|
+
const speakingIntervalMs = options?.speakingIntervalMs ?? defaultSpeakingIntervalMs;
|
|
141
|
+
if (!Number.isSafeInteger(speakingIntervalMs) ||
|
|
142
|
+
speakingIntervalMs < minSpeakingIntervalMs ||
|
|
143
|
+
speakingIntervalMs > maxSpeakingIntervalMs) {
|
|
144
|
+
throw new RangeError('Expected a safe integer speakingIntervalMs between 50 and 60000');
|
|
145
|
+
}
|
|
146
|
+
const rawConstraints = options?.audioConstraints;
|
|
147
|
+
if (rawConstraints !== undefined &&
|
|
148
|
+
rawConstraints !== true &&
|
|
149
|
+
(typeof rawConstraints !== 'object' || rawConstraints === null || Array.isArray(rawConstraints))) {
|
|
150
|
+
throw new TypeError('Expected audioConstraints to be true or a MediaTrackConstraints object');
|
|
151
|
+
}
|
|
152
|
+
const baseConstraints = rawConstraints === undefined
|
|
153
|
+
? { ...defaultAudioConstraints }
|
|
154
|
+
: rawConstraints === true
|
|
155
|
+
? true
|
|
156
|
+
: { ...rawConstraints };
|
|
157
|
+
const targetPeer = options?.to;
|
|
158
|
+
if (targetPeer !== undefined && typeof targetPeer !== 'string') {
|
|
159
|
+
throw new TypeError('Expected target peer ID to be a string');
|
|
160
|
+
}
|
|
161
|
+
const streamTag = options?.streamTag ?? defaultStreamTag;
|
|
162
|
+
if (typeof streamTag !== 'string' || !streamTagPattern.test(streamTag)) {
|
|
163
|
+
throw new TypeError('Invalid streamTag');
|
|
164
|
+
}
|
|
165
|
+
if (options?.strictStreamTag !== undefined && typeof options.strictStreamTag !== 'boolean') {
|
|
166
|
+
throw new TypeError('Expected strictStreamTag to be a boolean');
|
|
167
|
+
}
|
|
168
|
+
const strictStreamTag = options?.strictStreamTag ?? false;
|
|
169
|
+
const autoUnlock = options?.autoUnlock !== false;
|
|
170
|
+
const speakingDetection = options?.speakingDetection !== false;
|
|
171
|
+
let selectedDeviceId = null;
|
|
172
|
+
if (typeof baseConstraints === 'object' && baseConstraints.deviceId !== undefined) {
|
|
173
|
+
const rawDev = baseConstraints.deviceId;
|
|
174
|
+
if (typeof rawDev === 'string' && rawDev.trim().length > 0) {
|
|
175
|
+
selectedDeviceId = rawDev;
|
|
176
|
+
}
|
|
177
|
+
else if (rawDev && typeof rawDev === 'object' && !Array.isArray(rawDev)) {
|
|
178
|
+
const candidate = typeof rawDev.exact === 'string'
|
|
179
|
+
? rawDev.exact
|
|
180
|
+
: typeof rawDev.ideal === 'string'
|
|
181
|
+
? rawDev.ideal
|
|
182
|
+
: null;
|
|
183
|
+
if (candidate && candidate.trim().length > 0)
|
|
184
|
+
selectedDeviceId = candidate;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
function buildAudioConstraints(deviceOverride) {
|
|
188
|
+
if (deviceOverride !== null) {
|
|
189
|
+
const base = typeof baseConstraints === 'object'
|
|
190
|
+
? { ...baseConstraints }
|
|
191
|
+
: { ...defaultAudioConstraints };
|
|
192
|
+
base.deviceId = { exact: deviceOverride };
|
|
193
|
+
return base;
|
|
194
|
+
}
|
|
195
|
+
if (baseConstraints === true)
|
|
196
|
+
return true;
|
|
197
|
+
const copy = { ...baseConstraints };
|
|
198
|
+
delete copy.deviceId;
|
|
199
|
+
return copy;
|
|
200
|
+
}
|
|
201
|
+
let volume = initialVolume;
|
|
202
|
+
let deafened = Boolean(options?.deafened);
|
|
203
|
+
let micStatus = 'off';
|
|
204
|
+
let micError = null;
|
|
205
|
+
let autoplayBlocked = false;
|
|
206
|
+
let selfSpeaking = false;
|
|
207
|
+
let closed = false;
|
|
208
|
+
let localStream = null;
|
|
209
|
+
let localMeter = null;
|
|
210
|
+
let localTrackCleanups = [];
|
|
211
|
+
let micEpoch = 0;
|
|
212
|
+
let switchEpoch = 0;
|
|
213
|
+
let inFlightMic = null;
|
|
214
|
+
let swapQueue = Promise.resolve();
|
|
215
|
+
let audioSessionSwitched = false;
|
|
216
|
+
let prevAudioSessionType = null;
|
|
217
|
+
let audioCtx = null;
|
|
218
|
+
let silentSink = null;
|
|
219
|
+
let meterTimer;
|
|
220
|
+
let gestureListenersAttached = false;
|
|
221
|
+
let visibilityListenerAttached = false;
|
|
222
|
+
const remotePeers = new Map();
|
|
223
|
+
const speakingPeers = new Set();
|
|
224
|
+
const peerVolumes = new Map();
|
|
225
|
+
const mutedPeers = new Set();
|
|
226
|
+
const changes = listeners();
|
|
227
|
+
function effectiveVolumeFor(peerId) {
|
|
228
|
+
return Math.max(0, Math.min(1, volume * (peerVolumes.get(peerId) ?? 1)));
|
|
229
|
+
}
|
|
230
|
+
function effectiveMutedFor(peerId) {
|
|
231
|
+
return deafened || mutedPeers.has(peerId);
|
|
232
|
+
}
|
|
233
|
+
function validatePeerIdArg(peerId) {
|
|
234
|
+
if (typeof peerId !== 'string' || peerId.length === 0 || peerId.length > 128) {
|
|
235
|
+
throw new TypeError('Expected a non-empty peerId string');
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
function buildSnapshot() {
|
|
239
|
+
return Object.freeze({
|
|
240
|
+
micStatus,
|
|
241
|
+
micError,
|
|
242
|
+
deviceId: selectedDeviceId,
|
|
243
|
+
autoplayBlocked,
|
|
244
|
+
deafened,
|
|
245
|
+
volume,
|
|
246
|
+
selfSpeaking,
|
|
247
|
+
remotePeers: Object.freeze([...remotePeers.keys()]),
|
|
248
|
+
speakingPeers: Object.freeze([...speakingPeers]),
|
|
249
|
+
mutedPeers: Object.freeze([...mutedPeers])
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
function emitChange() {
|
|
253
|
+
if (closed)
|
|
254
|
+
return;
|
|
255
|
+
changes.fire(buildSnapshot());
|
|
256
|
+
}
|
|
257
|
+
function restoreAudioSession() {
|
|
258
|
+
if (!audioSessionSwitched)
|
|
259
|
+
return;
|
|
260
|
+
audioSessionSwitched = false;
|
|
261
|
+
const prev = prevAudioSessionType;
|
|
262
|
+
prevAudioSessionType = null;
|
|
263
|
+
if (prev === null)
|
|
264
|
+
return;
|
|
265
|
+
const session = getIosAudioSession();
|
|
266
|
+
if (session && session.type === 'play-and-record') {
|
|
267
|
+
try {
|
|
268
|
+
session.type = prev;
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
// Ignore restricted audioSession writes.
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
function switchAudioSessionForMic() {
|
|
276
|
+
const session = getIosAudioSession();
|
|
277
|
+
if (!session || session.type === 'play-and-record')
|
|
278
|
+
return;
|
|
279
|
+
const prev = session.type;
|
|
280
|
+
try {
|
|
281
|
+
session.type = 'play-and-record';
|
|
282
|
+
if (session.type === 'play-and-record') {
|
|
283
|
+
audioSessionSwitched = true;
|
|
284
|
+
prevAudioSessionType = prev;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
// Ignore unsupported audioSession writes.
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
function hasBlockedRemoteAudio() {
|
|
292
|
+
for (const streams of remotePeers.values()) {
|
|
293
|
+
for (const entry of streams.values()) {
|
|
294
|
+
if (entry.blocked || entry.audio.paused)
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
function attachGestureListeners() {
|
|
301
|
+
if (!autoUnlock || closed || gestureListenersAttached || typeof window === 'undefined')
|
|
302
|
+
return;
|
|
303
|
+
gestureListenersAttached = true;
|
|
304
|
+
for (const type of gestureEvents) {
|
|
305
|
+
window.addEventListener(type, unlockAudio, captureOpts);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
function detachGestureListeners() {
|
|
309
|
+
if (!gestureListenersAttached || typeof window === 'undefined')
|
|
310
|
+
return;
|
|
311
|
+
gestureListenersAttached = false;
|
|
312
|
+
for (const type of gestureEvents) {
|
|
313
|
+
window.removeEventListener(type, unlockAudio, captureOpts);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
function markAutoplayBlocked() {
|
|
317
|
+
if (closed)
|
|
318
|
+
return;
|
|
319
|
+
const changed = !autoplayBlocked;
|
|
320
|
+
autoplayBlocked = true;
|
|
321
|
+
attachGestureListeners();
|
|
322
|
+
if (changed)
|
|
323
|
+
emitChange();
|
|
324
|
+
}
|
|
325
|
+
function reconcileUnlockState() {
|
|
326
|
+
if (closed)
|
|
327
|
+
return;
|
|
328
|
+
let changed = false;
|
|
329
|
+
if (autoplayBlocked && !hasBlockedRemoteAudio()) {
|
|
330
|
+
autoplayBlocked = false;
|
|
331
|
+
changed = true;
|
|
332
|
+
}
|
|
333
|
+
if (!autoplayBlocked && !isAudioCtxPaused(audioCtx)) {
|
|
334
|
+
detachGestureListeners();
|
|
335
|
+
}
|
|
336
|
+
if (changed)
|
|
337
|
+
emitChange();
|
|
338
|
+
}
|
|
339
|
+
function tryPlayEntry(peerId, streamId, entry) {
|
|
340
|
+
let playPromise;
|
|
341
|
+
try {
|
|
342
|
+
playPromise = entry.audio.play();
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
if (!playPromise || typeof playPromise.then !== 'function')
|
|
348
|
+
return;
|
|
349
|
+
void playPromise
|
|
350
|
+
.then(() => {
|
|
351
|
+
if (closed || remotePeers.get(peerId)?.get(streamId) !== entry)
|
|
352
|
+
return;
|
|
353
|
+
entry.blocked = false;
|
|
354
|
+
reconcileUnlockState();
|
|
355
|
+
})
|
|
356
|
+
.catch((err) => {
|
|
357
|
+
if (closed || remotePeers.get(peerId)?.get(streamId) !== entry)
|
|
358
|
+
return;
|
|
359
|
+
const name = err && typeof err === 'object' && 'name' in err
|
|
360
|
+
? String(err.name)
|
|
361
|
+
: '';
|
|
362
|
+
if (name !== 'NotAllowedError')
|
|
363
|
+
return;
|
|
364
|
+
entry.blocked = true;
|
|
365
|
+
markAutoplayBlocked();
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
// Never gate on an in-flight boolean or await audioCtx.resume(): on iOS Safari,
|
|
369
|
+
// pointerdown is not a media activation gesture and leaves audioCtx.resume()
|
|
370
|
+
// pending forever until a subsequent touchend/pointerup/click calls resume() again.
|
|
371
|
+
function unlockAudio() {
|
|
372
|
+
if (closed)
|
|
373
|
+
return;
|
|
374
|
+
if (isAudioCtxPaused(audioCtx)) {
|
|
375
|
+
void audioCtx
|
|
376
|
+
.resume()
|
|
377
|
+
.then(() => reconcileUnlockState())
|
|
378
|
+
.catch(() => { });
|
|
379
|
+
}
|
|
380
|
+
let attemptedPlay = false;
|
|
381
|
+
for (const [peerId, streams] of remotePeers) {
|
|
382
|
+
for (const [streamId, entry] of streams) {
|
|
383
|
+
if (entry.audio.paused) {
|
|
384
|
+
attemptedPlay = true;
|
|
385
|
+
tryPlayEntry(peerId, streamId, entry);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
if (!attemptedPlay) {
|
|
390
|
+
reconcileUnlockState();
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
function isAnalyserActive(entry) {
|
|
394
|
+
if (!entry?.analyser || !entry.data)
|
|
395
|
+
return false;
|
|
396
|
+
entry.analyser.getByteTimeDomainData(entry.data);
|
|
397
|
+
let sum = 0;
|
|
398
|
+
for (let i = 0; i < entry.data.length; i++) {
|
|
399
|
+
const d = (entry.data[i] - 128) / 128;
|
|
400
|
+
sum += d * d;
|
|
401
|
+
}
|
|
402
|
+
return Math.sqrt(sum / entry.data.length) > speakingThreshold;
|
|
403
|
+
}
|
|
404
|
+
function ensureMeter() {
|
|
405
|
+
if (!speakingDetection || closed || meterTimer !== undefined)
|
|
406
|
+
return;
|
|
407
|
+
if (remotePeers.size === 0 && !localMeter)
|
|
408
|
+
return;
|
|
409
|
+
meterTimer = setInterval(() => {
|
|
410
|
+
if (closed)
|
|
411
|
+
return;
|
|
412
|
+
let changed = false;
|
|
413
|
+
for (const [peerId, streams] of remotePeers) {
|
|
414
|
+
let active = false;
|
|
415
|
+
for (const entry of streams.values()) {
|
|
416
|
+
if (isAnalyserActive(entry)) {
|
|
417
|
+
active = true;
|
|
418
|
+
break;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
const was = speakingPeers.has(peerId);
|
|
422
|
+
if (active && !was) {
|
|
423
|
+
speakingPeers.add(peerId);
|
|
424
|
+
changed = true;
|
|
425
|
+
}
|
|
426
|
+
else if (!active && was) {
|
|
427
|
+
speakingPeers.delete(peerId);
|
|
428
|
+
changed = true;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
const nextSelf = micStatus === 'live' && isAnalyserActive(localMeter);
|
|
432
|
+
if (nextSelf !== selfSpeaking) {
|
|
433
|
+
selfSpeaking = nextSelf;
|
|
434
|
+
changed = true;
|
|
435
|
+
}
|
|
436
|
+
if (changed)
|
|
437
|
+
emitChange();
|
|
438
|
+
}, speakingIntervalMs);
|
|
439
|
+
}
|
|
440
|
+
function stopMeterIfEmpty() {
|
|
441
|
+
if (remotePeers.size === 0) {
|
|
442
|
+
speakingPeers.clear();
|
|
443
|
+
autoplayBlocked = false;
|
|
444
|
+
if (!isAudioCtxPaused(audioCtx)) {
|
|
445
|
+
detachGestureListeners();
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
if (remotePeers.size > 0 || localMeter)
|
|
449
|
+
return;
|
|
450
|
+
if (meterTimer !== undefined) {
|
|
451
|
+
clearInterval(meterTimer);
|
|
452
|
+
meterTimer = undefined;
|
|
453
|
+
}
|
|
454
|
+
if (audioCtx) {
|
|
455
|
+
const ctx = audioCtx;
|
|
456
|
+
audioCtx = null;
|
|
457
|
+
silentSink?.disconnect();
|
|
458
|
+
silentSink = null;
|
|
459
|
+
ctx.onstatechange = null;
|
|
460
|
+
void ctx.close().catch(() => { });
|
|
461
|
+
}
|
|
462
|
+
detachGestureListeners();
|
|
463
|
+
}
|
|
464
|
+
function createAnalyser(stream) {
|
|
465
|
+
if (!speakingDetection || typeof AudioContext !== 'function')
|
|
466
|
+
return {};
|
|
467
|
+
try {
|
|
468
|
+
if (!audioCtx) {
|
|
469
|
+
const rawCtx = new AudioContext();
|
|
470
|
+
const ctx = rawCtx;
|
|
471
|
+
rawCtx.onstatechange = () => {
|
|
472
|
+
if (closed || audioCtx !== ctx)
|
|
473
|
+
return;
|
|
474
|
+
if (isAudioCtxPaused(ctx))
|
|
475
|
+
attachGestureListeners();
|
|
476
|
+
else
|
|
477
|
+
reconcileUnlockState();
|
|
478
|
+
};
|
|
479
|
+
const gain = rawCtx.createGain();
|
|
480
|
+
gain.gain.value = 0;
|
|
481
|
+
gain.connect(rawCtx.destination);
|
|
482
|
+
audioCtx = ctx;
|
|
483
|
+
silentSink = gain;
|
|
484
|
+
}
|
|
485
|
+
if (isAudioCtxPaused(audioCtx)) {
|
|
486
|
+
void audioCtx.resume().catch(() => { });
|
|
487
|
+
attachGestureListeners();
|
|
488
|
+
}
|
|
489
|
+
const rawCtx = audioCtx;
|
|
490
|
+
const source = rawCtx.createMediaStreamSource(stream);
|
|
491
|
+
const analyser = rawCtx.createAnalyser();
|
|
492
|
+
analyser.fftSize = 256;
|
|
493
|
+
source.connect(analyser);
|
|
494
|
+
if (silentSink)
|
|
495
|
+
analyser.connect(silentSink);
|
|
496
|
+
return { source, analyser, data: new Uint8Array(analyser.fftSize) };
|
|
497
|
+
}
|
|
498
|
+
catch {
|
|
499
|
+
return {};
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
function teardownLocalStream(detachFromRoom) {
|
|
503
|
+
let changed = false;
|
|
504
|
+
for (const cleanup of localTrackCleanups)
|
|
505
|
+
cleanup();
|
|
506
|
+
localTrackCleanups = [];
|
|
507
|
+
if (localMeter) {
|
|
508
|
+
localMeter.source?.disconnect();
|
|
509
|
+
localMeter.analyser?.disconnect();
|
|
510
|
+
localMeter = null;
|
|
511
|
+
}
|
|
512
|
+
if (selfSpeaking) {
|
|
513
|
+
selfSpeaking = false;
|
|
514
|
+
changed = true;
|
|
515
|
+
}
|
|
516
|
+
if (localStream) {
|
|
517
|
+
const stream = localStream;
|
|
518
|
+
localStream = null;
|
|
519
|
+
if (detachFromRoom && !isRoomClosed(room)) {
|
|
520
|
+
try {
|
|
521
|
+
room.removeStream(stream, targetPeer);
|
|
522
|
+
}
|
|
523
|
+
catch {
|
|
524
|
+
// Ignore if room closed concurrently.
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
for (const track of stream.getTracks())
|
|
528
|
+
track.stop();
|
|
529
|
+
changed = true;
|
|
530
|
+
}
|
|
531
|
+
if (micStatus !== 'off') {
|
|
532
|
+
micStatus = 'off';
|
|
533
|
+
changed = true;
|
|
534
|
+
}
|
|
535
|
+
if (micError !== null) {
|
|
536
|
+
micError = null;
|
|
537
|
+
changed = true;
|
|
538
|
+
}
|
|
539
|
+
restoreAudioSession();
|
|
540
|
+
stopMeterIfEmpty();
|
|
541
|
+
return changed;
|
|
542
|
+
}
|
|
543
|
+
function bindLocalTrackEnded(stream) {
|
|
544
|
+
for (const cleanup of localTrackCleanups)
|
|
545
|
+
cleanup();
|
|
546
|
+
localTrackCleanups = [];
|
|
547
|
+
const onTrackEnded = () => {
|
|
548
|
+
if (closed || localStream !== stream)
|
|
549
|
+
return;
|
|
550
|
+
const changed = teardownLocalStream(true);
|
|
551
|
+
if (changed)
|
|
552
|
+
emitChange();
|
|
553
|
+
};
|
|
554
|
+
for (const track of stream.getAudioTracks()) {
|
|
555
|
+
track.addEventListener('ended', onTrackEnded, { once: true });
|
|
556
|
+
localTrackCleanups.push(() => track.removeEventListener('ended', onTrackEnded));
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
function acquireMic() {
|
|
560
|
+
if (closed)
|
|
561
|
+
return Promise.resolve('off');
|
|
562
|
+
if (inFlightMic)
|
|
563
|
+
return inFlightMic;
|
|
564
|
+
if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia) {
|
|
565
|
+
micStatus = 'error';
|
|
566
|
+
micError = Object.freeze({
|
|
567
|
+
code: 'insecure-context',
|
|
568
|
+
message: 'Microphone access requires HTTPS or localhost'
|
|
569
|
+
});
|
|
570
|
+
emitChange();
|
|
571
|
+
return Promise.resolve('error');
|
|
572
|
+
}
|
|
573
|
+
const epoch = ++micEpoch;
|
|
574
|
+
const requestedDeviceId = selectedDeviceId;
|
|
575
|
+
micStatus = 'requesting';
|
|
576
|
+
micError = null;
|
|
577
|
+
emitChange();
|
|
578
|
+
if (closed || epoch !== micEpoch)
|
|
579
|
+
return Promise.resolve('off');
|
|
580
|
+
switchAudioSessionForMic();
|
|
581
|
+
const promise = (async () => {
|
|
582
|
+
let stream;
|
|
583
|
+
try {
|
|
584
|
+
stream = await navigator.mediaDevices.getUserMedia({
|
|
585
|
+
audio: buildAudioConstraints(requestedDeviceId)
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
catch (err) {
|
|
589
|
+
if (closed || epoch !== micEpoch)
|
|
590
|
+
return 'off';
|
|
591
|
+
restoreAudioSession();
|
|
592
|
+
micStatus = 'error';
|
|
593
|
+
micError = classifyMicError(err);
|
|
594
|
+
emitChange();
|
|
595
|
+
return 'error';
|
|
596
|
+
}
|
|
597
|
+
if (closed || epoch !== micEpoch || isRoomClosed(room)) {
|
|
598
|
+
for (const track of stream.getTracks())
|
|
599
|
+
track.stop();
|
|
600
|
+
if (!closed && epoch === micEpoch) {
|
|
601
|
+
restoreAudioSession();
|
|
602
|
+
micStatus = 'error';
|
|
603
|
+
micError = Object.freeze({
|
|
604
|
+
code: 'room-closed',
|
|
605
|
+
message: 'Room is closed'
|
|
606
|
+
});
|
|
607
|
+
emitChange();
|
|
608
|
+
return 'error';
|
|
609
|
+
}
|
|
610
|
+
return 'off';
|
|
611
|
+
}
|
|
612
|
+
try {
|
|
613
|
+
room.addStream(stream, {
|
|
614
|
+
...(targetPeer !== undefined ? { to: targetPeer } : {}),
|
|
615
|
+
tag: streamTag
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
catch {
|
|
619
|
+
restoreAudioSession();
|
|
620
|
+
for (const track of stream.getTracks())
|
|
621
|
+
track.stop();
|
|
622
|
+
micStatus = 'error';
|
|
623
|
+
micError = Object.freeze({
|
|
624
|
+
code: 'room-closed',
|
|
625
|
+
message: 'Room is closed'
|
|
626
|
+
});
|
|
627
|
+
emitChange();
|
|
628
|
+
return 'error';
|
|
629
|
+
}
|
|
630
|
+
localStream = stream;
|
|
631
|
+
const actualDeviceId = stream.getAudioTracks()[0]?.getSettings?.().deviceId;
|
|
632
|
+
selectedDeviceId =
|
|
633
|
+
requestedDeviceId ??
|
|
634
|
+
(typeof actualDeviceId === 'string' && actualDeviceId.length > 0 ? actualDeviceId : null);
|
|
635
|
+
micStatus = 'live';
|
|
636
|
+
micError = null;
|
|
637
|
+
bindLocalTrackEnded(stream);
|
|
638
|
+
const meter = createAnalyser(stream);
|
|
639
|
+
localMeter = meter.analyser ? meter : null;
|
|
640
|
+
ensureMeter();
|
|
641
|
+
unlockAudio();
|
|
642
|
+
emitChange();
|
|
643
|
+
return 'live';
|
|
644
|
+
})();
|
|
645
|
+
inFlightMic = promise;
|
|
646
|
+
void promise.finally(() => {
|
|
647
|
+
if (inFlightMic === promise) {
|
|
648
|
+
inFlightMic = null;
|
|
649
|
+
}
|
|
650
|
+
});
|
|
651
|
+
return promise;
|
|
652
|
+
}
|
|
653
|
+
function teardownRemoteEntry(entry) {
|
|
654
|
+
entry.source?.disconnect();
|
|
655
|
+
entry.analyser?.disconnect();
|
|
656
|
+
try {
|
|
657
|
+
entry.audio.pause();
|
|
658
|
+
}
|
|
659
|
+
catch {
|
|
660
|
+
// Ignore non-standard audio element implementations.
|
|
661
|
+
}
|
|
662
|
+
entry.audio.srcObject = null;
|
|
663
|
+
entry.audio.remove();
|
|
664
|
+
}
|
|
665
|
+
function addRemoteStream(peerId, stream, meta) {
|
|
666
|
+
if (closed || typeof document === 'undefined' || !document.body)
|
|
667
|
+
return;
|
|
668
|
+
if (!stream || typeof stream.getAudioTracks !== 'function')
|
|
669
|
+
return;
|
|
670
|
+
if (stream.getAudioTracks().length === 0)
|
|
671
|
+
return;
|
|
672
|
+
const incomingTag = meta?.tag;
|
|
673
|
+
if (incomingTag === undefined ? strictStreamTag : incomingTag !== streamTag)
|
|
674
|
+
return;
|
|
675
|
+
let byPeer = remotePeers.get(peerId);
|
|
676
|
+
if (!byPeer) {
|
|
677
|
+
byPeer = new Map();
|
|
678
|
+
remotePeers.set(peerId, byPeer);
|
|
679
|
+
}
|
|
680
|
+
if (byPeer.has(stream.id))
|
|
681
|
+
return;
|
|
682
|
+
if (byPeer.size >= maxRemoteStreamsPerPeer)
|
|
683
|
+
return;
|
|
684
|
+
const audio = document.createElement('audio');
|
|
685
|
+
audio.autoplay = true;
|
|
686
|
+
audio.setAttribute('playsinline', '');
|
|
687
|
+
audio.hidden = true;
|
|
688
|
+
audio.muted = effectiveMutedFor(peerId);
|
|
689
|
+
applyAudioVolume(audio, effectiveVolumeFor(peerId));
|
|
690
|
+
audio.srcObject = stream;
|
|
691
|
+
document.body.append(audio);
|
|
692
|
+
const meter = createAnalyser(stream);
|
|
693
|
+
const entry = { audio, blocked: false, ...meter };
|
|
694
|
+
byPeer.set(stream.id, entry);
|
|
695
|
+
const onPlaybackAccepted = () => {
|
|
696
|
+
if (closed || remotePeers.get(peerId)?.get(stream.id) !== entry || entry.audio.paused)
|
|
697
|
+
return;
|
|
698
|
+
entry.blocked = false;
|
|
699
|
+
reconcileUnlockState();
|
|
700
|
+
};
|
|
701
|
+
audio.addEventListener('play', onPlaybackAccepted);
|
|
702
|
+
audio.addEventListener('playing', onPlaybackAccepted);
|
|
703
|
+
tryPlayEntry(peerId, stream.id, entry);
|
|
704
|
+
ensureMeter();
|
|
705
|
+
emitChange();
|
|
706
|
+
}
|
|
707
|
+
function removeRemoteStream(peerId, stream) {
|
|
708
|
+
if (closed)
|
|
709
|
+
return;
|
|
710
|
+
const byPeer = remotePeers.get(peerId);
|
|
711
|
+
const entry = byPeer?.get(stream.id);
|
|
712
|
+
if (!entry || !byPeer)
|
|
713
|
+
return;
|
|
714
|
+
teardownRemoteEntry(entry);
|
|
715
|
+
byPeer.delete(stream.id);
|
|
716
|
+
if (byPeer.size === 0) {
|
|
717
|
+
remotePeers.delete(peerId);
|
|
718
|
+
speakingPeers.delete(peerId);
|
|
719
|
+
}
|
|
720
|
+
stopMeterIfEmpty();
|
|
721
|
+
reconcileUnlockState();
|
|
722
|
+
emitChange();
|
|
723
|
+
}
|
|
724
|
+
const onVisibilityChange = () => {
|
|
725
|
+
if (closed || typeof document === 'undefined' || document.visibilityState !== 'visible')
|
|
726
|
+
return;
|
|
727
|
+
if (isAudioCtxPaused(audioCtx)) {
|
|
728
|
+
void audioCtx
|
|
729
|
+
.resume()
|
|
730
|
+
.then(() => reconcileUnlockState())
|
|
731
|
+
.catch(() => { });
|
|
732
|
+
attachGestureListeners();
|
|
733
|
+
}
|
|
734
|
+
for (const [peerId, streams] of remotePeers) {
|
|
735
|
+
for (const [streamId, entry] of streams) {
|
|
736
|
+
if (entry.audio.paused) {
|
|
737
|
+
tryPlayEntry(peerId, streamId, entry);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
};
|
|
742
|
+
function closeInternal(roomClosing) {
|
|
743
|
+
if (closed)
|
|
744
|
+
return;
|
|
745
|
+
closed = true;
|
|
746
|
+
micEpoch++;
|
|
747
|
+
switchEpoch++;
|
|
748
|
+
inFlightMic = null;
|
|
749
|
+
offStream();
|
|
750
|
+
offStreamEnd();
|
|
751
|
+
offRoomClose();
|
|
752
|
+
if (visibilityListenerAttached && typeof document !== 'undefined') {
|
|
753
|
+
visibilityListenerAttached = false;
|
|
754
|
+
document.removeEventListener('visibilitychange', onVisibilityChange);
|
|
755
|
+
}
|
|
756
|
+
detachGestureListeners();
|
|
757
|
+
teardownLocalStream(!roomClosing);
|
|
758
|
+
for (const byPeer of remotePeers.values()) {
|
|
759
|
+
for (const entry of byPeer.values()) {
|
|
760
|
+
teardownRemoteEntry(entry);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
remotePeers.clear();
|
|
764
|
+
speakingPeers.clear();
|
|
765
|
+
peerVolumes.clear();
|
|
766
|
+
mutedPeers.clear();
|
|
767
|
+
autoplayBlocked = false;
|
|
768
|
+
stopMeterIfEmpty();
|
|
769
|
+
changes.clear();
|
|
770
|
+
}
|
|
771
|
+
let offStream = () => { };
|
|
772
|
+
let offStreamEnd = () => { };
|
|
773
|
+
let offRoomClose = () => { };
|
|
774
|
+
if (isRoomClosed(room)) {
|
|
775
|
+
closed = true;
|
|
776
|
+
changes.clear();
|
|
777
|
+
}
|
|
778
|
+
else {
|
|
779
|
+
offStream = room.onPeerStream(addRemoteStream);
|
|
780
|
+
offStreamEnd = room.onPeerStreamEnd(removeRemoteStream);
|
|
781
|
+
offRoomClose = onRoomClose(room, () => closeInternal(true));
|
|
782
|
+
if (autoUnlock && typeof document !== 'undefined') {
|
|
783
|
+
visibilityListenerAttached = true;
|
|
784
|
+
document.addEventListener('visibilitychange', onVisibilityChange);
|
|
785
|
+
}
|
|
786
|
+
for (const [peerId, stream, meta] of getRoomRemoteStreams(room)) {
|
|
787
|
+
addRemoteStream(peerId, stream, meta);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
return {
|
|
791
|
+
get micStatus() {
|
|
792
|
+
return micStatus;
|
|
793
|
+
},
|
|
794
|
+
get micError() {
|
|
795
|
+
return micError;
|
|
796
|
+
},
|
|
797
|
+
get deviceId() {
|
|
798
|
+
return selectedDeviceId;
|
|
799
|
+
},
|
|
800
|
+
get autoplayBlocked() {
|
|
801
|
+
return autoplayBlocked;
|
|
802
|
+
},
|
|
803
|
+
get deafened() {
|
|
804
|
+
return deafened;
|
|
805
|
+
},
|
|
806
|
+
get volume() {
|
|
807
|
+
return volume;
|
|
808
|
+
},
|
|
809
|
+
get selfSpeaking() {
|
|
810
|
+
return selfSpeaking;
|
|
811
|
+
},
|
|
812
|
+
get remotePeers() {
|
|
813
|
+
return Object.freeze([...remotePeers.keys()]);
|
|
814
|
+
},
|
|
815
|
+
get speakingPeers() {
|
|
816
|
+
return Object.freeze([...speakingPeers]);
|
|
817
|
+
},
|
|
818
|
+
get mutedPeers() {
|
|
819
|
+
return Object.freeze([...mutedPeers]);
|
|
820
|
+
},
|
|
821
|
+
getSnapshot: buildSnapshot,
|
|
822
|
+
toggleMic() {
|
|
823
|
+
if (closed)
|
|
824
|
+
return Promise.resolve('off');
|
|
825
|
+
if (inFlightMic)
|
|
826
|
+
return inFlightMic;
|
|
827
|
+
if (localStream) {
|
|
828
|
+
const nextMuted = micStatus === 'live';
|
|
829
|
+
for (const track of localStream.getAudioTracks()) {
|
|
830
|
+
track.enabled = !nextMuted;
|
|
831
|
+
}
|
|
832
|
+
micStatus = nextMuted ? 'muted' : 'live';
|
|
833
|
+
micError = null;
|
|
834
|
+
if (nextMuted)
|
|
835
|
+
selfSpeaking = false;
|
|
836
|
+
emitChange();
|
|
837
|
+
return Promise.resolve(micStatus);
|
|
838
|
+
}
|
|
839
|
+
return acquireMic();
|
|
840
|
+
},
|
|
841
|
+
startMic() {
|
|
842
|
+
if (closed)
|
|
843
|
+
return Promise.resolve('off');
|
|
844
|
+
if (inFlightMic)
|
|
845
|
+
return inFlightMic;
|
|
846
|
+
if (localStream) {
|
|
847
|
+
if (micStatus === 'muted') {
|
|
848
|
+
for (const track of localStream.getAudioTracks()) {
|
|
849
|
+
track.enabled = true;
|
|
850
|
+
}
|
|
851
|
+
micStatus = 'live';
|
|
852
|
+
micError = null;
|
|
853
|
+
emitChange();
|
|
854
|
+
}
|
|
855
|
+
return Promise.resolve('live');
|
|
856
|
+
}
|
|
857
|
+
return acquireMic();
|
|
858
|
+
},
|
|
859
|
+
setMuted(muted) {
|
|
860
|
+
if (closed || !localStream)
|
|
861
|
+
return;
|
|
862
|
+
const next = Boolean(muted);
|
|
863
|
+
const nextStatus = next ? 'muted' : 'live';
|
|
864
|
+
if (micStatus === nextStatus)
|
|
865
|
+
return;
|
|
866
|
+
for (const track of localStream.getAudioTracks()) {
|
|
867
|
+
track.enabled = !next;
|
|
868
|
+
}
|
|
869
|
+
micStatus = nextStatus;
|
|
870
|
+
micError = null;
|
|
871
|
+
if (next)
|
|
872
|
+
selfSpeaking = false;
|
|
873
|
+
emitChange();
|
|
874
|
+
},
|
|
875
|
+
stopMic() {
|
|
876
|
+
if (closed)
|
|
877
|
+
return;
|
|
878
|
+
const wasRequesting = inFlightMic !== null;
|
|
879
|
+
micEpoch++;
|
|
880
|
+
switchEpoch++;
|
|
881
|
+
inFlightMic = null;
|
|
882
|
+
const changed = teardownLocalStream(true);
|
|
883
|
+
if (changed || wasRequesting)
|
|
884
|
+
emitChange();
|
|
885
|
+
},
|
|
886
|
+
async switchDevice(deviceId) {
|
|
887
|
+
let nextDeviceId = null;
|
|
888
|
+
if (deviceId !== undefined && deviceId !== null && deviceId !== '') {
|
|
889
|
+
if (typeof deviceId !== 'string' || deviceId.trim().length === 0) {
|
|
890
|
+
throw new TypeError('Expected deviceId to be a non-empty string, null, or undefined');
|
|
891
|
+
}
|
|
892
|
+
nextDeviceId = deviceId;
|
|
893
|
+
}
|
|
894
|
+
if (closed)
|
|
895
|
+
return 'off';
|
|
896
|
+
if (inFlightMic !== null) {
|
|
897
|
+
micEpoch++;
|
|
898
|
+
switchEpoch++;
|
|
899
|
+
inFlightMic = null;
|
|
900
|
+
selectedDeviceId = nextDeviceId;
|
|
901
|
+
return acquireMic();
|
|
902
|
+
}
|
|
903
|
+
if (!localStream || (micStatus !== 'live' && micStatus !== 'muted')) {
|
|
904
|
+
if (selectedDeviceId !== nextDeviceId) {
|
|
905
|
+
selectedDeviceId = nextDeviceId;
|
|
906
|
+
emitChange();
|
|
907
|
+
}
|
|
908
|
+
return micStatus;
|
|
909
|
+
}
|
|
910
|
+
if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia) {
|
|
911
|
+
micError = Object.freeze({
|
|
912
|
+
code: 'insecure-context',
|
|
913
|
+
message: 'Microphone access requires HTTPS or localhost'
|
|
914
|
+
});
|
|
915
|
+
emitChange();
|
|
916
|
+
return micStatus;
|
|
917
|
+
}
|
|
918
|
+
if (typeof room.replaceStreamTrack !== 'function') {
|
|
919
|
+
throw new TypeError('Room instance does not support replaceStreamTrack');
|
|
920
|
+
}
|
|
921
|
+
const epoch = micEpoch;
|
|
922
|
+
const sEpoch = ++switchEpoch;
|
|
923
|
+
let newStream;
|
|
924
|
+
try {
|
|
925
|
+
newStream = await navigator.mediaDevices.getUserMedia({
|
|
926
|
+
audio: buildAudioConstraints(nextDeviceId)
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
catch (err) {
|
|
930
|
+
if (closed)
|
|
931
|
+
return 'off';
|
|
932
|
+
if (epoch !== micEpoch || sEpoch !== switchEpoch)
|
|
933
|
+
return micStatus;
|
|
934
|
+
micError = classifyMicError(err);
|
|
935
|
+
emitChange();
|
|
936
|
+
return micStatus;
|
|
937
|
+
}
|
|
938
|
+
if (closed ||
|
|
939
|
+
epoch !== micEpoch ||
|
|
940
|
+
sEpoch !== switchEpoch ||
|
|
941
|
+
!localStream ||
|
|
942
|
+
isRoomClosed(room)) {
|
|
943
|
+
for (const t of newStream.getTracks())
|
|
944
|
+
t.stop();
|
|
945
|
+
return closed ? 'off' : micStatus;
|
|
946
|
+
}
|
|
947
|
+
let resultStatus = micStatus;
|
|
948
|
+
const runSwap = swapQueue.then(async () => {
|
|
949
|
+
if (closed ||
|
|
950
|
+
epoch !== micEpoch ||
|
|
951
|
+
sEpoch !== switchEpoch ||
|
|
952
|
+
!localStream ||
|
|
953
|
+
isRoomClosed(room)) {
|
|
954
|
+
for (const t of newStream.getTracks())
|
|
955
|
+
t.stop();
|
|
956
|
+
resultStatus = closed ? 'off' : micStatus;
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
const audioTracks = newStream.getAudioTracks();
|
|
960
|
+
const newTrack = audioTracks[0];
|
|
961
|
+
for (const extra of newStream.getTracks()) {
|
|
962
|
+
if (extra !== newTrack)
|
|
963
|
+
extra.stop();
|
|
964
|
+
}
|
|
965
|
+
const targetStream = localStream;
|
|
966
|
+
const oldTrack = targetStream.getAudioTracks()[0];
|
|
967
|
+
if (!newTrack || !oldTrack) {
|
|
968
|
+
newTrack?.stop();
|
|
969
|
+
resultStatus = micStatus;
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
newTrack.enabled = micStatus === 'live';
|
|
973
|
+
for (const cleanup of localTrackCleanups)
|
|
974
|
+
cleanup();
|
|
975
|
+
localTrackCleanups = [];
|
|
976
|
+
let replaceInvoked = false;
|
|
977
|
+
try {
|
|
978
|
+
replaceInvoked = true;
|
|
979
|
+
await room.replaceStreamTrack(targetStream, oldTrack, newTrack);
|
|
980
|
+
}
|
|
981
|
+
catch (err) {
|
|
982
|
+
if (replaceInvoked && !targetStream.getTracks().includes(oldTrack)) {
|
|
983
|
+
oldTrack.stop();
|
|
984
|
+
}
|
|
985
|
+
newTrack.stop();
|
|
986
|
+
if (!closed && epoch === micEpoch && localStream === targetStream) {
|
|
987
|
+
if (!targetStream.getAudioTracks().length) {
|
|
988
|
+
teardownLocalStream(true);
|
|
989
|
+
}
|
|
990
|
+
else {
|
|
991
|
+
bindLocalTrackEnded(targetStream);
|
|
992
|
+
}
|
|
993
|
+
micError = classifyMicError(err);
|
|
994
|
+
emitChange();
|
|
995
|
+
}
|
|
996
|
+
resultStatus = closed ? 'off' : micStatus;
|
|
997
|
+
return;
|
|
998
|
+
}
|
|
999
|
+
// oldTrack has been removed from targetStream; always release hardware even if cancelled mid-await.
|
|
1000
|
+
oldTrack.stop();
|
|
1001
|
+
if (closed || epoch !== micEpoch || localStream !== targetStream) {
|
|
1002
|
+
newTrack.stop();
|
|
1003
|
+
resultStatus = closed ? 'off' : micStatus;
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
if (sEpoch !== switchEpoch) {
|
|
1007
|
+
// A newer switchDevice() is queued next in swapQueue and will replace newTrack!
|
|
1008
|
+
bindLocalTrackEnded(targetStream);
|
|
1009
|
+
resultStatus = micStatus;
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
bindLocalTrackEnded(targetStream);
|
|
1013
|
+
if (localMeter) {
|
|
1014
|
+
localMeter.source?.disconnect();
|
|
1015
|
+
localMeter.analyser?.disconnect();
|
|
1016
|
+
localMeter = null;
|
|
1017
|
+
}
|
|
1018
|
+
const meter = createAnalyser(targetStream);
|
|
1019
|
+
localMeter = meter.analyser ? meter : null;
|
|
1020
|
+
ensureMeter();
|
|
1021
|
+
const actualDeviceId = newTrack.getSettings?.().deviceId;
|
|
1022
|
+
selectedDeviceId =
|
|
1023
|
+
nextDeviceId ??
|
|
1024
|
+
(typeof actualDeviceId === 'string' && actualDeviceId.length > 0 ? actualDeviceId : null);
|
|
1025
|
+
micError = null;
|
|
1026
|
+
emitChange();
|
|
1027
|
+
resultStatus = micStatus;
|
|
1028
|
+
});
|
|
1029
|
+
swapQueue = runSwap.catch(() => { });
|
|
1030
|
+
await runSwap;
|
|
1031
|
+
return resultStatus;
|
|
1032
|
+
},
|
|
1033
|
+
setVolume(nextVolume) {
|
|
1034
|
+
if (typeof nextVolume !== 'number' || !Number.isFinite(nextVolume)) {
|
|
1035
|
+
throw new RangeError('Expected a finite volume');
|
|
1036
|
+
}
|
|
1037
|
+
if (closed)
|
|
1038
|
+
return;
|
|
1039
|
+
const clamped = Math.max(0, Math.min(1, nextVolume));
|
|
1040
|
+
if (clamped === volume)
|
|
1041
|
+
return;
|
|
1042
|
+
volume = clamped;
|
|
1043
|
+
for (const [peerId, byPeer] of remotePeers) {
|
|
1044
|
+
const eff = effectiveVolumeFor(peerId);
|
|
1045
|
+
for (const entry of byPeer.values()) {
|
|
1046
|
+
applyAudioVolume(entry.audio, eff);
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
emitChange();
|
|
1050
|
+
},
|
|
1051
|
+
setPeerVolume(peerId, nextPeerVolume) {
|
|
1052
|
+
validatePeerIdArg(peerId);
|
|
1053
|
+
if (typeof nextPeerVolume !== 'number' || !Number.isFinite(nextPeerVolume)) {
|
|
1054
|
+
throw new RangeError('Expected a finite volume');
|
|
1055
|
+
}
|
|
1056
|
+
if (closed)
|
|
1057
|
+
return;
|
|
1058
|
+
const clamped = Math.max(0, Math.min(1, nextPeerVolume));
|
|
1059
|
+
const prev = peerVolumes.get(peerId) ?? 1;
|
|
1060
|
+
if (clamped === prev)
|
|
1061
|
+
return;
|
|
1062
|
+
if (clamped === 1) {
|
|
1063
|
+
peerVolumes.delete(peerId);
|
|
1064
|
+
}
|
|
1065
|
+
else {
|
|
1066
|
+
if (!peerVolumes.has(peerId) && peerVolumes.size >= maxPeerAudioPrefs) {
|
|
1067
|
+
let victim;
|
|
1068
|
+
for (const k of peerVolumes.keys()) {
|
|
1069
|
+
if (!remotePeers.has(k)) {
|
|
1070
|
+
victim = k;
|
|
1071
|
+
break;
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
victim ??= peerVolumes.keys().next().value;
|
|
1075
|
+
if (victim !== undefined)
|
|
1076
|
+
peerVolumes.delete(victim);
|
|
1077
|
+
}
|
|
1078
|
+
peerVolumes.delete(peerId);
|
|
1079
|
+
peerVolumes.set(peerId, clamped);
|
|
1080
|
+
}
|
|
1081
|
+
const byPeer = remotePeers.get(peerId);
|
|
1082
|
+
if (byPeer) {
|
|
1083
|
+
const eff = effectiveVolumeFor(peerId);
|
|
1084
|
+
for (const entry of byPeer.values()) {
|
|
1085
|
+
applyAudioVolume(entry.audio, eff);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
emitChange();
|
|
1089
|
+
},
|
|
1090
|
+
getPeerVolume(peerId) {
|
|
1091
|
+
if (typeof peerId !== 'string' || peerId.length === 0)
|
|
1092
|
+
return 1;
|
|
1093
|
+
return peerVolumes.get(peerId) ?? 1;
|
|
1094
|
+
},
|
|
1095
|
+
setDeafened(nextDeafened) {
|
|
1096
|
+
if (closed)
|
|
1097
|
+
return;
|
|
1098
|
+
const next = Boolean(nextDeafened);
|
|
1099
|
+
if (next === deafened)
|
|
1100
|
+
return;
|
|
1101
|
+
deafened = next;
|
|
1102
|
+
for (const [peerId, byPeer] of remotePeers) {
|
|
1103
|
+
const effMuted = effectiveMutedFor(peerId);
|
|
1104
|
+
for (const entry of byPeer.values()) {
|
|
1105
|
+
entry.audio.muted = effMuted;
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
if (!next)
|
|
1109
|
+
unlockAudio();
|
|
1110
|
+
emitChange();
|
|
1111
|
+
},
|
|
1112
|
+
setPeerMuted(peerId, muted) {
|
|
1113
|
+
validatePeerIdArg(peerId);
|
|
1114
|
+
if (closed)
|
|
1115
|
+
return;
|
|
1116
|
+
const next = Boolean(muted);
|
|
1117
|
+
const was = mutedPeers.has(peerId);
|
|
1118
|
+
if (next === was)
|
|
1119
|
+
return;
|
|
1120
|
+
if (next) {
|
|
1121
|
+
if (mutedPeers.size >= maxPeerAudioPrefs) {
|
|
1122
|
+
let victim;
|
|
1123
|
+
for (const k of mutedPeers) {
|
|
1124
|
+
if (!remotePeers.has(k)) {
|
|
1125
|
+
victim = k;
|
|
1126
|
+
break;
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
victim ??= mutedPeers.values().next().value;
|
|
1130
|
+
if (victim !== undefined)
|
|
1131
|
+
mutedPeers.delete(victim);
|
|
1132
|
+
}
|
|
1133
|
+
mutedPeers.add(peerId);
|
|
1134
|
+
}
|
|
1135
|
+
else {
|
|
1136
|
+
mutedPeers.delete(peerId);
|
|
1137
|
+
}
|
|
1138
|
+
const byPeer = remotePeers.get(peerId);
|
|
1139
|
+
if (byPeer) {
|
|
1140
|
+
const effMuted = effectiveMutedFor(peerId);
|
|
1141
|
+
for (const entry of byPeer.values()) {
|
|
1142
|
+
entry.audio.muted = effMuted;
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
if (!next && !deafened)
|
|
1146
|
+
unlockAudio();
|
|
1147
|
+
emitChange();
|
|
1148
|
+
},
|
|
1149
|
+
isPeerMuted(peerId) {
|
|
1150
|
+
return typeof peerId === 'string' && mutedPeers.has(peerId);
|
|
1151
|
+
},
|
|
1152
|
+
unlockAudio,
|
|
1153
|
+
onChange(fn, listenOpts) {
|
|
1154
|
+
return changes.add(fn, listenOpts);
|
|
1155
|
+
},
|
|
1156
|
+
close() {
|
|
1157
|
+
closeInternal(false);
|
|
1158
|
+
}
|
|
1159
|
+
};
|
|
1160
|
+
}
|