pi-roundtable 0.47.3 → 0.48.1
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 +16 -0
- package/README.md +5 -0
- package/docs/plugins.md +57 -6
- package/package.json +6 -1
- package/src/core/builtin/discord.ts +41 -0
- package/src/core/config/adapters.ts +10 -0
- package/src/core/contract/surface.ts +5 -4
- package/src/core/discord/discord-surface.ts +4 -0
- package/src/core/discord/voice/voice-clock.ts +51 -0
- package/src/core/discord/voice/voice-discord.ts +185 -0
- package/src/core/discord/voice/voice-hearing.ts +357 -0
- package/src/core/discord/voice/voice-link.ts +418 -0
- package/src/core/discord/voice/voice-service.ts +336 -0
- package/src/core/discord/voice/voice-session.ts +230 -0
- package/src/core/discord/voice/voice.ts +144 -0
- package/src/core/domain/block-support.ts +15 -9
- package/src/core/host/define-roundtable.ts +1 -0
- package/src/core/testing/fake-discord.ts +7 -2
- package/src/core/testing/fake-voice.ts +229 -0
- package/src/core/testing/plugin-stand-ins.ts +27 -0
- package/src/core/testing/test-host.ts +5 -1
- package/src/discord/index.ts +14 -0
- package/src/testing.ts +7 -19
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
DiscordGatewayAdapterCreator,
|
|
3
|
+
VoiceConnection,
|
|
4
|
+
VoiceConnectionState,
|
|
5
|
+
} from "@discordjs/voice";
|
|
6
|
+
import type { Logger } from "../../kernel/log.ts";
|
|
7
|
+
import { systemClock, type VoiceClock } from "./voice-clock.ts";
|
|
8
|
+
import { hearingTaps, hearingWatch, networkingOf } from "./voice-hearing.ts";
|
|
9
|
+
import type {
|
|
10
|
+
VoiceLink,
|
|
11
|
+
VoiceLinkHandlers,
|
|
12
|
+
VoiceLinkStatus,
|
|
13
|
+
} from "./voice-service.ts";
|
|
14
|
+
|
|
15
|
+
/** What the link uses of @discordjs/voice, so a test gives a stand-in `joinVoiceChannel`. */
|
|
16
|
+
export type VoiceLib = Pick<
|
|
17
|
+
typeof import("@discordjs/voice"),
|
|
18
|
+
| "joinVoiceChannel"
|
|
19
|
+
| "getVoiceConnection"
|
|
20
|
+
| "VoiceConnectionStatus"
|
|
21
|
+
| "VoiceConnectionDisconnectReason"
|
|
22
|
+
| "EndBehaviorType"
|
|
23
|
+
>;
|
|
24
|
+
|
|
25
|
+
/** One speaker's Opus decoder: packets in, `VOICE_PCM` frames out. Opus keeps state between packets, so each speaker has their own. */
|
|
26
|
+
export interface OpusDecoder {
|
|
27
|
+
/** Throws for a packet that is no Opus. */
|
|
28
|
+
decode(packet: Uint8Array): Uint8Array;
|
|
29
|
+
free(): void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Discord's voice close code for a bot that was disconnected, moved, or whose channel was deleted. */
|
|
33
|
+
const DISCONNECTED = 4014;
|
|
34
|
+
/** How often a connection the main gateway could not carry is asked for again. */
|
|
35
|
+
const REJOIN_MS = 3_000;
|
|
36
|
+
/** The voice connection group, so a connection another library opened in the guild is never taken for ours. */
|
|
37
|
+
const GROUP = "pi-roundtable";
|
|
38
|
+
/**
|
|
39
|
+
* How long a speaker is quiet before their decoder is freed. opusscript's decoders share one
|
|
40
|
+
* fixed heap, which holds 79 of them in the whole process: one more decodes nothing until others
|
|
41
|
+
* are freed. So a decoder is kept only for who is speaking, not for everyone who ever spoke.
|
|
42
|
+
*/
|
|
43
|
+
const DECODER_IDLE_MS = 60_000;
|
|
44
|
+
|
|
45
|
+
/** One speaker's decoder, and when it last had a packet. */
|
|
46
|
+
interface Hearing {
|
|
47
|
+
decoder: OpusDecoder;
|
|
48
|
+
lastAt: number;
|
|
49
|
+
/** Runs when the speaker may have been quiet for `DECODER_IDLE_MS`. */
|
|
50
|
+
timer: unknown;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Loads @discordjs/voice with the DAVE library Discord's end-to-end encryption needs, which
|
|
55
|
+
* nothing else in the host imports: a host without `discord.voice` never loads them.
|
|
56
|
+
*/
|
|
57
|
+
export async function loadVoiceLib(): Promise<VoiceLib> {
|
|
58
|
+
try {
|
|
59
|
+
const [lib] = await Promise.all([
|
|
60
|
+
import("@discordjs/voice"),
|
|
61
|
+
import("@snazzah/davey"),
|
|
62
|
+
]);
|
|
63
|
+
return lib;
|
|
64
|
+
} catch (cause) {
|
|
65
|
+
throw new Error(
|
|
66
|
+
"discord.voice is on, but @discordjs/voice or @snazzah/davey could not be loaded. Install pi-roundtable's dependencies again (bun install), or set discord.voice to false.",
|
|
67
|
+
{ cause },
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Loads the Opus decoder (opusscript, WebAssembly: no native build) and answers a maker of 48 kHz mono decoders. */
|
|
73
|
+
export async function loadOpusDecoders(): Promise<() => OpusDecoder> {
|
|
74
|
+
try {
|
|
75
|
+
const { default: OpusScript } = await import("opusscript");
|
|
76
|
+
return () => {
|
|
77
|
+
// One channel: libopus mixes Discord's stereo down as it decodes.
|
|
78
|
+
const decoder = new OpusScript(48_000, 1);
|
|
79
|
+
return {
|
|
80
|
+
decode: (packet) =>
|
|
81
|
+
decoder.decode(
|
|
82
|
+
Buffer.isBuffer(packet) ? packet : Buffer.from(packet),
|
|
83
|
+
),
|
|
84
|
+
free: () => decoder.delete(),
|
|
85
|
+
};
|
|
86
|
+
};
|
|
87
|
+
} catch (cause) {
|
|
88
|
+
throw new Error(
|
|
89
|
+
"discord.voice is on, but opusscript could not be loaded. Install pi-roundtable's dependencies again (bun install), or set discord.voice to false.",
|
|
90
|
+
{ cause },
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface VoiceLinkOptions {
|
|
96
|
+
guildId: string;
|
|
97
|
+
channelId: string;
|
|
98
|
+
adapterCreator: DiscordGatewayAdapterCreator;
|
|
99
|
+
decoder: () => OpusDecoder;
|
|
100
|
+
logger: Logger;
|
|
101
|
+
/** What the rejoin attempts wait by. Default: the host's clock. */
|
|
102
|
+
clock?: VoiceClock;
|
|
103
|
+
/**
|
|
104
|
+
* Whether a moderator deafened the bot in the guild. Discord then sends it no audio, so a
|
|
105
|
+
* speaker it does not hear is no fault of the connection. Default: never.
|
|
106
|
+
*/
|
|
107
|
+
deafened?: () => boolean;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Joins the channel muted and not deafened, and hears every speaker: each one's Opus packets,
|
|
112
|
+
* already decrypted by @discordjs/voice (transport encryption and DAVE), are decoded here and
|
|
113
|
+
* handed on as frames. The audio is never logged and never written anywhere.
|
|
114
|
+
*/
|
|
115
|
+
export function openVoiceLink(
|
|
116
|
+
lib: VoiceLib,
|
|
117
|
+
options: VoiceLinkOptions,
|
|
118
|
+
): VoiceLink {
|
|
119
|
+
const { guildId, channelId } = options;
|
|
120
|
+
let connection: VoiceConnection | undefined;
|
|
121
|
+
try {
|
|
122
|
+
connection = lib.joinVoiceChannel({
|
|
123
|
+
guildId,
|
|
124
|
+
channelId,
|
|
125
|
+
group: GROUP,
|
|
126
|
+
adapterCreator: options.adapterCreator,
|
|
127
|
+
selfDeaf: false,
|
|
128
|
+
selfMute: true,
|
|
129
|
+
});
|
|
130
|
+
return linkOver(lib, connection, options);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
// Not left behind: the library keeps a connection by guild, even one whose join threw, and hands it to the guild's next join.
|
|
133
|
+
const left = connection ?? lib.getVoiceConnection(guildId, GROUP);
|
|
134
|
+
try {
|
|
135
|
+
if (left && left.state.status !== lib.VoiceConnectionStatus.Destroyed)
|
|
136
|
+
left.destroy();
|
|
137
|
+
} catch {
|
|
138
|
+
// The library forgot the connection before this threw; the failure to report is the first.
|
|
139
|
+
}
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The link over a connection the library made: what `openVoiceLink` answers. */
|
|
145
|
+
function linkOver(
|
|
146
|
+
lib: VoiceLib,
|
|
147
|
+
connection: VoiceConnection,
|
|
148
|
+
options: VoiceLinkOptions,
|
|
149
|
+
): VoiceLink {
|
|
150
|
+
const { guildId, channelId, logger } = options;
|
|
151
|
+
const clock = options.clock ?? systemClock;
|
|
152
|
+
const { VoiceConnectionStatus: Status } = lib;
|
|
153
|
+
const decoders = new Map<string, Hearing>();
|
|
154
|
+
/** How many packets of each speaker were not decoded. */
|
|
155
|
+
const undecoded = new Map<string, number>();
|
|
156
|
+
const subscribed = new Set<string>();
|
|
157
|
+
let handlers: VoiceLinkHandlers | undefined;
|
|
158
|
+
let closed = false;
|
|
159
|
+
/** The timer of the next rejoin, while the last one was refused. */
|
|
160
|
+
let rejoin: unknown;
|
|
161
|
+
/** Whether the connection is being asked for something right now, which it reports as a state change before it answers. */
|
|
162
|
+
let asking = false;
|
|
163
|
+
/** Whether the link itself left the channel to join it again, and the gateway has yet to report that leave. */
|
|
164
|
+
let leaving = false;
|
|
165
|
+
/** The networking the connection was last ready over: ready over it again is a resume, over another a new media path. */
|
|
166
|
+
let path: object | undefined;
|
|
167
|
+
|
|
168
|
+
const statusOf = (state: VoiceConnectionState): VoiceLinkStatus => {
|
|
169
|
+
if (state.status === Status.Ready) return "ready";
|
|
170
|
+
return state.status === Status.Destroyed ? "closed" : "reconnecting";
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* A connection the main gateway dropped is asked for again, once now and once every `REJOIN_MS`
|
|
175
|
+
* until it is carried; Discord's own disconnect is not. Whoever owns the link ends the waiting
|
|
176
|
+
* by closing it.
|
|
177
|
+
*/
|
|
178
|
+
const recover = (state: VoiceConnectionState): void => {
|
|
179
|
+
// `rejoin()` reports its own outcome as a state change before it answers: that one is not a drop to recover from.
|
|
180
|
+
if (asking) return;
|
|
181
|
+
clock.clearTimeout(rejoin);
|
|
182
|
+
rejoin = undefined;
|
|
183
|
+
if (closed || state.status !== Status.Disconnected) return;
|
|
184
|
+
const refused =
|
|
185
|
+
state.reason === lib.VoiceConnectionDisconnectReason.WebSocketClose &&
|
|
186
|
+
state.closeCode === DISCONNECTED;
|
|
187
|
+
if (refused) return;
|
|
188
|
+
let carried: boolean;
|
|
189
|
+
asking = true;
|
|
190
|
+
try {
|
|
191
|
+
// The link's own channel, which the connection no longer names once the link left it to join again.
|
|
192
|
+
carried = connection.rejoin({
|
|
193
|
+
channelId,
|
|
194
|
+
selfDeaf: false,
|
|
195
|
+
selfMute: true,
|
|
196
|
+
});
|
|
197
|
+
} finally {
|
|
198
|
+
asking = false;
|
|
199
|
+
}
|
|
200
|
+
if (carried) return;
|
|
201
|
+
rejoin = clock.setTimeout(() => retry(), REJOIN_MS);
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
/** A rejoin that throws, after the join itself, is a refused one: warned, no audio, asked for again. */
|
|
205
|
+
const retry = (): void => {
|
|
206
|
+
try {
|
|
207
|
+
recover(connection.state);
|
|
208
|
+
} catch (error) {
|
|
209
|
+
logger.warn(
|
|
210
|
+
{
|
|
211
|
+
guildId,
|
|
212
|
+
channelId,
|
|
213
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
214
|
+
},
|
|
215
|
+
"voice rejoin failed",
|
|
216
|
+
);
|
|
217
|
+
rejoin = clock.setTimeout(() => retry(), REJOIN_MS);
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
/** Frees a speaker's decoder; their next packet makes a new one. */
|
|
222
|
+
const forget = (userId: string): void => {
|
|
223
|
+
const hearing = decoders.get(userId);
|
|
224
|
+
if (!hearing) return;
|
|
225
|
+
decoders.delete(userId);
|
|
226
|
+
clock.clearTimeout(hearing.timer);
|
|
227
|
+
hearing.decoder.free();
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
/** The idle timer ran: the decoder is freed if no packet came since, else the timer waits out the rest. */
|
|
231
|
+
const idle = (userId: string): void => {
|
|
232
|
+
const hearing = decoders.get(userId);
|
|
233
|
+
if (!hearing) return;
|
|
234
|
+
const left = hearing.lastAt + DECODER_IDLE_MS - clock.now();
|
|
235
|
+
if (left > 0) hearing.timer = clock.setTimeout(() => idle(userId), left);
|
|
236
|
+
else forget(userId);
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
/** One packet through its speaker's decoder, which is made when first needed; undefined for a packet that was not decoded. */
|
|
240
|
+
const decode = (
|
|
241
|
+
userId: string,
|
|
242
|
+
packet: Uint8Array,
|
|
243
|
+
): Uint8Array | undefined => {
|
|
244
|
+
try {
|
|
245
|
+
let hearing = decoders.get(userId);
|
|
246
|
+
if (!hearing) {
|
|
247
|
+
hearing = { decoder: options.decoder(), lastAt: 0, timer: undefined };
|
|
248
|
+
hearing.timer = clock.setTimeout(() => idle(userId), DECODER_IDLE_MS);
|
|
249
|
+
decoders.set(userId, hearing);
|
|
250
|
+
}
|
|
251
|
+
hearing.lastAt = clock.now();
|
|
252
|
+
return hearing.decoder.decode(packet);
|
|
253
|
+
} catch (error) {
|
|
254
|
+
// Counted and named by its speaker, once; never logged with its bytes.
|
|
255
|
+
const lost = (undecoded.get(userId) ?? 0) + 1;
|
|
256
|
+
undecoded.set(userId, lost);
|
|
257
|
+
if (lost === 1)
|
|
258
|
+
logger.warn(
|
|
259
|
+
{
|
|
260
|
+
guildId,
|
|
261
|
+
userId,
|
|
262
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
263
|
+
},
|
|
264
|
+
"voice packet not decoded",
|
|
265
|
+
);
|
|
266
|
+
// The decoder may be one the heap had no room for: the next packet gets a new one, which decodes once others were freed.
|
|
267
|
+
forget(userId);
|
|
268
|
+
return undefined;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const hear = (userId: string): void => {
|
|
273
|
+
if (closed || subscribed.has(userId)) return;
|
|
274
|
+
subscribed.add(userId);
|
|
275
|
+
const stream = connection.receiver.subscribe(userId, {
|
|
276
|
+
end: { behavior: lib.EndBehaviorType.Manual },
|
|
277
|
+
});
|
|
278
|
+
stream.on("data", (packet: Uint8Array) => {
|
|
279
|
+
// A packet the stream still held when the link closed is not decoded: its decoder is freed.
|
|
280
|
+
if (closed) return;
|
|
281
|
+
const pcm = decode(userId, packet);
|
|
282
|
+
if (pcm) handlers?.frame(userId, pcm);
|
|
283
|
+
});
|
|
284
|
+
// @discordjs/voice destroys the stream on a packet it cannot decrypt; the speaker is heard again from the next one.
|
|
285
|
+
stream.on("error", (error: Error) =>
|
|
286
|
+
logger.debug(
|
|
287
|
+
{ guildId, userId, reason: error.message },
|
|
288
|
+
"voice stream failed",
|
|
289
|
+
),
|
|
290
|
+
);
|
|
291
|
+
stream.once("close", () => {
|
|
292
|
+
subscribed.delete(userId);
|
|
293
|
+
if (!closed && connection.state.status !== Status.Destroyed) hear(userId);
|
|
294
|
+
});
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
/** What the connection is asked for a link that does not hear; a failure is warned and never thrown into the watch's timer. */
|
|
298
|
+
const attempt = (what: string, run: () => void): void => {
|
|
299
|
+
asking = true;
|
|
300
|
+
try {
|
|
301
|
+
run();
|
|
302
|
+
} catch (error) {
|
|
303
|
+
logger.warn(
|
|
304
|
+
{
|
|
305
|
+
guildId,
|
|
306
|
+
channelId,
|
|
307
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
308
|
+
},
|
|
309
|
+
`voice ${what} failed`,
|
|
310
|
+
);
|
|
311
|
+
} finally {
|
|
312
|
+
asking = false;
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
const watch = hearingWatch({
|
|
316
|
+
clock,
|
|
317
|
+
logger,
|
|
318
|
+
fields: { guildId, channelId },
|
|
319
|
+
person: (userId) => handlers?.person(userId) ?? false,
|
|
320
|
+
deafened: () => options.deafened?.() ?? false,
|
|
321
|
+
rebuild: () => {
|
|
322
|
+
const before = networkingOf(connection.state);
|
|
323
|
+
attempt("networking", () => connection.configureNetworking());
|
|
324
|
+
return networkingOf(connection.state) !== before;
|
|
325
|
+
},
|
|
326
|
+
rejoin: () => {
|
|
327
|
+
leaving = true;
|
|
328
|
+
// Leaves the channel; `retry` then finds the connection disconnected and asks for the channel again.
|
|
329
|
+
attempt("leave", () => connection.disconnect());
|
|
330
|
+
retry();
|
|
331
|
+
},
|
|
332
|
+
giveUp: () => {
|
|
333
|
+
attempt("leave", close);
|
|
334
|
+
// A connection that could not be destroyed reports nothing: the session ends all the same.
|
|
335
|
+
if (connection.state.status !== Status.Destroyed)
|
|
336
|
+
attempt("leave", () => handlers?.status("closed"));
|
|
337
|
+
},
|
|
338
|
+
});
|
|
339
|
+
const taps = hearingTaps(connection, watch);
|
|
340
|
+
/** The watch is told when the connection can hear: over a new media path, or the one it had. */
|
|
341
|
+
const heardOver = (
|
|
342
|
+
before: VoiceConnectionState,
|
|
343
|
+
state: VoiceConnectionState,
|
|
344
|
+
): void => {
|
|
345
|
+
if (state.status !== Status.Ready) {
|
|
346
|
+
if (before.status === Status.Ready) watch.down();
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (before.status === Status.Ready) return;
|
|
350
|
+
leaving = false;
|
|
351
|
+
const networking = networkingOf(state);
|
|
352
|
+
if (networking !== undefined && networking === path) {
|
|
353
|
+
watch.resumed();
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
path = networking;
|
|
357
|
+
watch.up();
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
connection.receiver.speaking.on("start", hear);
|
|
361
|
+
connection.on("stateChange", (before, state) => {
|
|
362
|
+
taps.follow(state);
|
|
363
|
+
heardOver(before, state);
|
|
364
|
+
retry();
|
|
365
|
+
if (state.status === Status.Destroyed) release();
|
|
366
|
+
handlers?.status(statusOf(state));
|
|
367
|
+
});
|
|
368
|
+
connection.on("error", (error) =>
|
|
369
|
+
logger.warn({ guildId, channelId, err: error }, "voice connection error"),
|
|
370
|
+
);
|
|
371
|
+
|
|
372
|
+
const release = (): void => {
|
|
373
|
+
if (closed) return;
|
|
374
|
+
closed = true;
|
|
375
|
+
clock.clearTimeout(rejoin);
|
|
376
|
+
watch.stop();
|
|
377
|
+
taps.stop();
|
|
378
|
+
connection.receiver.speaking.off("start", hear);
|
|
379
|
+
for (const stream of connection.receiver.subscriptions.values())
|
|
380
|
+
stream.destroy();
|
|
381
|
+
for (const userId of [...decoders.keys()]) forget(userId);
|
|
382
|
+
let lost = 0;
|
|
383
|
+
for (const count of undecoded.values()) lost += count;
|
|
384
|
+
if (lost > 0)
|
|
385
|
+
logger.warn(
|
|
386
|
+
{ guildId, undecoded: lost, speakers: undecoded.size },
|
|
387
|
+
"voice packets were not decoded",
|
|
388
|
+
);
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
const close = (): void => {
|
|
392
|
+
release();
|
|
393
|
+
// Tells Discord the bot left the channel; reports `closed` through the state change.
|
|
394
|
+
if (connection.state.status !== Status.Destroyed) connection.destroy();
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
taps.follow(connection.state);
|
|
398
|
+
// A connection the library already had ready is heard over the networking it has.
|
|
399
|
+
if (connection.state.status === Status.Ready) {
|
|
400
|
+
path = networkingOf(connection.state);
|
|
401
|
+
watch.up();
|
|
402
|
+
}
|
|
403
|
+
// The join's own first request is not caught: a connection whose setup throws is not joined.
|
|
404
|
+
recover(connection.state);
|
|
405
|
+
return {
|
|
406
|
+
status: () => (closed ? "closed" : statusOf(connection.state)),
|
|
407
|
+
listen: (given) => {
|
|
408
|
+
handlers = given;
|
|
409
|
+
},
|
|
410
|
+
forget,
|
|
411
|
+
leftItself: () => {
|
|
412
|
+
if (!leaving || closed) return false;
|
|
413
|
+
leaving = false;
|
|
414
|
+
return true;
|
|
415
|
+
},
|
|
416
|
+
close,
|
|
417
|
+
};
|
|
418
|
+
}
|