@dimchansky/meshpost 0.6.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.
@@ -0,0 +1,496 @@
1
+ import { isRoomClosed } from './room.js';
2
+ /** @internal */
3
+ export const defaultAudioConstraints = Object.freeze({
4
+ echoCancellation: true,
5
+ noiseSuppression: true,
6
+ autoGainControl: true
7
+ });
8
+ /** @internal */
9
+ export const defaultMicAudioAdapter = {
10
+ get getUserMedia() {
11
+ if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia)
12
+ return undefined;
13
+ return (constraints) => navigator.mediaDevices.getUserMedia(constraints);
14
+ },
15
+ getAudioSession() {
16
+ if (typeof navigator === 'undefined')
17
+ return null;
18
+ const session = navigator.audioSession;
19
+ return session && typeof session === 'object' && typeof session.type === 'string'
20
+ ? session
21
+ : null;
22
+ }
23
+ };
24
+ /** @internal */
25
+ export function normalizeDeviceIdArg(deviceId) {
26
+ if (deviceId === undefined || deviceId === null || deviceId === '')
27
+ return null;
28
+ if (typeof deviceId !== 'string' || deviceId.trim().length === 0) {
29
+ throw new TypeError('Expected deviceId to be a non-empty string, null, or undefined');
30
+ }
31
+ return deviceId;
32
+ }
33
+ function buildAudioConstraints(baseConstraints, deviceOverride, exact) {
34
+ if (deviceOverride !== null) {
35
+ const base = typeof baseConstraints === 'object' ? { ...baseConstraints } : { ...defaultAudioConstraints };
36
+ base.deviceId = exact ? { exact: deviceOverride } : { ideal: deviceOverride };
37
+ return base;
38
+ }
39
+ if (baseConstraints === true)
40
+ return true;
41
+ const copy = { ...baseConstraints };
42
+ delete copy.deviceId;
43
+ return copy;
44
+ }
45
+ function classifyMicError(err) {
46
+ const name = err && typeof err === 'object' && 'name' in err ? String(err.name) : '';
47
+ if (name === 'NotAllowedError' || name === 'PermissionDeniedError') {
48
+ return Object.freeze({
49
+ code: 'permission-denied',
50
+ message: 'Microphone permission denied'
51
+ });
52
+ }
53
+ if (name === 'NotFoundError' ||
54
+ name === 'DevicesNotFoundError' ||
55
+ name === 'OverconstrainedError' ||
56
+ name === 'ConstraintNotSatisfiedError') {
57
+ return Object.freeze({
58
+ code: 'not-found',
59
+ message: 'No matching microphone device found'
60
+ });
61
+ }
62
+ if (name === 'NotReadableError' || name === 'TrackStartError') {
63
+ return Object.freeze({
64
+ code: 'in-use',
65
+ message: 'Microphone is already in use by another application'
66
+ });
67
+ }
68
+ if (name === 'SecurityError') {
69
+ return Object.freeze({
70
+ code: 'insecure-context',
71
+ message: 'Microphone access requires HTTPS or localhost'
72
+ });
73
+ }
74
+ return Object.freeze({
75
+ code: 'unknown',
76
+ message: 'Could not access microphone'
77
+ });
78
+ }
79
+ /** @internal */
80
+ export function createLocalMic(config) {
81
+ const { room, baseConstraints, fallbackToDefaultOnNotFound, targetPeer, streamTag, onLocalStream, onChange } = config;
82
+ const audio = config.audio ?? defaultMicAudioAdapter;
83
+ let selectedDeviceId = config.initialDeviceId;
84
+ let selectedDeviceExact = config.initialDeviceExact;
85
+ let micStatus = 'off';
86
+ let micError = null;
87
+ let micStopReason = null;
88
+ let closed = false;
89
+ let localStream = null;
90
+ let localTrackCleanups = [];
91
+ let micEpoch = 0;
92
+ let switchEpoch = 0;
93
+ let inFlightMic = null;
94
+ let swapQueue = Promise.resolve();
95
+ let audioSessionSwitched = false;
96
+ let prevAudioSessionType = null;
97
+ const buildConstraints = (deviceOverride, exact) => buildAudioConstraints(baseConstraints, deviceOverride, exact);
98
+ function restoreAudioSession() {
99
+ if (!audioSessionSwitched)
100
+ return;
101
+ audioSessionSwitched = false;
102
+ const prev = prevAudioSessionType;
103
+ prevAudioSessionType = null;
104
+ if (prev === null)
105
+ return;
106
+ const session = audio.getAudioSession();
107
+ if (session && session.type === 'play-and-record') {
108
+ try {
109
+ session.type = prev;
110
+ }
111
+ catch {
112
+ // Ignore restricted audioSession writes.
113
+ }
114
+ }
115
+ }
116
+ function switchAudioSessionForMic() {
117
+ const session = audio.getAudioSession();
118
+ if (!session || session.type === 'play-and-record')
119
+ return;
120
+ const prev = session.type;
121
+ try {
122
+ session.type = 'play-and-record';
123
+ if (session.type === 'play-and-record') {
124
+ audioSessionSwitched = true;
125
+ prevAudioSessionType = prev;
126
+ }
127
+ }
128
+ catch {
129
+ // Ignore unsupported audioSession writes.
130
+ }
131
+ }
132
+ function teardownLocalStream(detachFromRoom, reason = null) {
133
+ const hadActiveOrPending = Boolean(localStream) || micStatus !== 'off';
134
+ let changed = false;
135
+ for (const cleanup of localTrackCleanups)
136
+ cleanup();
137
+ localTrackCleanups = [];
138
+ if (localStream) {
139
+ const stream = localStream;
140
+ localStream = null;
141
+ if (detachFromRoom && !isRoomClosed(room)) {
142
+ try {
143
+ room.removeStream(stream, targetPeer);
144
+ }
145
+ catch {
146
+ // Ignore if room closed concurrently.
147
+ }
148
+ }
149
+ for (const track of stream.getTracks())
150
+ track.stop();
151
+ changed = true;
152
+ }
153
+ if (micStatus !== 'off') {
154
+ micStatus = 'off';
155
+ changed = true;
156
+ }
157
+ if (micError !== null) {
158
+ micError = null;
159
+ changed = true;
160
+ }
161
+ if (reason !== null && hadActiveOrPending && micStopReason !== reason) {
162
+ micStopReason = reason;
163
+ changed = true;
164
+ }
165
+ onLocalStream(null, { isLive: false });
166
+ restoreAudioSession();
167
+ return changed;
168
+ }
169
+ function bindLocalTrackEnded(stream) {
170
+ for (const cleanup of localTrackCleanups)
171
+ cleanup();
172
+ localTrackCleanups = [];
173
+ const onTrackEnded = () => {
174
+ if (closed || localStream !== stream)
175
+ return;
176
+ const changed = teardownLocalStream(true, 'ended');
177
+ if (changed)
178
+ onChange();
179
+ };
180
+ for (const track of stream.getAudioTracks()) {
181
+ track.addEventListener('ended', onTrackEnded, { once: true });
182
+ localTrackCleanups.push(() => track.removeEventListener('ended', onTrackEnded));
183
+ }
184
+ }
185
+ function failMic(error) {
186
+ restoreAudioSession();
187
+ micStatus = 'error';
188
+ micError = error;
189
+ micStopReason = null;
190
+ onChange();
191
+ return 'error';
192
+ }
193
+ function applySoftMute(muted) {
194
+ if (closed || !localStream)
195
+ return;
196
+ const next = Boolean(muted);
197
+ const nextStatus = next ? 'muted' : 'live';
198
+ if (micStatus === nextStatus)
199
+ return;
200
+ for (const track of localStream.getAudioTracks()) {
201
+ track.enabled = !next;
202
+ }
203
+ micStatus = nextStatus;
204
+ micError = null;
205
+ onLocalStream(localStream, { isLive: !next });
206
+ onChange();
207
+ }
208
+ function acquireMic() {
209
+ if (closed)
210
+ return Promise.resolve('off');
211
+ if (inFlightMic)
212
+ return inFlightMic;
213
+ const getUserMedia = audio.getUserMedia;
214
+ if (!getUserMedia) {
215
+ return Promise.resolve(failMic(Object.freeze({
216
+ code: 'insecure-context',
217
+ message: 'Microphone access requires HTTPS or localhost'
218
+ })));
219
+ }
220
+ const epoch = ++micEpoch;
221
+ const requestedDeviceId = selectedDeviceId;
222
+ const requestedDeviceExact = selectedDeviceExact;
223
+ micStatus = 'requesting';
224
+ micError = null;
225
+ micStopReason = null;
226
+ onChange();
227
+ if (closed || epoch !== micEpoch)
228
+ return Promise.resolve('off');
229
+ switchAudioSessionForMic();
230
+ const promise = (async () => {
231
+ let stream;
232
+ let fellBackToDefault = false;
233
+ try {
234
+ stream = await getUserMedia({
235
+ audio: buildConstraints(requestedDeviceId, requestedDeviceExact)
236
+ });
237
+ }
238
+ catch (err) {
239
+ if (closed || epoch !== micEpoch)
240
+ return 'off';
241
+ const classified = classifyMicError(err);
242
+ if (fallbackToDefaultOnNotFound &&
243
+ requestedDeviceId !== null &&
244
+ classified.code === 'not-found') {
245
+ try {
246
+ stream = await getUserMedia({ audio: buildConstraints(null, false) });
247
+ fellBackToDefault = true;
248
+ }
249
+ catch (fallbackErr) {
250
+ if (closed || epoch !== micEpoch)
251
+ return 'off';
252
+ return failMic(classifyMicError(fallbackErr));
253
+ }
254
+ }
255
+ else {
256
+ return failMic(classified);
257
+ }
258
+ }
259
+ if (closed || epoch !== micEpoch || isRoomClosed(room)) {
260
+ for (const track of stream.getTracks())
261
+ track.stop();
262
+ if (!closed && epoch === micEpoch) {
263
+ return failMic(Object.freeze({ code: 'room-closed', message: 'Room is closed' }));
264
+ }
265
+ return 'off';
266
+ }
267
+ try {
268
+ room.addStream(stream, {
269
+ ...(targetPeer !== undefined ? { to: targetPeer } : {}),
270
+ tag: streamTag
271
+ });
272
+ }
273
+ catch {
274
+ for (const track of stream.getTracks())
275
+ track.stop();
276
+ return failMic(Object.freeze({ code: 'room-closed', message: 'Room is closed' }));
277
+ }
278
+ localStream = stream;
279
+ const actualDeviceId = stream.getAudioTracks()[0]?.getSettings?.().deviceId;
280
+ const resolvedActual = typeof actualDeviceId === 'string' && actualDeviceId.length > 0 ? actualDeviceId : null;
281
+ if (fellBackToDefault) {
282
+ selectedDeviceId = resolvedActual;
283
+ selectedDeviceExact = false;
284
+ }
285
+ else {
286
+ selectedDeviceId = requestedDeviceId ?? resolvedActual;
287
+ }
288
+ micStatus = 'live';
289
+ micError = null;
290
+ bindLocalTrackEnded(stream);
291
+ onLocalStream(stream, { isLive: true, rebindAnalyser: true, unlock: true });
292
+ onChange();
293
+ return 'live';
294
+ })();
295
+ inFlightMic = promise;
296
+ void promise.finally(() => {
297
+ if (inFlightMic === promise)
298
+ inFlightMic = null;
299
+ });
300
+ return promise;
301
+ }
302
+ return {
303
+ get status() {
304
+ return micStatus;
305
+ },
306
+ get error() {
307
+ return micError;
308
+ },
309
+ get stopReason() {
310
+ return micStopReason;
311
+ },
312
+ get deviceId() {
313
+ return selectedDeviceId;
314
+ },
315
+ toggleMic() {
316
+ if (closed)
317
+ return Promise.resolve('off');
318
+ if (inFlightMic)
319
+ return inFlightMic;
320
+ if (localStream) {
321
+ applySoftMute(micStatus === 'live');
322
+ return Promise.resolve(micStatus);
323
+ }
324
+ return acquireMic();
325
+ },
326
+ startMic() {
327
+ if (closed)
328
+ return Promise.resolve('off');
329
+ if (inFlightMic)
330
+ return inFlightMic;
331
+ if (localStream) {
332
+ applySoftMute(false);
333
+ return Promise.resolve('live');
334
+ }
335
+ return acquireMic();
336
+ },
337
+ setMuted: applySoftMute,
338
+ stopMic() {
339
+ if (closed)
340
+ return;
341
+ const wasRequesting = inFlightMic !== null;
342
+ micEpoch++;
343
+ switchEpoch++;
344
+ inFlightMic = null;
345
+ const changed = teardownLocalStream(true, 'stopped');
346
+ if (changed || wasRequesting)
347
+ onChange();
348
+ },
349
+ async switchDevice(deviceId) {
350
+ const nextDeviceId = normalizeDeviceIdArg(deviceId);
351
+ if (closed)
352
+ return 'off';
353
+ if (inFlightMic !== null) {
354
+ micEpoch++;
355
+ switchEpoch++;
356
+ inFlightMic = null;
357
+ selectedDeviceId = nextDeviceId;
358
+ selectedDeviceExact = nextDeviceId !== null;
359
+ return acquireMic();
360
+ }
361
+ if (!localStream || (micStatus !== 'live' && micStatus !== 'muted')) {
362
+ const hadError = micStatus === 'error' || micError !== null;
363
+ const hadStopReason = micStopReason !== null;
364
+ const deviceChanged = selectedDeviceId !== nextDeviceId;
365
+ selectedDeviceId = nextDeviceId;
366
+ selectedDeviceExact = nextDeviceId !== null;
367
+ if (hadError) {
368
+ micStatus = 'off';
369
+ micError = null;
370
+ }
371
+ if (hadStopReason)
372
+ micStopReason = null;
373
+ if (hadError || hadStopReason || deviceChanged)
374
+ onChange();
375
+ return micStatus;
376
+ }
377
+ const getUserMedia = audio.getUserMedia;
378
+ if (!getUserMedia) {
379
+ micError = Object.freeze({
380
+ code: 'insecure-context',
381
+ message: 'Microphone access requires HTTPS or localhost'
382
+ });
383
+ onChange();
384
+ return micStatus;
385
+ }
386
+ if (typeof room.replaceStreamTrack !== 'function') {
387
+ throw new TypeError('Room instance does not support replaceStreamTrack');
388
+ }
389
+ const epoch = micEpoch;
390
+ const sEpoch = ++switchEpoch;
391
+ const isStale = () => closed || epoch !== micEpoch || sEpoch !== switchEpoch || !localStream || isRoomClosed(room);
392
+ let newStream;
393
+ try {
394
+ newStream = await getUserMedia({
395
+ audio: buildConstraints(nextDeviceId, nextDeviceId !== null)
396
+ });
397
+ }
398
+ catch (err) {
399
+ if (closed)
400
+ return 'off';
401
+ if (epoch !== micEpoch || sEpoch !== switchEpoch)
402
+ return micStatus;
403
+ micError = classifyMicError(err);
404
+ onChange();
405
+ return micStatus;
406
+ }
407
+ if (isStale()) {
408
+ for (const t of newStream.getTracks())
409
+ t.stop();
410
+ return closed ? 'off' : micStatus;
411
+ }
412
+ let resultStatus = micStatus;
413
+ const runSwap = swapQueue.then(async () => {
414
+ if (isStale()) {
415
+ for (const t of newStream.getTracks())
416
+ t.stop();
417
+ resultStatus = closed ? 'off' : micStatus;
418
+ return;
419
+ }
420
+ const audioTracks = newStream.getAudioTracks();
421
+ const newTrack = audioTracks[0];
422
+ for (const extra of newStream.getTracks()) {
423
+ if (extra !== newTrack)
424
+ extra.stop();
425
+ }
426
+ const targetStream = localStream;
427
+ const oldTrack = targetStream.getAudioTracks()[0];
428
+ if (!newTrack || !oldTrack) {
429
+ newTrack?.stop();
430
+ resultStatus = micStatus;
431
+ return;
432
+ }
433
+ newTrack.enabled = micStatus === 'live';
434
+ for (const cleanup of localTrackCleanups)
435
+ cleanup();
436
+ localTrackCleanups = [];
437
+ try {
438
+ await room.replaceStreamTrack(targetStream, oldTrack, newTrack);
439
+ }
440
+ catch (err) {
441
+ if (!targetStream.getTracks().includes(oldTrack)) {
442
+ oldTrack.stop();
443
+ }
444
+ newTrack.stop();
445
+ if (!closed && epoch === micEpoch && localStream === targetStream) {
446
+ if (!targetStream.getAudioTracks().length) {
447
+ teardownLocalStream(true, 'ended');
448
+ }
449
+ else {
450
+ bindLocalTrackEnded(targetStream);
451
+ }
452
+ micError = classifyMicError(err);
453
+ onChange();
454
+ }
455
+ resultStatus = closed ? 'off' : micStatus;
456
+ return;
457
+ }
458
+ // oldTrack has been removed from targetStream; always release hardware even if cancelled mid-await.
459
+ oldTrack.stop();
460
+ if (closed || epoch !== micEpoch || localStream !== targetStream) {
461
+ newTrack.stop();
462
+ resultStatus = closed ? 'off' : micStatus;
463
+ return;
464
+ }
465
+ if (sEpoch !== switchEpoch) {
466
+ // A newer switchDevice() is queued next in swapQueue and will replace newTrack!
467
+ bindLocalTrackEnded(targetStream);
468
+ resultStatus = micStatus;
469
+ return;
470
+ }
471
+ bindLocalTrackEnded(targetStream);
472
+ onLocalStream(targetStream, { isLive: micStatus === 'live', rebindAnalyser: true });
473
+ const actualDeviceId = newTrack.getSettings?.().deviceId;
474
+ selectedDeviceId =
475
+ nextDeviceId ??
476
+ (typeof actualDeviceId === 'string' && actualDeviceId.length > 0 ? actualDeviceId : null);
477
+ selectedDeviceExact = nextDeviceId !== null;
478
+ micError = null;
479
+ onChange();
480
+ resultStatus = micStatus;
481
+ });
482
+ swapQueue = runSwap.catch(() => { });
483
+ await runSwap;
484
+ return resultStatus;
485
+ },
486
+ close(roomClosing) {
487
+ if (closed)
488
+ return;
489
+ closed = true;
490
+ micEpoch++;
491
+ switchEpoch++;
492
+ inFlightMic = null;
493
+ teardownLocalStream(!roomClosing, 'stopped');
494
+ }
495
+ };
496
+ }