@midsummer-ai/sdk 0.1.0-staging.4790 → 0.1.0-staging.4910
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/calls/index.mjs +1 -1629
- package/calls/react.mjs +1 -1
- package/calls/stand-in.mjs +1 -1
- package/calls/ui.mjs +1 -1
- package/calls-CQQ0NnoP.mjs +1681 -0
- package/here-C2jhTheQ.mjs +1 -1
- package/package.json +1 -1
package/calls/index.mjs
CHANGED
|
@@ -1,1630 +1,2 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import { CALL_STATUS, TRACK_KINDS } from "./protocol.mjs";
|
|
3
|
-
//#region src/calls/index.ts
|
|
4
|
-
/**
|
|
5
|
-
* Calls: voice and video in an app, for the people who use it and for agents. A call is a room name in one of the
|
|
6
|
-
* project's environments. Whoever has a token the app's server made for that room is in, and the room opens with
|
|
7
|
-
* the first join: there is nothing to create first.
|
|
8
|
-
*
|
|
9
|
-
* In the browser:
|
|
10
|
-
*
|
|
11
|
-
* import { join } from "@midsummer-ai/sdk/calls"
|
|
12
|
-
*
|
|
13
|
-
* const call = await join("support-42", { token })
|
|
14
|
-
* await call.publish({ mic: true, camera: true })
|
|
15
|
-
* call.on("track", ({ participant, name, track }) => show(participant, name, track))
|
|
16
|
-
* await call.screen.share()
|
|
17
|
-
* call.send({ raised: true })
|
|
18
|
-
* await call.leave()
|
|
19
|
-
*
|
|
20
|
-
* On the app's server, a token for the person, made with no key in a deployment on Midsummer and under
|
|
21
|
-
* `midsummer dev`:
|
|
22
|
-
*
|
|
23
|
-
* import { callToken } from "@midsummer-ai/sdk/calls"
|
|
24
|
-
*
|
|
25
|
-
* return Response.json(await callToken({ room: "support-42", as: user.id, name: user.name }))
|
|
26
|
-
*
|
|
27
|
-
* An agent in Node joins the same way, with a token from `midsummer call token create` and any WebRTC library's
|
|
28
|
-
* `RTCPeerConnection` passed as `rtc`:
|
|
29
|
-
*
|
|
30
|
-
* const call = await join(room, { token, rtc: wrtc })
|
|
31
|
-
*
|
|
32
|
-
* `token` may be a function that asks the app's server for one; it's asked again five minutes before each token runs
|
|
33
|
-
* out. An app that signs people in with Auth can hand out tokens from `auth.handler` (`createAuth({ calls: { allow } })`):
|
|
34
|
-
*
|
|
35
|
-
* const call = await join("support-42", { token: () => fetch("/api/auth/call-token?room=support-42").then((r) => r.json()) })
|
|
36
|
-
*
|
|
37
|
-
* A call's `state` is `connecting` while it joins, `waiting` while nobody else is in the room, `in-call` once someone
|
|
38
|
-
* is (whether or not they send anything), `reconnecting` while the connection dropped and the call joins the room again
|
|
39
|
-
* (for up to 30 seconds, as the same participant, and back once its media connects again), `ended` once the room was
|
|
40
|
-
* ended or you left, and `failed` with `error`, a `CallError` whose `code` shows why. Each change is a `state` event.
|
|
41
|
-
* A call whose media can't connect within 15 seconds of joining fails with the reason `blocked`: the network lets
|
|
42
|
-
* nothing through to it.
|
|
43
|
-
*
|
|
44
|
-
* Every audio track in the room is received. Videos are received too, up to 9 at once at the half layer (`h`), unless
|
|
45
|
-
* `autoVideo` is false; a grid that shows fewer tiles asks for what it shows with `receive`, `setLayer` and
|
|
46
|
-
* `stopReceiving`. A camera is asked for at 1280×720 and sent in three layers: `q` (a quarter of its size, about
|
|
47
|
-
* 150 kbps), `h` (half, 500 kbps) and `f` (full, 1.5 Mbps). One that gives less than 960×540 is sent in two, its full
|
|
48
|
-
* size as `h` and half as `q`, and asking for `f` gets `h`. A participant receives at most 9 videos, 2 of them at
|
|
49
|
-
* `f`; asking for more is refused.
|
|
50
|
-
*
|
|
51
|
-
* Under `midsummer dev` and in tests there's no media server (`media: "relay"`): each pair of participants connects
|
|
52
|
-
* directly. The participant with the smaller id makes the one offer, with four two-way transceivers in the order mic,
|
|
53
|
-
* camera, screen and screen-audio and one data channel, and each sends it through the room (`signal`), whole, once
|
|
54
|
-
* its addresses are gathered. A track is sent by placing it on its transceiver, so nothing is offered again, and is
|
|
55
|
-
* known by its transceiver's place. Someone who joins again offers to everyone, and an offer always starts a new
|
|
56
|
-
* connection; of two offers that cross, the smaller id's stands.
|
|
57
|
-
*/
|
|
58
|
-
/** The most a message sent with `send` carries, as JSON. */
|
|
59
|
-
const MAX_MESSAGE_BYTES = 16384;
|
|
60
|
-
/** The most videos a participant receives at once, and how many of them at the full layer. */
|
|
61
|
-
const MAX_VIDEOS = 9;
|
|
62
|
-
const MAX_FULL_VIDEOS = 2;
|
|
63
|
-
/** How long before a token runs out it is asked for again. */
|
|
64
|
-
const RENEW_BEFORE_MS = 3e5;
|
|
65
|
-
/** How long a dropped call tries to join again before it fails. */
|
|
66
|
-
const REJOIN_FOR_MS = 3e4;
|
|
67
|
-
/** How long one watch waits on the room; the platform returns by then, and the next is asked at once. */
|
|
68
|
-
const WATCH_WAIT_MS = 25e3;
|
|
69
|
-
/** The most tracks one pull asks for. */
|
|
70
|
-
const PULL_MAX = 16;
|
|
71
|
-
/** The tracks' places on a direct connection, in order. */
|
|
72
|
-
const TRACK_ORDER = [
|
|
73
|
-
"mic",
|
|
74
|
-
"camera",
|
|
75
|
-
"screen",
|
|
76
|
-
"screen-audio"
|
|
77
|
-
];
|
|
78
|
-
/** How long a connection has to reach the media, from its first offer answered, before the network is taken to block it. */
|
|
79
|
-
const CONNECT_WITHIN_MS = 15e3;
|
|
80
|
-
/**
|
|
81
|
-
* What a viewer sends on its own channel to ask whoever sends a video for a key frame, followed by the sender's id and
|
|
82
|
-
* the track's name. It isn't JSON, so an SDK from before it takes it for no message at all.
|
|
83
|
-
*/
|
|
84
|
-
const KEY_FRAME = "msc:key ";
|
|
85
|
-
/** The least time between two key frames a sender makes because it was asked. */
|
|
86
|
-
const KEY_FRAME_EVERY_MS = 1e3;
|
|
87
|
-
/** How long a received video may show no new frame before its layer is taken to have stopped. */
|
|
88
|
-
const STALLED_MS = 2500;
|
|
89
|
-
/** How long a video that fell to the small layer stays there before the middle one is tried again, at first; doubled each time it stalls again, up to two minutes. */
|
|
90
|
-
const CLIMB_AFTER_MS = 15e3;
|
|
91
|
-
const CLIMB_AFTER_MAX_MS = 12e4;
|
|
92
|
-
/**
|
|
93
|
-
* Whether a received video's layer has stopped, decided once a second from how many frames it has decoded. The small
|
|
94
|
-
* and middle layers are sent exactly as asked, so a viewer on the middle one would freeze if its sender stopped
|
|
95
|
-
* sending it, as a browser on a weak connection does: stalled for `STALLED_MS` it is asked for at the small layer
|
|
96
|
-
* (`ask: "q"`), and once that moves, the middle one is tried again after a wait that doubles each time it stalls
|
|
97
|
-
* (`ask: "h"`). The small layer is always sent, and the full one falls by itself, so neither is watched. `layer` is
|
|
98
|
-
* the layer the page asked for.
|
|
99
|
-
*/
|
|
100
|
-
function layerWatch(layer, frames, now, before) {
|
|
101
|
-
const moved = before === void 0 || frames !== before.frames;
|
|
102
|
-
const state = {
|
|
103
|
-
...before,
|
|
104
|
-
frames,
|
|
105
|
-
movedAt: moved ? now : before.movedAt
|
|
106
|
-
};
|
|
107
|
-
if (layer !== "h") return { next: {
|
|
108
|
-
frames,
|
|
109
|
-
movedAt: state.movedAt
|
|
110
|
-
} };
|
|
111
|
-
const stalled = !moved && now - state.movedAt >= STALLED_MS;
|
|
112
|
-
if (state.climbing) {
|
|
113
|
-
if (stalled) return {
|
|
114
|
-
next: {
|
|
115
|
-
frames,
|
|
116
|
-
movedAt: now,
|
|
117
|
-
fell: {
|
|
118
|
-
climbAt: now + Math.min(state.climbing.waited * 2, CLIMB_AFTER_MAX_MS),
|
|
119
|
-
waited: Math.min(state.climbing.waited * 2, CLIMB_AFTER_MAX_MS)
|
|
120
|
-
}
|
|
121
|
-
},
|
|
122
|
-
ask: "q"
|
|
123
|
-
};
|
|
124
|
-
if (moved && now - state.climbing.since >= STALLED_MS * 2) return { next: {
|
|
125
|
-
frames,
|
|
126
|
-
movedAt: now
|
|
127
|
-
} };
|
|
128
|
-
return { next: state };
|
|
129
|
-
}
|
|
130
|
-
if (state.fell) {
|
|
131
|
-
if (moved && now >= state.fell.climbAt) return {
|
|
132
|
-
next: {
|
|
133
|
-
frames,
|
|
134
|
-
movedAt: now,
|
|
135
|
-
climbing: {
|
|
136
|
-
since: now,
|
|
137
|
-
waited: state.fell.waited
|
|
138
|
-
}
|
|
139
|
-
},
|
|
140
|
-
ask: "h"
|
|
141
|
-
};
|
|
142
|
-
return { next: state };
|
|
143
|
-
}
|
|
144
|
-
if (stalled) return {
|
|
145
|
-
next: {
|
|
146
|
-
frames,
|
|
147
|
-
movedAt: now,
|
|
148
|
-
fell: {
|
|
149
|
-
climbAt: now + CLIMB_AFTER_MS,
|
|
150
|
-
waited: CLIMB_AFTER_MS
|
|
151
|
-
}
|
|
152
|
-
},
|
|
153
|
-
ask: "q"
|
|
154
|
-
};
|
|
155
|
-
return { next: state };
|
|
156
|
-
}
|
|
157
|
-
/** A camera's three layers, smallest first. */
|
|
158
|
-
const SIMULCAST = [
|
|
159
|
-
{
|
|
160
|
-
rid: "q",
|
|
161
|
-
scaleResolutionDownBy: 4,
|
|
162
|
-
maxBitrate: 15e4
|
|
163
|
-
},
|
|
164
|
-
{
|
|
165
|
-
rid: "h",
|
|
166
|
-
scaleResolutionDownBy: 2,
|
|
167
|
-
maxBitrate: 5e5
|
|
168
|
-
},
|
|
169
|
-
{
|
|
170
|
-
rid: "f",
|
|
171
|
-
scaleResolutionDownBy: 1,
|
|
172
|
-
maxBitrate: 15e5
|
|
173
|
-
}
|
|
174
|
-
];
|
|
175
|
-
/**
|
|
176
|
-
* What a call asks a camera for: 1280×720, which its three layers are cut from. A browser left to choose gives 640×480,
|
|
177
|
-
* of which it sends two layers at most, the largest a quarter of that size.
|
|
178
|
-
*/
|
|
179
|
-
const CAMERA = {
|
|
180
|
-
width: { ideal: 1280 },
|
|
181
|
-
height: { ideal: 720 }
|
|
182
|
-
};
|
|
183
|
-
/**
|
|
184
|
-
* The layers a camera is sent in, smallest first. A browser sends three layers only of a picture of 960×540 or more,
|
|
185
|
-
* two of one from 480×270 and one of anything smaller, and leaves out the last it was asked for: so a smaller camera
|
|
186
|
-
* is asked for as many as it sends, its full size among them. They keep the smaller layers' names, and asking for one
|
|
187
|
-
* that isn't sent gets the largest that is.
|
|
188
|
-
*/
|
|
189
|
-
function layersOf(track) {
|
|
190
|
-
const { width, height } = track.getSettings?.() ?? {};
|
|
191
|
-
const pixels = width && height ? width * height : Number.POSITIVE_INFINITY;
|
|
192
|
-
if (pixels >= 518400) return SIMULCAST;
|
|
193
|
-
if (pixels >= 129600) return [{
|
|
194
|
-
rid: "q",
|
|
195
|
-
scaleResolutionDownBy: 2,
|
|
196
|
-
maxBitrate: 15e4
|
|
197
|
-
}, {
|
|
198
|
-
rid: "h",
|
|
199
|
-
scaleResolutionDownBy: 1,
|
|
200
|
-
maxBitrate: 5e5
|
|
201
|
-
}];
|
|
202
|
-
}
|
|
203
|
-
var CallError = class extends Error {
|
|
204
|
-
code;
|
|
205
|
-
reason;
|
|
206
|
-
constructor(code, why, reason) {
|
|
207
|
-
super(why);
|
|
208
|
-
this.code = code;
|
|
209
|
-
this.reason = reason;
|
|
210
|
-
this.name = "CallError";
|
|
211
|
-
}
|
|
212
|
-
};
|
|
213
|
-
/** A request that never reached the call's server, or found it down: what joining again is for. */
|
|
214
|
-
var Unreachable = class extends CallError {
|
|
215
|
-
constructor(why) {
|
|
216
|
-
super("unavailable", why);
|
|
217
|
-
}
|
|
218
|
-
};
|
|
219
|
-
/** Why a name can't be a room's, or undefined: 1 to 64 letters, digits, `-`, `_` and `.`, starting with a letter or digit. */
|
|
220
|
-
function roomProblem(name) {
|
|
221
|
-
if (typeof name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(name)) return `${JSON.stringify(name)} can't name a room. Use 1 to 64 letters, digits, dots, dashes and underscores, starting with a letter or digit, such as support-42.`;
|
|
222
|
-
}
|
|
223
|
-
/** Why `as` can't name a participant, or undefined: 1 to 128 printable characters. */
|
|
224
|
-
function identityProblem(as) {
|
|
225
|
-
if (typeof as !== "string" || !/^[\x21-\x7e]{1,128}$/u.test(as)) return `${JSON.stringify(as)} can't name a participant. Use 1 to 128 printable characters with no spaces, such as a user id or guest-7.`;
|
|
226
|
-
}
|
|
227
|
-
/**
|
|
228
|
-
* A token for one person in one room, made on the app's server: in a deployment on Midsummer with no key, and under
|
|
229
|
-
* `midsummer dev` by its stand-in. Hand it to the page, which joins with it.
|
|
230
|
-
*
|
|
231
|
-
* const token = await callToken({ room: "support-42", as: user.id, name: user.name })
|
|
232
|
-
*/
|
|
233
|
-
async function callToken(input) {
|
|
234
|
-
const problem = roomProblem(input.room) ?? identityProblem(input.as);
|
|
235
|
-
if (problem) throw new CallError("invalid", problem);
|
|
236
|
-
const handle = here()?.calls;
|
|
237
|
-
if (handle) return handle.token(input).catch((error) => {
|
|
238
|
-
throw new CallError("unavailable", error instanceof Error ? error.message : String(error));
|
|
239
|
-
});
|
|
240
|
-
const dev = processEnv().MIDSUMMER_CALLS_URL;
|
|
241
|
-
if (!dev) throw new CallError("unavailable", "callToken makes tokens in a deployment on Midsummer and under midsummer dev. Run it there, or make one with midsummer call token create.");
|
|
242
|
-
const url = `${dev.replace(/\/+$/u, "")}/token`;
|
|
243
|
-
const response = await fetch(url, {
|
|
244
|
-
method: "POST",
|
|
245
|
-
headers: {
|
|
246
|
-
"content-type": "application/json",
|
|
247
|
-
...clientHeaders("calls")
|
|
248
|
-
},
|
|
249
|
-
body: JSON.stringify(input)
|
|
250
|
-
}).catch(() => void 0);
|
|
251
|
-
if (!response) throw new CallError("unavailable", `midsummer dev's calls couldn't be reached at ${new URL(url).origin}. Is midsummer dev still running?`);
|
|
252
|
-
return await answerOf(response, "token");
|
|
253
|
-
}
|
|
254
|
-
/**
|
|
255
|
-
* Joins a room with a token the app's server made for it, and resolves once you're in: `waiting` or `in-call`. A
|
|
256
|
-
* refusal rejects with a `CallError`: `forbidden` for a token that isn't good, ran out or is for someone removed,
|
|
257
|
-
* `full`, `ended` for a room ended since the token was made, `unavailable` when the call can't be reached.
|
|
258
|
-
*/
|
|
259
|
-
async function join(room, options) {
|
|
260
|
-
const problem = roomProblem(room);
|
|
261
|
-
if (problem) throw new CallError("invalid", problem);
|
|
262
|
-
const call = new LiveCall(room, options, options.rtc ?? browserRtc());
|
|
263
|
-
await call.start();
|
|
264
|
-
return call;
|
|
265
|
-
}
|
|
266
|
-
function browserRtc() {
|
|
267
|
-
const found = globalThis;
|
|
268
|
-
if (!found.RTCPeerConnection) throw new CallError("unavailable", "There's no WebRTC here. Outside a browser, pass a WebRTC library: join(room, { token, rtc }).");
|
|
269
|
-
return {
|
|
270
|
-
RTCPeerConnection: found.RTCPeerConnection,
|
|
271
|
-
...found.MediaStream ? { MediaStream: found.MediaStream } : {}
|
|
272
|
-
};
|
|
273
|
-
}
|
|
274
|
-
async function answerOf(response, op) {
|
|
275
|
-
const body = await response.json().catch(() => void 0);
|
|
276
|
-
if (response.ok && body && typeof body === "object" && !body.error) return body;
|
|
277
|
-
const code = body?.error?.code, message = body?.error?.message;
|
|
278
|
-
if (code === "unavailable" && typeof message === "string") throw new Unreachable(message);
|
|
279
|
-
if (typeof code === "string" && Object.hasOwn(CALL_STATUS, code) && typeof message === "string") throw new CallError(code, message);
|
|
280
|
-
if (response.status >= 500) throw new Unreachable(`The call returned ${response.status}.`);
|
|
281
|
-
throw new CallError("invalid", `The call returned ${response.status} to ${op}.`);
|
|
282
|
-
}
|
|
283
|
-
/** One op of the call wire, with the token, as JSON. */
|
|
284
|
-
async function request(url, token, op, body) {
|
|
285
|
-
const response = await fetch(`${url}/${op}`, {
|
|
286
|
-
method: "POST",
|
|
287
|
-
headers: {
|
|
288
|
-
authorization: `Bearer ${token}`,
|
|
289
|
-
"content-type": "application/json",
|
|
290
|
-
...clientHeaders("calls")
|
|
291
|
-
},
|
|
292
|
-
body: JSON.stringify(body)
|
|
293
|
-
}).catch(() => void 0);
|
|
294
|
-
if (!response) throw new Unreachable(`The call couldn't be reached at ${new URL(url).origin}. Check your network.`);
|
|
295
|
-
return await answerOf(response, op);
|
|
296
|
-
}
|
|
297
|
-
/** When a token runs out, from its claims: only a call token's signature is secret (`mcall_<claims>.<signature>`). */
|
|
298
|
-
function claimedExpiry(token) {
|
|
299
|
-
try {
|
|
300
|
-
const body = token.slice(token.indexOf("_") + 1).split(".")[0] ?? "";
|
|
301
|
-
const claims = JSON.parse(atob(body.replace(/-/g, "+").replace(/_/g, "/")));
|
|
302
|
-
return typeof claims.expiresAt === "number" ? claims.expiresAt : void 0;
|
|
303
|
-
} catch {
|
|
304
|
-
return;
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
const credentialOf = (given) => {
|
|
308
|
-
if (typeof given === "string") {
|
|
309
|
-
const expiresAt = claimedExpiry(given);
|
|
310
|
-
return {
|
|
311
|
-
token: given,
|
|
312
|
-
...expiresAt !== void 0 ? { expiresAt } : {}
|
|
313
|
-
};
|
|
314
|
-
}
|
|
315
|
-
return {
|
|
316
|
-
token: given.token,
|
|
317
|
-
url: given.url,
|
|
318
|
-
expiresAt: given.expiresAt
|
|
319
|
-
};
|
|
320
|
-
};
|
|
321
|
-
const sdpOf = (description) => {
|
|
322
|
-
if (!description?.sdp || description.type !== "offer" && description.type !== "answer") throw new CallError("unavailable", "The browser made no offer or answer for the call.");
|
|
323
|
-
return {
|
|
324
|
-
type: description.type,
|
|
325
|
-
sdp: description.sdp
|
|
326
|
-
};
|
|
327
|
-
};
|
|
328
|
-
const configOf = (iceServers) => ({
|
|
329
|
-
iceServers: iceServers.map((server) => ({
|
|
330
|
-
urls: typeof server.urls === "string" ? server.urls : [...server.urls],
|
|
331
|
-
...server.username !== void 0 ? { username: server.username } : {},
|
|
332
|
-
...server.credential !== void 0 ? { credential: server.credential } : {}
|
|
333
|
-
})),
|
|
334
|
-
bundlePolicy: "max-bundle"
|
|
335
|
-
});
|
|
336
|
-
/** Resolves once a connection has gathered its addresses, so its offer or answer goes whole, with no trickling. */
|
|
337
|
-
const gathered = (pc) => new Promise((resolve) => {
|
|
338
|
-
if (pc.iceGatheringState === "complete") return resolve();
|
|
339
|
-
const done = () => {
|
|
340
|
-
pc.removeEventListener("icegatheringstatechange", check);
|
|
341
|
-
pc.removeEventListener("icecandidate", last);
|
|
342
|
-
resolve();
|
|
343
|
-
};
|
|
344
|
-
const check = () => {
|
|
345
|
-
if (pc.iceGatheringState === "complete") done();
|
|
346
|
-
};
|
|
347
|
-
const last = (event) => {
|
|
348
|
-
if (!event.candidate) done();
|
|
349
|
-
};
|
|
350
|
-
pc.addEventListener("icegatheringstatechange", check);
|
|
351
|
-
pc.addEventListener("icecandidate", last);
|
|
352
|
-
});
|
|
353
|
-
const sizeProblem = (bytes) => `A message is at most 16 KiB as JSON; this one is ${Math.ceil(bytes / 1024)} KiB.`;
|
|
354
|
-
const audioOnlyProblem = "This room is audio-only, so it takes no camera or screen.";
|
|
355
|
-
const videoCapProblem = `A participant receives at most 9 videos at once. Stop receiving one first, as a grid does for tiles out of view.`;
|
|
356
|
-
const fullCapProblem = `A participant receives at most 2 videos at full quality at once. Ask for h or q for the others.`;
|
|
357
|
-
/** Messages sent before a channel opens wait for it, a few at most. */
|
|
358
|
-
function channelSend(channel, outbox, text) {
|
|
359
|
-
if (channel.readyState === "open") channel.send(text);
|
|
360
|
-
else if (channel.readyState === "connecting" && outbox.length < 64) outbox.push(text);
|
|
361
|
-
}
|
|
362
|
-
/** Media through the media server: one connection, a transceiver for each track published and each received. */
|
|
363
|
-
function sfuMedia(ctx, auto, declined, offer) {
|
|
364
|
-
const pc = new ctx.rtc.RTCPeerConnection(configOf(ctx.iceServers));
|
|
365
|
-
const sent = /* @__PURE__ */ new Map();
|
|
366
|
-
const pulled = /* @__PURE__ */ new Map();
|
|
367
|
-
const pending = /* @__PURE__ */ new Set();
|
|
368
|
-
const key = (of, name) => `${of}/${name}`;
|
|
369
|
-
const channels = /* @__PURE__ */ new Map();
|
|
370
|
-
const outbox = [];
|
|
371
|
-
let own;
|
|
372
|
-
/** Whether the channels are being asked for now, so one ask goes at a time, and whether the room changed meanwhile. */
|
|
373
|
-
let dataAsking = false;
|
|
374
|
-
let dataAgain = false;
|
|
375
|
-
/** Each person's connection as last seen: what was received from an earlier one is dropped. */
|
|
376
|
-
const connections = /* @__PURE__ */ new Map();
|
|
377
|
-
let others = [];
|
|
378
|
-
let closed = false;
|
|
379
|
-
let connectBy;
|
|
380
|
-
/** Whether the room changed while a track of it was on its way, so the tracks to receive are worked out again once it has come. */
|
|
381
|
-
let missed = false;
|
|
382
|
-
/**
|
|
383
|
-
* The session's one queue: every change to it on the media server (a publish, a receive, a layer, a stop, the data
|
|
384
|
-
* channels, a restart) waits for the one before it, offer and answer and all. The media server takes a session's
|
|
385
|
-
* changes one at a time and may refuse one that comes while another is on its way: staging, 16 Nov, a publish and the
|
|
386
|
-
* data channels' ask sent together were both refused, about one start in five. Work in the queue calls `ctx.post`
|
|
387
|
-
* itself; anywhere else a change goes through `change`.
|
|
388
|
-
*/
|
|
389
|
-
let chain = Promise.resolve();
|
|
390
|
-
const serial = (work) => {
|
|
391
|
-
const next = chain.then(work, work);
|
|
392
|
-
chain = next.catch(() => void 0);
|
|
393
|
-
return next;
|
|
394
|
-
};
|
|
395
|
-
const change = (op, body) => serial(() => ctx.post(op, body));
|
|
396
|
-
const find = (of, name) => [...pulled].find(([, pull]) => pull.of === of && pull.name === name);
|
|
397
|
-
const videos = () => [...pulled.values()].filter((pull) => TRACK_KINDS[pull.name] === "video");
|
|
398
|
-
const publishes = (of, name) => others.some((other) => other.id === of && other.tracks.some((track) => track.name === name));
|
|
399
|
-
pc.addEventListener("track", (event) => {
|
|
400
|
-
const pull = event.transceiver.mid ? pulled.get(event.transceiver.mid) : void 0;
|
|
401
|
-
if (!pull) return;
|
|
402
|
-
pull.track = event.track;
|
|
403
|
-
ctx.arrived(pull.of, pull.name, event.track);
|
|
404
|
-
});
|
|
405
|
-
pc.addEventListener("connectionstatechange", () => {
|
|
406
|
-
if (pc.connectionState === "connected") {
|
|
407
|
-
clearTimeout(connectBy);
|
|
408
|
-
ctx.reached();
|
|
409
|
-
}
|
|
410
|
-
if (!closed && (pc.connectionState === "failed" || pc.connectionState === "disconnected")) ctx.broken();
|
|
411
|
-
});
|
|
412
|
-
const timed = () => {
|
|
413
|
-
if (!closed && connectBy === void 0 && pc.connectionState !== "connected") connectBy = setTimeout(() => {
|
|
414
|
-
if (!closed && pc.connectionState !== "connected") ctx.broken();
|
|
415
|
-
}, CONNECT_WITHIN_MS);
|
|
416
|
-
};
|
|
417
|
-
/** Puts tracks on transceivers of their own and makes the offer that publishes them. */
|
|
418
|
-
const offerTracks = async (tracks) => {
|
|
419
|
-
const made = tracks.map(({ name, track }) => ({
|
|
420
|
-
name,
|
|
421
|
-
track,
|
|
422
|
-
transceiver: pc.addTransceiver(track, {
|
|
423
|
-
direction: "sendonly",
|
|
424
|
-
...name === "camera" && layersOf(track) ? { sendEncodings: layersOf(track) } : {},
|
|
425
|
-
...ctx.rtc.MediaStream ? { streams: [new ctx.rtc.MediaStream([track])] } : {}
|
|
426
|
-
})
|
|
427
|
-
}));
|
|
428
|
-
await pc.setLocalDescription(await pc.createOffer());
|
|
429
|
-
const sentIn = (name, track) => name === "camera" && (layersOf(track)?.length ?? 1) < SIMULCAST.length ? { layers: layersOf(track)?.length ?? 1 } : {};
|
|
430
|
-
return {
|
|
431
|
-
made,
|
|
432
|
-
body: {
|
|
433
|
-
offer: sdpOf(pc.localDescription),
|
|
434
|
-
tracks: made.map(({ name, track, transceiver }) => ({
|
|
435
|
-
mid: transceiver.mid ?? "",
|
|
436
|
-
name,
|
|
437
|
-
...sentIn(name, track)
|
|
438
|
-
}))
|
|
439
|
-
}
|
|
440
|
-
};
|
|
441
|
-
};
|
|
442
|
-
/** Applies the media server's answer to a publish: its tracks are sent from now on. */
|
|
443
|
-
const tookPublished = async (offered, answered) => {
|
|
444
|
-
if (answered.answer) await pc.setRemoteDescription(answered.answer);
|
|
445
|
-
timed();
|
|
446
|
-
for (const { name, transceiver } of offered.made) sent.set(name, transceiver);
|
|
447
|
-
return answered.room;
|
|
448
|
-
};
|
|
449
|
-
/** Takes back a publish that was refused. */
|
|
450
|
-
const unoffer = async (offered) => {
|
|
451
|
-
if (pc.signalingState === "have-local-offer") await pc.setLocalDescription({ type: "rollback" });
|
|
452
|
-
for (const { transceiver } of offered.made) {
|
|
453
|
-
transceiver.direction = "inactive";
|
|
454
|
-
await transceiver.sender.replaceTrack(null);
|
|
455
|
-
}
|
|
456
|
-
};
|
|
457
|
-
/** The first tracks published before the join's offer is answered, which go with that answer. */
|
|
458
|
-
let earlyPublish;
|
|
459
|
-
const answer = async (offered) => {
|
|
460
|
-
try {
|
|
461
|
-
await pc.setRemoteDescription(offered);
|
|
462
|
-
await pc.setLocalDescription(await pc.createAnswer());
|
|
463
|
-
await ctx.post("answer", {
|
|
464
|
-
participant: ctx.me,
|
|
465
|
-
answer: sdpOf(pc.localDescription)
|
|
466
|
-
});
|
|
467
|
-
} finally {
|
|
468
|
-
timed();
|
|
469
|
-
}
|
|
470
|
-
};
|
|
471
|
-
/**
|
|
472
|
-
* The tracks asked for before the join's offer is answered, which the room's first reading does: they go with that
|
|
473
|
-
* answer, in one trip, where a pull of their own waited for it and then made another. Undefined once it is sent.
|
|
474
|
-
*/
|
|
475
|
-
let early = offer ? [] : void 0;
|
|
476
|
-
let earlyDone;
|
|
477
|
-
const first = async (offered) => {
|
|
478
|
-
let asked = [];
|
|
479
|
-
try {
|
|
480
|
-
await pc.setRemoteDescription(offered);
|
|
481
|
-
await pc.setLocalDescription(await pc.createAnswer());
|
|
482
|
-
const answered0 = sdpOf(pc.localDescription);
|
|
483
|
-
asked = early ?? [];
|
|
484
|
-
early = void 0;
|
|
485
|
-
const publishing = earlyPublish;
|
|
486
|
-
earlyPublish = void 0;
|
|
487
|
-
const offeredNow = publishing ? await offerTracks(publishing.tracks).catch((error) => {
|
|
488
|
-
publishing.reject(error);
|
|
489
|
-
}) : void 0;
|
|
490
|
-
const chunk = asked.filter((track) => publishes(track.of, track.name) && !find(track.of, track.name)).slice(0, PULL_MAX);
|
|
491
|
-
const were = new Map(chunk.map((track) => [track.of, connections.get(track.of)]));
|
|
492
|
-
let answered;
|
|
493
|
-
try {
|
|
494
|
-
answered = await ctx.post("answer", {
|
|
495
|
-
participant: ctx.me,
|
|
496
|
-
answer: answered0,
|
|
497
|
-
...chunk.length ? { pull: chunk } : {},
|
|
498
|
-
...offeredNow ? { publish: offeredNow.body } : {}
|
|
499
|
-
});
|
|
500
|
-
} catch (error) {
|
|
501
|
-
if (offeredNow) {
|
|
502
|
-
await unoffer(offeredNow).catch(() => void 0);
|
|
503
|
-
publishing.reject(error);
|
|
504
|
-
}
|
|
505
|
-
throw error;
|
|
506
|
-
}
|
|
507
|
-
timed();
|
|
508
|
-
if (offeredNow) try {
|
|
509
|
-
publishing.resolve(await tookPublished(offeredNow, answered.published ?? await ctx.post("publish", {
|
|
510
|
-
participant: ctx.me,
|
|
511
|
-
...offeredNow.body
|
|
512
|
-
})));
|
|
513
|
-
} catch (error) {
|
|
514
|
-
await unoffer(offeredNow).catch(() => void 0);
|
|
515
|
-
publishing.reject(error);
|
|
516
|
-
}
|
|
517
|
-
if (chunk.length && answered.offer && answered.tracks) await took(chunk, were, {
|
|
518
|
-
offer: answered.offer,
|
|
519
|
-
tracks: answered.tracks
|
|
520
|
-
});
|
|
521
|
-
} finally {
|
|
522
|
-
early = void 0;
|
|
523
|
-
timed();
|
|
524
|
-
for (const track of asked) pending.delete(key(track.of, track.name));
|
|
525
|
-
if (earlyPublish) {
|
|
526
|
-
earlyPublish.reject(new CallError("unavailable", "The call's connection couldn't be made, so nothing was published. Join again."));
|
|
527
|
-
earlyPublish = void 0;
|
|
528
|
-
}
|
|
529
|
-
}
|
|
530
|
-
const rest = asked.filter((track) => publishes(track.of, track.name) && !find(track.of, track.name));
|
|
531
|
-
if (rest.length && !closed) pull(rest).catch(ctx.failed);
|
|
532
|
-
if (missed) {
|
|
533
|
-
missed = false;
|
|
534
|
-
want(false);
|
|
535
|
-
}
|
|
536
|
-
};
|
|
537
|
-
const set = offer ? (earlyDone = serial(() => first(offer))).then(() => true, (error) => {
|
|
538
|
-
ctx.failed(error);
|
|
539
|
-
return false;
|
|
540
|
-
}) : Promise.resolve(true);
|
|
541
|
-
/**
|
|
542
|
-
* Asks whoever sends a video for a key frame, on this call's own channel, which they receive. A viewer is moved to
|
|
543
|
-
* another layer at that layer's next key frame, and the media server asks the sender for one only every ten seconds
|
|
544
|
-
* or so, so a tile that changed size would stay soft that long. With no channel open yet nothing is asked, and the
|
|
545
|
-
* media server's own ask stands.
|
|
546
|
-
*/
|
|
547
|
-
const askKey = (of, name) => {
|
|
548
|
-
if (!closed && own?.readyState === "open" && TRACK_KINDS[name] === "video") own.send(`${KEY_FRAME}${of} ${name}`);
|
|
549
|
-
};
|
|
550
|
-
/** When each video sent last made a key frame because it was asked, and the one waiting its turn. */
|
|
551
|
-
const keyed = /* @__PURE__ */ new Map();
|
|
552
|
-
/**
|
|
553
|
-
* Makes a key frame on a video this call sends, on every layer, because a viewer asked: at most one a second,
|
|
554
|
-
* however many ask, with one more at the second's end for those who asked meanwhile. A browser that can't make one
|
|
555
|
-
* when asked ignores it.
|
|
556
|
-
*/
|
|
557
|
-
const makeKey = (name) => {
|
|
558
|
-
const sender = sent.get(name)?.sender;
|
|
559
|
-
if (closed || !sender || TRACK_KINDS[name] !== "video" || typeof sender.getParameters !== "function") return;
|
|
560
|
-
const last = keyed.get(name);
|
|
561
|
-
if (last?.timer !== void 0) return;
|
|
562
|
-
const make = () => {
|
|
563
|
-
keyed.set(name, { at: Date.now() });
|
|
564
|
-
if (closed || sent.get(name)?.sender !== sender) return;
|
|
565
|
-
const parameters = sender.getParameters();
|
|
566
|
-
sender.setParameters(parameters, { encodingOptions: (parameters.encodings ?? []).map(() => ({ keyFrame: true })) }).catch(() => void 0);
|
|
567
|
-
};
|
|
568
|
-
const wait = last ? last.at + KEY_FRAME_EVERY_MS - Date.now() : 0;
|
|
569
|
-
if (wait <= 0) make();
|
|
570
|
-
else keyed.set(name, {
|
|
571
|
-
at: last.at,
|
|
572
|
-
timer: setTimeout(make, wait)
|
|
573
|
-
});
|
|
574
|
-
};
|
|
575
|
-
/**
|
|
576
|
-
* Once a second, each camera received on the middle layer is looked at (`layerWatch`): one whose frames stopped is
|
|
577
|
-
* asked for at the small layer, and at the middle one again later. The page's own ask stays what it was: `layer` on
|
|
578
|
-
* the track is still the middle one, so the tile's next ask changes nothing it didn't mean to.
|
|
579
|
-
*/
|
|
580
|
-
let watching = false;
|
|
581
|
-
const watchLayers = async () => {
|
|
582
|
-
if (closed || watching || typeof pc.getStats !== "function") return;
|
|
583
|
-
watching = true;
|
|
584
|
-
try {
|
|
585
|
-
const decoded = /* @__PURE__ */ new Map();
|
|
586
|
-
(await pc.getStats()).forEach((stat) => {
|
|
587
|
-
if (stat.type === "inbound-rtp" && stat.kind === "video" && stat.mid !== void 0) decoded.set(stat.mid, stat.framesDecoded ?? 0);
|
|
588
|
-
});
|
|
589
|
-
for (const [mid, pull] of pulled) {
|
|
590
|
-
const frames = decoded.get(mid);
|
|
591
|
-
if (closed || pull.name !== "camera" || !pull.track || frames === void 0) continue;
|
|
592
|
-
const { next, ask } = layerWatch(pull.layer ?? "h", frames, Date.now(), pull.watch);
|
|
593
|
-
pull.watch = next;
|
|
594
|
-
if (!ask) continue;
|
|
595
|
-
change("layer", {
|
|
596
|
-
participant: ctx.me,
|
|
597
|
-
mid,
|
|
598
|
-
layer: ask,
|
|
599
|
-
of: pull.of
|
|
600
|
-
}).then(() => askKey(pull.of, pull.name), () => void 0);
|
|
601
|
-
}
|
|
602
|
-
} catch {} finally {
|
|
603
|
-
watching = false;
|
|
604
|
-
}
|
|
605
|
-
};
|
|
606
|
-
const layerTimer = setInterval(() => {
|
|
607
|
-
watchLayers();
|
|
608
|
-
}, 1e3);
|
|
609
|
-
/** A message on someone's channel: a viewer's ask for a key frame, acted on when it is for a video of this call's, or their words. */
|
|
610
|
-
const heard = (of, text) => {
|
|
611
|
-
if (!text.startsWith(KEY_FRAME)) return ctx.message(of, text);
|
|
612
|
-
const [who, name] = text.slice(8).split(" ");
|
|
613
|
-
if (who === ctx.me && name !== void 0 && Object.hasOwn(TRACK_KINDS, name)) makeKey(name);
|
|
614
|
-
};
|
|
615
|
-
/** The people whose channel isn't received yet. */
|
|
616
|
-
const unheard = () => others.filter((other) => other.kind === "person" && !channels.has(other.id)).map((other) => other.id);
|
|
617
|
-
/** Opens this call's channel, once, and receives the channel of each person who has one open and isn't received yet: who was asked for. */
|
|
618
|
-
async function openData() {
|
|
619
|
-
const from = unheard();
|
|
620
|
-
if (closed || own && !from.length) return from;
|
|
621
|
-
const were = new Map(from.map((of) => [of, connections.get(of)]));
|
|
622
|
-
const opened = await ctx.post("data", {
|
|
623
|
-
participant: ctx.me,
|
|
624
|
-
from
|
|
625
|
-
});
|
|
626
|
-
if (closed) return from;
|
|
627
|
-
if (opened.own !== void 0 && !own) {
|
|
628
|
-
own = pc.createDataChannel("data", {
|
|
629
|
-
negotiated: true,
|
|
630
|
-
id: opened.own
|
|
631
|
-
});
|
|
632
|
-
const channel = own;
|
|
633
|
-
channel.addEventListener("open", () => {
|
|
634
|
-
for (const text of outbox.splice(0)) channel.send(text);
|
|
635
|
-
});
|
|
636
|
-
}
|
|
637
|
-
for (const { of, id } of opened.from) {
|
|
638
|
-
if (channels.has(of) || connections.get(of) !== were.get(of)) continue;
|
|
639
|
-
const channel = pc.createDataChannel(`data:${of}`, {
|
|
640
|
-
negotiated: true,
|
|
641
|
-
id
|
|
642
|
-
});
|
|
643
|
-
channel.addEventListener("message", (event) => heard(of, String(event.data)));
|
|
644
|
-
channels.set(of, channel);
|
|
645
|
-
}
|
|
646
|
-
return from;
|
|
647
|
-
}
|
|
648
|
-
/**
|
|
649
|
-
* Asks for the channels, one ask at a time, once the join's offer is answered: a channel needs the connection that
|
|
650
|
-
* set up and no offer of its own, so the ask takes its turn in the session's queue behind whatever is being
|
|
651
|
-
* published or received then, never ahead of it. Someone who came while an ask was out is asked for after it;
|
|
652
|
-
* someone whose own isn't open yet is asked for again when the room next changes, which their opening it does; a
|
|
653
|
-
* refusal likewise.
|
|
654
|
-
*/
|
|
655
|
-
function askData() {
|
|
656
|
-
if (dataAsking) dataAgain = true;
|
|
657
|
-
if (dataAsking || closed || own && !unheard().length) return;
|
|
658
|
-
dataAsking = true;
|
|
659
|
-
dataAgain = false;
|
|
660
|
-
set.then((up) => up ? serial(openData) : unheard()).then((asked) => {
|
|
661
|
-
dataAsking = false;
|
|
662
|
-
if (dataAgain || unheard().some((of) => !asked.includes(of))) askData();
|
|
663
|
-
}, (error) => {
|
|
664
|
-
dataAsking = false;
|
|
665
|
-
ctx.failed(error);
|
|
666
|
-
});
|
|
667
|
-
}
|
|
668
|
-
/** Takes what a pull brought: keeps each track's mid, answers the offer, and drops what came from a connection its sender has since left. */
|
|
669
|
-
async function took(chunk, asked, pulledNow) {
|
|
670
|
-
for (const track of pulledNow.tracks) {
|
|
671
|
-
const layer = chunk.find((each) => each.of === track.of && each.name === track.name)?.layer;
|
|
672
|
-
pulled.set(track.mid, {
|
|
673
|
-
of: track.of,
|
|
674
|
-
name: track.name,
|
|
675
|
-
...layer ? { layer } : {}
|
|
676
|
-
});
|
|
677
|
-
}
|
|
678
|
-
await answer(pulledNow.offer);
|
|
679
|
-
for (const track of pulledNow.tracks) askKey(track.of, track.name);
|
|
680
|
-
const old = pulledNow.tracks.filter((track) => pulled.has(track.mid) && connections.get(track.of) !== asked.get(track.of));
|
|
681
|
-
for (const track of old) {
|
|
682
|
-
if (pulled.get(track.mid)?.track) ctx.ended(track.of, track.name);
|
|
683
|
-
pulled.delete(track.mid);
|
|
684
|
-
}
|
|
685
|
-
if (old.length) {
|
|
686
|
-
missed = true;
|
|
687
|
-
await ctx.post("unpull", {
|
|
688
|
-
participant: ctx.me,
|
|
689
|
-
mids: old.map((track) => track.mid)
|
|
690
|
-
});
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
const pull = (tracks) => {
|
|
694
|
-
for (const track of tracks) pending.add(key(track.of, track.name));
|
|
695
|
-
if (early && earlyDone) {
|
|
696
|
-
early.push(...tracks);
|
|
697
|
-
return earlyDone;
|
|
698
|
-
}
|
|
699
|
-
return serial(async () => {
|
|
700
|
-
try {
|
|
701
|
-
const still = tracks.filter((track) => publishes(track.of, track.name) && !find(track.of, track.name));
|
|
702
|
-
for (let at = 0; at < still.length && !closed; at += PULL_MAX) {
|
|
703
|
-
const chunk = still.slice(at, at + PULL_MAX);
|
|
704
|
-
await took(chunk, new Map(chunk.map((track) => [track.of, connections.get(track.of)])), await ctx.post("pull", {
|
|
705
|
-
participant: ctx.me,
|
|
706
|
-
tracks: chunk
|
|
707
|
-
}));
|
|
708
|
-
}
|
|
709
|
-
} finally {
|
|
710
|
-
for (const track of tracks) pending.delete(key(track.of, track.name));
|
|
711
|
-
if (missed) {
|
|
712
|
-
missed = false;
|
|
713
|
-
want(false);
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
});
|
|
717
|
-
};
|
|
718
|
-
/** Receives every sound others publish, and their videos up to 9 unless the page chooses them, that isn't received or on its way. */
|
|
719
|
-
function want(changed) {
|
|
720
|
-
if (closed) return;
|
|
721
|
-
const wanted = [];
|
|
722
|
-
let video = videos().length + [...pending].filter((each) => TRACK_KINDS[each.slice(each.lastIndexOf("/") + 1)] === "video").length;
|
|
723
|
-
for (const other of others) for (const track of other.tracks) {
|
|
724
|
-
const at = key(other.id, track.name);
|
|
725
|
-
if (changed && pending.has(at)) missed = true;
|
|
726
|
-
if (find(other.id, track.name) || pending.has(at) || declined.has(at)) continue;
|
|
727
|
-
if (track.kind === "audio") wanted.push({
|
|
728
|
-
of: other.id,
|
|
729
|
-
name: track.name
|
|
730
|
-
});
|
|
731
|
-
else if (auto && video < 9) {
|
|
732
|
-
wanted.push({
|
|
733
|
-
of: other.id,
|
|
734
|
-
name: track.name,
|
|
735
|
-
layer: "h"
|
|
736
|
-
});
|
|
737
|
-
video += 1;
|
|
738
|
-
}
|
|
739
|
-
}
|
|
740
|
-
if (wanted.length) pull(wanted).catch(ctx.failed);
|
|
741
|
-
}
|
|
742
|
-
return {
|
|
743
|
-
publish: (tracks) => {
|
|
744
|
-
if (early !== void 0 && !earlyPublish) return new Promise((resolve, reject) => {
|
|
745
|
-
earlyPublish = {
|
|
746
|
-
tracks,
|
|
747
|
-
resolve,
|
|
748
|
-
reject
|
|
749
|
-
};
|
|
750
|
-
});
|
|
751
|
-
return serial(async () => {
|
|
752
|
-
const made = await offerTracks(tracks);
|
|
753
|
-
try {
|
|
754
|
-
return await tookPublished(made, await ctx.post("publish", {
|
|
755
|
-
participant: ctx.me,
|
|
756
|
-
...made.body
|
|
757
|
-
}));
|
|
758
|
-
} catch (error) {
|
|
759
|
-
await unoffer(made);
|
|
760
|
-
throw error;
|
|
761
|
-
}
|
|
762
|
-
});
|
|
763
|
-
},
|
|
764
|
-
async replace(name, track) {
|
|
765
|
-
await sent.get(name)?.sender.replaceTrack(track);
|
|
766
|
-
},
|
|
767
|
-
async unpublish(names) {
|
|
768
|
-
const answered = await change("unpublish", {
|
|
769
|
-
participant: ctx.me,
|
|
770
|
-
names
|
|
771
|
-
});
|
|
772
|
-
for (const name of names) {
|
|
773
|
-
await sent.get(name)?.sender.replaceTrack(null);
|
|
774
|
-
sent.delete(name);
|
|
775
|
-
}
|
|
776
|
-
return answered.room;
|
|
777
|
-
},
|
|
778
|
-
sync(list) {
|
|
779
|
-
others = list;
|
|
780
|
-
const back = new Set(list.filter((other) => connections.has(other.id) && connections.get(other.id) !== (other.connection ?? 1)).map((other) => other.id));
|
|
781
|
-
for (const other of list) connections.set(other.id, other.connection ?? 1);
|
|
782
|
-
for (const of of [...connections.keys()]) if (!list.some((other) => other.id === of)) connections.delete(of);
|
|
783
|
-
const gone = [...pulled].filter(([, pull]) => back.has(pull.of) || !publishes(pull.of, pull.name));
|
|
784
|
-
for (const [mid, pull] of gone) {
|
|
785
|
-
pulled.delete(mid);
|
|
786
|
-
if (pull.track) ctx.ended(pull.of, pull.name);
|
|
787
|
-
}
|
|
788
|
-
if (gone.length) change("unpull", {
|
|
789
|
-
participant: ctx.me,
|
|
790
|
-
mids: gone.map(([mid]) => mid)
|
|
791
|
-
}).catch(ctx.failed);
|
|
792
|
-
for (const of of [...channels.keys()]) if (back.has(of) || !list.some((other) => other.id === of)) {
|
|
793
|
-
channels.get(of)?.close();
|
|
794
|
-
channels.delete(of);
|
|
795
|
-
}
|
|
796
|
-
askData();
|
|
797
|
-
want(true);
|
|
798
|
-
},
|
|
799
|
-
signals() {},
|
|
800
|
-
async receive(of, name, layer) {
|
|
801
|
-
const found = find(of, name);
|
|
802
|
-
if (found) {
|
|
803
|
-
if (TRACK_KINDS[name] === "video" && layer && layer !== (found[1].layer ?? "h")) await this.setLayer(of, name, layer);
|
|
804
|
-
return;
|
|
805
|
-
}
|
|
806
|
-
if (!publishes(of, name)) throw new CallError("not-found", `${of} publishes no ${name} in this call now.`);
|
|
807
|
-
if (TRACK_KINDS[name] === "video") {
|
|
808
|
-
if (videos().length + 1 > 9) throw new CallError("invalid", videoCapProblem);
|
|
809
|
-
if (layer === "f" && videos().filter((pull) => pull.layer === "f").length + 1 > 2) throw new CallError("invalid", fullCapProblem);
|
|
810
|
-
}
|
|
811
|
-
await pull([{
|
|
812
|
-
of,
|
|
813
|
-
name,
|
|
814
|
-
...TRACK_KINDS[name] === "video" ? { layer: layer ?? "h" } : {}
|
|
815
|
-
}]);
|
|
816
|
-
},
|
|
817
|
-
async setLayer(of, name, layer) {
|
|
818
|
-
const found = find(of, name);
|
|
819
|
-
if (!found || TRACK_KINDS[name] !== "video") throw new CallError("not-found", `You receive no ${name} from ${of}.`);
|
|
820
|
-
const [mid, pulledTrack] = found;
|
|
821
|
-
if (layer === pulledTrack.layer) return;
|
|
822
|
-
if (layer === "f" && videos().filter((each) => each.layer === "f").length + 1 > 2) throw new CallError("invalid", fullCapProblem);
|
|
823
|
-
await change("layer", {
|
|
824
|
-
participant: ctx.me,
|
|
825
|
-
mid,
|
|
826
|
-
layer,
|
|
827
|
-
of
|
|
828
|
-
});
|
|
829
|
-
pulledTrack.layer = layer;
|
|
830
|
-
delete pulledTrack.watch;
|
|
831
|
-
askKey(of, name);
|
|
832
|
-
},
|
|
833
|
-
async stopReceiving(of, name) {
|
|
834
|
-
declined.add(key(of, name));
|
|
835
|
-
const found = find(of, name);
|
|
836
|
-
if (!found) return;
|
|
837
|
-
const [mid, pulledTrack] = found;
|
|
838
|
-
pulled.delete(mid);
|
|
839
|
-
if (pulledTrack.track) ctx.ended(of, name);
|
|
840
|
-
await change("unpull", {
|
|
841
|
-
participant: ctx.me,
|
|
842
|
-
mids: [mid]
|
|
843
|
-
});
|
|
844
|
-
},
|
|
845
|
-
send(text) {
|
|
846
|
-
if (own) channelSend(own, outbox, text);
|
|
847
|
-
else if (outbox.length < 64) outbox.push(text);
|
|
848
|
-
},
|
|
849
|
-
async renewRelays() {
|
|
850
|
-
if (closed || !await relayed(pc)) return;
|
|
851
|
-
const given = await ctx.post("relays", { participant: ctx.me });
|
|
852
|
-
if (closed || !given.iceServers.some((server) => server.username)) return;
|
|
853
|
-
pc.setConfiguration({
|
|
854
|
-
...pc.getConfiguration(),
|
|
855
|
-
...configOf(given.iceServers)
|
|
856
|
-
});
|
|
857
|
-
await serial(async () => {
|
|
858
|
-
if (closed) return;
|
|
859
|
-
pc.restartIce();
|
|
860
|
-
await pc.setLocalDescription(await pc.createOffer());
|
|
861
|
-
try {
|
|
862
|
-
const { answer: restarted } = await ctx.post("restart", {
|
|
863
|
-
participant: ctx.me,
|
|
864
|
-
offer: sdpOf(pc.localDescription)
|
|
865
|
-
});
|
|
866
|
-
await pc.setRemoteDescription(restarted);
|
|
867
|
-
} catch (error) {
|
|
868
|
-
if (!closed && pc.signalingState === "have-local-offer") await pc.setLocalDescription({ type: "rollback" }).catch(() => void 0);
|
|
869
|
-
throw error;
|
|
870
|
-
}
|
|
871
|
-
});
|
|
872
|
-
},
|
|
873
|
-
close() {
|
|
874
|
-
closed = true;
|
|
875
|
-
clearTimeout(connectBy);
|
|
876
|
-
for (const { timer } of keyed.values()) clearTimeout(timer);
|
|
877
|
-
clearInterval(layerTimer);
|
|
878
|
-
for (const channel of channels.values()) channel.close();
|
|
879
|
-
own?.close();
|
|
880
|
-
pc.close();
|
|
881
|
-
}
|
|
882
|
-
};
|
|
883
|
-
}
|
|
884
|
-
/** Whether a connection reaches the media through a relay now. */
|
|
885
|
-
async function relayed(pc) {
|
|
886
|
-
if (typeof pc.getStats !== "function") return false;
|
|
887
|
-
const report = await pc.getStats();
|
|
888
|
-
let found = false;
|
|
889
|
-
report.forEach((each) => {
|
|
890
|
-
if (each.type !== "transport" || !each.selectedCandidatePairId) return;
|
|
891
|
-
const pair = report.get(each.selectedCandidatePairId);
|
|
892
|
-
if ((pair?.localCandidateId ? report.get(pair.localCandidateId) : void 0)?.candidateType === "relay") found = true;
|
|
893
|
-
});
|
|
894
|
-
return found;
|
|
895
|
-
}
|
|
896
|
-
/** Media with no media server: a connection to each other participant, made once (see the top of this file). */
|
|
897
|
-
function relayMedia(ctx, rejoined) {
|
|
898
|
-
const peers = /* @__PURE__ */ new Map();
|
|
899
|
-
let others = [];
|
|
900
|
-
let offerAll = rejoined;
|
|
901
|
-
let signalling = Promise.resolve();
|
|
902
|
-
function make(of) {
|
|
903
|
-
const pc = new ctx.rtc.RTCPeerConnection(configOf(ctx.iceServers));
|
|
904
|
-
const channel = pc.createDataChannel("data", {
|
|
905
|
-
negotiated: true,
|
|
906
|
-
id: 0
|
|
907
|
-
});
|
|
908
|
-
const peer = {
|
|
909
|
-
of,
|
|
910
|
-
pc,
|
|
911
|
-
channel,
|
|
912
|
-
outbox: [],
|
|
913
|
-
received: /* @__PURE__ */ new Set()
|
|
914
|
-
};
|
|
915
|
-
channel.addEventListener("message", (event) => ctx.message(of, String(event.data)));
|
|
916
|
-
channel.addEventListener("open", () => {
|
|
917
|
-
for (const text of peer.outbox.splice(0)) channel.send(text);
|
|
918
|
-
});
|
|
919
|
-
pc.addEventListener("connectionstatechange", () => {
|
|
920
|
-
if (pc.connectionState === "connected") ctx.reached();
|
|
921
|
-
if (peers.get(of) !== peer || pc.connectionState !== "failed") return;
|
|
922
|
-
drop(peer);
|
|
923
|
-
if (ctx.me < of) offer(of).catch(ctx.failed);
|
|
924
|
-
});
|
|
925
|
-
peers.set(of, peer);
|
|
926
|
-
return peer;
|
|
927
|
-
}
|
|
928
|
-
function drop(peer) {
|
|
929
|
-
if (peers.get(peer.of) === peer) peers.delete(peer.of);
|
|
930
|
-
for (const name of peer.received) ctx.ended(peer.of, name);
|
|
931
|
-
peer.received.clear();
|
|
932
|
-
peer.channel.close();
|
|
933
|
-
peer.pc.close();
|
|
934
|
-
}
|
|
935
|
-
async function put(peer) {
|
|
936
|
-
const sending = ctx.sending();
|
|
937
|
-
await Promise.all(TRACK_ORDER.map((name, at) => peer.transceivers?.[at]?.sender.replaceTrack(sending.find((each) => each.name === name)?.track ?? null)));
|
|
938
|
-
}
|
|
939
|
-
/** Hands over each track the other publishes, from its transceiver's place, and ends those they stopped. */
|
|
940
|
-
function match(peer) {
|
|
941
|
-
if (!peer.transceivers || peer.pc.signalingState !== "stable") return;
|
|
942
|
-
const published = others.find((other) => other.id === peer.of)?.tracks ?? [];
|
|
943
|
-
for (const [at, name] of TRACK_ORDER.entries()) {
|
|
944
|
-
const on = published.some((track) => track.name === name);
|
|
945
|
-
const transceiver = peer.transceivers[at];
|
|
946
|
-
if (on && transceiver && !peer.received.has(name)) {
|
|
947
|
-
peer.received.add(name);
|
|
948
|
-
ctx.arrived(peer.of, name, transceiver.receiver.track);
|
|
949
|
-
} else if (!on && peer.received.has(name)) {
|
|
950
|
-
peer.received.delete(name);
|
|
951
|
-
ctx.ended(peer.of, name);
|
|
952
|
-
}
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
async function send(peer) {
|
|
956
|
-
await gathered(peer.pc);
|
|
957
|
-
if (peers.get(peer.of) !== peer) return;
|
|
958
|
-
try {
|
|
959
|
-
await ctx.post("signal", {
|
|
960
|
-
participant: ctx.me,
|
|
961
|
-
to: peer.of,
|
|
962
|
-
sdp: sdpOf(peer.pc.localDescription)
|
|
963
|
-
});
|
|
964
|
-
} catch (error) {
|
|
965
|
-
if (error instanceof CallError && error.code === "not-found") return drop(peer);
|
|
966
|
-
throw error;
|
|
967
|
-
}
|
|
968
|
-
}
|
|
969
|
-
async function offer(of) {
|
|
970
|
-
const peer = make(of);
|
|
971
|
-
peer.transceivers = TRACK_ORDER.map((name) => peer.pc.addTransceiver(TRACK_KINDS[name], { direction: "sendrecv" }));
|
|
972
|
-
await put(peer);
|
|
973
|
-
await peer.pc.setLocalDescription(await peer.pc.createOffer());
|
|
974
|
-
await send(peer);
|
|
975
|
-
}
|
|
976
|
-
async function answer(of, sdp) {
|
|
977
|
-
const existing = peers.get(of);
|
|
978
|
-
if (existing && existing.pc.signalingState === "have-local-offer" && ctx.me < of) return;
|
|
979
|
-
if (existing) drop(existing);
|
|
980
|
-
const peer = make(of);
|
|
981
|
-
await peer.pc.setRemoteDescription(sdp);
|
|
982
|
-
const transceivers = peer.pc.getTransceivers();
|
|
983
|
-
if (transceivers.length < TRACK_ORDER.length) throw new CallError("invalid", `${of} offered a connection without the call's ${TRACK_ORDER.length} tracks. Is it on another version of the SDK?`);
|
|
984
|
-
for (const transceiver of transceivers) transceiver.direction = "sendrecv";
|
|
985
|
-
peer.transceivers = transceivers.slice(0, TRACK_ORDER.length);
|
|
986
|
-
await put(peer);
|
|
987
|
-
await peer.pc.setLocalDescription(await peer.pc.createAnswer());
|
|
988
|
-
match(peer);
|
|
989
|
-
await send(peer);
|
|
990
|
-
}
|
|
991
|
-
async function answered(of, sdp) {
|
|
992
|
-
const peer = peers.get(of);
|
|
993
|
-
if (!peer || peer.pc.signalingState !== "have-local-offer") return;
|
|
994
|
-
await peer.pc.setRemoteDescription(sdp);
|
|
995
|
-
match(peer);
|
|
996
|
-
}
|
|
997
|
-
const each = async (work) => {
|
|
998
|
-
await Promise.all([...peers.values()].filter((peer) => peer.transceivers).map(work));
|
|
999
|
-
};
|
|
1000
|
-
return {
|
|
1001
|
-
async publish(tracks) {
|
|
1002
|
-
await each(put);
|
|
1003
|
-
return (await ctx.post("publish", {
|
|
1004
|
-
participant: ctx.me,
|
|
1005
|
-
tracks: tracks.map(({ name }) => ({ name }))
|
|
1006
|
-
})).room;
|
|
1007
|
-
},
|
|
1008
|
-
async replace(name, track) {
|
|
1009
|
-
const at = TRACK_ORDER.indexOf(name);
|
|
1010
|
-
await each(async (peer) => {
|
|
1011
|
-
await peer.transceivers?.[at]?.sender.replaceTrack(track);
|
|
1012
|
-
});
|
|
1013
|
-
},
|
|
1014
|
-
async unpublish(names) {
|
|
1015
|
-
const room = (await ctx.post("unpublish", {
|
|
1016
|
-
participant: ctx.me,
|
|
1017
|
-
names
|
|
1018
|
-
})).room;
|
|
1019
|
-
for (const name of names) await this.replace(name, null);
|
|
1020
|
-
return room;
|
|
1021
|
-
},
|
|
1022
|
-
sync(list) {
|
|
1023
|
-
others = list;
|
|
1024
|
-
for (const peer of [...peers.values()]) if (!list.some((other) => other.id === peer.of)) drop(peer);
|
|
1025
|
-
for (const other of list) {
|
|
1026
|
-
const peer = peers.get(other.id);
|
|
1027
|
-
if (peer) match(peer);
|
|
1028
|
-
else if (ctx.me < other.id || offerAll) offer(other.id).catch(ctx.failed);
|
|
1029
|
-
}
|
|
1030
|
-
offerAll = false;
|
|
1031
|
-
},
|
|
1032
|
-
signals(list) {
|
|
1033
|
-
for (const signal of list) signalling = signalling.then(() => signal.sdp.type === "offer" ? answer(signal.from, signal.sdp) : answered(signal.from, signal.sdp)).catch(ctx.failed);
|
|
1034
|
-
},
|
|
1035
|
-
async receive(of, name) {
|
|
1036
|
-
if (!others.some((other) => other.id === of && other.tracks.some((track) => track.name === name))) throw new CallError("not-found", `${of} publishes no ${name} in this call now.`);
|
|
1037
|
-
},
|
|
1038
|
-
async setLayer() {},
|
|
1039
|
-
async stopReceiving() {},
|
|
1040
|
-
send(text) {
|
|
1041
|
-
for (const peer of peers.values()) channelSend(peer.channel, peer.outbox, text);
|
|
1042
|
-
},
|
|
1043
|
-
async renewRelays() {},
|
|
1044
|
-
close() {
|
|
1045
|
-
for (const peer of [...peers.values()]) drop(peer);
|
|
1046
|
-
}
|
|
1047
|
-
};
|
|
1048
|
-
}
|
|
1049
|
-
var LiveCall = class {
|
|
1050
|
-
room;
|
|
1051
|
-
options;
|
|
1052
|
-
rtc;
|
|
1053
|
-
state = "connecting";
|
|
1054
|
-
error;
|
|
1055
|
-
audioOnly = false;
|
|
1056
|
-
me;
|
|
1057
|
-
participants = [];
|
|
1058
|
-
local = [];
|
|
1059
|
-
screen = {
|
|
1060
|
-
share: () => this.share(),
|
|
1061
|
-
stop: () => this.unshare()
|
|
1062
|
-
};
|
|
1063
|
-
listeners = /* @__PURE__ */ new Map();
|
|
1064
|
-
sending = /* @__PURE__ */ new Map();
|
|
1065
|
-
received = /* @__PURE__ */ new Map();
|
|
1066
|
-
declined = /* @__PURE__ */ new Set();
|
|
1067
|
-
wire = /* @__PURE__ */ new Map();
|
|
1068
|
-
departed = /* @__PURE__ */ new Map();
|
|
1069
|
-
meWire;
|
|
1070
|
-
session;
|
|
1071
|
-
credential;
|
|
1072
|
-
renewed = false;
|
|
1073
|
-
renewal;
|
|
1074
|
-
shown = "";
|
|
1075
|
-
left = false;
|
|
1076
|
-
/** The devices `publish` in the join's options started, until the join takes them. */
|
|
1077
|
-
capturing;
|
|
1078
|
-
/** Whether media ever connected, which tells a dropped call from a network that let nothing through. */
|
|
1079
|
-
connectedOnce = false;
|
|
1080
|
-
/** While a dropped call joins again: when it gives up. The call is back once its media connects, not once the room answers. */
|
|
1081
|
-
rejoinUntil;
|
|
1082
|
-
rejoining = false;
|
|
1083
|
-
constructor(room, options, rtc) {
|
|
1084
|
-
this.room = room;
|
|
1085
|
-
this.options = options;
|
|
1086
|
-
this.rtc = rtc;
|
|
1087
|
-
}
|
|
1088
|
-
async start() {
|
|
1089
|
-
if (this.options.publish) this.capturing = this.capture(this.options.publish).catch((error) => {
|
|
1090
|
-
this.background(error);
|
|
1091
|
-
return [];
|
|
1092
|
-
});
|
|
1093
|
-
try {
|
|
1094
|
-
const source = this.options.token;
|
|
1095
|
-
this.credential = credentialOf(typeof source === "function" ? await source() : source);
|
|
1096
|
-
await this.connect(false);
|
|
1097
|
-
} catch (error) {
|
|
1098
|
-
const refused = callErrorOf(error);
|
|
1099
|
-
this.error = refused;
|
|
1100
|
-
this.state = "failed";
|
|
1101
|
-
clearTimeout(this.renewal);
|
|
1102
|
-
throw refused;
|
|
1103
|
-
}
|
|
1104
|
-
}
|
|
1105
|
-
on(event, fn) {
|
|
1106
|
-
const set = this.listeners.get(event) ?? /* @__PURE__ */ new Set();
|
|
1107
|
-
this.listeners.set(event, set);
|
|
1108
|
-
set.add(fn);
|
|
1109
|
-
return () => {
|
|
1110
|
-
set.delete(fn);
|
|
1111
|
-
};
|
|
1112
|
-
}
|
|
1113
|
-
emit(event, value) {
|
|
1114
|
-
for (const fn of [...this.listeners.get(event) ?? []]) try {
|
|
1115
|
-
fn(value);
|
|
1116
|
-
} catch (error) {
|
|
1117
|
-
queueMicrotask(() => {
|
|
1118
|
-
throw error;
|
|
1119
|
-
});
|
|
1120
|
-
}
|
|
1121
|
-
}
|
|
1122
|
-
url() {
|
|
1123
|
-
return (this.options.url ?? this.credential.url ?? `${platformApi()}/call/app`).replace(/\/+$/u, "");
|
|
1124
|
-
}
|
|
1125
|
-
post(op, body) {
|
|
1126
|
-
return request(this.url(), this.credential.token, op, body);
|
|
1127
|
-
}
|
|
1128
|
-
setState(next) {
|
|
1129
|
-
if (this.state === next || this.state === "ended" || this.state === "failed") return;
|
|
1130
|
-
this.state = next;
|
|
1131
|
-
this.emit("state", next);
|
|
1132
|
-
}
|
|
1133
|
-
/** Joins the room, and publishes again what this call published before it dropped. */
|
|
1134
|
-
async connect(rejoining) {
|
|
1135
|
-
const joined = await this.post("join", {});
|
|
1136
|
-
if (this.left) return void await this.post("leave", { participant: joined.participant.id });
|
|
1137
|
-
if (joined.room.name !== this.room) {
|
|
1138
|
-
await this.post("leave", { participant: joined.participant.id });
|
|
1139
|
-
throw new CallError("invalid", `This token is for the call ${joined.room.name}, not ${this.room}. Ask the app's server for a token for ${this.room}.`);
|
|
1140
|
-
}
|
|
1141
|
-
this.credential = {
|
|
1142
|
-
...this.credential,
|
|
1143
|
-
expiresAt: joined.expiresAt
|
|
1144
|
-
};
|
|
1145
|
-
this.schedule();
|
|
1146
|
-
const capturing = this.capturing;
|
|
1147
|
-
this.capturing = void 0;
|
|
1148
|
-
if (capturing) {
|
|
1149
|
-
for (const { name, track, owned } of await capturing) {
|
|
1150
|
-
if (joined.room.audioOnly && TRACK_KINDS[name] === "video") {
|
|
1151
|
-
if (owned) track.stop();
|
|
1152
|
-
this.background(new CallError("invalid", audioOnlyProblem));
|
|
1153
|
-
continue;
|
|
1154
|
-
}
|
|
1155
|
-
this.sending.set(name, {
|
|
1156
|
-
track,
|
|
1157
|
-
owned,
|
|
1158
|
-
muted: false
|
|
1159
|
-
});
|
|
1160
|
-
}
|
|
1161
|
-
this.showLocal();
|
|
1162
|
-
}
|
|
1163
|
-
const session = {
|
|
1164
|
-
participant: joined.participant.id,
|
|
1165
|
-
connects: joined.media === "sfu" && joined.offer !== void 0,
|
|
1166
|
-
alive: true,
|
|
1167
|
-
changed: -1,
|
|
1168
|
-
ack: 0
|
|
1169
|
-
};
|
|
1170
|
-
const ctx = this.context(session, joined.iceServers);
|
|
1171
|
-
session.media = joined.media === "relay" ? relayMedia(ctx, rejoining) : sfuMedia(ctx, this.options.autoVideo !== false, this.declined, joined.offer);
|
|
1172
|
-
this.session = session;
|
|
1173
|
-
this.meWire = joined.participant;
|
|
1174
|
-
this.apply(session, joined.room);
|
|
1175
|
-
const again = [...this.sending].map(([name, { track }]) => ({
|
|
1176
|
-
name,
|
|
1177
|
-
track
|
|
1178
|
-
}));
|
|
1179
|
-
if (again.length) {
|
|
1180
|
-
const room = await session.media.publish(again);
|
|
1181
|
-
for (const [name, sending] of this.sending) if (sending.muted) await session.media.replace(name, null);
|
|
1182
|
-
if (room) this.apply(session, room);
|
|
1183
|
-
}
|
|
1184
|
-
this.watch(session);
|
|
1185
|
-
}
|
|
1186
|
-
context(session, iceServers) {
|
|
1187
|
-
const live = () => this.session === session && session.alive;
|
|
1188
|
-
return {
|
|
1189
|
-
me: session.participant,
|
|
1190
|
-
iceServers,
|
|
1191
|
-
rtc: this.rtc,
|
|
1192
|
-
post: (op, body) => this.post(op, body),
|
|
1193
|
-
sending: () => [...this.sending].map(([name, { track, muted }]) => ({
|
|
1194
|
-
name,
|
|
1195
|
-
track: muted ? null : track
|
|
1196
|
-
})),
|
|
1197
|
-
arrived: (of, name, track) => {
|
|
1198
|
-
if (!live()) return;
|
|
1199
|
-
const tracks = this.received.get(of) ?? /* @__PURE__ */ new Map();
|
|
1200
|
-
this.received.set(of, tracks);
|
|
1201
|
-
tracks.set(name, track);
|
|
1202
|
-
this.refresh();
|
|
1203
|
-
const participant = this.snapshotOf(of);
|
|
1204
|
-
if (participant) this.emit("track", {
|
|
1205
|
-
participant,
|
|
1206
|
-
name,
|
|
1207
|
-
track
|
|
1208
|
-
});
|
|
1209
|
-
},
|
|
1210
|
-
ended: (of, name) => {
|
|
1211
|
-
if (!live()) return;
|
|
1212
|
-
const track = this.received.get(of)?.get(name);
|
|
1213
|
-
this.received.get(of)?.delete(name);
|
|
1214
|
-
if (!track) return;
|
|
1215
|
-
this.refresh();
|
|
1216
|
-
const participant = this.snapshotOf(of);
|
|
1217
|
-
if (participant) this.emit("track-ended", {
|
|
1218
|
-
participant,
|
|
1219
|
-
name,
|
|
1220
|
-
track
|
|
1221
|
-
});
|
|
1222
|
-
},
|
|
1223
|
-
message: (of, text) => {
|
|
1224
|
-
if (!live()) return;
|
|
1225
|
-
const from = this.snapshotOf(of);
|
|
1226
|
-
let data;
|
|
1227
|
-
try {
|
|
1228
|
-
data = JSON.parse(text);
|
|
1229
|
-
} catch {
|
|
1230
|
-
return;
|
|
1231
|
-
}
|
|
1232
|
-
if (from) this.emit("data", {
|
|
1233
|
-
from,
|
|
1234
|
-
data
|
|
1235
|
-
});
|
|
1236
|
-
},
|
|
1237
|
-
broken: () => {
|
|
1238
|
-
if (live()) this.reconnect(true);
|
|
1239
|
-
},
|
|
1240
|
-
reached: () => {
|
|
1241
|
-
this.connectedOnce = true;
|
|
1242
|
-
if (!live() || this.rejoinUntil === void 0) return;
|
|
1243
|
-
this.rejoinUntil = void 0;
|
|
1244
|
-
this.setState(this.wire.size ? "in-call" : "waiting");
|
|
1245
|
-
},
|
|
1246
|
-
failed: (error) => {
|
|
1247
|
-
if (live()) this.background(error);
|
|
1248
|
-
}
|
|
1249
|
-
};
|
|
1250
|
-
}
|
|
1251
|
-
async watch(session) {
|
|
1252
|
-
while (session.alive && !this.left) {
|
|
1253
|
-
let watched;
|
|
1254
|
-
try {
|
|
1255
|
-
watched = await this.post("watch", {
|
|
1256
|
-
participant: session.participant,
|
|
1257
|
-
after: session.changed,
|
|
1258
|
-
waitMs: WATCH_WAIT_MS,
|
|
1259
|
-
...session.ack ? { ack: session.ack } : {}
|
|
1260
|
-
});
|
|
1261
|
-
} catch (error) {
|
|
1262
|
-
if (!session.alive || this.left) return;
|
|
1263
|
-
if (error instanceof Unreachable) this.reconnect();
|
|
1264
|
-
else this.fail(error);
|
|
1265
|
-
return;
|
|
1266
|
-
}
|
|
1267
|
-
if (!session.alive) return;
|
|
1268
|
-
if (watched.signals.length) {
|
|
1269
|
-
session.ack = Math.max(session.ack, ...watched.signals.map((signal) => signal.seq));
|
|
1270
|
-
session.media.signals(watched.signals);
|
|
1271
|
-
}
|
|
1272
|
-
this.apply(session, watched.room);
|
|
1273
|
-
}
|
|
1274
|
-
}
|
|
1275
|
-
/** Takes the room as the wire gives it: who is in it, what they publish, and the state that proves. */
|
|
1276
|
-
apply(session, room) {
|
|
1277
|
-
this.audioOnly = room.audioOnly;
|
|
1278
|
-
if (!session.alive || room.changed < session.changed) return;
|
|
1279
|
-
session.changed = room.changed;
|
|
1280
|
-
if (room.state === "ended") return this.finish();
|
|
1281
|
-
const mine = room.participants.find((participant) => participant.id === session.participant);
|
|
1282
|
-
if (mine) this.meWire = mine;
|
|
1283
|
-
const others = room.participants.filter((participant) => participant.id !== session.participant && participant.state !== "left");
|
|
1284
|
-
const before = this.wire;
|
|
1285
|
-
this.wire = new Map(others.map((participant) => [participant.id, participant]));
|
|
1286
|
-
this.departed = new Map([...before].filter(([id]) => !this.wire.has(id)));
|
|
1287
|
-
session.media.sync(others);
|
|
1288
|
-
for (const id of this.departed.keys()) this.received.delete(id);
|
|
1289
|
-
this.departed.clear();
|
|
1290
|
-
this.refresh();
|
|
1291
|
-
if (!(session.connects && this.rejoinUntil !== void 0)) this.setState(others.length ? "in-call" : "waiting");
|
|
1292
|
-
}
|
|
1293
|
-
snapshotOf(id) {
|
|
1294
|
-
const wire = this.wire.get(id) ?? this.departed.get(id);
|
|
1295
|
-
return wire && {
|
|
1296
|
-
...wire,
|
|
1297
|
-
received: Object.fromEntries(this.received.get(id) ?? [])
|
|
1298
|
-
};
|
|
1299
|
-
}
|
|
1300
|
-
/** Builds the participants anew, and says so, when anything about them changed. */
|
|
1301
|
-
refresh() {
|
|
1302
|
-
const me = {
|
|
1303
|
-
...this.meWire,
|
|
1304
|
-
received: {}
|
|
1305
|
-
};
|
|
1306
|
-
const participants = [...this.wire.keys()].flatMap((id) => this.snapshotOf(id) ?? []);
|
|
1307
|
-
const shown = JSON.stringify([me, participants.map((participant) => ({
|
|
1308
|
-
...participant,
|
|
1309
|
-
received: Object.entries(participant.received).map(([name, track]) => [name, track?.id])
|
|
1310
|
-
}))]);
|
|
1311
|
-
if (shown === this.shown) return;
|
|
1312
|
-
this.shown = shown;
|
|
1313
|
-
this.me = me;
|
|
1314
|
-
this.participants = participants;
|
|
1315
|
-
this.emit("participants", participants);
|
|
1316
|
-
}
|
|
1317
|
-
showLocal() {
|
|
1318
|
-
this.local = [...this.sending].map(([name, { track, muted }]) => ({
|
|
1319
|
-
name,
|
|
1320
|
-
track,
|
|
1321
|
-
muted
|
|
1322
|
-
}));
|
|
1323
|
-
this.emit("local", this.local);
|
|
1324
|
-
}
|
|
1325
|
-
/** Ends this session's media, keeping what this call publishes for the next. */
|
|
1326
|
-
teardown() {
|
|
1327
|
-
const session = this.session;
|
|
1328
|
-
if (session) {
|
|
1329
|
-
session.alive = false;
|
|
1330
|
-
session.media.close();
|
|
1331
|
-
}
|
|
1332
|
-
for (const [of, tracks] of this.received) for (const [name, track] of tracks) {
|
|
1333
|
-
const participant = this.snapshotOf(of);
|
|
1334
|
-
tracks.delete(name);
|
|
1335
|
-
if (participant) this.emit("track-ended", {
|
|
1336
|
-
participant,
|
|
1337
|
-
name,
|
|
1338
|
-
track
|
|
1339
|
-
});
|
|
1340
|
-
}
|
|
1341
|
-
this.received.clear();
|
|
1342
|
-
this.refresh();
|
|
1343
|
-
}
|
|
1344
|
-
/**
|
|
1345
|
-
* Joins the room again after a drop, as the same participant, for up to 30 seconds from the drop: until the media
|
|
1346
|
-
* is connected again, however many joins that takes. `media` says the media's connection is what broke, with the
|
|
1347
|
-
* room still answering: when it was never made, the network lets none through, and joining again can't help.
|
|
1348
|
-
*/
|
|
1349
|
-
async reconnect(media = false) {
|
|
1350
|
-
if (this.left || this.rejoining || this.state === "ended" || this.state === "failed") return;
|
|
1351
|
-
const blocked = new CallError("unavailable", "Your network let no connection through to the call. Try another network, or one that allows UDP or TCP port 80.", "blocked");
|
|
1352
|
-
const dropped = new CallError("unavailable", "The call's connection dropped and couldn't be made again within 30 seconds. Check your network, then join again.", "dropped");
|
|
1353
|
-
if (media && !this.connectedOnce) return this.fail(blocked);
|
|
1354
|
-
const until = this.rejoinUntil ??= Date.now() + REJOIN_FOR_MS;
|
|
1355
|
-
if (Date.now() >= until) return this.fail(dropped);
|
|
1356
|
-
this.rejoining = true;
|
|
1357
|
-
this.setState("reconnecting");
|
|
1358
|
-
this.teardown();
|
|
1359
|
-
let wait = 500;
|
|
1360
|
-
try {
|
|
1361
|
-
for (;;) try {
|
|
1362
|
-
await this.freshen();
|
|
1363
|
-
await this.connect(true);
|
|
1364
|
-
if (!this.session?.connects) this.rejoinUntil = void 0;
|
|
1365
|
-
return;
|
|
1366
|
-
} catch (error) {
|
|
1367
|
-
if (this.left) return;
|
|
1368
|
-
if (!(error instanceof Unreachable)) return this.fail(error);
|
|
1369
|
-
if (Date.now() + wait > until) return this.fail(this.connectedOnce ? dropped : blocked);
|
|
1370
|
-
await new Promise((resolve) => setTimeout(resolve, wait));
|
|
1371
|
-
wait = Math.min(wait * 2, 4e3);
|
|
1372
|
-
}
|
|
1373
|
-
} finally {
|
|
1374
|
-
this.rejoining = false;
|
|
1375
|
-
}
|
|
1376
|
-
}
|
|
1377
|
-
/** Asks for a new token now when this one runs out within five minutes. */
|
|
1378
|
-
async freshen() {
|
|
1379
|
-
const expiresAt = this.credential.expiresAt;
|
|
1380
|
-
if (typeof this.options.token === "function" && (expiresAt === void 0 || expiresAt - Date.now() < RENEW_BEFORE_MS)) await this.renew();
|
|
1381
|
-
}
|
|
1382
|
-
schedule() {
|
|
1383
|
-
clearTimeout(this.renewal);
|
|
1384
|
-
const expiresAt = this.credential.expiresAt;
|
|
1385
|
-
if (typeof this.options.token !== "function" || this.left || expiresAt === void 0) return;
|
|
1386
|
-
const remaining = expiresAt - Date.now();
|
|
1387
|
-
const delay = remaining > RENEW_BEFORE_MS ? remaining - RENEW_BEFORE_MS : this.renewed ? Math.max(remaining / 2, 0) : 0;
|
|
1388
|
-
this.renewal = setTimeout(() => {
|
|
1389
|
-
this.renew().catch((error) => this.background(error));
|
|
1390
|
-
}, delay);
|
|
1391
|
-
}
|
|
1392
|
-
async renew() {
|
|
1393
|
-
const source = this.options.token;
|
|
1394
|
-
if (typeof source !== "function") return;
|
|
1395
|
-
const next = credentialOf(await source());
|
|
1396
|
-
if (this.left) return;
|
|
1397
|
-
this.credential = next;
|
|
1398
|
-
this.renewed = true;
|
|
1399
|
-
this.schedule();
|
|
1400
|
-
const session = this.session;
|
|
1401
|
-
if (session?.alive) await session.media.renewRelays().catch((error) => {
|
|
1402
|
-
const refused = callErrorOf(error);
|
|
1403
|
-
if (refused.code !== "invalid" && refused.code !== "not-found") throw error;
|
|
1404
|
-
});
|
|
1405
|
-
}
|
|
1406
|
-
/** Something in the background failed: a drop joins again, an ended room ends the call, anything else is an `error` event. */
|
|
1407
|
-
background(error) {
|
|
1408
|
-
if (this.left || this.state === "ended" || this.state === "failed") return;
|
|
1409
|
-
if (error instanceof Unreachable) return void this.reconnect();
|
|
1410
|
-
const refused = callErrorOf(error);
|
|
1411
|
-
if (refused.code === "ended") return this.finish();
|
|
1412
|
-
this.emit("error", refused);
|
|
1413
|
-
}
|
|
1414
|
-
release() {
|
|
1415
|
-
clearTimeout(this.renewal);
|
|
1416
|
-
for (const { track, owned } of this.sending.values()) if (owned) track.stop();
|
|
1417
|
-
this.sending.clear();
|
|
1418
|
-
this.showLocal();
|
|
1419
|
-
}
|
|
1420
|
-
finish() {
|
|
1421
|
-
if (this.state === "ended" || this.state === "failed") return;
|
|
1422
|
-
this.teardown();
|
|
1423
|
-
this.release();
|
|
1424
|
-
this.setState("ended");
|
|
1425
|
-
}
|
|
1426
|
-
fail(error) {
|
|
1427
|
-
const refused = callErrorOf(error);
|
|
1428
|
-
if (refused.code === "ended") return this.finish();
|
|
1429
|
-
if (this.state === "ended" || this.state === "failed") return;
|
|
1430
|
-
this.teardown();
|
|
1431
|
-
this.release();
|
|
1432
|
-
this.error = refused;
|
|
1433
|
-
this.setState("failed");
|
|
1434
|
-
}
|
|
1435
|
-
ready() {
|
|
1436
|
-
if (this.left || this.state === "ended") throw new CallError("ended", "This call has ended.");
|
|
1437
|
-
if (this.state === "failed") throw this.error ?? new CallError("unavailable", "This call failed. Join again.");
|
|
1438
|
-
return this.session?.alive ? this.session : void 0;
|
|
1439
|
-
}
|
|
1440
|
-
devices() {
|
|
1441
|
-
const devices = this.rtc.mediaDevices ?? globalThis.navigator?.mediaDevices;
|
|
1442
|
-
if (!devices) throw new CallError("unavailable", "There's no camera, microphone or screen to capture here. Publish tracks of your own instead.");
|
|
1443
|
-
return devices;
|
|
1444
|
-
}
|
|
1445
|
-
/** Publishes tracks, replacing any already published under the same name. */
|
|
1446
|
-
async put(tracks) {
|
|
1447
|
-
const session = this.ready();
|
|
1448
|
-
const fresh = [];
|
|
1449
|
-
for (const { name, track, owned } of tracks) {
|
|
1450
|
-
const was = this.sending.get(name);
|
|
1451
|
-
if (!was) {
|
|
1452
|
-
fresh.push({
|
|
1453
|
-
name,
|
|
1454
|
-
track,
|
|
1455
|
-
owned
|
|
1456
|
-
});
|
|
1457
|
-
continue;
|
|
1458
|
-
}
|
|
1459
|
-
this.sending.set(name, {
|
|
1460
|
-
track,
|
|
1461
|
-
owned,
|
|
1462
|
-
muted: was.muted
|
|
1463
|
-
});
|
|
1464
|
-
if (session && !was.muted) await session.media.replace(name, track);
|
|
1465
|
-
if (was.owned && was.track !== track) was.track.stop();
|
|
1466
|
-
}
|
|
1467
|
-
for (const { name, track, owned } of fresh) this.sending.set(name, {
|
|
1468
|
-
track,
|
|
1469
|
-
owned,
|
|
1470
|
-
muted: false
|
|
1471
|
-
});
|
|
1472
|
-
if (session && fresh.length) try {
|
|
1473
|
-
const room = await session.media.publish(fresh);
|
|
1474
|
-
if (room) this.apply(session, room);
|
|
1475
|
-
} catch (error) {
|
|
1476
|
-
if (!session.alive && !this.left && this.state !== "failed" && this.state !== "ended") return this.showLocal();
|
|
1477
|
-
for (const { name, track, owned } of fresh) {
|
|
1478
|
-
this.sending.delete(name);
|
|
1479
|
-
if (owned) track.stop();
|
|
1480
|
-
}
|
|
1481
|
-
this.showLocal();
|
|
1482
|
-
throw callErrorOf(error);
|
|
1483
|
-
}
|
|
1484
|
-
this.showLocal();
|
|
1485
|
-
}
|
|
1486
|
-
async publish(asked) {
|
|
1487
|
-
this.ready();
|
|
1488
|
-
if (this.audioOnly && asked.camera) throw new CallError("invalid", audioOnlyProblem);
|
|
1489
|
-
const tracks = asked.mic === true || asked.camera === true ? await this.capture(asked) : this.given(asked);
|
|
1490
|
-
await this.put(tracks);
|
|
1491
|
-
}
|
|
1492
|
-
/** The tracks `asked` gives as they are, none started here. */
|
|
1493
|
-
given(asked) {
|
|
1494
|
-
return [...typeof asked.mic === "object" ? [{
|
|
1495
|
-
name: "mic",
|
|
1496
|
-
track: asked.mic,
|
|
1497
|
-
owned: false
|
|
1498
|
-
}] : [], ...typeof asked.camera === "object" ? [{
|
|
1499
|
-
name: "camera",
|
|
1500
|
-
track: asked.camera,
|
|
1501
|
-
owned: false
|
|
1502
|
-
}] : []];
|
|
1503
|
-
}
|
|
1504
|
-
/** The tracks `asked` names: a track given as it is, and `true` started from the browser's devices. */
|
|
1505
|
-
async capture(asked) {
|
|
1506
|
-
const audio = asked.mic === true, video = asked.camera === true;
|
|
1507
|
-
let captured;
|
|
1508
|
-
if (audio || video) captured = await this.devices().getUserMedia({
|
|
1509
|
-
audio,
|
|
1510
|
-
video: video ? CAMERA : false
|
|
1511
|
-
}).catch((error) => {
|
|
1512
|
-
throw new CallError(deviceRefused(error) ? "forbidden" : "unavailable", deviceRefused(error) ? "The browser didn't allow the microphone or camera. Allow them in the site's settings, then try again." : `The microphone or camera couldn't be started: ${messageOf(error)}`);
|
|
1513
|
-
});
|
|
1514
|
-
const tracks = [];
|
|
1515
|
-
const mic = typeof asked.mic === "object" ? asked.mic : audio ? captured?.getAudioTracks()[0] : void 0;
|
|
1516
|
-
const camera = typeof asked.camera === "object" ? asked.camera : video ? captured?.getVideoTracks()[0] : void 0;
|
|
1517
|
-
if (mic) tracks.push({
|
|
1518
|
-
name: "mic",
|
|
1519
|
-
track: mic,
|
|
1520
|
-
owned: mic !== asked.mic
|
|
1521
|
-
});
|
|
1522
|
-
if (camera) tracks.push({
|
|
1523
|
-
name: "camera",
|
|
1524
|
-
track: camera,
|
|
1525
|
-
owned: camera !== asked.camera
|
|
1526
|
-
});
|
|
1527
|
-
return tracks;
|
|
1528
|
-
}
|
|
1529
|
-
async unpublish(name) {
|
|
1530
|
-
await this.stop([name]);
|
|
1531
|
-
}
|
|
1532
|
-
async stop(names) {
|
|
1533
|
-
const session = this.ready();
|
|
1534
|
-
const stopping = names.filter((name) => this.sending.has(name));
|
|
1535
|
-
if (!stopping.length) return;
|
|
1536
|
-
if (session) this.apply(session, await session.media.unpublish(stopping));
|
|
1537
|
-
for (const name of stopping) {
|
|
1538
|
-
const was = this.sending.get(name);
|
|
1539
|
-
this.sending.delete(name);
|
|
1540
|
-
if (was?.owned) was.track.stop();
|
|
1541
|
-
}
|
|
1542
|
-
this.showLocal();
|
|
1543
|
-
}
|
|
1544
|
-
async mute(name) {
|
|
1545
|
-
await this.muting(name, true);
|
|
1546
|
-
}
|
|
1547
|
-
async unmute(name) {
|
|
1548
|
-
await this.muting(name, false);
|
|
1549
|
-
}
|
|
1550
|
-
async muting(name, muted) {
|
|
1551
|
-
const session = this.ready();
|
|
1552
|
-
const was = this.sending.get(name);
|
|
1553
|
-
if (!was || was.muted === muted) return;
|
|
1554
|
-
this.sending.set(name, {
|
|
1555
|
-
...was,
|
|
1556
|
-
muted
|
|
1557
|
-
});
|
|
1558
|
-
if (session) await session.media.replace(name, muted ? null : was.track);
|
|
1559
|
-
this.showLocal();
|
|
1560
|
-
}
|
|
1561
|
-
async share() {
|
|
1562
|
-
this.ready();
|
|
1563
|
-
if (this.audioOnly) throw new CallError("invalid", audioOnlyProblem);
|
|
1564
|
-
const stream = await this.devices().getDisplayMedia({
|
|
1565
|
-
video: true,
|
|
1566
|
-
audio: true
|
|
1567
|
-
}).catch((error) => {
|
|
1568
|
-
throw new CallError(deviceRefused(error) ? "forbidden" : "unavailable", deviceRefused(error) ? "Sharing the screen wasn't allowed." : `The screen couldn't be shared: ${messageOf(error)}`);
|
|
1569
|
-
});
|
|
1570
|
-
const screen = stream.getVideoTracks()[0], sound = stream.getAudioTracks()[0];
|
|
1571
|
-
if (!screen) throw new CallError("unavailable", "No screen was picked to share.");
|
|
1572
|
-
screen.addEventListener("ended", () => {
|
|
1573
|
-
if (this.sending.get("screen")?.track === screen) this.unshare().catch((error) => this.background(error));
|
|
1574
|
-
});
|
|
1575
|
-
await this.put([{
|
|
1576
|
-
name: "screen",
|
|
1577
|
-
track: screen,
|
|
1578
|
-
owned: true
|
|
1579
|
-
}, ...sound ? [{
|
|
1580
|
-
name: "screen-audio",
|
|
1581
|
-
track: sound,
|
|
1582
|
-
owned: true
|
|
1583
|
-
}] : []]);
|
|
1584
|
-
}
|
|
1585
|
-
async unshare() {
|
|
1586
|
-
await this.stop(["screen", "screen-audio"]);
|
|
1587
|
-
}
|
|
1588
|
-
media() {
|
|
1589
|
-
const session = this.ready();
|
|
1590
|
-
if (!session) throw new CallError("unavailable", "The call is joining again. Try once it's back.");
|
|
1591
|
-
return session.media;
|
|
1592
|
-
}
|
|
1593
|
-
async receive(participantId, name, options = {}) {
|
|
1594
|
-
const media = this.media();
|
|
1595
|
-
this.declined.delete(`${participantId}/${name}`);
|
|
1596
|
-
await media.receive(participantId, name, options.layer);
|
|
1597
|
-
}
|
|
1598
|
-
async setLayer(participantId, name, layer) {
|
|
1599
|
-
await this.media().setLayer(participantId, name, layer);
|
|
1600
|
-
}
|
|
1601
|
-
async stopReceiving(participantId, name) {
|
|
1602
|
-
await this.media().stopReceiving(participantId, name);
|
|
1603
|
-
}
|
|
1604
|
-
send(data) {
|
|
1605
|
-
const session = this.ready();
|
|
1606
|
-
const text = JSON.stringify(data);
|
|
1607
|
-
const bytes = new TextEncoder().encode(text).length;
|
|
1608
|
-
if (bytes > 16384) throw new CallError("invalid", sizeProblem(bytes));
|
|
1609
|
-
session?.media.send(text);
|
|
1610
|
-
}
|
|
1611
|
-
async leave() {
|
|
1612
|
-
if (this.left) return;
|
|
1613
|
-
const session = this.session;
|
|
1614
|
-
const was = this.state;
|
|
1615
|
-
this.left = true;
|
|
1616
|
-
this.teardown();
|
|
1617
|
-
this.release();
|
|
1618
|
-
this.setState("ended");
|
|
1619
|
-
if (session && was !== "ended" && was !== "failed") await this.post("leave", { participant: session.participant });
|
|
1620
|
-
}
|
|
1621
|
-
};
|
|
1622
|
-
const deviceRefused = (error) => error?.name === "NotAllowedError";
|
|
1623
|
-
const messageOf = (error) => error instanceof Error ? error.message : String(error);
|
|
1624
|
-
function callErrorOf(error) {
|
|
1625
|
-
if (error instanceof CallError && error.code === "forbidden" && !error.reason && /removed from this call/u.test(error.message)) return new CallError(error.code, error.message, "removed");
|
|
1626
|
-
if (error instanceof CallError) return error;
|
|
1627
|
-
return new CallError("unavailable", `The call's connection couldn't be made: ${messageOf(error)}`);
|
|
1628
|
-
}
|
|
1629
|
-
//#endregion
|
|
1
|
+
import { a as MAX_VIDEOS, c as join, i as MAX_MESSAGE_BYTES, l as layerWatch, n as CallError, o as callToken, r as MAX_FULL_VIDEOS, s as identityProblem, t as CAMERA, u as roomProblem } from "../calls-CQQ0NnoP.mjs";
|
|
1630
2
|
export { CAMERA, CallError, MAX_FULL_VIDEOS, MAX_MESSAGE_BYTES, MAX_VIDEOS, callToken, identityProblem, join, layerWatch, roomProblem };
|