@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.
- package/dist/blob.js +36 -36
- package/dist/channel.d.ts +4 -0
- package/dist/channel.js +4 -0
- package/dist/combine.d.ts +9 -2
- package/dist/combine.js +35 -33
- package/dist/index.d.ts +2 -1
- package/dist/mqtt.js +59 -109
- package/dist/nostr.js +71 -131
- package/dist/peer-link.js +983 -0
- package/dist/presence.js +74 -0
- package/dist/public.js +16 -23
- package/dist/relay-core.js +219 -143
- package/dist/room-reclaim.js +5 -1
- package/dist/room.js +300 -463
- package/dist/rpc.js +25 -28
- package/dist/signaling.js +2 -11
- package/dist/state.js +22 -31
- package/dist/tabs.js +6 -50
- package/dist/voice-mic.js +496 -0
- package/dist/voice-remote.js +568 -0
- package/dist/voice.d.ts +8 -0
- package/dist/voice.js +71 -816
- package/dist/ws.js +20 -58
- package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
- package/docs/api.md +6 -4
- package/docs/behavior.md +4 -4
- package/package.json +4 -2
- package/dist/room-hello.js +0 -129
- package/dist/room-ice.js +0 -115
- package/dist/room-media.js +0 -477
- package/dist/voice-helpers.js +0 -100
- package/dist/voice-meter.d.ts +0 -1
- package/dist/voice-meter.js +0 -79
- /package/dist/{room-hello.d.ts → peer-link.d.ts} +0 -0
- /package/dist/{room-ice.d.ts → presence.d.ts} +0 -0
- /package/dist/{room-media.d.ts → voice-mic.d.ts} +0 -0
- /package/dist/{voice-helpers.d.ts → voice-remote.d.ts} +0 -0
|
@@ -0,0 +1,983 @@
|
|
|
1
|
+
import { decodeCanonicalBase64Url, extractUniqueDtlsFingerprint, signIdentityProof, verifyIdentityProof } from './identity.js';
|
|
2
|
+
import { computeReclaimCommit } from './room-reclaim.js';
|
|
3
|
+
import { parsePeerStats } from './room-stats.js';
|
|
4
|
+
import { isUuid } from './signaling.js';
|
|
5
|
+
/** @internal */
|
|
6
|
+
export const maxPacketBytes = 16 * 1024;
|
|
7
|
+
const bufferLimit = { unreliable: 64 * 1024, reliable: 256 * 1024 };
|
|
8
|
+
const disconnectGrace = 8_000;
|
|
9
|
+
const trickleBatchMs = 50;
|
|
10
|
+
const trickleBatchSize = 16;
|
|
11
|
+
/** @internal */
|
|
12
|
+
export const maxTrickleCandidates = 64;
|
|
13
|
+
const leaveNotice = 'meshpost/1/leave';
|
|
14
|
+
const helloPrefix = 'meshpost/1/hello:';
|
|
15
|
+
const maxHelloBytes = 4096;
|
|
16
|
+
const rtcControlPrefix = 'meshpost/1/rtc:';
|
|
17
|
+
const maxRtcControlBytes = 64 * 1024;
|
|
18
|
+
const maxRtcQueueDepth = 16;
|
|
19
|
+
const maxRemoteStreamsPerPeer = 32;
|
|
20
|
+
const maxRemoteStreamTags = 64;
|
|
21
|
+
/** @internal */
|
|
22
|
+
export const streamTagPattern = /^[a-zA-Z0-9._-]{1,32}$/;
|
|
23
|
+
const emptyStreamMeta = Object.freeze({});
|
|
24
|
+
function buildStreamMeta(tag) {
|
|
25
|
+
return tag !== undefined ? Object.freeze({ tag }) : emptyStreamMeta;
|
|
26
|
+
}
|
|
27
|
+
function parseIncomingStreamTags(raw) {
|
|
28
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
29
|
+
return null;
|
|
30
|
+
const entries = Object.entries(raw);
|
|
31
|
+
if (entries.length > maxRemoteStreamsPerPeer)
|
|
32
|
+
return null;
|
|
33
|
+
const out = [];
|
|
34
|
+
for (const [id, tag] of entries) {
|
|
35
|
+
if (id.length === 0 ||
|
|
36
|
+
id.length > 128 ||
|
|
37
|
+
id === '__proto__' ||
|
|
38
|
+
id === 'constructor' ||
|
|
39
|
+
id === 'prototype' ||
|
|
40
|
+
typeof tag !== 'string' ||
|
|
41
|
+
!streamTagPattern.test(tag)) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
out.push([id, tag]);
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
function parseHelloFrame(data, self, peerId) {
|
|
49
|
+
if (data.length > maxHelloBytes) {
|
|
50
|
+
return { ok: false, error: 'Peer handshake frame exceeded size limit' };
|
|
51
|
+
}
|
|
52
|
+
let parsed = null;
|
|
53
|
+
try {
|
|
54
|
+
const raw = JSON.parse(data.slice(helloPrefix.length));
|
|
55
|
+
parsed =
|
|
56
|
+
raw && typeof raw === 'object' && !Array.isArray(raw)
|
|
57
|
+
? raw
|
|
58
|
+
: null;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
parsed = null;
|
|
62
|
+
}
|
|
63
|
+
if (!parsed || parsed.v !== 1) {
|
|
64
|
+
return { ok: false, error: 'Invalid peer handshake frame' };
|
|
65
|
+
}
|
|
66
|
+
let rc = null;
|
|
67
|
+
if (parsed.rc !== undefined) {
|
|
68
|
+
if (decodeCanonicalBase64Url(parsed.rc, 43, 32) === null) {
|
|
69
|
+
return { ok: false, error: 'Invalid peer handshake commitment' };
|
|
70
|
+
}
|
|
71
|
+
rc = parsed.rc;
|
|
72
|
+
}
|
|
73
|
+
let reclaimCandidate = null;
|
|
74
|
+
if (parsed.reclaim !== undefined) {
|
|
75
|
+
const rec = parsed.reclaim && typeof parsed.reclaim === 'object' && !Array.isArray(parsed.reclaim)
|
|
76
|
+
? parsed.reclaim
|
|
77
|
+
: null;
|
|
78
|
+
if (!rec ||
|
|
79
|
+
typeof rec.id !== 'string' ||
|
|
80
|
+
!isUuid(rec.id) ||
|
|
81
|
+
rec.id === self ||
|
|
82
|
+
rec.id === peerId ||
|
|
83
|
+
decodeCanonicalBase64Url(rec.secret, 22, 16) === null) {
|
|
84
|
+
return { ok: false, error: 'Invalid peer session reclaim proof' };
|
|
85
|
+
}
|
|
86
|
+
reclaimCandidate = { id: rec.id, secret: rec.secret };
|
|
87
|
+
}
|
|
88
|
+
let initialStreamTags = null;
|
|
89
|
+
if (parsed.st !== undefined) {
|
|
90
|
+
initialStreamTags = parseIncomingStreamTags(parsed.st);
|
|
91
|
+
if (!initialStreamTags) {
|
|
92
|
+
return { ok: false, error: 'Invalid peer stream metadata' };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
let idProof = null;
|
|
96
|
+
if (parsed.id !== undefined) {
|
|
97
|
+
if (!parsed.id || typeof parsed.id !== 'object' || Array.isArray(parsed.id)) {
|
|
98
|
+
return { ok: false, error: 'Invalid peer identity proof' };
|
|
99
|
+
}
|
|
100
|
+
idProof = parsed.id;
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
ok: true,
|
|
104
|
+
parsed: { rc, reclaimCandidate, initialStreamTags, idProof }
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** @internal */
|
|
108
|
+
export function createPeerLink(config) {
|
|
109
|
+
const { appId, roomName, self, peerId, attempt, PeerConnection, rtcConfig, useTrickle, needsRelay, hasTurn, timeoutMs, gatherTimeoutMs, extendedGatherMs, identity, localReclaimCommitPromise, getPendingReclaim, getDesiredStreams, getStreamTag, onPublishSdp, onSendIce, onReclaim, onReady, onDrop, onPacket, onDrain, onStream, onStreamEnd, onMediaError } = config;
|
|
110
|
+
const pc = new PeerConnection(rtcConfig);
|
|
111
|
+
// Fixed stream IDs let both endpoints create identical channels without glare.
|
|
112
|
+
let channels;
|
|
113
|
+
try {
|
|
114
|
+
channels = {
|
|
115
|
+
unreliable: pc.createDataChannel('meshpost/1/unreliable', {
|
|
116
|
+
negotiated: true,
|
|
117
|
+
id: 0,
|
|
118
|
+
ordered: false,
|
|
119
|
+
maxRetransmits: 0,
|
|
120
|
+
protocol: appId
|
|
121
|
+
}),
|
|
122
|
+
reliable: pc.createDataChannel('meshpost/1/reliable', {
|
|
123
|
+
negotiated: true,
|
|
124
|
+
id: 1,
|
|
125
|
+
ordered: true,
|
|
126
|
+
protocol: appId
|
|
127
|
+
})
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
pc.close();
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
let closed = false;
|
|
135
|
+
let channelsOpen = false;
|
|
136
|
+
let helloSent = false;
|
|
137
|
+
let helloReceived = false;
|
|
138
|
+
let helloVerified = false;
|
|
139
|
+
let ready = false;
|
|
140
|
+
let accepted = false;
|
|
141
|
+
let published = false;
|
|
142
|
+
let answerApplied = false;
|
|
143
|
+
let remoteDescApplied = false;
|
|
144
|
+
let userId = null;
|
|
145
|
+
let verifiedUserId = null;
|
|
146
|
+
let reclaimCommit = null;
|
|
147
|
+
let remoteReclaimCommit = null;
|
|
148
|
+
let pendingReclaimMatch = null;
|
|
149
|
+
const pendingCandidates = [];
|
|
150
|
+
const early = [];
|
|
151
|
+
const earlyRtc = [];
|
|
152
|
+
const earlyStreams = [];
|
|
153
|
+
let earlyBytes = 0;
|
|
154
|
+
let rtcQueue = Promise.resolve();
|
|
155
|
+
let rtcPending = 0;
|
|
156
|
+
let renegotiateQueued = false;
|
|
157
|
+
const pendingStreamEnds = new Set();
|
|
158
|
+
const senders = new Map();
|
|
159
|
+
const remoteStreams = new Map();
|
|
160
|
+
const remoteStreamTags = new Map();
|
|
161
|
+
let deadline;
|
|
162
|
+
let gather;
|
|
163
|
+
let iceFlush;
|
|
164
|
+
let grace;
|
|
165
|
+
const clearAllTimers = () => {
|
|
166
|
+
clearTimeout(deadline);
|
|
167
|
+
deadline = undefined;
|
|
168
|
+
clearTimeout(gather);
|
|
169
|
+
gather = undefined;
|
|
170
|
+
clearTimeout(iceFlush);
|
|
171
|
+
iceFlush = undefined;
|
|
172
|
+
clearTimeout(grace);
|
|
173
|
+
grace = undefined;
|
|
174
|
+
};
|
|
175
|
+
const remoteMetaFor = (streamId) => buildStreamMeta(remoteStreamTags.get(streamId));
|
|
176
|
+
const collectStreamTags = () => {
|
|
177
|
+
let out;
|
|
178
|
+
for (const stream of senders.keys()) {
|
|
179
|
+
const tag = getStreamTag(stream);
|
|
180
|
+
if (tag !== undefined) {
|
|
181
|
+
out ??= {};
|
|
182
|
+
out[stream.id] = tag;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
};
|
|
187
|
+
const mergeRemoteStreamTags = (entries) => {
|
|
188
|
+
for (const [id, tag] of entries) {
|
|
189
|
+
if (remoteStreamTags.has(id)) {
|
|
190
|
+
remoteStreamTags.delete(id);
|
|
191
|
+
remoteStreamTags.set(id, tag);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
if (remoteStreamTags.size >= maxRemoteStreamTags) {
|
|
195
|
+
let evicted = false;
|
|
196
|
+
for (const existingId of remoteStreamTags.keys()) {
|
|
197
|
+
if (!remoteStreams.has(existingId)) {
|
|
198
|
+
remoteStreamTags.delete(existingId);
|
|
199
|
+
evicted = true;
|
|
200
|
+
break;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (!evicted)
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
remoteStreamTags.set(id, tag);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
const sendRtcControl = (payload) => {
|
|
210
|
+
if (closed || channels.reliable.readyState !== 'open')
|
|
211
|
+
return false;
|
|
212
|
+
try {
|
|
213
|
+
channels.reliable.send(rtcControlPrefix + JSON.stringify(payload));
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
const attachStreamInternal = (stream) => {
|
|
221
|
+
if (closed || senders.has(stream))
|
|
222
|
+
return false;
|
|
223
|
+
const tracks = stream.getTracks();
|
|
224
|
+
if (tracks.length === 0)
|
|
225
|
+
return false;
|
|
226
|
+
const added = [];
|
|
227
|
+
for (const track of tracks) {
|
|
228
|
+
added.push(pc.addTrack(track, stream));
|
|
229
|
+
}
|
|
230
|
+
senders.set(stream, added);
|
|
231
|
+
pendingStreamEnds.delete(stream.id);
|
|
232
|
+
return true;
|
|
233
|
+
};
|
|
234
|
+
const detachStreamInternal = (stream) => {
|
|
235
|
+
const added = senders.get(stream);
|
|
236
|
+
if (!added)
|
|
237
|
+
return false;
|
|
238
|
+
senders.delete(stream);
|
|
239
|
+
for (const sender of added) {
|
|
240
|
+
try {
|
|
241
|
+
pc.removeTrack(sender);
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
// Ignore if connection is closing.
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
pendingStreamEnds.add(stream.id);
|
|
248
|
+
return true;
|
|
249
|
+
};
|
|
250
|
+
const enqueueRenegotiate = () => {
|
|
251
|
+
renegotiateQueued = true;
|
|
252
|
+
rtcQueue = rtcQueue.then(async () => {
|
|
253
|
+
if (closed || !ready || !renegotiateQueued || channels.reliable.readyState !== 'open')
|
|
254
|
+
return;
|
|
255
|
+
if (pc.signalingState !== 'stable')
|
|
256
|
+
return;
|
|
257
|
+
renegotiateQueued = false;
|
|
258
|
+
try {
|
|
259
|
+
const offer = await pc.createOffer();
|
|
260
|
+
if (closed)
|
|
261
|
+
return;
|
|
262
|
+
await pc.setLocalDescription(offer);
|
|
263
|
+
if (closed || !pc.localDescription)
|
|
264
|
+
return;
|
|
265
|
+
const tags = collectStreamTags();
|
|
266
|
+
if (sendRtcControl({
|
|
267
|
+
kind: 'offer',
|
|
268
|
+
sdp: pc.localDescription.sdp,
|
|
269
|
+
...(tags ? { tags } : {})
|
|
270
|
+
})) {
|
|
271
|
+
for (const id of pendingStreamEnds) {
|
|
272
|
+
sendRtcControl({ kind: 'stream-end', id });
|
|
273
|
+
}
|
|
274
|
+
pendingStreamEnds.clear();
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
if (!closed)
|
|
279
|
+
onMediaError('Failed to negotiate media tracks');
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
};
|
|
283
|
+
const handleRtcControl = (raw) => {
|
|
284
|
+
if (closed || raw.length > maxRtcControlBytes || rtcPending >= maxRtcQueueDepth)
|
|
285
|
+
return;
|
|
286
|
+
let msg;
|
|
287
|
+
try {
|
|
288
|
+
const parsed = JSON.parse(raw.slice(rtcControlPrefix.length));
|
|
289
|
+
msg = parsed && typeof parsed === 'object' ? parsed : null;
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if (!msg || typeof msg.kind !== 'string')
|
|
295
|
+
return;
|
|
296
|
+
if (msg.kind === 'stream-end' && typeof msg.id === 'string') {
|
|
297
|
+
const streamId = msg.id;
|
|
298
|
+
rtcPending++;
|
|
299
|
+
rtcQueue = rtcQueue.then(() => {
|
|
300
|
+
rtcPending--;
|
|
301
|
+
if (closed || !ready)
|
|
302
|
+
return;
|
|
303
|
+
const stream = remoteStreams.get(streamId);
|
|
304
|
+
const meta = remoteMetaFor(streamId);
|
|
305
|
+
remoteStreamTags.delete(streamId);
|
|
306
|
+
if (stream) {
|
|
307
|
+
remoteStreams.delete(streamId);
|
|
308
|
+
onStreamEnd(stream, meta);
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
if ((msg.kind !== 'offer' && msg.kind !== 'answer') || typeof msg.sdp !== 'string')
|
|
314
|
+
return;
|
|
315
|
+
let incomingTags = null;
|
|
316
|
+
if (msg.tags !== undefined) {
|
|
317
|
+
incomingTags = parseIncomingStreamTags(msg.tags);
|
|
318
|
+
if (!incomingTags)
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
const kind = msg.kind;
|
|
322
|
+
const sdp = msg.sdp;
|
|
323
|
+
const polite = self > peerId;
|
|
324
|
+
rtcPending++;
|
|
325
|
+
rtcQueue = rtcQueue.then(async () => {
|
|
326
|
+
try {
|
|
327
|
+
if (closed || !ready)
|
|
328
|
+
return;
|
|
329
|
+
if (kind === 'offer') {
|
|
330
|
+
const collision = pc.signalingState !== 'stable';
|
|
331
|
+
if (!polite && collision)
|
|
332
|
+
return;
|
|
333
|
+
try {
|
|
334
|
+
if (polite && collision) {
|
|
335
|
+
await pc.setLocalDescription({ type: 'rollback' });
|
|
336
|
+
renegotiateQueued = true;
|
|
337
|
+
}
|
|
338
|
+
if (incomingTags)
|
|
339
|
+
mergeRemoteStreamTags(incomingTags);
|
|
340
|
+
await pc.setRemoteDescription({ type: 'offer', sdp });
|
|
341
|
+
if (closed)
|
|
342
|
+
return;
|
|
343
|
+
const answer = await pc.createAnswer();
|
|
344
|
+
if (closed)
|
|
345
|
+
return;
|
|
346
|
+
await pc.setLocalDescription(answer);
|
|
347
|
+
if (closed || !pc.localDescription)
|
|
348
|
+
return;
|
|
349
|
+
const answerTags = collectStreamTags();
|
|
350
|
+
sendRtcControl({
|
|
351
|
+
kind: 'answer',
|
|
352
|
+
sdp: pc.localDescription.sdp,
|
|
353
|
+
...(answerTags ? { tags: answerTags } : {})
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
if (!closed)
|
|
358
|
+
onMediaError('Failed to apply media offer');
|
|
359
|
+
}
|
|
360
|
+
if (!closed && renegotiateQueued)
|
|
361
|
+
enqueueRenegotiate();
|
|
362
|
+
}
|
|
363
|
+
else {
|
|
364
|
+
if (pc.signalingState !== 'have-local-offer')
|
|
365
|
+
return;
|
|
366
|
+
try {
|
|
367
|
+
if (incomingTags)
|
|
368
|
+
mergeRemoteStreamTags(incomingTags);
|
|
369
|
+
await pc.setRemoteDescription({ type: 'answer', sdp });
|
|
370
|
+
}
|
|
371
|
+
catch {
|
|
372
|
+
if (!closed)
|
|
373
|
+
onMediaError('Failed to apply media answer');
|
|
374
|
+
}
|
|
375
|
+
if (!closed && renegotiateQueued)
|
|
376
|
+
enqueueRenegotiate();
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
finally {
|
|
380
|
+
rtcPending--;
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
};
|
|
384
|
+
const teardown = (flushLeave) => {
|
|
385
|
+
clearAllTimers();
|
|
386
|
+
const reliable = channels.reliable;
|
|
387
|
+
if (flushLeave && reliable.readyState === 'open') {
|
|
388
|
+
// Give SCTP a bounded opportunity to deliver the departure before closing DTLS.
|
|
389
|
+
const closeTimer = setTimeout(() => pc.close(), 750);
|
|
390
|
+
reliable.addEventListener('close', () => {
|
|
391
|
+
clearTimeout(closeTimer);
|
|
392
|
+
pc.close();
|
|
393
|
+
}, { once: true });
|
|
394
|
+
try {
|
|
395
|
+
reliable.send(leaveNotice);
|
|
396
|
+
reliable.close();
|
|
397
|
+
}
|
|
398
|
+
catch {
|
|
399
|
+
clearTimeout(closeTimer);
|
|
400
|
+
pc.close();
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
else {
|
|
404
|
+
pc.close();
|
|
405
|
+
}
|
|
406
|
+
const endedStreams = ready
|
|
407
|
+
? [...remoteStreams.values()].map((s) => [s, remoteMetaFor(s.id)])
|
|
408
|
+
: [];
|
|
409
|
+
remoteStreams.clear();
|
|
410
|
+
remoteStreamTags.clear();
|
|
411
|
+
senders.clear();
|
|
412
|
+
pendingStreamEnds.clear();
|
|
413
|
+
pendingCandidates.length = 0;
|
|
414
|
+
early.length = 0;
|
|
415
|
+
earlyRtc.length = 0;
|
|
416
|
+
earlyStreams.length = 0;
|
|
417
|
+
return endedStreams;
|
|
418
|
+
};
|
|
419
|
+
const dropInternal = (event, flushLeave = false) => {
|
|
420
|
+
if (closed)
|
|
421
|
+
return;
|
|
422
|
+
closed = true;
|
|
423
|
+
const endedStreams = teardown(flushLeave);
|
|
424
|
+
onDrop({ ...event, endedStreams });
|
|
425
|
+
};
|
|
426
|
+
const applyCandidates = (candidates) => {
|
|
427
|
+
for (const item of candidates) {
|
|
428
|
+
if (closed)
|
|
429
|
+
return;
|
|
430
|
+
void pc.addIceCandidate(item).catch(() => { });
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
const reconcileStreams = () => {
|
|
434
|
+
if (closed || !ready)
|
|
435
|
+
return;
|
|
436
|
+
const desired = getDesiredStreams();
|
|
437
|
+
let needsRenegotiate = false;
|
|
438
|
+
for (const stream of desired) {
|
|
439
|
+
if (attachStreamInternal(stream))
|
|
440
|
+
needsRenegotiate = true;
|
|
441
|
+
}
|
|
442
|
+
for (const stream of [...senders.keys()]) {
|
|
443
|
+
if (!desired.has(stream) && detachStreamInternal(stream)) {
|
|
444
|
+
needsRenegotiate = true;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
if (needsRenegotiate)
|
|
448
|
+
enqueueRenegotiate();
|
|
449
|
+
};
|
|
450
|
+
const tryPromoteReady = () => {
|
|
451
|
+
if (closed || ready || !channelsOpen || !helloSent || !helloVerified)
|
|
452
|
+
return;
|
|
453
|
+
const reclaimMatch = pendingReclaimMatch;
|
|
454
|
+
pendingReclaimMatch = null;
|
|
455
|
+
if (reclaimMatch && !onReclaim(reclaimMatch))
|
|
456
|
+
return;
|
|
457
|
+
if (closed)
|
|
458
|
+
return;
|
|
459
|
+
clearTimeout(deadline);
|
|
460
|
+
deadline = undefined;
|
|
461
|
+
clearTimeout(iceFlush);
|
|
462
|
+
iceFlush = undefined;
|
|
463
|
+
reclaimCommit = remoteReclaimCommit;
|
|
464
|
+
userId = verifiedUserId;
|
|
465
|
+
ready = true;
|
|
466
|
+
onReady();
|
|
467
|
+
if (closed)
|
|
468
|
+
return;
|
|
469
|
+
for (const stream of earlyStreams) {
|
|
470
|
+
if (closed)
|
|
471
|
+
break;
|
|
472
|
+
onStream(stream, remoteMetaFor(stream.id));
|
|
473
|
+
}
|
|
474
|
+
earlyStreams.length = 0;
|
|
475
|
+
for (const raw of earlyRtc) {
|
|
476
|
+
if (closed)
|
|
477
|
+
break;
|
|
478
|
+
handleRtcControl(raw);
|
|
479
|
+
}
|
|
480
|
+
earlyRtc.length = 0;
|
|
481
|
+
for (const [bytes, mode] of early) {
|
|
482
|
+
if (closed)
|
|
483
|
+
break;
|
|
484
|
+
onPacket(bytes, mode);
|
|
485
|
+
}
|
|
486
|
+
early.length = 0;
|
|
487
|
+
reconcileStreams();
|
|
488
|
+
};
|
|
489
|
+
const buildHelloFrame = async () => {
|
|
490
|
+
const rc = await localReclaimCommitPromise;
|
|
491
|
+
const payload = { v: 1 };
|
|
492
|
+
if (rc)
|
|
493
|
+
payload.rc = rc;
|
|
494
|
+
const initialTags = collectStreamTags();
|
|
495
|
+
if (initialTags)
|
|
496
|
+
payload.st = initialTags;
|
|
497
|
+
const pendingReclaim = getPendingReclaim();
|
|
498
|
+
if (pendingReclaim) {
|
|
499
|
+
payload.reclaim = { id: pendingReclaim.id, secret: pendingReclaim.secret };
|
|
500
|
+
}
|
|
501
|
+
if (identity) {
|
|
502
|
+
const localSdp = pc.currentLocalDescription?.sdp ?? pc.localDescription?.sdp;
|
|
503
|
+
const remoteSdp = pc.currentRemoteDescription?.sdp ?? pc.remoteDescription?.sdp;
|
|
504
|
+
const localFp = extractUniqueDtlsFingerprint(localSdp);
|
|
505
|
+
const remoteFp = extractUniqueDtlsFingerprint(remoteSdp);
|
|
506
|
+
if (!localFp || !remoteFp) {
|
|
507
|
+
throw new Error('Missing unique DTLS fingerprint for identity binding');
|
|
508
|
+
}
|
|
509
|
+
payload.id = await signIdentityProof(identity, {
|
|
510
|
+
appId,
|
|
511
|
+
room: roomName,
|
|
512
|
+
signerId: self,
|
|
513
|
+
verifierId: peerId,
|
|
514
|
+
signerFp: localFp,
|
|
515
|
+
verifierFp: remoteFp
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
return helloPrefix + JSON.stringify(payload);
|
|
519
|
+
};
|
|
520
|
+
const verifyHello = async (parsed) => {
|
|
521
|
+
let checkedUserId = null;
|
|
522
|
+
if (parsed.idProof) {
|
|
523
|
+
const localSdp = pc.currentLocalDescription?.sdp ?? pc.localDescription?.sdp;
|
|
524
|
+
const remoteSdp = pc.currentRemoteDescription?.sdp ?? pc.remoteDescription?.sdp;
|
|
525
|
+
const localFp = extractUniqueDtlsFingerprint(localSdp);
|
|
526
|
+
const remoteFp = extractUniqueDtlsFingerprint(remoteSdp);
|
|
527
|
+
if (!localFp || !remoteFp) {
|
|
528
|
+
return {
|
|
529
|
+
ok: false,
|
|
530
|
+
error: 'Missing unique DTLS fingerprint for identity verification'
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
checkedUserId = await verifyIdentityProof(parsed.idProof, {
|
|
534
|
+
appId,
|
|
535
|
+
room: roomName,
|
|
536
|
+
signerId: peerId,
|
|
537
|
+
verifierId: self,
|
|
538
|
+
signerFp: remoteFp,
|
|
539
|
+
verifierFp: localFp
|
|
540
|
+
});
|
|
541
|
+
if (!checkedUserId) {
|
|
542
|
+
return { ok: false, error: 'Peer identity verification failed' };
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
let reclaimMatch = null;
|
|
546
|
+
if (parsed.reclaimCandidate) {
|
|
547
|
+
const commit = await computeReclaimCommit(parsed.reclaimCandidate.id, parsed.reclaimCandidate.secret);
|
|
548
|
+
if (commit)
|
|
549
|
+
reclaimMatch = { id: parsed.reclaimCandidate.id, commit };
|
|
550
|
+
}
|
|
551
|
+
return { ok: true, verifiedUserId: checkedUserId, reclaimMatch };
|
|
552
|
+
};
|
|
553
|
+
// Attach active local streams before initial createOffer() on the offerer for 0-RTT media setup.
|
|
554
|
+
if (self < peerId) {
|
|
555
|
+
for (const stream of getDesiredStreams()) {
|
|
556
|
+
attachStreamInternal(stream);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
pc.ontrack = (event) => {
|
|
560
|
+
if (closed)
|
|
561
|
+
return;
|
|
562
|
+
const stream = event.streams[0] ??
|
|
563
|
+
(typeof MediaStream === 'function' ? new MediaStream([event.track]) : undefined);
|
|
564
|
+
if (!stream)
|
|
565
|
+
return;
|
|
566
|
+
if (remoteStreams.has(stream.id) || remoteStreams.size >= maxRemoteStreamsPerPeer)
|
|
567
|
+
return;
|
|
568
|
+
remoteStreams.set(stream.id, stream);
|
|
569
|
+
if (ready)
|
|
570
|
+
onStream(stream, remoteMetaFor(stream.id));
|
|
571
|
+
else
|
|
572
|
+
earlyStreams.push(stream);
|
|
573
|
+
};
|
|
574
|
+
deadline = setTimeout(() => dropInternal({
|
|
575
|
+
shouldRetry: true,
|
|
576
|
+
error: { code: 'ice-failed', message: 'Connection handshake timed out' }
|
|
577
|
+
}), timeoutMs);
|
|
578
|
+
pc.onconnectionstatechange = () => {
|
|
579
|
+
if (closed)
|
|
580
|
+
return;
|
|
581
|
+
if (pc.connectionState === 'failed') {
|
|
582
|
+
dropInternal({
|
|
583
|
+
shouldRetry: true,
|
|
584
|
+
error: { code: 'ice-failed', message: 'Peer connection failed' }
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
else if (pc.connectionState === 'closed') {
|
|
588
|
+
dropInternal({ shouldRetry: true });
|
|
589
|
+
}
|
|
590
|
+
else if (pc.connectionState === 'disconnected') {
|
|
591
|
+
grace ??= setTimeout(() => dropInternal({ shouldRetry: true }), disconnectGrace);
|
|
592
|
+
}
|
|
593
|
+
else {
|
|
594
|
+
clearTimeout(grace);
|
|
595
|
+
grace = undefined;
|
|
596
|
+
}
|
|
597
|
+
};
|
|
598
|
+
for (const delivery of ['unreliable', 'reliable']) {
|
|
599
|
+
const channel = channels[delivery];
|
|
600
|
+
channel.binaryType = 'arraybuffer';
|
|
601
|
+
channel.bufferedAmountLowThreshold = Math.floor(bufferLimit[delivery] / 2);
|
|
602
|
+
channel.onbufferedamountlow = () => {
|
|
603
|
+
if (!closed && ready)
|
|
604
|
+
onDrain(delivery);
|
|
605
|
+
};
|
|
606
|
+
channel.onclose = () => dropInternal({ shouldRetry: true });
|
|
607
|
+
channel.onerror = () => dropInternal({ shouldRetry: true });
|
|
608
|
+
channel.onopen = () => {
|
|
609
|
+
if (closed || channelsOpen)
|
|
610
|
+
return;
|
|
611
|
+
if (!Object.values(channels).every((c) => c.readyState === 'open'))
|
|
612
|
+
return;
|
|
613
|
+
channelsOpen = true;
|
|
614
|
+
void (async () => {
|
|
615
|
+
try {
|
|
616
|
+
const frame = await buildHelloFrame();
|
|
617
|
+
if (closed)
|
|
618
|
+
return;
|
|
619
|
+
if (channels.reliable.readyState !== 'open') {
|
|
620
|
+
dropInternal({ shouldRetry: true });
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
channels.reliable.send(frame);
|
|
624
|
+
helloSent = true;
|
|
625
|
+
tryPromoteReady();
|
|
626
|
+
}
|
|
627
|
+
catch {
|
|
628
|
+
if (!closed)
|
|
629
|
+
dropInternal({ shouldRetry: true });
|
|
630
|
+
}
|
|
631
|
+
})();
|
|
632
|
+
};
|
|
633
|
+
channel.onmessage = ({ data }) => {
|
|
634
|
+
if (closed)
|
|
635
|
+
return;
|
|
636
|
+
if (data === leaveNotice && delivery === 'reliable') {
|
|
637
|
+
dropInternal({ shouldRetry: true, remoteLeave: true });
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
if (typeof data === 'string' && delivery === 'reliable' && data.startsWith(helloPrefix)) {
|
|
641
|
+
if (helloReceived) {
|
|
642
|
+
dropInternal({ shouldRetry: true });
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
helloReceived = true;
|
|
646
|
+
const parsedRes = parseHelloFrame(data, self, peerId);
|
|
647
|
+
if (!parsedRes.ok) {
|
|
648
|
+
dropInternal({
|
|
649
|
+
shouldRetry: true,
|
|
650
|
+
error: { code: 'auth-failed', message: parsedRes.error }
|
|
651
|
+
});
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
const { parsed } = parsedRes;
|
|
655
|
+
void verifyHello(parsed).then((verified) => {
|
|
656
|
+
if (closed)
|
|
657
|
+
return;
|
|
658
|
+
if (!verified.ok) {
|
|
659
|
+
dropInternal({
|
|
660
|
+
shouldRetry: true,
|
|
661
|
+
error: { code: 'auth-failed', message: verified.error }
|
|
662
|
+
});
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
if (parsed.initialStreamTags)
|
|
666
|
+
mergeRemoteStreamTags(parsed.initialStreamTags);
|
|
667
|
+
verifiedUserId = verified.verifiedUserId;
|
|
668
|
+
remoteReclaimCommit = parsed.rc;
|
|
669
|
+
pendingReclaimMatch = verified.reclaimMatch;
|
|
670
|
+
helloVerified = true;
|
|
671
|
+
tryPromoteReady();
|
|
672
|
+
});
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
if (typeof data === 'string' &&
|
|
676
|
+
delivery === 'reliable' &&
|
|
677
|
+
data.startsWith(rtcControlPrefix)) {
|
|
678
|
+
if (ready)
|
|
679
|
+
handleRtcControl(data);
|
|
680
|
+
else if (earlyRtc.length < 16 && data.length <= maxRtcControlBytes)
|
|
681
|
+
earlyRtc.push(data);
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
if (!(data instanceof ArrayBuffer))
|
|
685
|
+
return;
|
|
686
|
+
if (data.byteLength > maxPacketBytes) {
|
|
687
|
+
if (delivery === 'reliable')
|
|
688
|
+
dropInternal({ shouldRetry: true });
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
const bytes = new Uint8Array(data);
|
|
692
|
+
if (ready)
|
|
693
|
+
onPacket(bytes, delivery);
|
|
694
|
+
else if (early.length >= 64 || earlyBytes + bytes.byteLength > 256 * 1024) {
|
|
695
|
+
if (delivery === 'reliable')
|
|
696
|
+
dropInternal({ shouldRetry: true });
|
|
697
|
+
}
|
|
698
|
+
else {
|
|
699
|
+
early.push([bytes, delivery]);
|
|
700
|
+
earlyBytes += bytes.byteLength;
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
const publishLocalDescription = async (description) => {
|
|
705
|
+
const publish = (force = false) => {
|
|
706
|
+
if (published || closed)
|
|
707
|
+
return;
|
|
708
|
+
if (!force && pc.iceGatheringState !== 'complete')
|
|
709
|
+
return;
|
|
710
|
+
const local = pc.localDescription;
|
|
711
|
+
if (!local || (local.type !== 'offer' && local.type !== 'answer'))
|
|
712
|
+
return;
|
|
713
|
+
clearTimeout(gather);
|
|
714
|
+
gather = undefined;
|
|
715
|
+
published = true;
|
|
716
|
+
if (!onPublishSdp(local.type, local.sdp))
|
|
717
|
+
dropInternal({ shouldRetry: true });
|
|
718
|
+
};
|
|
719
|
+
if (useTrickle) {
|
|
720
|
+
const outgoing = [];
|
|
721
|
+
let totalQueued = 0;
|
|
722
|
+
let gatheringDone = false;
|
|
723
|
+
const flushIce = () => {
|
|
724
|
+
clearTimeout(iceFlush);
|
|
725
|
+
iceFlush = undefined;
|
|
726
|
+
if (!published || closed || ready)
|
|
727
|
+
return;
|
|
728
|
+
while (outgoing.length > 0) {
|
|
729
|
+
onSendIce(outgoing.splice(0, trickleBatchSize));
|
|
730
|
+
}
|
|
731
|
+
};
|
|
732
|
+
const scheduleFlush = (immediate = false) => {
|
|
733
|
+
if (!published || closed || ready)
|
|
734
|
+
return;
|
|
735
|
+
if (immediate || outgoing.length >= trickleBatchSize) {
|
|
736
|
+
flushIce();
|
|
737
|
+
}
|
|
738
|
+
else if (!iceFlush) {
|
|
739
|
+
iceFlush = setTimeout(flushIce, trickleBatchMs);
|
|
740
|
+
}
|
|
741
|
+
};
|
|
742
|
+
pc.onicecandidate = (event) => {
|
|
743
|
+
if (closed || ready)
|
|
744
|
+
return;
|
|
745
|
+
if (!event.candidate) {
|
|
746
|
+
gatheringDone = true;
|
|
747
|
+
if (totalQueued < maxTrickleCandidates) {
|
|
748
|
+
outgoing.push({ candidate: '' });
|
|
749
|
+
totalQueued++;
|
|
750
|
+
}
|
|
751
|
+
scheduleFlush(true);
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
if (totalQueued >= maxTrickleCandidates)
|
|
755
|
+
return;
|
|
756
|
+
outgoing.push({
|
|
757
|
+
candidate: event.candidate.candidate,
|
|
758
|
+
...(event.candidate.sdpMid !== null ? { sdpMid: event.candidate.sdpMid } : {}),
|
|
759
|
+
...(event.candidate.sdpMLineIndex !== null
|
|
760
|
+
? { sdpMLineIndex: event.candidate.sdpMLineIndex }
|
|
761
|
+
: {})
|
|
762
|
+
});
|
|
763
|
+
totalQueued++;
|
|
764
|
+
scheduleFlush(false);
|
|
765
|
+
};
|
|
766
|
+
await pc.setLocalDescription(description);
|
|
767
|
+
if (closed)
|
|
768
|
+
return;
|
|
769
|
+
publish(true);
|
|
770
|
+
if (outgoing.length > 0)
|
|
771
|
+
scheduleFlush(gatheringDone);
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
let hasRelay = false;
|
|
775
|
+
let hasSrflx = false;
|
|
776
|
+
let softExpired = false;
|
|
777
|
+
pc.onicecandidate = (event) => {
|
|
778
|
+
if (closed || published)
|
|
779
|
+
return;
|
|
780
|
+
if (!event.candidate) {
|
|
781
|
+
publish(true);
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
const type = event.candidate.type;
|
|
785
|
+
if (type === 'relay')
|
|
786
|
+
hasRelay = true;
|
|
787
|
+
else if (type === 'srflx')
|
|
788
|
+
hasSrflx = true;
|
|
789
|
+
if (softExpired && (hasRelay || (!needsRelay && hasSrflx))) {
|
|
790
|
+
publish(true);
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
pc.onicegatheringstatechange = () => publish(false);
|
|
794
|
+
await pc.setLocalDescription(description);
|
|
795
|
+
if (closed)
|
|
796
|
+
return;
|
|
797
|
+
publish(false);
|
|
798
|
+
if (!published) {
|
|
799
|
+
gather = setTimeout(() => {
|
|
800
|
+
softExpired = true;
|
|
801
|
+
const waitingForRelay = (needsRelay && !hasRelay) || (hasTurn && !hasRelay && !hasSrflx);
|
|
802
|
+
if (waitingForRelay && extendedGatherMs > gatherTimeoutMs) {
|
|
803
|
+
gather = setTimeout(() => publish(true), extendedGatherMs - gatherTimeoutMs);
|
|
804
|
+
}
|
|
805
|
+
else {
|
|
806
|
+
publish(true);
|
|
807
|
+
}
|
|
808
|
+
}, gatherTimeoutMs);
|
|
809
|
+
}
|
|
810
|
+
};
|
|
811
|
+
return {
|
|
812
|
+
attempt,
|
|
813
|
+
get ready() {
|
|
814
|
+
return ready;
|
|
815
|
+
},
|
|
816
|
+
get accepted() {
|
|
817
|
+
return accepted;
|
|
818
|
+
},
|
|
819
|
+
get userId() {
|
|
820
|
+
return userId;
|
|
821
|
+
},
|
|
822
|
+
get reclaimCommit() {
|
|
823
|
+
return reclaimCommit;
|
|
824
|
+
},
|
|
825
|
+
async start(remoteOffer, earlyCandidates) {
|
|
826
|
+
try {
|
|
827
|
+
if (remoteOffer !== undefined) {
|
|
828
|
+
await pc.setRemoteDescription({ type: 'offer', sdp: remoteOffer });
|
|
829
|
+
if (closed)
|
|
830
|
+
return;
|
|
831
|
+
remoteDescApplied = true;
|
|
832
|
+
if (earlyCandidates && earlyCandidates.length > 0) {
|
|
833
|
+
applyCandidates(earlyCandidates);
|
|
834
|
+
}
|
|
835
|
+
if (pendingCandidates.length > 0) {
|
|
836
|
+
applyCandidates(pendingCandidates.splice(0));
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
accepted = true;
|
|
840
|
+
const description = remoteOffer === undefined ? await pc.createOffer() : await pc.createAnswer();
|
|
841
|
+
if (closed)
|
|
842
|
+
return;
|
|
843
|
+
await publishLocalDescription(description);
|
|
844
|
+
}
|
|
845
|
+
catch {
|
|
846
|
+
dropInternal({ shouldRetry: true });
|
|
847
|
+
}
|
|
848
|
+
},
|
|
849
|
+
applyAnswer(sdp) {
|
|
850
|
+
if (closed || answerApplied || pc.signalingState !== 'have-local-offer')
|
|
851
|
+
return;
|
|
852
|
+
answerApplied = true;
|
|
853
|
+
void pc
|
|
854
|
+
.setRemoteDescription({ type: 'answer', sdp })
|
|
855
|
+
.then(() => {
|
|
856
|
+
if (closed)
|
|
857
|
+
return;
|
|
858
|
+
remoteDescApplied = true;
|
|
859
|
+
if (pendingCandidates.length > 0) {
|
|
860
|
+
applyCandidates(pendingCandidates.splice(0));
|
|
861
|
+
}
|
|
862
|
+
})
|
|
863
|
+
.catch(() => dropInternal({ shouldRetry: true }));
|
|
864
|
+
},
|
|
865
|
+
addRemoteCandidates(candidates) {
|
|
866
|
+
if (closed)
|
|
867
|
+
return;
|
|
868
|
+
if (remoteDescApplied) {
|
|
869
|
+
applyCandidates(candidates);
|
|
870
|
+
}
|
|
871
|
+
else {
|
|
872
|
+
for (const item of candidates) {
|
|
873
|
+
if (pendingCandidates.length >= maxTrickleCandidates)
|
|
874
|
+
break;
|
|
875
|
+
pendingCandidates.push(item);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
},
|
|
879
|
+
resendOfferIfPending() {
|
|
880
|
+
if (closed ||
|
|
881
|
+
ready ||
|
|
882
|
+
answerApplied ||
|
|
883
|
+
!published ||
|
|
884
|
+
pc.signalingState !== 'have-local-offer' ||
|
|
885
|
+
pc.localDescription?.type !== 'offer') {
|
|
886
|
+
return true;
|
|
887
|
+
}
|
|
888
|
+
const ok = onPublishSdp('offer', pc.localDescription.sdp);
|
|
889
|
+
if (!ok)
|
|
890
|
+
dropInternal({ shouldRetry: true });
|
|
891
|
+
return ok;
|
|
892
|
+
},
|
|
893
|
+
send(bytes, delivery) {
|
|
894
|
+
const channel = channels[delivery];
|
|
895
|
+
if (closed || !ready || channel.readyState !== 'open')
|
|
896
|
+
return 'unavailable';
|
|
897
|
+
if (bytes.byteLength > Math.min(maxPacketBytes, pc.sctp?.maxMessageSize || Infinity)) {
|
|
898
|
+
return 'too-large';
|
|
899
|
+
}
|
|
900
|
+
if (channel.bufferedAmount + bytes.byteLength > bufferLimit[delivery])
|
|
901
|
+
return 'busy';
|
|
902
|
+
try {
|
|
903
|
+
channel.send(bytes.buffer instanceof ArrayBuffer
|
|
904
|
+
? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
|
905
|
+
: Uint8Array.from(bytes));
|
|
906
|
+
return 'accepted';
|
|
907
|
+
}
|
|
908
|
+
catch (error) {
|
|
909
|
+
const isOpError = ((typeof DOMException === 'function' && error instanceof DOMException) ||
|
|
910
|
+
error instanceof Error) &&
|
|
911
|
+
error.name === 'OperationError';
|
|
912
|
+
return isOpError ? 'busy' : 'unavailable';
|
|
913
|
+
}
|
|
914
|
+
},
|
|
915
|
+
sendUnloadLeave() {
|
|
916
|
+
if (!closed && channels.reliable.readyState === 'open') {
|
|
917
|
+
try {
|
|
918
|
+
channels.reliable.send(leaveNotice);
|
|
919
|
+
}
|
|
920
|
+
catch {
|
|
921
|
+
// Best-effort unload departure hint.
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
},
|
|
925
|
+
async getStats() {
|
|
926
|
+
if (closed || !ready)
|
|
927
|
+
return null;
|
|
928
|
+
try {
|
|
929
|
+
const report = await pc.getStats();
|
|
930
|
+
if (closed || !ready)
|
|
931
|
+
return null;
|
|
932
|
+
return parsePeerStats(report, channels.unreliable.bufferedAmount, channels.reliable.bufferedAmount);
|
|
933
|
+
}
|
|
934
|
+
catch {
|
|
935
|
+
return null;
|
|
936
|
+
}
|
|
937
|
+
},
|
|
938
|
+
attachStream(stream, renegotiate = true) {
|
|
939
|
+
const added = attachStreamInternal(stream);
|
|
940
|
+
if (added && renegotiate && ready)
|
|
941
|
+
enqueueRenegotiate();
|
|
942
|
+
return added;
|
|
943
|
+
},
|
|
944
|
+
detachStream(stream, renegotiate = true) {
|
|
945
|
+
const removed = detachStreamInternal(stream);
|
|
946
|
+
if (removed && renegotiate && ready)
|
|
947
|
+
enqueueRenegotiate();
|
|
948
|
+
return removed;
|
|
949
|
+
},
|
|
950
|
+
reconcileStreams,
|
|
951
|
+
async replaceTrack(stream, oldTrack, newTrack) {
|
|
952
|
+
const senderList = senders.get(stream);
|
|
953
|
+
if (closed || !senderList)
|
|
954
|
+
return;
|
|
955
|
+
let targetSender = senderList.find((s) => s.track === oldTrack);
|
|
956
|
+
if (!targetSender) {
|
|
957
|
+
const sameKind = senderList.filter((s) => s.track?.kind === newTrack.kind);
|
|
958
|
+
if (sameKind.length === 1)
|
|
959
|
+
targetSender = sameKind[0];
|
|
960
|
+
}
|
|
961
|
+
if (!targetSender)
|
|
962
|
+
return;
|
|
963
|
+
try {
|
|
964
|
+
await targetSender.replaceTrack(newTrack);
|
|
965
|
+
}
|
|
966
|
+
catch {
|
|
967
|
+
if (!closed && ready)
|
|
968
|
+
onMediaError('Failed to replace media track');
|
|
969
|
+
}
|
|
970
|
+
},
|
|
971
|
+
getRemoteStreams() {
|
|
972
|
+
if (closed || !ready)
|
|
973
|
+
return [];
|
|
974
|
+
return [...remoteStreams.values()].map((s) => [s, remoteMetaFor(s.id)]);
|
|
975
|
+
},
|
|
976
|
+
close(options) {
|
|
977
|
+
if (closed)
|
|
978
|
+
return [];
|
|
979
|
+
closed = true;
|
|
980
|
+
return teardown(options?.flushLeave === true);
|
|
981
|
+
}
|
|
982
|
+
};
|
|
983
|
+
}
|