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,336 @@
|
|
|
1
|
+
import type { Logger } from "../../kernel/log.ts";
|
|
2
|
+
import type {
|
|
3
|
+
DiscordVoice,
|
|
4
|
+
VoiceDisconnectReason,
|
|
5
|
+
VoiceJoinFailure,
|
|
6
|
+
VoiceJoinOptions,
|
|
7
|
+
VoiceJoinResult,
|
|
8
|
+
VoiceMember,
|
|
9
|
+
} from "./voice.ts";
|
|
10
|
+
import { systemClock, type VoiceClock } from "./voice-clock.ts";
|
|
11
|
+
import { VoiceSessionState } from "./voice-session.ts";
|
|
12
|
+
|
|
13
|
+
/** A channel as the bot sees it, read when a join is asked. */
|
|
14
|
+
export interface VoiceChannelFacts {
|
|
15
|
+
guildId: string;
|
|
16
|
+
kind: "voice" | "stage" | "other";
|
|
17
|
+
/** Whether the bot may see the channel and connect to it. */
|
|
18
|
+
connectable: boolean;
|
|
19
|
+
/** Whether the channel is at its user limit and the bot may not move members. */
|
|
20
|
+
full: boolean;
|
|
21
|
+
/** Who is in it now, without the bot. */
|
|
22
|
+
members: VoiceMember[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Someone's voice channel changed: `channelId` is where they are now, undefined for nowhere. */
|
|
26
|
+
export interface VoiceStateChange {
|
|
27
|
+
guildId: string;
|
|
28
|
+
userId: string;
|
|
29
|
+
channelId: string | undefined;
|
|
30
|
+
member: VoiceMember;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** `ready` hears audio; `reconnecting` is trying to; `closed` never will again. */
|
|
34
|
+
export type VoiceLinkStatus = "ready" | "reconnecting" | "closed";
|
|
35
|
+
|
|
36
|
+
/** What a voice connection reports to the session that owns it. */
|
|
37
|
+
export interface VoiceLinkHandlers {
|
|
38
|
+
status(status: VoiceLinkStatus): void;
|
|
39
|
+
/** One decoded frame of a speaker, in the `VOICE_PCM` format, which the link keeps no reference to. */
|
|
40
|
+
frame(userId: string, pcm: Uint8Array): void;
|
|
41
|
+
/** Whether the user is a person in the channel, not a bot; with no user, whether any person is. */
|
|
42
|
+
person(userId?: string): boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** One voice connection: the bot in a channel, muted and not deafened. */
|
|
46
|
+
export interface VoiceLink {
|
|
47
|
+
status(): VoiceLinkStatus;
|
|
48
|
+
/** Takes the one listener of the link; what happened before it is read from `status()`. */
|
|
49
|
+
listen(handlers: VoiceLinkHandlers): void;
|
|
50
|
+
/** Someone left the channel: what the link kept to hear them is freed, and made again if they are heard after all. */
|
|
51
|
+
forget(userId: string): void;
|
|
52
|
+
/**
|
|
53
|
+
* Whether the bot's leaving the channel, as the gateway now reports it, is the link's own on
|
|
54
|
+
* its way to join again, as it does for a speaker it does not hear. True once for each such leave: a second one before the link is back
|
|
55
|
+
* is someone removing the bot.
|
|
56
|
+
*/
|
|
57
|
+
leftItself(): boolean;
|
|
58
|
+
/** Leaves the channel and frees the decoders; does nothing the second time. */
|
|
59
|
+
close(): void;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** What the voice service needs of Discord: discord.js and @discordjs/voice in a host, a stand-in in a test. */
|
|
63
|
+
export interface VoiceGateway {
|
|
64
|
+
/** Whether the gateway connection is up. */
|
|
65
|
+
ready(): boolean;
|
|
66
|
+
/** The bot's own user id; undefined until the connection is ready. */
|
|
67
|
+
botId(): string | undefined;
|
|
68
|
+
/** The channel as it is now; `gone` for one Discord does not know, `forbidden` for one the bot may not see. Throws when Discord cannot be reached. */
|
|
69
|
+
channel(channelId: string): Promise<VoiceChannelFacts | "gone" | "forbidden">;
|
|
70
|
+
/** Reports every voice channel change in every guild. */
|
|
71
|
+
onVoiceState(listener: (change: VoiceStateChange) => void): void;
|
|
72
|
+
/**
|
|
73
|
+
* Reports each time the gateway connection is up again, resumed or identified anew: who is in
|
|
74
|
+
* a channel may have changed meanwhile with no word of it.
|
|
75
|
+
*/
|
|
76
|
+
onReady(listener: () => void): void;
|
|
77
|
+
/** Loads what a connection needs, so a host that cannot hear fails as it starts. */
|
|
78
|
+
prepare(): Promise<void>;
|
|
79
|
+
/** Opens the voice connection; rejects when it cannot be opened at all. */
|
|
80
|
+
connect(target: { guildId: string; channelId: string }): Promise<VoiceLink>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface VoiceServiceOptions {
|
|
84
|
+
gateway: VoiceGateway;
|
|
85
|
+
logger: Logger;
|
|
86
|
+
clock?: VoiceClock;
|
|
87
|
+
/** How long a new connection may take to become ready. Default 20 s. */
|
|
88
|
+
connectMs?: number;
|
|
89
|
+
/** How long a dropped connection may take to come back before the session ends; at most 30 s. Default 20 s. */
|
|
90
|
+
resumeMs?: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The voice service as the Discord plugin holds it: what plugins get, and its place in the host's start and stop. */
|
|
94
|
+
export interface VoiceService extends DiscordVoice {
|
|
95
|
+
start(): Promise<void>;
|
|
96
|
+
/** Ends every session with `stopped` and refuses joins from then on. */
|
|
97
|
+
stop(): Promise<void>;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const DEFAULTS = { silenceMs: 800, maxUtteranceMs: 30_000 };
|
|
101
|
+
const MAX_RESUME_MS = 30_000;
|
|
102
|
+
|
|
103
|
+
function inRange(name: string, value: number, min: number, max: number) {
|
|
104
|
+
if (!Number.isInteger(value) || value < min || value > max)
|
|
105
|
+
throw new RangeError(
|
|
106
|
+
`voice join: ${name} must be a whole number from ${min} to ${max}, got ${value}.`,
|
|
107
|
+
);
|
|
108
|
+
return value;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const MESSAGES: Record<VoiceJoinFailure, string> = {
|
|
112
|
+
forbidden:
|
|
113
|
+
"The bot may not connect to the channel. Give it View Channel and Connect there.",
|
|
114
|
+
channel_gone: "The guild has no such channel.",
|
|
115
|
+
not_voice: "The channel is neither a voice nor a stage channel.",
|
|
116
|
+
full: "The channel is full.",
|
|
117
|
+
unavailable: "Discord voice is not available right now. Try again.",
|
|
118
|
+
already_joined:
|
|
119
|
+
"The bot is already in a voice channel of this guild, or joining one. Leave it first.",
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
function failed(failure: VoiceJoinFailure, message?: string): VoiceJoinResult {
|
|
123
|
+
return { ok: false, failure, message: message ?? MESSAGES[failure] };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
interface Joined {
|
|
127
|
+
session: VoiceSessionState;
|
|
128
|
+
link: VoiceLink | undefined;
|
|
129
|
+
/** Whether `join` answered with the session: until then nothing ends it but the join itself. */
|
|
130
|
+
open: boolean;
|
|
131
|
+
/** Runs when the connection stayed down too long. */
|
|
132
|
+
resume: unknown;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Voice sessions over a gateway, one per guild. A join checks the channel before it connects, so
|
|
137
|
+
* each refusal has its own failure; a connection that drops has `resumeMs` to come back.
|
|
138
|
+
*/
|
|
139
|
+
export function voiceService(options: VoiceServiceOptions): VoiceService {
|
|
140
|
+
const { gateway, logger } = options;
|
|
141
|
+
const clock = options.clock ?? systemClock;
|
|
142
|
+
const connectMs = options.connectMs ?? 20_000;
|
|
143
|
+
const resumeMs = Math.min(options.resumeMs ?? 20_000, MAX_RESUME_MS);
|
|
144
|
+
/** By guild: Discord has one voice connection per guild. */
|
|
145
|
+
const joined = new Map<string, Joined>();
|
|
146
|
+
let stopping = false;
|
|
147
|
+
|
|
148
|
+
const end = (entry: Joined, reason: VoiceDisconnectReason): void => {
|
|
149
|
+
const { session } = entry;
|
|
150
|
+
if (joined.get(session.guildId) === entry) joined.delete(session.guildId);
|
|
151
|
+
clock.clearTimeout(entry.resume);
|
|
152
|
+
entry.resume = undefined;
|
|
153
|
+
session.end(reason);
|
|
154
|
+
entry.link?.close();
|
|
155
|
+
logger.info(
|
|
156
|
+
{ guildId: session.guildId, channelId: session.channelId, reason },
|
|
157
|
+
"voice session ended",
|
|
158
|
+
);
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
const onStatus = (entry: Joined, status: VoiceLinkStatus): void => {
|
|
162
|
+
if (!entry.open || entry.session.ended() !== undefined) return;
|
|
163
|
+
if (status === "closed") {
|
|
164
|
+
end(entry, "connection_lost");
|
|
165
|
+
} else if (status === "ready") {
|
|
166
|
+
if (entry.resume === undefined) return;
|
|
167
|
+
clock.clearTimeout(entry.resume);
|
|
168
|
+
entry.resume = undefined;
|
|
169
|
+
void reread(entry);
|
|
170
|
+
} else {
|
|
171
|
+
entry.resume ??= clock.setTimeout(
|
|
172
|
+
() => end(entry, "connection_lost"),
|
|
173
|
+
resumeMs,
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
/** Someone is no longer in the session's channel: what they were saying is delivered, then the link lets go of them. */
|
|
179
|
+
const gone = (entry: Joined, userId: string): void => {
|
|
180
|
+
entry.session.memberLeft(userId);
|
|
181
|
+
entry.link?.forget(userId);
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* A dropped connection is back, the voice one or the gateway's: who is in the channel is read
|
|
186
|
+
* again, and whoever left or entered meanwhile is reported now. A gateway that had to identify
|
|
187
|
+
* again is sent the guild's voice states anew, with no word of what changed.
|
|
188
|
+
*/
|
|
189
|
+
const reread = async (entry: Joined): Promise<void> => {
|
|
190
|
+
const { session } = entry;
|
|
191
|
+
try {
|
|
192
|
+
const facts = await gateway.channel(session.channelId);
|
|
193
|
+
if (session.ended() !== undefined || typeof facts === "string") return;
|
|
194
|
+
const there = new Set(facts.members.map((member) => member.userId));
|
|
195
|
+
for (const { userId } of session.members())
|
|
196
|
+
if (!there.has(userId)) gone(entry, userId);
|
|
197
|
+
for (const member of facts.members) session.memberJoined(member);
|
|
198
|
+
} catch (error) {
|
|
199
|
+
logger.warn(
|
|
200
|
+
{ guildId: session.guildId, channelId: session.channelId, err: error },
|
|
201
|
+
"voice members not read again",
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
// A gateway that identified again holds the guild's voice states anew, whatever the voice connection did meanwhile.
|
|
207
|
+
gateway.onReady(() => {
|
|
208
|
+
for (const entry of [...joined.values()]) void reread(entry);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
gateway.onVoiceState((change) => {
|
|
212
|
+
const entry = joined.get(change.guildId);
|
|
213
|
+
if (!entry) return;
|
|
214
|
+
const { session } = entry;
|
|
215
|
+
if (change.userId === gateway.botId()) {
|
|
216
|
+
// Its own way into the channel is the join's to wait for.
|
|
217
|
+
if (!entry.open || change.channelId === session.channelId) return;
|
|
218
|
+
// A link that left to join again, for a speaker it does not hear, was not removed.
|
|
219
|
+
if (change.channelId === undefined && entry.link?.leftItself()) return;
|
|
220
|
+
return end(entry, change.channelId === undefined ? "removed" : "moved");
|
|
221
|
+
}
|
|
222
|
+
if (change.channelId === session.channelId)
|
|
223
|
+
session.memberJoined(change.member);
|
|
224
|
+
else gone(entry, change.userId);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
/** Resolves true once the link is ready; false when it closed or took longer than `connectMs`. */
|
|
228
|
+
const comesUp = (entry: Joined, link: VoiceLink): Promise<boolean> =>
|
|
229
|
+
new Promise((resolve) => {
|
|
230
|
+
const timer = clock.setTimeout(() => resolve(false), connectMs);
|
|
231
|
+
const settle = (status: VoiceLinkStatus) => {
|
|
232
|
+
if (status === "reconnecting") return;
|
|
233
|
+
clock.clearTimeout(timer);
|
|
234
|
+
resolve(status === "ready");
|
|
235
|
+
};
|
|
236
|
+
link.listen({
|
|
237
|
+
status: (status) => {
|
|
238
|
+
settle(status);
|
|
239
|
+
onStatus(entry, status);
|
|
240
|
+
},
|
|
241
|
+
frame: (userId, pcm) => entry.session.frame(userId, pcm),
|
|
242
|
+
person: (userId) =>
|
|
243
|
+
entry.session
|
|
244
|
+
.members()
|
|
245
|
+
.some(
|
|
246
|
+
(member) =>
|
|
247
|
+
!member.bot &&
|
|
248
|
+
(userId === undefined || member.userId === userId),
|
|
249
|
+
),
|
|
250
|
+
});
|
|
251
|
+
settle(link.status());
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
const join = async (
|
|
255
|
+
target: { guildId: string; channelId: string },
|
|
256
|
+
given: VoiceJoinOptions = {},
|
|
257
|
+
): Promise<VoiceJoinResult> => {
|
|
258
|
+
const silenceMs = inRange(
|
|
259
|
+
"silenceMs",
|
|
260
|
+
given.silenceMs ?? DEFAULTS.silenceMs,
|
|
261
|
+
200,
|
|
262
|
+
5_000,
|
|
263
|
+
);
|
|
264
|
+
const maxUtteranceMs = inRange(
|
|
265
|
+
"maxUtteranceMs",
|
|
266
|
+
given.maxUtteranceMs ?? DEFAULTS.maxUtteranceMs,
|
|
267
|
+
1_000,
|
|
268
|
+
300_000,
|
|
269
|
+
);
|
|
270
|
+
const { guildId, channelId } = target;
|
|
271
|
+
if (stopping || !gateway.ready()) return failed("unavailable");
|
|
272
|
+
if (joined.has(guildId)) return failed("already_joined");
|
|
273
|
+
// Held from here on, so a second join of the guild is refused while this one is under way.
|
|
274
|
+
const entry: Joined = {
|
|
275
|
+
session: new VoiceSessionState({
|
|
276
|
+
guildId,
|
|
277
|
+
channelId,
|
|
278
|
+
members: [],
|
|
279
|
+
silenceMs,
|
|
280
|
+
maxUtteranceMs,
|
|
281
|
+
clock,
|
|
282
|
+
logger,
|
|
283
|
+
leave: () => end(entry, "left"),
|
|
284
|
+
}),
|
|
285
|
+
link: undefined,
|
|
286
|
+
open: false,
|
|
287
|
+
resume: undefined,
|
|
288
|
+
};
|
|
289
|
+
joined.set(guildId, entry);
|
|
290
|
+
const refuse = (failure: VoiceJoinFailure, error?: unknown) => {
|
|
291
|
+
if (joined.get(guildId) === entry) joined.delete(guildId);
|
|
292
|
+
entry.link?.close();
|
|
293
|
+
if (error !== undefined)
|
|
294
|
+
logger.warn({ guildId, channelId, err: error }, "voice join failed");
|
|
295
|
+
return failed(failure);
|
|
296
|
+
};
|
|
297
|
+
try {
|
|
298
|
+
const facts = await gateway.channel(channelId);
|
|
299
|
+
if (facts === "gone") return refuse("channel_gone");
|
|
300
|
+
if (facts === "forbidden") return refuse("forbidden");
|
|
301
|
+
if (facts.kind === "other") return refuse("not_voice");
|
|
302
|
+
if (facts.guildId !== guildId) return refuse("channel_gone");
|
|
303
|
+
if (!facts.connectable) return refuse("forbidden");
|
|
304
|
+
if (facts.full) return refuse("full");
|
|
305
|
+
// Whoever enters or leaves while the connection comes up is heard through the gateway from here.
|
|
306
|
+
for (const member of facts.members) entry.session.memberJoined(member);
|
|
307
|
+
if (stopping) return refuse("unavailable");
|
|
308
|
+
const link = await gateway.connect(target);
|
|
309
|
+
entry.link = link;
|
|
310
|
+
const up = await comesUp(entry, link);
|
|
311
|
+
if (stopping || !up || link.status() === "closed")
|
|
312
|
+
return refuse("unavailable");
|
|
313
|
+
entry.open = true;
|
|
314
|
+
// A drop between coming up and here starts the resume time like any later one.
|
|
315
|
+
if (link.status() === "reconnecting") onStatus(entry, "reconnecting");
|
|
316
|
+
} catch (error) {
|
|
317
|
+
return refuse("unavailable", error);
|
|
318
|
+
}
|
|
319
|
+
logger.info({ guildId, channelId }, "voice session joined");
|
|
320
|
+
return { ok: true, session: entry.session };
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
return {
|
|
324
|
+
join,
|
|
325
|
+
session: (guildId) => {
|
|
326
|
+
const entry = joined.get(guildId);
|
|
327
|
+
return entry?.open ? entry.session : undefined;
|
|
328
|
+
},
|
|
329
|
+
start: () => gateway.prepare(),
|
|
330
|
+
stop: async () => {
|
|
331
|
+
stopping = true;
|
|
332
|
+
for (const entry of [...joined.values()])
|
|
333
|
+
if (entry.open) end(entry, "stopped");
|
|
334
|
+
},
|
|
335
|
+
};
|
|
336
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import type { Logger } from "../../kernel/log.ts";
|
|
2
|
+
import {
|
|
3
|
+
VOICE_PCM,
|
|
4
|
+
type VoiceDisconnectEvent,
|
|
5
|
+
type VoiceDisconnectReason,
|
|
6
|
+
type VoiceMember,
|
|
7
|
+
type VoiceMemberEvent,
|
|
8
|
+
type VoiceSession,
|
|
9
|
+
type VoiceSpeakingEvent,
|
|
10
|
+
type VoiceUtterance,
|
|
11
|
+
} from "./voice.ts";
|
|
12
|
+
import type { VoiceClock } from "./voice-clock.ts";
|
|
13
|
+
|
|
14
|
+
/** Bytes of `VOICE_PCM` audio in one millisecond. */
|
|
15
|
+
const BYTES_PER_MS =
|
|
16
|
+
(VOICE_PCM.sampleRate * VOICE_PCM.channels * VOICE_PCM.bytesPerSample) /
|
|
17
|
+
1_000;
|
|
18
|
+
|
|
19
|
+
export interface VoiceSessionOptions {
|
|
20
|
+
guildId: string;
|
|
21
|
+
channelId: string;
|
|
22
|
+
members: readonly VoiceMember[];
|
|
23
|
+
silenceMs: number;
|
|
24
|
+
maxUtteranceMs: number;
|
|
25
|
+
clock: VoiceClock;
|
|
26
|
+
logger: Logger;
|
|
27
|
+
/** What `leave()` does: the service closes the connection and ends the session. */
|
|
28
|
+
leave: () => void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** One speaker's utterance while it is still heard. */
|
|
32
|
+
interface OpenUtterance {
|
|
33
|
+
chunks: Uint8Array[];
|
|
34
|
+
bytes: number;
|
|
35
|
+
startedAt: number;
|
|
36
|
+
lastAt: number;
|
|
37
|
+
timer: unknown;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
class Listeners<T> {
|
|
41
|
+
readonly #listeners = new Set<(event: T) => void>();
|
|
42
|
+
readonly #logger: Logger;
|
|
43
|
+
readonly #what: string;
|
|
44
|
+
constructor(logger: Logger, what: string) {
|
|
45
|
+
this.#logger = logger;
|
|
46
|
+
this.#what = what;
|
|
47
|
+
}
|
|
48
|
+
add(listener: (event: T) => void): () => void {
|
|
49
|
+
this.#listeners.add(listener);
|
|
50
|
+
return () => {
|
|
51
|
+
this.#listeners.delete(listener);
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
emit(event: T): void {
|
|
55
|
+
for (const listener of [...this.#listeners]) this.call(listener, event);
|
|
56
|
+
}
|
|
57
|
+
/** Never logs the event: an utterance holds audio. */
|
|
58
|
+
call(listener: (event: T) => void, event: T): void {
|
|
59
|
+
try {
|
|
60
|
+
listener(event);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
this.#logger.error({ err: error }, `voice ${this.#what} listener failed`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
clear(): void {
|
|
66
|
+
this.#listeners.clear();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A voice session's own state: who is in the channel, and each speaker's audio cut into
|
|
72
|
+
* utterances. Whatever holds the connection (the Discord service, or a test's stand-in) feeds it
|
|
73
|
+
* members and decoded frames and ends it; it keeps audio only until the utterance is delivered.
|
|
74
|
+
*/
|
|
75
|
+
export class VoiceSessionState implements VoiceSession {
|
|
76
|
+
readonly guildId: string;
|
|
77
|
+
readonly channelId: string;
|
|
78
|
+
readonly #options: VoiceSessionOptions;
|
|
79
|
+
readonly #members = new Map<string, VoiceMember>();
|
|
80
|
+
readonly #open = new Map<string, OpenUtterance>();
|
|
81
|
+
readonly #maxBytes: number;
|
|
82
|
+
readonly #member: Listeners<VoiceMemberEvent>;
|
|
83
|
+
readonly #speaking: Listeners<VoiceSpeakingEvent>;
|
|
84
|
+
readonly #utterance: Listeners<VoiceUtterance>;
|
|
85
|
+
readonly #disconnect: Listeners<VoiceDisconnectEvent>;
|
|
86
|
+
#ended: VoiceDisconnectReason | undefined;
|
|
87
|
+
|
|
88
|
+
constructor(options: VoiceSessionOptions) {
|
|
89
|
+
this.#options = options;
|
|
90
|
+
this.guildId = options.guildId;
|
|
91
|
+
this.channelId = options.channelId;
|
|
92
|
+
this.#maxBytes = options.maxUtteranceMs * BYTES_PER_MS;
|
|
93
|
+
for (const member of options.members)
|
|
94
|
+
this.#members.set(member.userId, member);
|
|
95
|
+
this.#member = new Listeners(options.logger, "member");
|
|
96
|
+
this.#speaking = new Listeners(options.logger, "speaking");
|
|
97
|
+
this.#utterance = new Listeners(options.logger, "utterance");
|
|
98
|
+
this.#disconnect = new Listeners(options.logger, "disconnect");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
members(): VoiceMember[] {
|
|
102
|
+
return [...this.#members.values()];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
onMember(listener: (event: VoiceMemberEvent) => void): () => void {
|
|
106
|
+
return this.#member.add(listener);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
onSpeaking(listener: (event: VoiceSpeakingEvent) => void): () => void {
|
|
110
|
+
return this.#speaking.add(listener);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
onUtterance(listener: (utterance: VoiceUtterance) => void): () => void {
|
|
114
|
+
return this.#utterance.add(listener);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
onDisconnect(listener: (event: VoiceDisconnectEvent) => void): () => void {
|
|
118
|
+
const reason = this.#ended;
|
|
119
|
+
if (reason === undefined) return this.#disconnect.add(listener);
|
|
120
|
+
queueMicrotask(() => this.#disconnect.call(listener, { reason }));
|
|
121
|
+
return () => undefined;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
ended(): VoiceDisconnectReason | undefined {
|
|
125
|
+
return this.#ended;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async leave(): Promise<void> {
|
|
129
|
+
if (this.#ended === undefined) this.#options.leave();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Someone is in the channel: reported as joined unless they already were. */
|
|
133
|
+
memberJoined(member: VoiceMember): void {
|
|
134
|
+
if (this.#ended !== undefined) return;
|
|
135
|
+
const known = this.#members.has(member.userId);
|
|
136
|
+
this.#members.set(member.userId, member);
|
|
137
|
+
if (!known) this.#member.emit({ kind: "joined", member });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Someone is no longer in the channel: what they were saying is delivered first. */
|
|
141
|
+
memberLeft(userId: string): void {
|
|
142
|
+
const member = this.#members.get(userId);
|
|
143
|
+
if (this.#ended !== undefined || !member) return;
|
|
144
|
+
this.#finish(userId);
|
|
145
|
+
this.#members.delete(userId);
|
|
146
|
+
this.#member.emit({ kind: "left", member });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** One decoded frame of a speaker, in the `VOICE_PCM` format; the caller keeps no reference to it. */
|
|
150
|
+
frame(userId: string, pcm: Uint8Array): void {
|
|
151
|
+
if (this.#ended !== undefined || pcm.byteLength === 0) return;
|
|
152
|
+
const { clock, silenceMs } = this.#options;
|
|
153
|
+
const now = clock.now();
|
|
154
|
+
let open = this.#open.get(userId);
|
|
155
|
+
/** The utterance this frame cuts off, when the one before it was full. */
|
|
156
|
+
let cut: OpenUtterance | undefined;
|
|
157
|
+
if (!open) {
|
|
158
|
+
open = { chunks: [], bytes: 0, startedAt: now, lastAt: now, timer: 0 };
|
|
159
|
+
open.timer = clock.setTimeout(() => this.#quiet(userId), silenceMs);
|
|
160
|
+
this.#open.set(userId, open);
|
|
161
|
+
this.#speaking.emit({ userId, speaking: true, at: now });
|
|
162
|
+
} else if (open.bytes >= this.#maxBytes) {
|
|
163
|
+
// Full, and only now known to go on: this frame starts the next utterance, in the same breath.
|
|
164
|
+
cut = { ...open };
|
|
165
|
+
open.chunks = [];
|
|
166
|
+
open.bytes = 0;
|
|
167
|
+
open.startedAt = now;
|
|
168
|
+
}
|
|
169
|
+
open.chunks.push(pcm);
|
|
170
|
+
open.bytes += pcm.byteLength;
|
|
171
|
+
open.lastAt = now;
|
|
172
|
+
// Handed over last, with the open utterance already holding what follows: a listener that
|
|
173
|
+
// ends the session here is handed the rest once, and none of this audio again.
|
|
174
|
+
if (cut) this.#deliver(userId, cut, true);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Ends the session, once: every open utterance is delivered, then the disconnect is reported. */
|
|
178
|
+
end(reason: VoiceDisconnectReason): void {
|
|
179
|
+
if (this.#ended !== undefined) return;
|
|
180
|
+
for (const userId of [...this.#open.keys()]) this.#finish(userId);
|
|
181
|
+
this.#ended = reason;
|
|
182
|
+
this.#members.clear();
|
|
183
|
+
this.#disconnect.emit({ reason });
|
|
184
|
+
for (const listeners of [
|
|
185
|
+
this.#member,
|
|
186
|
+
this.#speaking,
|
|
187
|
+
this.#utterance,
|
|
188
|
+
this.#disconnect,
|
|
189
|
+
])
|
|
190
|
+
listeners.clear();
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** The silence timer fired: the utterance ends if nothing came since, else the timer waits out the rest. */
|
|
194
|
+
#quiet(userId: string): void {
|
|
195
|
+
const open = this.#open.get(userId);
|
|
196
|
+
if (!open) return;
|
|
197
|
+
const { clock, silenceMs } = this.#options;
|
|
198
|
+
const left = open.lastAt + silenceMs - clock.now();
|
|
199
|
+
if (left > 0) {
|
|
200
|
+
open.timer = clock.setTimeout(() => this.#quiet(userId), left);
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
this.#finish(userId);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
#finish(userId: string): void {
|
|
207
|
+
const open = this.#open.get(userId);
|
|
208
|
+
if (!open) return;
|
|
209
|
+
this.#open.delete(userId);
|
|
210
|
+
this.#options.clock.clearTimeout(open.timer);
|
|
211
|
+
this.#speaking.emit({ userId, speaking: false, at: open.lastAt });
|
|
212
|
+
if (open.bytes > 0) this.#deliver(userId, open, false);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
#deliver(userId: string, open: OpenUtterance, continues: boolean): void {
|
|
216
|
+
const pcm = new Uint8Array(open.bytes);
|
|
217
|
+
let offset = 0;
|
|
218
|
+
for (const chunk of open.chunks) {
|
|
219
|
+
pcm.set(chunk, offset);
|
|
220
|
+
offset += chunk.byteLength;
|
|
221
|
+
}
|
|
222
|
+
this.#utterance.emit({
|
|
223
|
+
userId,
|
|
224
|
+
pcm,
|
|
225
|
+
startedAt: open.startedAt,
|
|
226
|
+
endedAt: open.lastAt,
|
|
227
|
+
continues,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
}
|