@voltkit-rtc/client 0.7.3 → 0.9.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/CHANGELOG.md +86 -0
- package/README.md +346 -2
- package/dist/cjs/adaptive.d.ts +104 -0
- package/dist/cjs/adaptive.d.ts.map +1 -0
- package/dist/cjs/adaptive.js +263 -0
- package/dist/cjs/adaptive.js.map +1 -0
- package/dist/cjs/devices.d.ts +42 -0
- package/dist/cjs/devices.d.ts.map +1 -0
- package/dist/cjs/devices.js +56 -0
- package/dist/cjs/devices.js.map +1 -0
- package/dist/cjs/diagnostics.d.ts +65 -0
- package/dist/cjs/diagnostics.d.ts.map +1 -0
- package/dist/cjs/diagnostics.js +69 -0
- package/dist/cjs/diagnostics.js.map +1 -0
- package/dist/cjs/effects-core.d.ts +95 -0
- package/dist/cjs/effects-core.d.ts.map +1 -0
- package/dist/cjs/effects-core.js +154 -0
- package/dist/cjs/effects-core.js.map +1 -0
- package/dist/cjs/effects-gl.d.ts +79 -0
- package/dist/cjs/effects-gl.d.ts.map +1 -0
- package/dist/cjs/effects-gl.js +351 -0
- package/dist/cjs/effects-gl.js.map +1 -0
- package/dist/cjs/fallback.d.ts +81 -0
- package/dist/cjs/fallback.d.ts.map +1 -0
- package/dist/cjs/fallback.js +148 -0
- package/dist/cjs/fallback.js.map +1 -0
- package/dist/cjs/health.d.ts +70 -0
- package/dist/cjs/health.d.ts.map +1 -0
- package/dist/cjs/health.js +116 -0
- package/dist/cjs/health.js.map +1 -0
- package/dist/cjs/index.d.ts +396 -0
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +1367 -81
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/link.d.ts +99 -0
- package/dist/cjs/link.d.ts.map +1 -0
- package/dist/cjs/link.js +219 -0
- package/dist/cjs/link.js.map +1 -0
- package/dist/cjs/noise-suppression.d.ts +44 -0
- package/dist/cjs/noise-suppression.d.ts.map +1 -0
- package/dist/cjs/noise-suppression.js +103 -0
- package/dist/cjs/noise-suppression.js.map +1 -0
- package/dist/cjs/preflight.d.ts +79 -0
- package/dist/cjs/preflight.d.ts.map +1 -0
- package/dist/cjs/preflight.js +159 -0
- package/dist/cjs/preflight.js.map +1 -0
- package/dist/cjs/processors.d.ts +34 -0
- package/dist/cjs/processors.d.ts.map +1 -0
- package/dist/cjs/processors.js +10 -0
- package/dist/cjs/processors.js.map +1 -0
- package/dist/cjs/speakers.d.ts +34 -0
- package/dist/cjs/speakers.d.ts.map +1 -0
- package/dist/cjs/speakers.js +71 -0
- package/dist/cjs/speakers.js.map +1 -0
- package/dist/cjs/video-effects.d.ts +93 -0
- package/dist/cjs/video-effects.d.ts.map +1 -0
- package/dist/cjs/video-effects.js +493 -0
- package/dist/cjs/video-effects.js.map +1 -0
- package/dist/esm/adaptive.d.ts +104 -0
- package/dist/esm/adaptive.d.ts.map +1 -0
- package/dist/esm/adaptive.js +256 -0
- package/dist/esm/adaptive.js.map +1 -0
- package/dist/esm/devices.d.ts +42 -0
- package/dist/esm/devices.d.ts.map +1 -0
- package/dist/esm/devices.js +50 -0
- package/dist/esm/devices.js.map +1 -0
- package/dist/esm/diagnostics.d.ts +65 -0
- package/dist/esm/diagnostics.d.ts.map +1 -0
- package/dist/esm/diagnostics.js +65 -0
- package/dist/esm/diagnostics.js.map +1 -0
- package/dist/esm/effects-core.d.ts +95 -0
- package/dist/esm/effects-core.d.ts.map +1 -0
- package/dist/esm/effects-core.js +142 -0
- package/dist/esm/effects-core.js.map +1 -0
- package/dist/esm/effects-gl.d.ts +79 -0
- package/dist/esm/effects-gl.d.ts.map +1 -0
- package/dist/esm/effects-gl.js +347 -0
- package/dist/esm/effects-gl.js.map +1 -0
- package/dist/esm/fallback.d.ts +81 -0
- package/dist/esm/fallback.d.ts.map +1 -0
- package/dist/esm/fallback.js +142 -0
- package/dist/esm/fallback.js.map +1 -0
- package/dist/esm/health.d.ts +70 -0
- package/dist/esm/health.d.ts.map +1 -0
- package/dist/esm/health.js +111 -0
- package/dist/esm/health.js.map +1 -0
- package/dist/esm/index.d.ts +396 -0
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +1365 -81
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/link.d.ts +99 -0
- package/dist/esm/link.d.ts.map +1 -0
- package/dist/esm/link.js +214 -0
- package/dist/esm/link.js.map +1 -0
- package/dist/esm/noise-suppression.d.ts +44 -0
- package/dist/esm/noise-suppression.d.ts.map +1 -0
- package/dist/esm/noise-suppression.js +99 -0
- package/dist/esm/noise-suppression.js.map +1 -0
- package/dist/esm/preflight.d.ts +79 -0
- package/dist/esm/preflight.d.ts.map +1 -0
- package/dist/esm/preflight.js +153 -0
- package/dist/esm/preflight.js.map +1 -0
- package/dist/esm/processors.d.ts +34 -0
- package/dist/esm/processors.d.ts.map +1 -0
- package/dist/esm/processors.js +9 -0
- package/dist/esm/processors.js.map +1 -0
- package/dist/esm/speakers.d.ts +34 -0
- package/dist/esm/speakers.d.ts.map +1 -0
- package/dist/esm/speakers.js +67 -0
- package/dist/esm/speakers.js.map +1 -0
- package/dist/esm/video-effects.d.ts +93 -0
- package/dist/esm/video-effects.d.ts.map +1 -0
- package/dist/esm/video-effects.js +488 -0
- package/dist/esm/video-effects.js.map +1 -0
- package/package.json +31 -1
- package/src/adaptive.ts +295 -0
- package/src/devices.ts +70 -0
- package/src/diagnostics.ts +94 -0
- package/src/effects-core.ts +177 -0
- package/src/effects-gl.ts +384 -0
- package/src/fallback.ts +169 -0
- package/src/health.ts +127 -0
- package/src/index.ts +1364 -81
- package/src/link.ts +255 -0
- package/src/noise-suppression.ts +135 -0
- package/src/preflight.ts +191 -0
- package/src/processors.ts +35 -0
- package/src/speakers.ts +66 -0
- package/src/video-effects.ts +552 -0
package/src/link.ts
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeping the connection alive between drops (docs/implementation-progress/RTC_PERF_PROGRESS.md G1, G2).
|
|
3
|
+
*
|
|
4
|
+
* Two failures the socket's own close never reports:
|
|
5
|
+
*
|
|
6
|
+
* - **The media path dies while the socket lives** (Wi-Fi to mobile data, a NAT rebinding, UDP blocked mid-call).
|
|
7
|
+
* The video freezes for good. Twilio and LiveKit restart ICE on the same transports first -- new ICE credentials
|
|
8
|
+
* from the server, the same producers and consumers -- and rejoin only when that does not bring the path back.
|
|
9
|
+
* {@link MediaPathWatch} does the same: a transport `disconnected` for {@link DISCONNECTED_GRACE_MS} or `failed`
|
|
10
|
+
* restarts ICE; not `connected` within {@link RESTART_TIMEOUT_MS} of starting recovery (including the request), or a server without `restartIce`, is a
|
|
11
|
+
* full reconnect.
|
|
12
|
+
* - **The socket dies silently**: the network went away and TCP has not noticed yet, which can take minutes. The
|
|
13
|
+
* server pings, but a browser cannot see those. LiveKit pings from the client and reconnects when no pong comes.
|
|
14
|
+
* {@link SocketLiveness} sends `ping` after {@link IDLE_MS} with nothing received, and calls the socket dead when
|
|
15
|
+
* nothing at all arrives within {@link PING_TIMEOUT_MS} of it. Any frame counts, so an older server's
|
|
16
|
+
* `unknown-method` reply proves the socket as well as a pong.
|
|
17
|
+
*
|
|
18
|
+
* Pure: timers and the clock are injectable, so the decisions are unit-tested on their own.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** A transport `disconnected` this long is restarted (it often recovers by itself within a second or two). */
|
|
22
|
+
export const DISCONNECTED_GRACE_MS = 3000;
|
|
23
|
+
/** The whole ICE recovery, including the request, has this long before the session rejoins. */
|
|
24
|
+
export const RESTART_TIMEOUT_MS = 10_000;
|
|
25
|
+
/** With nothing received for this long, the client pings. */
|
|
26
|
+
export const IDLE_MS = 15_000;
|
|
27
|
+
/** A ping with nothing at all received for this long after it: the socket is dead. */
|
|
28
|
+
export const PING_TIMEOUT_MS = 8000;
|
|
29
|
+
/** How often liveness is checked. Background tabs may run it less often; the decisions use the clock, not counts. */
|
|
30
|
+
export const LIVENESS_TICK_MS = 5000;
|
|
31
|
+
|
|
32
|
+
export type TransportState = 'new' | 'connecting' | 'connected' | 'disconnected' | 'failed' | 'closed';
|
|
33
|
+
|
|
34
|
+
/** What an ICE restart came to. */
|
|
35
|
+
export type RestartOutcome =
|
|
36
|
+
/** New credentials applied: wait for `connected`. */
|
|
37
|
+
| 'restarted'
|
|
38
|
+
/** The server has no restartIce (older than 2026-10-19): rejoin instead. */
|
|
39
|
+
| 'unsupported'
|
|
40
|
+
/** It could not be done now (the socket is down, the session is going): the socket's own recovery handles it. */
|
|
41
|
+
| 'skipped';
|
|
42
|
+
|
|
43
|
+
export interface MediaPathHost {
|
|
44
|
+
/** Whether the session is connected; nothing is done otherwise (a reconnect is already under way, or it ended). */
|
|
45
|
+
active(): boolean;
|
|
46
|
+
/** Ask the server for new ICE credentials for this transport and apply them. */
|
|
47
|
+
restartIce(transportId: string): Promise<RestartOutcome>;
|
|
48
|
+
/** Give up on this connection and rejoin. */
|
|
49
|
+
reconnect(reason: string): void;
|
|
50
|
+
/** Told when a transport's media path is lost and when it is back (for `mediaReconnecting`-style UI). */
|
|
51
|
+
onPathChange?(transportId: string, lost: boolean): void;
|
|
52
|
+
setTimer?(fn: () => void, ms: number): unknown;
|
|
53
|
+
clearTimer?(handle: unknown): void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface PathEntry {
|
|
57
|
+
revision: number;
|
|
58
|
+
state: TransportState;
|
|
59
|
+
timer: unknown;
|
|
60
|
+
/** One restart is in flight; repeated loss notifications share its deadline. */
|
|
61
|
+
restarting: boolean;
|
|
62
|
+
lost: boolean;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Watches each media transport's connection state and recovers a dead path. */
|
|
66
|
+
export class MediaPathWatch {
|
|
67
|
+
private readonly entries = new Map<string, PathEntry>();
|
|
68
|
+
private readonly setTimer: (fn: () => void, ms: number) => unknown;
|
|
69
|
+
private readonly clearTimer: (handle: unknown) => void;
|
|
70
|
+
|
|
71
|
+
constructor(private readonly host: MediaPathHost) {
|
|
72
|
+
this.setTimer = host.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
|
|
73
|
+
this.clearTimer = host.clearTimer ?? ((h) => clearTimeout(h as ReturnType<typeof setTimeout>));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A transport's connection state changed (mediasoup-client `connectionstatechange`). */
|
|
77
|
+
update(transportId: string, state: TransportState): void {
|
|
78
|
+
let entry = this.entries.get(transportId);
|
|
79
|
+
if (!entry) {
|
|
80
|
+
entry = { state, timer: null, restarting: false, lost: false, revision: 0 };
|
|
81
|
+
this.entries.set(transportId, entry);
|
|
82
|
+
}
|
|
83
|
+
entry.state = state;
|
|
84
|
+
switch (state) {
|
|
85
|
+
case 'connected':
|
|
86
|
+
entry.revision++;
|
|
87
|
+
this.cancel(entry);
|
|
88
|
+
entry.restarting = false;
|
|
89
|
+
this.setLost(transportId, entry, false);
|
|
90
|
+
return;
|
|
91
|
+
case 'closed':
|
|
92
|
+
this.forget(transportId);
|
|
93
|
+
return;
|
|
94
|
+
case 'disconnected':
|
|
95
|
+
// A restart is already waiting for `connected`; its own deadline decides.
|
|
96
|
+
if (entry.restarting || entry.timer !== null) return;
|
|
97
|
+
entry.timer = this.setTimer(() => {
|
|
98
|
+
entry.timer = null;
|
|
99
|
+
if (entry.state === 'disconnected' || entry.state === 'failed') void this.restart(transportId, entry);
|
|
100
|
+
}, DISCONNECTED_GRACE_MS);
|
|
101
|
+
return;
|
|
102
|
+
case 'failed':
|
|
103
|
+
if (entry.restarting) return; // duplicate notification; the deadline decides
|
|
104
|
+
this.cancel(entry);
|
|
105
|
+
void this.restart(transportId, entry);
|
|
106
|
+
return;
|
|
107
|
+
default:
|
|
108
|
+
// new / connecting: a fresh transport, or one mid-restart.
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The transport went away with its session (teardown): no more decisions for it. */
|
|
114
|
+
forget(transportId: string): void {
|
|
115
|
+
const entry = this.entries.get(transportId);
|
|
116
|
+
if (!entry) return;
|
|
117
|
+
this.cancel(entry);
|
|
118
|
+
this.entries.delete(transportId);
|
|
119
|
+
if (entry.lost) this.host.onPathChange?.(transportId, false);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Every transport went away (teardown, close). */
|
|
123
|
+
reset(): void {
|
|
124
|
+
for (const id of [...this.entries.keys()]) this.forget(id);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** For tests and the network-change nudge: is this transport being recovered now? */
|
|
128
|
+
restartingNow(transportId: string): boolean {
|
|
129
|
+
return this.entries.get(transportId)?.restarting === true;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private async restart(transportId: string, entry: PathEntry): Promise<void> {
|
|
133
|
+
if (!this.host.active() || this.entries.get(transportId) !== entry) return;
|
|
134
|
+
entry.restarting = true;
|
|
135
|
+
const revision = ++entry.revision;
|
|
136
|
+
// Include both the RPC and the platform call in the deadline: neither is
|
|
137
|
+
// guaranteed to settle when a network/interface disappears.
|
|
138
|
+
this.cancel(entry);
|
|
139
|
+
entry.timer = this.setTimer(() => {
|
|
140
|
+
entry.timer = null;
|
|
141
|
+
if (!entry.restarting || this.entries.get(transportId) !== entry) return;
|
|
142
|
+
entry.revision++;
|
|
143
|
+
entry.restarting = false;
|
|
144
|
+
if (this.host.active()) this.host.reconnect('media-timeout');
|
|
145
|
+
}, RESTART_TIMEOUT_MS);
|
|
146
|
+
this.setLost(transportId, entry, true);
|
|
147
|
+
let outcome: RestartOutcome;
|
|
148
|
+
try {
|
|
149
|
+
outcome = await this.host.restartIce(transportId);
|
|
150
|
+
} catch {
|
|
151
|
+
outcome = 'unsupported';
|
|
152
|
+
}
|
|
153
|
+
if (this.entries.get(transportId) !== entry || entry.revision !== revision) return;
|
|
154
|
+
if (outcome === 'skipped') {
|
|
155
|
+
this.cancel(entry);
|
|
156
|
+
entry.restarting = false;
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (outcome === 'unsupported') {
|
|
160
|
+
this.cancel(entry);
|
|
161
|
+
entry.restarting = false;
|
|
162
|
+
if (this.host.active()) this.host.reconnect('media-failed');
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
// `connected` clears the deadline, including when it arrives during the await.
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
private setLost(transportId: string, entry: PathEntry, lost: boolean): void {
|
|
169
|
+
if (entry.lost === lost) return;
|
|
170
|
+
entry.lost = lost;
|
|
171
|
+
this.host.onPathChange?.(transportId, lost);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
private cancel(entry: PathEntry): void {
|
|
175
|
+
if (entry.timer !== null) this.clearTimer(entry.timer);
|
|
176
|
+
entry.timer = null;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export interface LivenessHost {
|
|
181
|
+
/** Whether the session's socket should be checked now (connected, not closing). */
|
|
182
|
+
active(): boolean;
|
|
183
|
+
/** Send a ping; its reply (or error reply) reaches {@link SocketLiveness.received} like any frame. */
|
|
184
|
+
ping(): void;
|
|
185
|
+
/** Nothing came back: close the socket so the normal reconnect runs. */
|
|
186
|
+
dead(): void;
|
|
187
|
+
now?(): number;
|
|
188
|
+
setInterval?(fn: () => void, ms: number): unknown;
|
|
189
|
+
clearInterval?(handle: unknown): void;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Notices a socket that died without closing. */
|
|
193
|
+
export class SocketLiveness {
|
|
194
|
+
private lastReceived = 0;
|
|
195
|
+
private pingSentAt: number | null = null;
|
|
196
|
+
private timer: unknown = null;
|
|
197
|
+
private readonly now: () => number;
|
|
198
|
+
|
|
199
|
+
constructor(private readonly host: LivenessHost) {
|
|
200
|
+
this.now = host.now ?? Date.now;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Start watching a newly opened socket. */
|
|
204
|
+
start(): void {
|
|
205
|
+
this.stop();
|
|
206
|
+
this.lastReceived = this.now();
|
|
207
|
+
this.pingSentAt = null;
|
|
208
|
+
const every = this.host.setInterval ?? ((fn, ms) => setInterval(fn, ms));
|
|
209
|
+
this.timer = every(() => this.check(), LIVENESS_TICK_MS);
|
|
210
|
+
// A Node/SSR process with no other work need not stay alive for a browser
|
|
211
|
+
// connection watch. Browser timers are numbers and have no unref.
|
|
212
|
+
(this.timer as { unref?: () => void })?.unref?.();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
stop(): void {
|
|
216
|
+
if (this.timer !== null) (this.host.clearInterval ?? ((h) => clearInterval(h as ReturnType<typeof setInterval>)))(this.timer);
|
|
217
|
+
this.timer = null;
|
|
218
|
+
this.pingSentAt = null;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
get running(): boolean {
|
|
222
|
+
return this.timer !== null;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Any frame arrived on the socket. */
|
|
226
|
+
received(): void {
|
|
227
|
+
this.lastReceived = this.now();
|
|
228
|
+
this.pingSentAt = null;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Check now instead of at the next tick (the browser said the network changed). */
|
|
232
|
+
checkNow(): void {
|
|
233
|
+
if (this.timer === null || !this.host.active()) return;
|
|
234
|
+
if (this.pingSentAt === null) {
|
|
235
|
+
this.pingSentAt = this.now();
|
|
236
|
+
this.host.ping();
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
check(): void {
|
|
241
|
+
if (this.timer === null || !this.host.active()) return;
|
|
242
|
+
const now = this.now();
|
|
243
|
+
if (this.pingSentAt !== null) {
|
|
244
|
+
if (now - this.pingSentAt >= PING_TIMEOUT_MS) {
|
|
245
|
+
this.stop();
|
|
246
|
+
this.host.dead();
|
|
247
|
+
}
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (now - this.lastReceived >= IDLE_MS) {
|
|
251
|
+
this.pingSentAt = now;
|
|
252
|
+
this.host.ping();
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI noise suppression for the microphone (docs/implementation-progress/RTC_PERF_PROGRESS.md P3-4): what Agora's AI
|
|
3
|
+
* Denoiser, LiveKit's Krisp filter and ZEGOCLOUD's AI noise suppression do, with RNNoise -- the open neural-network
|
|
4
|
+
* denoiser Jitsi uses -- through `@sapphi-red/web-noise-suppressor` (MIT): a Web Audio worklet in the browser's
|
|
5
|
+
* audio thread. Fans, traffic and room rumble fall away (measured in Chromium: rumble-like noise down by more than
|
|
6
|
+
* 60 dB, steady white hiss by 7-12 dB); voices stay.
|
|
7
|
+
*
|
|
8
|
+
* Imported on its own (`@voltkit-rtc/client/noise-suppression`), so an app that does not use it never ships it:
|
|
9
|
+
*
|
|
10
|
+
* import { createNoiseSuppressor } from '@voltkit-rtc/client/noise-suppression';
|
|
11
|
+
* await client.setAudioProcessor(createNoiseSuppressor());
|
|
12
|
+
*
|
|
13
|
+
* The worklet (64 kB) and the model (150 kB) are fetched when it starts: from jsDelivr, at the exact version this
|
|
14
|
+
* SDK was tested with, unless you serve them yourself (`workletUrl`, `wasmUrl`, `simdWasmUrl`) -- copy them from
|
|
15
|
+
* `node_modules/@sapphi-red/web-noise-suppressor/dist` to your own site for a strict Content-Security-Policy.
|
|
16
|
+
*/
|
|
17
|
+
import type { AudioTrackProcessor } from './processors.js';
|
|
18
|
+
|
|
19
|
+
/** The package version the default URLs point at; equal to this SDK's pinned dependency (a test checks it). */
|
|
20
|
+
export const NOISE_SUPPRESSOR_VERSION = '0.4.1';
|
|
21
|
+
const CDN = `https://cdn.jsdelivr.net/npm/@sapphi-red/web-noise-suppressor@${NOISE_SUPPRESSOR_VERSION}/dist`;
|
|
22
|
+
|
|
23
|
+
export interface NoiseSuppressorOptions {
|
|
24
|
+
/** Where `rnnoise/workletProcessor.js` is served. Default: jsDelivr, pinned. */
|
|
25
|
+
workletUrl?: string;
|
|
26
|
+
/** Where `rnnoise.wasm` is served. Default: jsDelivr, pinned. */
|
|
27
|
+
wasmUrl?: string;
|
|
28
|
+
/** Where `rnnoise_simd.wasm` is served (used where the browser supports SIMD). Default: jsDelivr, pinned. */
|
|
29
|
+
simdWasmUrl?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** What the processor needs from the browser; stood in for by tests. */
|
|
33
|
+
export interface NoiseSuppressorDeps {
|
|
34
|
+
createContext(): AudioContext;
|
|
35
|
+
loadModel(urls: { url: string; simdUrl: string }): Promise<ArrayBuffer>;
|
|
36
|
+
createNode(context: AudioContext, wasmBinary: ArrayBuffer): Promise<DenoiseNode> | DenoiseNode;
|
|
37
|
+
createStream(tracks: MediaStreamTrack[]): MediaStream;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
type DenoiseNode = AudioNode & { destroy?(): void };
|
|
41
|
+
type Library = typeof import('@sapphi-red/web-noise-suppressor');
|
|
42
|
+
let library: Promise<Library> | null = null;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The library is loaded on first use, not with this module: it extends `AudioWorkletNode` as it loads, which exists
|
|
46
|
+
* only in browsers, so a static import would break a server render (Next.js) or Node.
|
|
47
|
+
*/
|
|
48
|
+
const load = (): Promise<Library> =>
|
|
49
|
+
(library ??= import('@sapphi-red/web-noise-suppressor').catch((err: unknown) => {
|
|
50
|
+
library = null;
|
|
51
|
+
throw err;
|
|
52
|
+
}));
|
|
53
|
+
|
|
54
|
+
const browserDeps: NoiseSuppressorDeps = {
|
|
55
|
+
// RNNoise works on 48 kHz audio.
|
|
56
|
+
createContext: () => new AudioContext({ sampleRate: 48000 }),
|
|
57
|
+
loadModel: async (urls) => (await load()).loadRnnoise(urls),
|
|
58
|
+
createNode: async (context, wasmBinary) => new (await load()).RnnoiseWorkletNode(context, { wasmBinary, maxChannels: 1 }),
|
|
59
|
+
createStream: (tracks) => new MediaStream(tracks),
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/** An `AudioTrackProcessor` for `client.setAudioProcessor()` that removes background noise with RNNoise. */
|
|
63
|
+
export function createNoiseSuppressor(options: NoiseSuppressorOptions = {}, deps: NoiseSuppressorDeps = browserDeps): AudioTrackProcessor {
|
|
64
|
+
let context: AudioContext | null = null;
|
|
65
|
+
let ready: Promise<ArrayBuffer> | null = null;
|
|
66
|
+
let graph: { source: AudioNode; node: DenoiseNode; output: MediaStreamTrack } | null = null;
|
|
67
|
+
let resumeOnGesture: (() => void) | null = null;
|
|
68
|
+
|
|
69
|
+
const release = () => {
|
|
70
|
+
if (!graph) return;
|
|
71
|
+
try {
|
|
72
|
+
graph.source.disconnect();
|
|
73
|
+
graph.node.disconnect();
|
|
74
|
+
graph.node.destroy?.();
|
|
75
|
+
} catch {
|
|
76
|
+
// Already gone.
|
|
77
|
+
}
|
|
78
|
+
graph.output.stop();
|
|
79
|
+
graph = null;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** A context made without a tap starts suspended: no sound would go out until the page is touched. */
|
|
83
|
+
const keepRunning = (ctx: AudioContext) => {
|
|
84
|
+
void ctx.resume?.().catch(() => undefined);
|
|
85
|
+
if (ctx.state === 'running' || typeof document === 'undefined' || resumeOnGesture) return;
|
|
86
|
+
resumeOnGesture = () => {
|
|
87
|
+
void ctx.resume().catch(() => undefined);
|
|
88
|
+
if (ctx.state === 'running' && resumeOnGesture) {
|
|
89
|
+
for (const type of ['pointerdown', 'keydown'] as const) document.removeEventListener(type, resumeOnGesture, { capture: true });
|
|
90
|
+
resumeOnGesture = null;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
for (const type of ['pointerdown', 'keydown'] as const) document.addEventListener(type, resumeOnGesture, { capture: true });
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
name: 'noise-suppression',
|
|
98
|
+
async process(track: MediaStreamTrack): Promise<MediaStreamTrack> {
|
|
99
|
+
const ctx = (context ??= deps.createContext());
|
|
100
|
+
ready ??= Promise.all([
|
|
101
|
+
deps.loadModel({ url: options.wasmUrl ?? `${CDN}/rnnoise.wasm`, simdUrl: options.simdWasmUrl ?? `${CDN}/rnnoise_simd.wasm` }),
|
|
102
|
+
ctx.audioWorklet.addModule(options.workletUrl ?? `${CDN}/rnnoise/workletProcessor.js`),
|
|
103
|
+
]).then(([model]) => model);
|
|
104
|
+
let model: ArrayBuffer;
|
|
105
|
+
try {
|
|
106
|
+
model = await ready;
|
|
107
|
+
} catch (err) {
|
|
108
|
+
ready = null; // try again next time (a network blip)
|
|
109
|
+
throw err;
|
|
110
|
+
}
|
|
111
|
+
const node = await deps.createNode(ctx, model);
|
|
112
|
+
release();
|
|
113
|
+
const source = ctx.createMediaStreamSource(deps.createStream([track]));
|
|
114
|
+
const destination = ctx.createMediaStreamDestination();
|
|
115
|
+
source.connect(node);
|
|
116
|
+
node.connect(destination);
|
|
117
|
+
const output = destination.stream.getAudioTracks()[0];
|
|
118
|
+
if (!output) throw new Error('the audio graph gave no track');
|
|
119
|
+
graph = { source, node, output };
|
|
120
|
+
keepRunning(ctx);
|
|
121
|
+
return output;
|
|
122
|
+
},
|
|
123
|
+
async destroy(): Promise<void> {
|
|
124
|
+
release();
|
|
125
|
+
if (resumeOnGesture && typeof document !== 'undefined') {
|
|
126
|
+
for (const type of ['pointerdown', 'keydown'] as const) document.removeEventListener(type, resumeOnGesture, { capture: true });
|
|
127
|
+
}
|
|
128
|
+
resumeOnGesture = null;
|
|
129
|
+
const ctx = context;
|
|
130
|
+
context = null;
|
|
131
|
+
ready = null;
|
|
132
|
+
await ctx?.close().catch(() => undefined);
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
package/src/preflight.ts
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pre-call check (docs/implementation-progress/RTC_PERF_PROGRESS.md L1).
|
|
3
|
+
*
|
|
4
|
+
* - Twilio's `runPreflight` (read from its code) joins a test room, publishes synthetic audio and video and reports
|
|
5
|
+
* timings, the connection path, round trip, jitter and loss.
|
|
6
|
+
* - LiveKit's `ConnectionCheck` runs separate checks -- WebSocket, WebRTC, TURN, publishing audio and video, UDP
|
|
7
|
+
* against TCP -- each with messages and warnings.
|
|
8
|
+
* - Agora's `startLastmileProbeTest` measures the last mile before a call.
|
|
9
|
+
*
|
|
10
|
+
* This joins the room the token names (mint one for a test room nobody else is in: the session is real, and billed
|
|
11
|
+
* like any other for its few seconds), publishes what it is given -- or a tone and a picture it makes -- and reports
|
|
12
|
+
* what it saw. The orchestration takes a small target interface, so it is tested without a browser.
|
|
13
|
+
*/
|
|
14
|
+
import { networkQualityOf, readTransportStats, type NetworkQualityLevel, type TransportSample } from './network.js';
|
|
15
|
+
import type { StatsEntry } from './stats.js';
|
|
16
|
+
import type { MediaWarningCode } from './health.js';
|
|
17
|
+
|
|
18
|
+
export interface PreflightOptions {
|
|
19
|
+
/** What to publish (cloned; your tracks are left running). Without it, a tone and a moving picture are made. */
|
|
20
|
+
media?: MediaStream;
|
|
21
|
+
/** How long media is measured once it flows. Default 5 s. */
|
|
22
|
+
durationMs?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type PreflightStepName = 'join' | 'media';
|
|
26
|
+
|
|
27
|
+
export interface PreflightStep {
|
|
28
|
+
name: PreflightStepName;
|
|
29
|
+
ok: boolean;
|
|
30
|
+
/** How long it took, in ms. */
|
|
31
|
+
ms: number | null;
|
|
32
|
+
error?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface PreflightReport {
|
|
36
|
+
/** Joined, and media reached the server. */
|
|
37
|
+
ok: boolean;
|
|
38
|
+
steps: PreflightStep[];
|
|
39
|
+
/** How media travelled: UDP is best; TCP or a relay means a firewall in the way (it works, with more delay). */
|
|
40
|
+
path: { protocol: 'udp' | 'tcp' | null; relayed: boolean } | null;
|
|
41
|
+
rttMs: number | null;
|
|
42
|
+
lossPct: number | null;
|
|
43
|
+
/** The upload the browser estimated it could use, in kbps. */
|
|
44
|
+
uploadKbps: number | null;
|
|
45
|
+
level: NetworkQualityLevel | null;
|
|
46
|
+
/** Camera and microphone problems seen during the test (see the mediaWarning event). */
|
|
47
|
+
warnings: MediaWarningCode[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** What a pre-call check needs from a client. */
|
|
51
|
+
export interface PreflightTarget {
|
|
52
|
+
connect(): Promise<unknown>;
|
|
53
|
+
publish(stream: MediaStream): Promise<void>;
|
|
54
|
+
/** The send transport's connection state, or null before there is one. */
|
|
55
|
+
sendState(): string | null;
|
|
56
|
+
/** The send transport's statistics, or null without one. */
|
|
57
|
+
sendStats(): Promise<Iterable<StatsEntry> | null>;
|
|
58
|
+
onWarning(listener: (code: MediaWarningCode, active: boolean) => void): () => void;
|
|
59
|
+
close(): void;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface PreflightEnv {
|
|
63
|
+
now(): number;
|
|
64
|
+
sleep(ms: number): Promise<void>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const realEnv: PreflightEnv = { now: () => Date.now(), sleep: (ms) => new Promise((r) => setTimeout(r, ms)) };
|
|
68
|
+
|
|
69
|
+
/** Media has this long to connect once published. */
|
|
70
|
+
export const MEDIA_CONNECT_TIMEOUT_MS = 10_000;
|
|
71
|
+
/** Statistics are read this often while measuring. */
|
|
72
|
+
export const PREFLIGHT_SAMPLE_MS = 1000;
|
|
73
|
+
|
|
74
|
+
/** The selected candidate pair's protocol, and whether either end is a relay. */
|
|
75
|
+
export function connectionPath(report: Iterable<StatsEntry>): PreflightReport['path'] {
|
|
76
|
+
const entries = [...report];
|
|
77
|
+
const byId = new Map<string, StatsEntry>();
|
|
78
|
+
for (const e of entries) if (typeof e.id === 'string') byId.set(e.id, e);
|
|
79
|
+
let pair: StatsEntry | undefined;
|
|
80
|
+
for (const t of entries.filter((e) => e.type === 'transport')) {
|
|
81
|
+
if (typeof t.selectedCandidatePairId === 'string') pair = byId.get(t.selectedCandidatePairId);
|
|
82
|
+
if (pair) break;
|
|
83
|
+
}
|
|
84
|
+
pair ??= entries.find((e) => e.type === 'candidate-pair' && e.nominated === true && e.state === 'succeeded');
|
|
85
|
+
if (!pair) return null;
|
|
86
|
+
const local = typeof pair.localCandidateId === 'string' ? byId.get(pair.localCandidateId) : undefined;
|
|
87
|
+
const remote = typeof pair.remoteCandidateId === 'string' ? byId.get(pair.remoteCandidateId) : undefined;
|
|
88
|
+
const protocol = local?.protocol === 'udp' || local?.protocol === 'tcp' ? local.protocol : null;
|
|
89
|
+
const relayed = local?.candidateType === 'relay' || remote?.candidateType === 'relay';
|
|
90
|
+
return { protocol, relayed };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Run the check on `target`, closing it at the end whatever happens. */
|
|
94
|
+
export async function runPreflight(target: PreflightTarget, stream: MediaStream, options: PreflightOptions = {}, env: PreflightEnv = realEnv): Promise<PreflightReport> {
|
|
95
|
+
const report: PreflightReport = { ok: false, steps: [], path: null, rttMs: null, lossPct: null, uploadKbps: null, level: null, warnings: [] };
|
|
96
|
+
const seen = new Set<MediaWarningCode>();
|
|
97
|
+
const stopWarnings = target.onWarning((code, active) => { if (active) seen.add(code); });
|
|
98
|
+
try {
|
|
99
|
+
let started = env.now();
|
|
100
|
+
try {
|
|
101
|
+
await target.connect();
|
|
102
|
+
report.steps.push({ name: 'join', ok: true, ms: env.now() - started });
|
|
103
|
+
} catch (err) {
|
|
104
|
+
report.steps.push({ name: 'join', ok: false, ms: null, error: String((err as Error)?.message ?? err) });
|
|
105
|
+
return report;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
started = env.now();
|
|
109
|
+
try {
|
|
110
|
+
await target.publish(stream);
|
|
111
|
+
while (target.sendState() !== 'connected') {
|
|
112
|
+
const state = target.sendState();
|
|
113
|
+
if (state === 'failed' || state === 'closed') throw new Error(`media connection ${state}`);
|
|
114
|
+
if (env.now() - started > MEDIA_CONNECT_TIMEOUT_MS) throw new Error('media did not connect in time (a firewall blocking UDP and TCP?)');
|
|
115
|
+
await env.sleep(100);
|
|
116
|
+
}
|
|
117
|
+
report.steps.push({ name: 'media', ok: true, ms: env.now() - started });
|
|
118
|
+
} catch (err) {
|
|
119
|
+
report.steps.push({ name: 'media', ok: false, ms: null, error: String((err as Error)?.message ?? err) });
|
|
120
|
+
return report;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Measure: the worst round trip and loss over the run, the last upload estimate.
|
|
124
|
+
const duration = options.durationMs ?? 5000;
|
|
125
|
+
let previous = new Map<string, TransportSample>();
|
|
126
|
+
const until = env.now() + duration;
|
|
127
|
+
while (env.now() < until) {
|
|
128
|
+
await env.sleep(PREFLIGHT_SAMPLE_MS);
|
|
129
|
+
const stats = await target.sendStats().catch(() => null);
|
|
130
|
+
if (!stats) continue;
|
|
131
|
+
const entries = [...stats];
|
|
132
|
+
report.path = connectionPath(entries) ?? report.path;
|
|
133
|
+
const now = new Map([['send', readTransportStats(entries)]]);
|
|
134
|
+
const q = networkQualityOf(now, previous, true);
|
|
135
|
+
previous = now;
|
|
136
|
+
if (q.rttMs !== null) report.rttMs = Math.max(report.rttMs ?? 0, q.rttMs);
|
|
137
|
+
if (q.lossPct !== null) report.lossPct = Math.max(report.lossPct ?? 0, q.lossPct);
|
|
138
|
+
if (q.availableKbps !== null) report.uploadKbps = q.availableKbps;
|
|
139
|
+
report.level = q.level;
|
|
140
|
+
}
|
|
141
|
+
report.ok = true;
|
|
142
|
+
return report;
|
|
143
|
+
} finally {
|
|
144
|
+
report.warnings = [...seen];
|
|
145
|
+
stopWarnings();
|
|
146
|
+
target.close();
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* A tone and a moving picture to publish when the app gives none (Twilio's preflight makes synthetic media too).
|
|
152
|
+
* Returns the stream and a function that stops everything it made. Browser only.
|
|
153
|
+
*/
|
|
154
|
+
export function syntheticMedia(): { stream: MediaStream; stop: () => void } {
|
|
155
|
+
const tracks: MediaStreamTrack[] = [];
|
|
156
|
+
const stops: (() => void)[] = [];
|
|
157
|
+
const AudioCtx = (globalThis as { AudioContext?: typeof AudioContext }).AudioContext;
|
|
158
|
+
if (AudioCtx) {
|
|
159
|
+
const ctx = new AudioCtx();
|
|
160
|
+
const osc = ctx.createOscillator();
|
|
161
|
+
const gain = ctx.createGain();
|
|
162
|
+
gain.gain.value = 0.05;
|
|
163
|
+
const dest = ctx.createMediaStreamDestination();
|
|
164
|
+
osc.connect(gain).connect(dest);
|
|
165
|
+
osc.start();
|
|
166
|
+
tracks.push(...dest.stream.getAudioTracks());
|
|
167
|
+
stops.push(() => { osc.stop(); void ctx.close(); });
|
|
168
|
+
}
|
|
169
|
+
if (typeof document !== 'undefined') {
|
|
170
|
+
const canvas = document.createElement('canvas');
|
|
171
|
+
canvas.width = 640;
|
|
172
|
+
canvas.height = 360;
|
|
173
|
+
const g = canvas.getContext('2d');
|
|
174
|
+
let frame = 0;
|
|
175
|
+
const draw = () => {
|
|
176
|
+
if (!g) return;
|
|
177
|
+
frame += 1;
|
|
178
|
+
g.fillStyle = `hsl(${frame % 360}, 60%, 40%)`;
|
|
179
|
+
g.fillRect(0, 0, canvas.width, canvas.height);
|
|
180
|
+
g.fillStyle = '#fff';
|
|
181
|
+
g.fillRect((frame * 8) % canvas.width, 150, 60, 60);
|
|
182
|
+
};
|
|
183
|
+
draw();
|
|
184
|
+
const timer = setInterval(draw, 1000 / 30);
|
|
185
|
+
const captured = (canvas as HTMLCanvasElement & { captureStream?: (fps: number) => MediaStream }).captureStream?.(30);
|
|
186
|
+
if (captured) tracks.push(...captured.getVideoTracks());
|
|
187
|
+
stops.push(() => clearInterval(timer));
|
|
188
|
+
}
|
|
189
|
+
const stream = new MediaStream(tracks);
|
|
190
|
+
return { stream, stop: () => { for (const t of tracks) t.stop(); for (const s of stops) s(); } };
|
|
191
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Track processors (docs/implementation-progress/RTC_PERF_PROGRESS.md P3-4, P3-5): the published microphone or
|
|
3
|
+
* camera sent through something that changes it first -- noise suppression, a blurred or replaced background, beauty.
|
|
4
|
+
* LiveKit (`setProcessor`: Krisp, background blur), Agora and TRTC (extensions and plugins) do it the same way: the
|
|
5
|
+
* device's track goes in, a processed track goes out and is published in its place; the device's own track stays the
|
|
6
|
+
* one watched for unplugging, given new constraints and released at the end.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Something the microphone passes through before it is sent. */
|
|
10
|
+
export interface AudioTrackProcessor {
|
|
11
|
+
/** A short name, for diagnostics. */
|
|
12
|
+
readonly name: string;
|
|
13
|
+
/**
|
|
14
|
+
* Process `track` and return the track to send. Called again whenever the microphone's track changes (another
|
|
15
|
+
* device, a reconnect): the processor then lets go of what it made for the previous one.
|
|
16
|
+
*/
|
|
17
|
+
process(track: MediaStreamTrack): Promise<MediaStreamTrack>;
|
|
18
|
+
/** Let go of everything (the processor was removed, or the session ended). */
|
|
19
|
+
destroy(): Promise<void> | void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Something the camera passes through before it is sent (and shown in `client.local`). */
|
|
23
|
+
export interface VideoTrackProcessor {
|
|
24
|
+
/** A short name, for diagnostics. */
|
|
25
|
+
readonly name: string;
|
|
26
|
+
/**
|
|
27
|
+
* Process `track` and return the track to send, at the same size and frame rate. Called again when the camera's
|
|
28
|
+
* track changes (another camera, `replaceVideoTrack`): the processor then lets go of what it made for the previous
|
|
29
|
+
* one. A picture the SDK no longer sends is stopped by the SDK; stop drawing it once its `readyState` is 'ended',
|
|
30
|
+
* and skip the work while it is switched off (`enabled` false: the camera is paused).
|
|
31
|
+
*/
|
|
32
|
+
process(track: MediaStreamTrack): Promise<MediaStreamTrack>;
|
|
33
|
+
/** Let go of everything (the processor was removed, or the session ended). */
|
|
34
|
+
destroy(): Promise<void> | void;
|
|
35
|
+
}
|
package/src/speakers.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Audio levels and active speakers (docs/implementation-progress/RTC_PERF_PROGRESS.md J1).
|
|
3
|
+
*
|
|
4
|
+
* - Agora `volume-indicator` and Tencent TRTC `AUDIO_VOLUME` report every participant's volume on an interval.
|
|
5
|
+
* - Amazon Chime's `DefaultActiveSpeakerPolicy` (read from its code) ranks speakers: a volume above a silence
|
|
6
|
+
* threshold counts as speaking (1, else 0); each sample the speaker's score becomes `score × 0.9 + speaking × 0.1`,
|
|
7
|
+
* and everyone else's drops by `0.2 × speaking` (the takeover); scores under 0.01 are 0. Its detector updates every
|
|
8
|
+
* 200 ms. Sampled together here, so two people speaking at once both stay; the takeover applies to the silent.
|
|
9
|
+
* - LiveKit's server counts a participant as speaking above -35 dBov.
|
|
10
|
+
*
|
|
11
|
+
* Levels are WebRTC's `audioLevel`: linear, 0 = silence, 1 = 0 dBov. -35 dBov is 10^(-35/20) ≈ 0.0178.
|
|
12
|
+
* Pure: the ranking takes levels and gives the order.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Above this level a participant is speaking (LiveKit's -35 dBov). */
|
|
16
|
+
export const SPEAKING_LEVEL = 0.0178;
|
|
17
|
+
/** How often levels are read while someone listens (Chime's detector: 200 ms). */
|
|
18
|
+
export const AUDIO_LEVEL_INTERVAL_MS = 250;
|
|
19
|
+
|
|
20
|
+
export const SPEAKER_WEIGHT = 0.9;
|
|
21
|
+
export const TAKEOVER_RATE = 0.2;
|
|
22
|
+
export const SCORE_CUTOFF = 0.01;
|
|
23
|
+
|
|
24
|
+
/** Chime's active speaker ranking: who has been speaking recently, the most recent and steady first. */
|
|
25
|
+
export class ActiveSpeakers {
|
|
26
|
+
private readonly scores = new Map<string, number>();
|
|
27
|
+
private last: string[] = [];
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* One sample: each identity's loudest level now (0..1). Identities missing from it count as silent. Returns the new
|
|
31
|
+
* order when it changed, else null.
|
|
32
|
+
*/
|
|
33
|
+
update(levels: ReadonlyMap<string, number>): string[] | null {
|
|
34
|
+
for (const id of levels.keys()) if (!this.scores.has(id)) this.scores.set(id, 0);
|
|
35
|
+
// Chime updates one attendee at a time as volumes arrive; here everyone is sampled together, so people speaking
|
|
36
|
+
// at the same moment do not take over from each other -- only the silent ones lose ground.
|
|
37
|
+
const speakingNow = new Set([...levels].filter(([, level]) => level > SPEAKING_LEVEL).map(([id]) => id));
|
|
38
|
+
for (const id of this.scores.keys()) {
|
|
39
|
+
const speaking = speakingNow.has(id) ? 1 : 0;
|
|
40
|
+
let score = (this.scores.get(id) ?? 0) * SPEAKER_WEIGHT + speaking * (1 - SPEAKER_WEIGHT);
|
|
41
|
+
if (!speaking && speakingNow.size > 0) score = Math.max(score - TAKEOVER_RATE, 0);
|
|
42
|
+
this.scores.set(id, score);
|
|
43
|
+
}
|
|
44
|
+
const order = [...this.scores.entries()]
|
|
45
|
+
.filter(([, score]) => score >= SCORE_CUTOFF)
|
|
46
|
+
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
|
|
47
|
+
.map(([id]) => id);
|
|
48
|
+
if (order.length === this.last.length && order.every((id, i) => id === this.last[i])) return null;
|
|
49
|
+
this.last = order;
|
|
50
|
+
return order;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Someone left: forget them. Returns the new order when it changed. */
|
|
54
|
+
remove(identity: string): string[] | null {
|
|
55
|
+
if (!this.scores.delete(identity)) return null;
|
|
56
|
+
const order = this.last.filter((id) => id !== identity);
|
|
57
|
+
if (order.length === this.last.length) return null;
|
|
58
|
+
this.last = order;
|
|
59
|
+
return order;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
reset(): void {
|
|
63
|
+
this.scores.clear();
|
|
64
|
+
this.last = [];
|
|
65
|
+
}
|
|
66
|
+
}
|