@zygout/eris 0.19.0 → 0.19.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.
Files changed (88) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +109 -80
  3. package/esm.mjs +72 -72
  4. package/index.d.ts +4407 -4397
  5. package/index.js +75 -75
  6. package/lib/Client.js +4708 -4683
  7. package/lib/Constants.d.ts +990 -988
  8. package/lib/Constants.js +1163 -1161
  9. package/lib/command/Command.js +552 -552
  10. package/lib/command/CommandClient.js +460 -460
  11. package/lib/errors/DiscordHTTPError.js +63 -63
  12. package/lib/errors/DiscordRESTError.js +77 -77
  13. package/lib/gateway/Shard.js +3029 -3029
  14. package/lib/gateway/ShardManager.js +164 -164
  15. package/lib/rest/Endpoints.js +172 -172
  16. package/lib/rest/RequestHandler.js +459 -459
  17. package/lib/structures/ApplicationCommand.js +125 -125
  18. package/lib/structures/AutoModerationRule.js +143 -143
  19. package/lib/structures/AutocompleteInteraction.js +80 -80
  20. package/lib/structures/Base.js +81 -81
  21. package/lib/structures/CategoryChannel.js +77 -77
  22. package/lib/structures/Channel.js +98 -98
  23. package/lib/structures/CommandInteraction.js +473 -473
  24. package/lib/structures/ComponentInteraction.js +538 -538
  25. package/lib/structures/DMChannel.js +278 -278
  26. package/lib/structures/Entitlement.js +77 -77
  27. package/lib/structures/ExtendedUser.js +46 -46
  28. package/lib/structures/ForumChannel.js +24 -24
  29. package/lib/structures/GroupChannel.js +106 -106
  30. package/lib/structures/Guild.js +1677 -1677
  31. package/lib/structures/GuildAuditLogEntry.js +190 -190
  32. package/lib/structures/GuildChannel.js +128 -128
  33. package/lib/structures/GuildIntegration.js +99 -99
  34. package/lib/structures/GuildPreview.js +97 -97
  35. package/lib/structures/GuildScheduledEvent.js +176 -176
  36. package/lib/structures/GuildTemplate.js +76 -76
  37. package/lib/structures/GuildTextableChannel.js +260 -260
  38. package/lib/structures/Interaction.js +133 -133
  39. package/lib/structures/Invite.js +143 -143
  40. package/lib/structures/Lobby.js +108 -108
  41. package/lib/structures/LobbyMember.js +59 -59
  42. package/lib/structures/MediaChannel.js +216 -216
  43. package/lib/structures/Member.js +371 -371
  44. package/lib/structures/Message.js +708 -708
  45. package/lib/structures/ModalSubmitInteraction.js +478 -478
  46. package/lib/structures/NewsChannel.js +34 -34
  47. package/lib/structures/NewsThreadChannel.js +12 -12
  48. package/lib/structures/Permission.js +80 -80
  49. package/lib/structures/PermissionOverwrite.js +32 -32
  50. package/lib/structures/PingInteraction.js +39 -39
  51. package/lib/structures/PrivateThreadChannel.js +25 -25
  52. package/lib/structures/PublicThreadChannel.js +26 -26
  53. package/lib/structures/Role.js +163 -163
  54. package/lib/structures/SKU.js +80 -80
  55. package/lib/structures/SoundboardSound.js +79 -79
  56. package/lib/structures/StageChannel.js +59 -59
  57. package/lib/structures/StageInstance.js +55 -55
  58. package/lib/structures/Subscription.js +69 -69
  59. package/lib/structures/TextChannel.js +202 -202
  60. package/lib/structures/ThreadChannel.js +143 -143
  61. package/lib/structures/ThreadMember.js +59 -59
  62. package/lib/structures/UnavailableGuild.js +26 -26
  63. package/lib/structures/UnknownInteraction.js +502 -502
  64. package/lib/structures/User.js +296 -296
  65. package/lib/structures/VoiceChannel.js +166 -166
  66. package/lib/structures/VoiceState.js +84 -84
  67. package/lib/util/BrowserWebSocket.js +76 -76
  68. package/lib/util/Bucket.js +89 -89
  69. package/lib/util/Collection.js +202 -202
  70. package/lib/util/MultipartData.js +70 -70
  71. package/lib/util/Opus.js +33 -33
  72. package/lib/util/SequentialBucket.js +83 -83
  73. package/lib/util/emitDeprecation.js +26 -26
  74. package/lib/voice/Piper.js +300 -300
  75. package/lib/voice/SharedStream.js +238 -238
  76. package/lib/voice/VoiceConnection.js +1440 -1440
  77. package/lib/voice/VoiceConnectionManager.js +151 -151
  78. package/lib/voice/VoiceDataStream.js +22 -22
  79. package/lib/voice/streams/BaseTransformer.js +40 -40
  80. package/lib/voice/streams/DCAOpusTransformer.js +78 -78
  81. package/lib/voice/streams/FFmpegDuplex.js +192 -192
  82. package/lib/voice/streams/FFmpegOggTransformer.js +35 -35
  83. package/lib/voice/streams/FFmpegPCMTransformer.js +26 -26
  84. package/lib/voice/streams/OggOpusTransformer.js +108 -108
  85. package/lib/voice/streams/PCMOpusTransformer.js +61 -61
  86. package/lib/voice/streams/VolumeTransformer.js +50 -50
  87. package/lib/voice/streams/WebmOpusTransformer.js +258 -258
  88. package/package.json +83 -82
@@ -1,1440 +1,1440 @@
1
- "use strict";
2
-
3
- const util = require("util");
4
- const Base = require("../structures/Base");
5
- const ChildProcess = require("child_process");
6
- const { GatewayOPCodes, VOICE_VERSION, VoiceOPCodes } = require("../Constants");
7
- const Dgram = require("dgram");
8
- const Net = require("net");
9
- const Piper = require("./Piper");
10
- const VoiceDataStream = require("./VoiceDataStream");
11
- const { createOpus } = require("../util/Opus");
12
-
13
- const WebSocket = typeof window !== "undefined" ? require("../util/BrowserWebSocket") : require("ws");
14
-
15
- let EventEmitter;
16
- try {
17
- EventEmitter = require("eventemitter3");
18
- } catch {
19
- EventEmitter = require("events").EventEmitter;
20
- }
21
-
22
- let NodeCrypto = null;
23
- let Davey = null;
24
- let Sodium = null;
25
- let StableLib = null;
26
- let aes256Available = false;
27
- let librariesLoaded = false;
28
-
29
- const ENCRYPTION_MODE_AES256 = "aead_aes256_gcm_rtpsize";
30
- const ENCRYPTION_MODE_XCHACHA20 = "aead_xchacha20_poly1305_rtpsize";
31
- const DAVE_MEDIA_TYPE_AUDIO = 0;
32
- const DAVE_RECOVERY_INTERVAL = 10000;
33
- const AUTH_TAG_SIZE = 16;
34
- const IP_DISCOVERY_TIMEOUT = 10000;
35
- const NONCE_SUFFIX_SIZE = 4;
36
- const RTP_HEADER_SIZE = 12;
37
- const SILENCE_FRAME = Buffer.from([0xF8, 0xFF, 0xFE]);
38
- const UDP_KEEP_ALIVE = Buffer.from([0x80, 0xC8, 0x0, 0x0]);
39
-
40
- function loadLibraries() {
41
- if (librariesLoaded) {
42
- return;
43
- }
44
- librariesLoaded = true;
45
- try {
46
- NodeCrypto = require("crypto");
47
- aes256Available = NodeCrypto.getCiphers().includes("aes-256-gcm");
48
- } catch {} // eslint-disable-line no-empty
49
- try {
50
- Sodium = require("sodium-native");
51
- if (typeof Sodium.crypto_aead_xchacha20poly1305_ietf_encrypt !== "function") {
52
- Sodium = null;
53
- }
54
- } catch {} // eslint-disable-line no-empty
55
- if (!Sodium) {
56
- try {
57
- StableLib = require("@stablelib/xchacha20poly1305");
58
- } catch {} // eslint-disable-line no-empty
59
- }
60
- try {
61
- Davey = require("@snazzah/davey");
62
- } catch {} // eslint-disable-line no-empty
63
- }
64
-
65
- // Sorted by preference
66
- function getAvailableEncryptionModes() {
67
- const modes = [];
68
- if (aes256Available) {
69
- modes.push(ENCRYPTION_MODE_AES256);
70
- }
71
- if (Sodium || StableLib) {
72
- modes.push(ENCRYPTION_MODE_XCHACHA20);
73
- }
74
- return modes;
75
- }
76
-
77
- // DAVE encrypted frames end with the 0xFAFA magic marker
78
- function isDaveFrame(frame) {
79
- return frame.length > 2 && frame[frame.length - 1] === 0xFA && frame[frame.length - 2] === 0xFA;
80
- }
81
-
82
- // Opus silence frames are never end-to-end encrypted
83
- function isSilenceFrame(frame) {
84
- return frame.length === 3 && frame[0] === 0xF8 && frame[1] === 0xFF && frame[2] === 0xFE;
85
- }
86
-
87
- const converterCommand = {
88
- cmd: null,
89
- libopus: false,
90
- };
91
-
92
- converterCommand.pickCommand = function pickCommand() {
93
- let tenative;
94
- for (const command of ["./ffmpeg", "./avconv", "ffmpeg", "avconv"]) {
95
- const res = ChildProcess.spawnSync(command, ["-encoders"]);
96
- if (!res.error) {
97
- if (!res.stdout.toString().includes("libopus")) {
98
- tenative = command;
99
- continue;
100
- }
101
- converterCommand.cmd = command;
102
- converterCommand.libopus = true;
103
- return;
104
- }
105
- }
106
- if (tenative) {
107
- converterCommand.cmd = tenative;
108
- return;
109
- }
110
- };
111
-
112
- /**
113
- * Represents a voice connection
114
- * Transport encryption uses AES-256-GCM through Node.js' crypto module, or XChaCha20-Poly1305 through `sodium-native` or `@stablelib/xchacha20poly1305`.
115
- * End-to-end encryption (DAVE protocol, required by Discord for voice channels) needs the optional `@snazzah/davey` dependency
116
- * @extends EventEmitter
117
- * @prop {String} channelID The ID of the voice connection's current channel
118
- * @prop {Boolean} connecting Whether the voice connection is connecting
119
- * @prop {Object?} current The state of the currently playing stream
120
- * @prop {Object} current.options The custom options for the current stream
121
- * @prop {Array<String>?} current.options.encoderArgs Additional encoder parameters to pass to ffmpeg/avconv (after -i)
122
- * @prop {String?} current.options.format The format of the resource. If null, FFmpeg will attempt to guess and play the format. Available options: "dca", "ogg", "webm", "pcm", "opusPackets", null
123
- * @prop {Number?} current.options.frameDuration The resource opus frame duration (required for DCA/Ogg)
124
- * @prop {Number?} current.options.frameSize The resource opus frame size
125
- * @prop {Boolean?} current.options.inlineVolume Whether to enable on-the-fly volume changing. Note that enabling this leads to increased CPU usage
126
- * @prop {Array<String>?} current.options.inputArgs Additional input parameters to pass to ffmpeg/avconv (before -i)
127
- * @prop {Number?} current.options.sampleRate The resource audio sampling rate
128
- * @prop {Number?} current.options.voiceDataTimeout Timeout when waiting for voice data (-1 for no timeout)
129
- * @prop {Number} current.pausedTime How long the current stream has been paused for, in milliseconds
130
- * @prop {Number} current.pausedTimestamp The timestamp of the most recent pause
131
- * @prop {Number} current.playTime How long the current stream has been playing for, in milliseconds
132
- * @prop {Number} current.startTime The timestamp of the start of the current stream
133
- * @prop {Boolean} daveEnabled Whether the connection supports end-to-end encryption (DAVE protocol). Requires the `@snazzah/davey` package
134
- * @prop {Number} daveProtocolVersion The DAVE protocol version used by the call. `0` means the call is not end-to-end encrypted
135
- * @prop {Object?} daveSession The `@snazzah/davey` DAVE session, if the call is end-to-end encrypted
136
- * @prop {Number} decryptionFailureTolerance The number of consecutive end-to-end decryption failures from a single user after which the DAVE session is recovered (0 to never recover). Recoveries are at least 10 seconds apart, and skipped while packets from other users still decrypt
137
- * @prop {String} id The ID of the voice connection (guild ID)
138
- * @prop {String?} mode The transport encryption mode of the connection
139
- * @prop {Boolean} paused Whether the voice connection is paused
140
- * @prop {Boolean} playing Whether the voice connection is playing something
141
- * @prop {Boolean} ready Whether the voice connection is ready
142
- * @prop {Boolean} resuming Whether the voice connection is waiting for resuming
143
- * @prop {String?} voicePrivacyCode The voice privacy code of the call, if it is end-to-end encrypted. It matches the code displayed in the Discord client
144
- * @prop {Number} volume The current volume level of the connection
145
- * @prop {Number} wsSequence The sequence number of the last numbered message received from the voice gateway
146
- */
147
- class VoiceConnection extends EventEmitter {
148
- constructor(id, options = {}) {
149
- super();
150
-
151
- if (typeof window !== "undefined") {
152
- throw new Error("Voice is not supported in browsers at this time");
153
- }
154
-
155
- loadLibraries();
156
- if (getAvailableEncryptionModes().length === 0) {
157
- throw new Error("No voice encryption available. Use a Node.js build supporting AES-256-GCM, or install sodium-native or @stablelib/xchacha20poly1305");
158
- }
159
-
160
- this.id = id;
161
- this.samplingRate = 48000;
162
- this.channels = 2;
163
- this.frameDuration = 20;
164
- this.frameSize = this.samplingRate * this.frameDuration / 1000;
165
- this.pcmSize = this.frameSize * this.channels * 2;
166
- this.bitrate = 64000;
167
- this.shared = !!options.shared;
168
- this.shard = options.shard || {};
169
- this.opusOnly = !!options.opusOnly;
170
- this.daveEnabled = options.daveEncryption !== false && !!Davey;
171
- this.decryptionFailureTolerance = options.decryptionFailureTolerance !== undefined ? options.decryptionFailureTolerance : 36;
172
-
173
- if (!this.opusOnly && !this.shared) {
174
- this.opus = {};
175
- }
176
-
177
- this.channelID = null;
178
- this.paused = true;
179
- this.speaking = false;
180
- this.sequence = 0;
181
- this.timestamp = 0;
182
- this.ssrcUserMap = {};
183
- this.connectionTimeout = null;
184
- this.connecting = false;
185
- this.reconnecting = false;
186
- this.resuming = false;
187
- this.ready = false;
188
- this.sessionID = null;
189
- this.token = null;
190
- this.wsSequence = -1;
191
-
192
- this.daveProtocolVersion = 0;
193
- this.daveSession = null;
194
- this._connectedUsers = new Set();
195
- this._daveDecryptionFailures = new Map();
196
- this._daveDowngraded = false;
197
- this._daveExternalSender = null;
198
- this._daveLastDecryption = 0;
199
- this._daveLastDecryptionUserID = null;
200
- this._daveLastRecovery = 0;
201
- this._davePendingTransitions = new Map();
202
- this._daveReinitializing = false;
203
- this._daveWarned = false;
204
- this._ipDiscoveryTimeout = null;
205
- this._lastTransitionID = null;
206
- this._nonce = 0;
207
- this._receiveNonce = null;
208
- this._receiveSocket = null;
209
- this._sendNonce = null;
210
- this._stablelib = null;
211
- this._userID = null;
212
-
213
- this.sendHeader = Buffer.alloc(RTP_HEADER_SIZE);
214
- this.sendHeader[0] = 0x80;
215
- this.sendHeader[1] = 0x78;
216
-
217
- if (!options.shared) {
218
- if (!converterCommand.cmd) {
219
- converterCommand.pickCommand();
220
- }
221
-
222
- this.piper = new Piper(converterCommand.cmd, () => createOpus(this.samplingRate, this.channels, this.bitrate));
223
- /**
224
- * Fired when the voice connection encounters an error. This event should be handled by users
225
- * @event VoiceConnection#error
226
- * @prop {Error} err The error object
227
- */
228
- this.piper.on("error", (e) => this.emit("error", e));
229
- if (!converterCommand.libopus) {
230
- this.piper.libopus = false;
231
- }
232
- }
233
-
234
- this._send = this._send.bind(this);
235
- }
236
-
237
- get voicePrivacyCode() {
238
- return (this.daveSession && this.daveSession.voicePrivacyCode) || null;
239
- }
240
-
241
- get volume() {
242
- return this.piper.volumeLevel;
243
- }
244
-
245
- connect(data) {
246
- this.connecting = true;
247
- if (this.ws && this.ws.readyState !== WebSocket.CLOSED) {
248
- this.disconnect(undefined, true);
249
- setTimeout(() => {
250
- if (!this.connecting && !this.ready) {
251
- this.connect(data);
252
- }
253
- }, 500).unref();
254
- return;
255
- }
256
- clearTimeout(this.connectionTimeout);
257
- this.connectionTimeout = setTimeout(() => {
258
- if (this.connecting) {
259
- this.disconnect(new Error("Voice connection timeout"));
260
- }
261
- this.connectionTimeout = null;
262
- }, this.shard.client ? this.shard.client.options.connectionTimeout : 30000).unref();
263
- if (!data.endpoint) {
264
- return; // Endpoint null, wait next update.
265
- }
266
- if (!data.token || !data.session_id || !data.user_id) {
267
- this.disconnect(new Error("Malformed voice server update: " + JSON.stringify(data)));
268
- return;
269
- }
270
- this.channelID = data.channel_id;
271
- this._userID = data.user_id;
272
- const lastEndpoint = this.endpoint ? this.endpoint.hostname : null;
273
- this.endpoint = new URL(`wss://${data.endpoint}`);
274
- if (this.endpoint.port === "80") {
275
- this.endpoint.port = "";
276
- }
277
- this.endpoint.searchParams.set("v", VOICE_VERSION);
278
- this.resuming = this.reconnecting && !!this.udpSocket && data.session_id === this.sessionID && data.token === this.token && lastEndpoint === this.endpoint.hostname;
279
- const ws = this.ws = new WebSocket(this.endpoint.href);
280
- /**
281
- * Fired when stuff happens and gives more info
282
- * @event VoiceConnection#debug
283
- * @prop {String} message The debug message
284
- */
285
- this.emit("debug", "Connection: " + JSON.stringify(data));
286
- ws.on("open", () => {
287
- if (this.ws !== ws) {
288
- return;
289
- }
290
- /**
291
- * Fired when the voice connection connects
292
- * @event VoiceConnection#connect
293
- */
294
- this.emit("connect");
295
- if (this.connectionTimeout) {
296
- clearTimeout(this.connectionTimeout);
297
- this.connectionTimeout = null;
298
- }
299
- if (this.resuming) {
300
- this.emit("debug", `Resuming session (sequence ${this.wsSequence})`);
301
- this.sendWS(VoiceOPCodes.RESUME, {
302
- server_id: this.id,
303
- session_id: data.session_id,
304
- token: data.token,
305
- seq_ack: this.wsSequence,
306
- });
307
- } else {
308
- this._closeUDP();
309
- this._connectedUsers.clear();
310
- this._daveDecryptionFailures.clear();
311
- this.wsSequence = -1;
312
- if (!this.daveEnabled && !this._daveWarned) {
313
- this._daveWarned = true;
314
- /**
315
- * Fired to warn of something weird but non-breaking happening
316
- * @event VoiceConnection#warn
317
- * @prop {String} message The warning message
318
- */
319
- this.emit("warn", "End-to-end encryption (DAVE protocol) is not available" + (Davey ? "" : ", install @snazzah/davey to enable it") + ". Discord will refuse the connection for channels requiring it");
320
- }
321
- this.sendWS(VoiceOPCodes.IDENTIFY, {
322
- server_id: this.id,
323
- user_id: data.user_id,
324
- session_id: data.session_id,
325
- token: data.token,
326
- max_dave_protocol_version: this.daveEnabled ? Davey.DAVE_PROTOCOL_VERSION : 0,
327
- });
328
- }
329
- });
330
- ws.on("message", (m, isBinary) => {
331
- if (this.ws !== ws) {
332
- return;
333
- }
334
- if (isBinary) {
335
- if (m instanceof ArrayBuffer) {
336
- m = Buffer.from(m);
337
- } else if (Array.isArray(m)) {
338
- m = Buffer.concat(m);
339
- }
340
- return this._handleBinaryMessage(m);
341
- }
342
- const packet = JSON.parse(m);
343
- if (this.listeners("debug").length > 0) {
344
- this.emit("debug", "Rec: " + JSON.stringify(packet));
345
- }
346
- if (packet.seq !== undefined) {
347
- this.wsSequence = packet.seq;
348
- }
349
- switch (packet.op) {
350
- case VoiceOPCodes.READY: {
351
- this.ssrc = packet.d.ssrc;
352
- this.sendHeader.writeUInt32BE(this.ssrc, 8);
353
-
354
- this.modes = packet.d.modes;
355
- const mode = getAvailableEncryptionModes().find((mode) => packet.d.modes.includes(mode));
356
- if (!mode) {
357
- this.disconnect(new Error("No supported voice encryption mode found. Available modes: " + packet.d.modes.join(", ")));
358
- return;
359
- }
360
-
361
- this.udpIP = packet.d.ip;
362
- this.udpPort = packet.d.port;
363
- this.sessionID = data.session_id;
364
- this.token = data.token;
365
-
366
- this.emit("debug", "Connecting to UDP: " + this.udpIP + ":" + this.udpPort);
367
-
368
- const udpSocket = this.udpSocket = Dgram.createSocket(Net.isIPv6(this.udpIP) ? "udp6" : "udp4");
369
- udpSocket.on("error", (err, msg) => {
370
- if (this.udpSocket !== udpSocket) {
371
- return;
372
- }
373
- this.emit("error", err);
374
- if (msg) {
375
- this.emit("debug", "Voice UDP error: " + msg);
376
- }
377
- if (this.ready || this.connecting) {
378
- this.disconnect(err);
379
- }
380
- });
381
- udpSocket.once("message", (packet) => {
382
- if (this.udpSocket !== udpSocket) {
383
- return;
384
- }
385
- clearTimeout(this._ipDiscoveryTimeout);
386
- this._ipDiscoveryTimeout = null;
387
- let i = 8;
388
- while (packet[i] !== 0) {
389
- i++;
390
- }
391
- const localIP = packet.toString("ascii", 8, i);
392
- const localPort = packet.readUInt16BE(packet.length - 2);
393
- this.emit("debug", `Discovered IP: ${localIP}:${localPort} (${packet.toString("hex")})`);
394
-
395
- this.sendWS(VoiceOPCodes.SELECT_PROTOCOL, {
396
- protocol: "udp",
397
- data: {
398
- address: localIP,
399
- port: localPort,
400
- mode: mode,
401
- },
402
- });
403
- });
404
- udpSocket.on("close", (err) => {
405
- if (this.udpSocket !== udpSocket) {
406
- return;
407
- }
408
- if (err) {
409
- this.emit("warn", "Voice UDP close: " + err);
410
- }
411
- if (this.ready || this.connecting) {
412
- this.disconnect(err);
413
- }
414
- });
415
- clearTimeout(this._ipDiscoveryTimeout);
416
- this._ipDiscoveryTimeout = setTimeout(() => {
417
- this._ipDiscoveryTimeout = null;
418
- if (this.udpSocket === udpSocket && !this.ready) {
419
- this.disconnect(new Error("Voice IP discovery timeout"));
420
- }
421
- }, IP_DISCOVERY_TIMEOUT).unref();
422
- const udpMessage = Buffer.alloc(74);
423
- udpMessage.writeUInt16BE(0x1, 0);
424
- udpMessage.writeUInt16BE(70, 2);
425
- udpMessage.writeUInt32BE(this.ssrc, 4);
426
- this.sendUDPPacket(udpMessage);
427
- break;
428
- }
429
- case VoiceOPCodes.RESUMED: {
430
- this.connecting = false;
431
- this.reconnecting = false;
432
- this.resuming = false;
433
- this.ready = true;
434
- /**
435
- * Fired when the voice connection resumes its session
436
- * @event VoiceConnection#resumed
437
- */
438
- this.emit("resumed");
439
- this.resume();
440
- break;
441
- }
442
- case VoiceOPCodes.SESSION_DESCRIPTION: {
443
- this.mode = packet.d.mode;
444
- this.secret = Buffer.from(packet.d.secret_key);
445
- const nonceSize = this.mode === ENCRYPTION_MODE_AES256 ? 12 : 24;
446
- this._nonce = 0;
447
- this._receiveNonce = Buffer.alloc(nonceSize);
448
- this._sendNonce = Buffer.alloc(nonceSize);
449
- this._stablelib = this.mode === ENCRYPTION_MODE_XCHACHA20 && !Sodium ? new StableLib.XChaCha20Poly1305(this.secret) : null;
450
- this.daveProtocolVersion = packet.d.dave_protocol_version || 0;
451
- this._daveDowngraded = this.daveProtocolVersion === 0;
452
- this.connecting = false;
453
- this.reconnecting = false;
454
- this.resuming = false;
455
- this.ready = true;
456
- this._reinitDaveSession();
457
- // Send audio to properly establish the socket (e.g. for voice receive)
458
- this.sendAudioFrame(SILENCE_FRAME, this.frameSize);
459
- /**
460
- * Fired when the voice connection turns ready
461
- * @event VoiceConnection#ready
462
- */
463
- this.emit("ready");
464
- this.resume();
465
- if (this.receiveStreamOpus || this.receiveStreamPCM) {
466
- this.registerReceiveEventHandler();
467
- }
468
- break;
469
- }
470
- case VoiceOPCodes.HEARTBEAT_ACK: {
471
- /**
472
- * Fired when the voice connection receives a pong
473
- * @event VoiceConnection#pong
474
- * @prop {Number} latency The current latency in milliseconds
475
- */
476
- this.emit("pong", Date.now() - (packet.d && typeof packet.d === "object" ? packet.d.t : packet.d));
477
- break;
478
- }
479
- case VoiceOPCodes.SPEAKING: {
480
- this.ssrcUserMap[packet.d.ssrc] = packet.d.user_id;
481
- /**
482
- * Fired when a user begins speaking
483
- * @event VoiceConnection#speakingStart
484
- * @prop {String} userID The ID of the user that began speaking
485
- */
486
- /**
487
- * Fired when a user stops speaking
488
- * @event VoiceConnection#speakingStop
489
- * @prop {String} userID The ID of the user that stopped speaking
490
- */
491
- this.emit(packet.d.speaking ? "speakingStart" : "speakingStop", packet.d.user_id);
492
- break;
493
- }
494
- case VoiceOPCodes.HELLO: {
495
- if (this.heartbeatInterval) {
496
- clearInterval(this.heartbeatInterval);
497
- }
498
- this.heartbeatInterval = setInterval(() => {
499
- this.heartbeat();
500
- }, packet.d.heartbeat_interval);
501
-
502
- this.heartbeat();
503
- break;
504
- }
505
- case VoiceOPCodes.CLIENTS_CONNECT: {
506
- for (const userID of packet.d.user_ids) {
507
- this._connectedUsers.add(userID);
508
- }
509
- /**
510
- * Fired when one or more clients connect to the voice channel
511
- * @event VoiceConnection#usersConnect
512
- * @prop {String[]} userIDs The IDs of the users that connected
513
- */
514
- this.emit("usersConnect", packet.d.user_ids);
515
- break;
516
- }
517
- case VoiceOPCodes.CLIENT_DISCONNECT: {
518
- if (this.opus) {
519
- // opusscript requires manual cleanup
520
- if (this.opus[packet.d.user_id] && this.opus[packet.d.user_id].delete) {
521
- this.opus[packet.d.user_id].delete();
522
- }
523
-
524
- delete this.opus[packet.d.user_id];
525
- }
526
-
527
- this._connectedUsers.delete(packet.d.user_id);
528
- this._daveDecryptionFailures.delete(packet.d.user_id);
529
- for (const ssrc in this.ssrcUserMap) {
530
- if (this.ssrcUserMap[ssrc] === packet.d.user_id) {
531
- delete this.ssrcUserMap[ssrc];
532
- }
533
- }
534
-
535
- /**
536
- * Fired when a user disconnects from the voice server
537
- * @event VoiceConnection#userDisconnect
538
- * @prop {String} userID The ID of the user that disconnected
539
- */
540
- this.emit("userDisconnect", packet.d.user_id);
541
- break;
542
- }
543
- case VoiceOPCodes.DAVE_PREPARE_TRANSITION: {
544
- this.emit("debug", `Preparing DAVE transition ${packet.d.transition_id} (protocol version ${packet.d.protocol_version})`);
545
- this._davePendingTransitions.set(packet.d.transition_id, packet.d.protocol_version);
546
- if (this.daveSession) {
547
- this.daveSession.prepareTransition(packet.d.transition_id, packet.d.protocol_version);
548
- // Downgrading to transport-only encryption, unencrypted frames can be received right away
549
- if (packet.d.protocol_version === 0) {
550
- this.daveSession.setPassthroughMode(true);
551
- }
552
- }
553
- // Transition ID 0 is a (re)initialization and is executed immediately
554
- if (packet.d.transition_id === 0) {
555
- this._executeDaveTransition(0);
556
- } else {
557
- this.sendWS(VoiceOPCodes.DAVE_TRANSITION_READY, {
558
- transition_id: packet.d.transition_id,
559
- });
560
- }
561
- break;
562
- }
563
- case VoiceOPCodes.DAVE_EXECUTE_TRANSITION: {
564
- this._executeDaveTransition(packet.d.transition_id);
565
- break;
566
- }
567
- case VoiceOPCodes.DAVE_PREPARE_EPOCH: {
568
- this.emit("debug", `Preparing DAVE epoch ${packet.d.epoch} (protocol version ${packet.d.protocol_version})`);
569
- // Epoch 1 means a new MLS group is being created
570
- if (packet.d.epoch === 1) {
571
- this.daveProtocolVersion = packet.d.protocol_version;
572
- this._reinitDaveSession();
573
- }
574
- break;
575
- }
576
- default: {
577
- this.emit("unknown", packet);
578
- break;
579
- }
580
- }
581
- });
582
- ws.on("error", (err) => {
583
- if (this.ws !== ws) {
584
- return;
585
- }
586
- this.emit("error", err);
587
- });
588
- ws.on("close", (code, reason) => {
589
- if (this.ws !== ws) {
590
- return;
591
- }
592
- let err = !code || code === 1000 ? null : new Error(code + ": " + reason);
593
- this.emit("warn", `Voice WS close ${code}: ${reason}`);
594
- if (this.connecting || this.ready) {
595
- let reconnecting = true;
596
- const resumable = !code || code < 4000 || code === 4015;
597
- if (code === 1000 || code === 4004 || code === 4006 || code === 4016 || code === 4021) {
598
- reconnecting = false;
599
- } else if (code === 4017) {
600
- reconnecting = false;
601
- err = new Error(code + ": " + reason + (this.daveEnabled ? "" : Davey ? " (end-to-end encryption is disabled by the daveEncryption option)" : " (end-to-end encryption requires the @snazzah/davey package)"));
602
- } else if (code === 4014 || code === 4022) {
603
- if (this.channelID) {
604
- data.endpoint = null;
605
- err = null;
606
- } else {
607
- reconnecting = false;
608
- }
609
- } else if (resumable) {
610
- err = null; // Already reported by the warn event, the session is resumed
611
- }
612
- this.disconnect(err, reconnecting);
613
- if (reconnecting) {
614
- if (!resumable) {
615
- // The session can't be resumed
616
- this.sessionID = null;
617
- this.token = null;
618
- this.wsSequence = -1;
619
- this._closeUDP();
620
- }
621
- setTimeout(() => {
622
- if (!this.connecting && !this.ready) {
623
- this.connect(data);
624
- }
625
- }, 500).unref();
626
- }
627
- }
628
- });
629
- }
630
-
631
- disconnect(error, reconnecting) {
632
- this.connecting = false;
633
- this.reconnecting = reconnecting;
634
- this.resuming = false;
635
- this.ready = false;
636
-
637
- if (this.connectionTimeout) {
638
- clearTimeout(this.connectionTimeout);
639
- this.connectionTimeout = null;
640
- }
641
- if (this._ipDiscoveryTimeout) {
642
- clearTimeout(this._ipDiscoveryTimeout);
643
- this._ipDiscoveryTimeout = null;
644
- }
645
-
646
- try {
647
- if (reconnecting) {
648
- this.pause();
649
- } else {
650
- this.stopPlaying();
651
- }
652
- } catch (err) {
653
- this.emit("error", err);
654
- }
655
- if (this.heartbeatInterval) {
656
- clearInterval(this.heartbeatInterval);
657
- this.heartbeatInterval = null;
658
- }
659
- if (!reconnecting) {
660
- this.speaking = false;
661
- this.timestamp = 0;
662
- this.sequence = 0;
663
- this._closeUDP();
664
- }
665
- if (this.ws) {
666
- const ws = this.ws;
667
- this.ws = null;
668
- try {
669
- if (reconnecting) {
670
- if (ws.readyState === WebSocket.OPEN) {
671
- ws.close(4901, "Eris: reconnect");
672
- } else {
673
- this.emit("debug", `Terminating websocket (state: ${ws.readyState})`);
674
- ws.terminate();
675
- }
676
- } else {
677
- ws.close(1000, "Eris: normal");
678
- }
679
- } catch (err) {
680
- this.emit("error", err);
681
- }
682
- }
683
- if (reconnecting) {
684
- if (error) {
685
- this.emit("error", error);
686
- }
687
- } else {
688
- this.channelID = null;
689
- this.sessionID = null;
690
- this.token = null;
691
- this.wsSequence = -1;
692
- this.daveProtocolVersion = 0;
693
- this.daveSession = null;
694
- this._connectedUsers.clear();
695
- this._daveDecryptionFailures.clear();
696
- this._daveExternalSender = null;
697
- this._daveLastDecryption = 0;
698
- this._daveLastDecryptionUserID = null;
699
- this._daveLastRecovery = 0;
700
- this._davePendingTransitions.clear();
701
- this._lastTransitionID = null;
702
- this._stablelib = null;
703
- this.updateVoiceState();
704
- /**
705
- * Fired when the voice connection disconnects
706
- * @event VoiceConnection#disconnect
707
- * @prop {Error?} error The error, if any
708
- */
709
- this.emit("disconnect", error);
710
- }
711
- }
712
-
713
- /**
714
- * Get the verification code of a user in the end-to-end encrypted call. It matches the code displayed in the Discord client
715
- * @arg {String} userID The ID of the user
716
- * @returns {Promise<String>}
717
- */
718
- getVerificationCode(userID) {
719
- if (!this.daveSession) {
720
- return Promise.reject(new Error("The call is not end-to-end encrypted"));
721
- }
722
- return this.daveSession.getVerificationCode(userID);
723
- }
724
-
725
- heartbeat() {
726
- this.sendWS(VoiceOPCodes.HEARTBEAT, {
727
- t: Date.now(),
728
- seq_ack: this.wsSequence,
729
- });
730
- if (this.udpSocket) {
731
- // NAT/connection table keep-alive
732
- this.sendUDPPacket(UDP_KEEP_ALIVE);
733
- }
734
- }
735
-
736
- /**
737
- * Pause sending audio (if playing)
738
- */
739
- pause() {
740
- this.paused = true;
741
- this.setSpeaking(0);
742
- if (this.current) {
743
- if (!this.current.pausedTimestamp) {
744
- this.current.pausedTimestamp = Date.now();
745
- }
746
- if (this.current.timeout) {
747
- clearTimeout(this.current.timeout);
748
- this.current.timeout = null;
749
- }
750
- }
751
- }
752
-
753
- /**
754
- * Play an audio or video resource. If playing from a non-opus resource, FFMPEG should be compiled with --enable-libopus for best performance. If playing from HTTPS, FFMPEG must be compiled with --enable-openssl
755
- * @arg {ReadableStream | String} resource The audio or video resource, either a ReadableStream, URL, or file path
756
- * @arg {Object} [options] Music options
757
- * @arg {Array<String>} [options.encoderArgs] Additional encoder parameters to pass to ffmpeg/avconv (after -i)
758
- * @arg {String} [options.format] The format of the resource. If null, FFmpeg will attempt to guess and play the format. Available options: "dca", "ogg", "webm", "pcm", null
759
- * @arg {Number} [options.frameDuration=20] The resource opus frame duration (required for DCA/Ogg)
760
- * @arg {Number} [options.frameSize=2880] The resource opus frame size
761
- * @arg {Boolean} [options.inlineVolume=false] Whether to enable on-the-fly volume changing. Note that enabling this leads to increased CPU usage
762
- * @arg {Array<String>} [options.inputArgs] Additional input parameters to pass to ffmpeg/avconv (before -i)
763
- * @arg {Number} [options.pcmSize=options.frameSize*2*this.channels] The PCM size if the "pcm" format is used
764
- * @arg {Number} [options.samplingRate=48000] The resource audio sampling rate
765
- * @arg {Number} [options.voiceDataTimeout=2000] Timeout when waiting for voice data (-1 for no timeout)
766
- */
767
- play(source, options = {}) {
768
- if (this.shared) {
769
- throw new Error("Cannot play stream on shared voice connection");
770
- }
771
- if (!this.ready) {
772
- throw new Error("Not ready yet");
773
- }
774
-
775
- options.format = options.format || null;
776
- options.voiceDataTimeout = !isNaN(options.voiceDataTimeout) ? options.voiceDataTimeout : 2000;
777
- options.inlineVolume = !!options.inlineVolume;
778
- options.inputArgs = options.inputArgs || [];
779
- options.encoderArgs = options.encoderArgs || [];
780
-
781
- options.samplingRate = options.samplingRate || this.samplingRate;
782
- options.frameDuration = options.frameDuration || this.frameDuration;
783
- options.frameSize = options.frameSize || options.samplingRate * options.frameDuration / 1000;
784
- options.pcmSize = options.pcmSize || options.frameSize * 2 * this.channels;
785
-
786
- if (!this.piper.encode(source, options)) {
787
- this.emit("error", new Error("Unable to encode source"));
788
- return;
789
- }
790
-
791
- this.ended = false;
792
- this.current = {
793
- startTime: 0, // later
794
- playTime: 0,
795
- pausedTimestamp: 0,
796
- pausedTime: 0,
797
- bufferingTicks: 0,
798
- options: options,
799
- timeout: null,
800
- buffer: null,
801
- };
802
-
803
- this.playing = true;
804
-
805
- /**
806
- * Fired when the voice connection starts playing a stream
807
- * @event VoiceConnection#start
808
- */
809
- this.emit("start");
810
-
811
- this._send();
812
- }
813
-
814
- /**
815
- * Generate a receive stream for the voice connection.
816
- * @arg {String} [type="pcm"] The desired voice data type, either "opus" or "pcm"
817
- * @returns {VoiceDataStream}
818
- */
819
- receive(type) {
820
- if (type === "pcm") {
821
- if (!this.receiveStreamPCM) {
822
- this.receiveStreamPCM = new VoiceDataStream(type);
823
- if (!this.receiveStreamOpus) {
824
- this.registerReceiveEventHandler();
825
- }
826
- }
827
- } else if (type === "opus") {
828
- if (!this.receiveStreamOpus) {
829
- this.receiveStreamOpus = new VoiceDataStream(type);
830
- if (!this.receiveStreamPCM) {
831
- this.registerReceiveEventHandler();
832
- }
833
- }
834
- } else {
835
- throw new Error(`Unsupported voice data type: ${type}`);
836
- }
837
- return type === "pcm" ? this.receiveStreamPCM : this.receiveStreamOpus;
838
- }
839
-
840
- registerReceiveEventHandler() {
841
- const udpSocket = this.udpSocket;
842
- if (!udpSocket || this._receiveSocket === udpSocket) {
843
- return;
844
- }
845
- this._receiveSocket = udpSocket;
846
- udpSocket.on("message", (msg) => {
847
- if (this.udpSocket === udpSocket) {
848
- this._onUDPMessage(msg);
849
- }
850
- });
851
- }
852
-
853
- /**
854
- * Resume sending audio (if paused)
855
- */
856
- resume() {
857
- this.paused = false;
858
- if (this.current) {
859
- this.setSpeaking(1);
860
- if (this.current.pausedTimestamp) {
861
- this.current.pausedTime += Date.now() - this.current.pausedTimestamp;
862
- this.current.pausedTimestamp = 0;
863
- }
864
- this._send();
865
- } else {
866
- this.setSpeaking(0);
867
- }
868
- }
869
-
870
- /**
871
- * Send a packet containing an Opus audio frame
872
- * @arg {Buffer} frame The Opus audio frame
873
- * @arg {Number} [frameSize] The size (in samples) of the Opus audio frame
874
- */
875
- sendAudioFrame(frame, frameSize = this.frameSize) {
876
- this.timestamp = (this.timestamp + frameSize) >>> 0;
877
- this.sequence = (this.sequence + 1) & 0xFFFF;
878
-
879
- return this._sendAudioFrame(frame);
880
- }
881
-
882
- /**
883
- * Send a packet through the connection's UDP socket. The packet is dropped if the socket isn't established
884
- * @arg {Buffer} packet The packet data
885
- */
886
- sendUDPPacket(packet) {
887
- if (this.udpSocket) {
888
- try {
889
- this.udpSocket.send(packet, 0, packet.length, this.udpPort, this.udpIP);
890
- } catch (e) {
891
- this.emit("error", e);
892
- }
893
- }
894
- }
895
-
896
- sendWS(op, data) {
897
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
898
- data = JSON.stringify({ op: op, d: data });
899
- this.ws.send(data);
900
- this.emit("debug", data);
901
- }
902
- }
903
-
904
- /**
905
- * Send a binary message through the voice gateway (used by the DAVE protocol)
906
- * @arg {Number} op The opcode of the message
907
- * @arg {Buffer} data The payload of the message
908
- */
909
- sendWSBinary(op, data) {
910
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
911
- const packet = Buffer.allocUnsafe(data.length + 1);
912
- packet[0] = op;
913
- data.copy(packet, 1);
914
- this.ws.send(packet);
915
- this.emit("debug", `Sent binary opcode ${op} (${data.length} bytes)`);
916
- }
917
- }
918
-
919
- setSpeaking(value, delay = 0) {
920
- this.speaking = value === true ? 1 : value === false ? 0 : value;
921
- this.sendWS(VoiceOPCodes.SPEAKING, {
922
- speaking: value,
923
- delay: delay,
924
- ssrc: this.ssrc,
925
- });
926
- }
927
-
928
- /**
929
- * Modify the output volume of the current stream (if inlineVolume is enabled for the current stream)
930
- * @arg {Number} [volume=1.0] The desired volume. 0.0 is 0%, 1.0 is 100%, 2.0 is 200%, etc. It is not recommended to go above 2.0
931
- */
932
- setVolume(volume) {
933
- this.piper.setVolume(volume);
934
- }
935
-
936
- /**
937
- * Stop the bot from sending audio
938
- */
939
- stopPlaying() {
940
- if (this.ended) {
941
- return;
942
- }
943
- this.ended = true;
944
- if (this.current && this.current.timeout) {
945
- clearTimeout(this.current.timeout);
946
- this.current.timeout = null;
947
- }
948
- this.current = null;
949
- if (this.piper) {
950
- this.piper.stop();
951
- this.piper.resetPackets();
952
- }
953
-
954
- if (this.secret) {
955
- for (let i = 0; i < 5; i++) {
956
- this.sendAudioFrame(SILENCE_FRAME, this.frameSize);
957
- }
958
- }
959
- this.playing = false;
960
- this.setSpeaking(0);
961
-
962
- /**
963
- * Fired when the voice connection finishes playing a stream
964
- * @event VoiceConnection#end
965
- */
966
- this.emit("end");
967
- }
968
-
969
- /**
970
- * Switch the voice channel the bot is in. The channel to switch to must be in the same guild as the current voice channel
971
- * @arg {String} channelID The ID of the voice channel
972
- */
973
- switchChannel(channelID, reactive) {
974
- if (this.channelID === channelID) {
975
- return;
976
- }
977
-
978
- this.channelID = channelID;
979
- if (reactive) {
980
- if (this.reconnecting && !channelID) {
981
- this.disconnect();
982
- }
983
- } else {
984
- this.updateVoiceState();
985
- }
986
- }
987
-
988
- /**
989
- * Update the bot's voice state
990
- * @arg {Boolean} selfMute Whether the bot muted itself or not (audio receiving is unaffected)
991
- * @arg {Boolean} selfDeaf Whether the bot deafened itself or not (audio sending is unaffected)
992
- */
993
- updateVoiceState(selfMute, selfDeaf) {
994
- if (this.shard.sendWS) {
995
- this.shard.sendWS(GatewayOPCodes.VOICE_STATE_UPDATE, {
996
- guild_id: this.id === "call" ? null : this.id,
997
- channel_id: this.channelID || null,
998
- self_mute: !!selfMute,
999
- self_deaf: !!selfDeaf,
1000
- });
1001
- }
1002
- }
1003
-
1004
- _closeUDP() {
1005
- if (this.udpSocket) {
1006
- const udpSocket = this.udpSocket;
1007
- this.udpSocket = null;
1008
- try {
1009
- udpSocket.close();
1010
- } catch (err) {
1011
- if (err.message !== "Not running") {
1012
- this.emit("error", err);
1013
- }
1014
- }
1015
- }
1016
- }
1017
-
1018
- _daveDecrypt(userID, data) {
1019
- const session = this.daveSession;
1020
- if (!session.ready) {
1021
- if (this.daveProtocolVersion !== 0 && !this._daveDowngraded) {
1022
- return null; // The session isn't established yet
1023
- }
1024
- return data;
1025
- }
1026
- if (!userID) {
1027
- return null; // Unknown sender, can't be decrypted
1028
- }
1029
- try {
1030
- if (this._isDaveActive() || session.canPassthrough(userID)) {
1031
- data = session.decrypt(userID, DAVE_MEDIA_TYPE_AUDIO, data);
1032
- if (this._daveDecryptionFailures.size !== 0) {
1033
- // Only tracked while a user fails, so that the common case costs nothing
1034
- this._daveDecryptionFailures.delete(userID);
1035
- this._daveLastDecryption = Date.now();
1036
- this._daveLastDecryptionUserID = userID;
1037
- }
1038
- } else if (isDaveFrame(data)) {
1039
- return null;
1040
- }
1041
- return data;
1042
- } catch (err) {
1043
- if (!this._isDaveActive()) {
1044
- this.emit("debug", `Failed to decrypt end-to-end encrypted packet from ${userID} (session downgraded)`);
1045
- } else if (this._daveReinitializing || this._davePendingTransitions.size > 0) {
1046
- this.emit("debug", `Failed to decrypt end-to-end encrypted packet from ${userID} (session transitioning)`);
1047
- } else {
1048
- // Failures are counted per user, so that the packets of one user can't reset the count of another
1049
- const failures = (this._daveDecryptionFailures.get(userID) || 0) + 1;
1050
- this._daveDecryptionFailures.set(userID, failures);
1051
- this.emit("debug", `Failed to decrypt end-to-end encrypted packet from ${userID} (${failures} consecutive failures): ${err.message}`);
1052
- if (this.decryptionFailureTolerance > 0 && this._lastTransitionID !== null && failures > this.decryptionFailureTolerance) {
1053
- const now = Date.now();
1054
- // Packets from other users still decrypting means the session is fine and only this user's packets are broken
1055
- const othersDecrypt = this._daveLastDecryptionUserID !== userID && now - this._daveLastDecryption < DAVE_RECOVERY_INTERVAL;
1056
- if (!othersDecrypt && now - this._daveLastRecovery >= DAVE_RECOVERY_INTERVAL) {
1057
- this.emit("warn", `Failed to decrypt ${failures} consecutive end-to-end encrypted packets from ${userID}: ${err.message}`);
1058
- this._daveLastRecovery = now;
1059
- this._recoverFromInvalidTransition(this._lastTransitionID);
1060
- }
1061
- }
1062
- }
1063
- return null;
1064
- }
1065
- }
1066
-
1067
- _decryptPacket(msg, headerSize) {
1068
- const end = msg.length - NONCE_SUFFIX_SIZE;
1069
- if (end - headerSize < AUTH_TAG_SIZE) {
1070
- return null;
1071
- }
1072
- const nonce = this._receiveNonce;
1073
- msg.copy(nonce, 0, end);
1074
- try {
1075
- if (this.mode === ENCRYPTION_MODE_AES256) {
1076
- const decipher = NodeCrypto.createDecipheriv("aes-256-gcm", this.secret, nonce);
1077
- decipher.setAAD(msg.subarray(0, headerSize));
1078
- decipher.setAuthTag(msg.subarray(end - AUTH_TAG_SIZE, end));
1079
- const data = decipher.update(msg.subarray(headerSize, end - AUTH_TAG_SIZE));
1080
- decipher.final();
1081
- return data;
1082
- }
1083
- if (Sodium) {
1084
- const data = Buffer.allocUnsafe(end - headerSize - AUTH_TAG_SIZE);
1085
- Sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(data, null, msg.subarray(headerSize, end), msg.subarray(0, headerSize), nonce, this.secret);
1086
- return data;
1087
- }
1088
- const data = this._stablelib.open(nonce, msg.subarray(headerSize, end), msg.subarray(0, headerSize));
1089
- return data && Buffer.from(data.buffer, data.byteOffset, data.byteLength);
1090
- } catch {
1091
- return null;
1092
- }
1093
- }
1094
-
1095
- _destroy() {
1096
- if (this.opus) {
1097
- for (const key in this.opus) {
1098
- if (this.opus[key].delete) {
1099
- this.opus[key].delete();
1100
- }
1101
- delete this.opus[key];
1102
- }
1103
- }
1104
- delete this.piper;
1105
- if (this.receiveStreamOpus) {
1106
- this.receiveStreamOpus.removeAllListeners();
1107
- this.receiveStreamOpus = null;
1108
- }
1109
- if (this.receiveStreamPCM) {
1110
- this.receiveStreamPCM.removeAllListeners();
1111
- this.receiveStreamPCM = null;
1112
- }
1113
- }
1114
-
1115
- _executeDaveTransition(transitionID) {
1116
- if (!this._davePendingTransitions.has(transitionID)) {
1117
- this.emit("warn", `Received DAVE execute transition ${transitionID}, but it was not prepared`);
1118
- return false;
1119
- }
1120
- // Transition 0 is executed by the DAVE session itself
1121
- if (transitionID !== 0 && this.daveSession) {
1122
- let executed = false;
1123
- try {
1124
- executed = this.daveSession.executeTransition(transitionID);
1125
- } catch (err) {
1126
- this.emit("warn", `Failed to execute DAVE transition ${transitionID}: ${err.message}`);
1127
- }
1128
- if (!executed) {
1129
- this._davePendingTransitions.delete(transitionID);
1130
- return false;
1131
- }
1132
- }
1133
-
1134
- const oldVersion = this.daveProtocolVersion;
1135
- this.daveProtocolVersion = this._davePendingTransitions.get(transitionID);
1136
- this._davePendingTransitions.delete(transitionID);
1137
- if (oldVersion !== this.daveProtocolVersion && this.daveProtocolVersion === 0) {
1138
- this._daveDowngraded = true;
1139
- this.emit("debug", "DAVE protocol downgraded");
1140
- } else if (transitionID > 0 && this._daveDowngraded) {
1141
- this._daveDowngraded = false;
1142
- if (this.daveSession) {
1143
- this.daveSession.setPassthroughMode(false, 10);
1144
- }
1145
- this.emit("debug", "DAVE protocol upgraded");
1146
- }
1147
- this._daveReinitializing = false;
1148
- this._lastTransitionID = transitionID;
1149
- this.emit("debug", `DAVE transition ${transitionID} executed (protocol version ${oldVersion} -> ${this.daveProtocolVersion})`);
1150
- /**
1151
- * Fired when the end-to-end encryption of the call transitions to a new state (new participants, protocol version change...)
1152
- * @event VoiceConnection#daveTransition
1153
- * @prop {Number} transitionID The ID of the transition
1154
- * @prop {Number} protocolVersion The DAVE protocol version of the call after the transition. `0` means the call is not end-to-end encrypted anymore
1155
- */
1156
- this.emit("daveTransition", transitionID, this.daveProtocolVersion);
1157
- return true;
1158
- }
1159
-
1160
- _handleBinaryMessage(message) {
1161
- if (message.length < 3) {
1162
- return;
1163
- }
1164
- // Server binary messages: sequence (uint16) | opcode (uint8) | payload
1165
- this.wsSequence = message.readUInt16BE(0);
1166
- const op = message[2];
1167
- if (this.listeners("debug").length > 0) {
1168
- this.emit("debug", `Rec binary opcode ${op} (${message.length - 3} bytes)`);
1169
- }
1170
- if (op === VoiceOPCodes.DAVE_MLS_EXTERNAL_SENDER) {
1171
- this._daveExternalSender = message.subarray(3);
1172
- if (this.daveSession) {
1173
- try {
1174
- this.daveSession.setExternalSender(this._daveExternalSender);
1175
- this.emit("debug", "Set DAVE MLS external sender");
1176
- } catch (err) {
1177
- this.emit("warn", `Failed to set DAVE MLS external sender: ${err.message}`);
1178
- }
1179
- }
1180
- return;
1181
- }
1182
- if (!this.daveSession) {
1183
- return;
1184
- }
1185
- switch (op) {
1186
- case VoiceOPCodes.DAVE_MLS_PROPOSALS: {
1187
- try {
1188
- const result = this.daveSession.processProposals(message[3], message.subarray(4), this._recognizedUsers());
1189
- if (result.commit) {
1190
- this.sendWSBinary(VoiceOPCodes.DAVE_MLS_COMMIT_WELCOME, result.welcome ? Buffer.concat([result.commit, result.welcome]) : result.commit);
1191
- }
1192
- } catch (err) {
1193
- this.emit("warn", `Failed to process DAVE MLS proposals: ${err.message}`);
1194
- if (this._lastTransitionID !== null) {
1195
- if (!this._daveReinitializing) {
1196
- this._recoverFromInvalidTransition(this._lastTransitionID);
1197
- }
1198
- } else {
1199
- this.disconnect(new Error("Failed to process DAVE MLS proposals"));
1200
- }
1201
- }
1202
- break;
1203
- }
1204
- case VoiceOPCodes.DAVE_MLS_ANNOUNCE_COMMIT_TRANSITION:
1205
- case VoiceOPCodes.DAVE_MLS_WELCOME: {
1206
- const transitionID = message.readUInt16BE(3);
1207
- try {
1208
- if (op === VoiceOPCodes.DAVE_MLS_WELCOME) {
1209
- this.daveSession.processWelcome(message.subarray(5), this._recognizedUsers());
1210
- } else if (!this.daveSession.processCommit(message.subarray(5))) {
1211
- this.emit("debug", `DAVE MLS commit ignored (transition ${transitionID})`);
1212
- break;
1213
- }
1214
- this.daveSession.prepareTransition(transitionID, this.daveSession.protocolVersion);
1215
- this._davePendingTransitions.set(transitionID, this.daveSession.protocolVersion);
1216
- // Transition ID 0 is a (re)initialization and is executed immediately
1217
- if (transitionID === 0) {
1218
- this._executeDaveTransition(0);
1219
- } else {
1220
- this.sendWS(VoiceOPCodes.DAVE_TRANSITION_READY, {
1221
- transition_id: transitionID,
1222
- });
1223
- }
1224
- } catch (err) {
1225
- this.emit("warn", `Failed to process DAVE MLS ${op === VoiceOPCodes.DAVE_MLS_WELCOME ? "welcome" : "commit"} (transition ${transitionID}): ${err.message}`);
1226
- this._recoverFromInvalidTransition(transitionID);
1227
- }
1228
- break;
1229
- }
1230
- }
1231
- }
1232
-
1233
- _isDaveActive() {
1234
- return this.daveProtocolVersion !== 0 && !this._daveDowngraded && !!this.daveSession && this.daveSession.ready;
1235
- }
1236
-
1237
- _onUDPMessage(msg) {
1238
- // RTP version 2 and Opus payload type only
1239
- if (!this._receiveNonce || msg.length < RTP_HEADER_SIZE + AUTH_TAG_SIZE + NONCE_SUFFIX_SIZE || msg[1] !== 0x78 || (msg[0] >> 6) !== 2) {
1240
- return;
1241
- }
1242
- const hasPadding = !!(msg[0] & 0b100000);
1243
- const hasExtension = !!(msg[0] & 0b10000);
1244
- // With rtpsize modes, the header, the CSRCs and the extension header are unencrypted, and the extension data is encrypted
1245
- const headerSize = RTP_HEADER_SIZE + (msg[0] & 0b1111) * 4 + (hasExtension ? 4 : 0);
1246
- let data = this._decryptPacket(msg, headerSize);
1247
- if (!data) {
1248
- this.emit("warn", "Failed to decrypt received packet");
1249
- return;
1250
- }
1251
- if (hasPadding && data.length > 0 && data[data.length - 1] <= data.length) {
1252
- data = data.subarray(0, data.length - data[data.length - 1]);
1253
- }
1254
- if (hasExtension) { // RFC3550 5.3.1: RTP Header Extension, length in 32-bit words
1255
- data = data.subarray(msg.readUInt16BE(headerSize - 2) * 4);
1256
- }
1257
- if (data.length === 0) {
1258
- return;
1259
- }
1260
-
1261
- const userID = this.ssrcUserMap[msg.readUInt32BE(8)];
1262
- if (this.daveSession && !isSilenceFrame(data)) {
1263
- data = this._daveDecrypt(userID, data);
1264
- if (!data) {
1265
- return;
1266
- }
1267
- }
1268
- const timestamp = msg.readUInt32BE(4);
1269
- const sequence = msg.readUInt16BE(2);
1270
- if (this.receiveStreamOpus) {
1271
- /**
1272
- * Fired when a voice data packet is received
1273
- * @event VoiceDataStream#data
1274
- * @prop {Buffer} data The voice data
1275
- * @prop {String} userID The user who sent the voice packet
1276
- * @prop {Number} timestamp The intended timestamp of the packet
1277
- * @prop {Number} sequence The intended sequence number of the packet
1278
- */
1279
- this.receiveStreamOpus.emit("data", data, userID, timestamp, sequence);
1280
- }
1281
- if (this.receiveStreamPCM) {
1282
- if (!this.opus[userID]) {
1283
- this.opus[userID] = createOpus(this.samplingRate, this.channels, this.bitrate);
1284
- }
1285
-
1286
- data = this.opus[userID].decode(data, this.frameSize);
1287
- if (!data) {
1288
- return this.emit("warn", "Failed to decode received packet");
1289
- }
1290
- this.receiveStreamPCM.emit("data", data, userID, timestamp, sequence);
1291
- }
1292
- }
1293
-
1294
- _recognizedUsers() {
1295
- return Array.from(this._connectedUsers).concat(this._userID);
1296
- }
1297
-
1298
- _recoverFromInvalidTransition(transitionID) {
1299
- this.emit("warn", `Invalidating DAVE transition ${transitionID}`);
1300
- this._daveReinitializing = true;
1301
- this._daveDecryptionFailures.clear();
1302
- this.sendWS(VoiceOPCodes.DAVE_MLS_INVALID_COMMIT_WELCOME, {
1303
- transition_id: transitionID,
1304
- });
1305
- this._reinitDaveSession();
1306
- }
1307
-
1308
- _reinitDaveSession() {
1309
- // Resetting the session drops its prepared transitions
1310
- this._davePendingTransitions.clear();
1311
- if (this.daveProtocolVersion > 0 && this.daveEnabled) {
1312
- if (this.daveSession) {
1313
- this.daveSession.reinit(this.daveProtocolVersion, this._userID, this.channelID);
1314
- this.emit("debug", `DAVE session reinitialized (protocol version ${this.daveProtocolVersion})`);
1315
- } else {
1316
- this.daveSession = new Davey.DAVESession(this.daveProtocolVersion, this._userID, this.channelID);
1317
- this.emit("debug", `DAVE session initialized (protocol version ${this.daveProtocolVersion})`);
1318
- }
1319
- if (this._daveExternalSender) {
1320
- try {
1321
- this.daveSession.setExternalSender(this._daveExternalSender);
1322
- } catch {} // eslint-disable-line no-empty
1323
- }
1324
- // When upgrading, unencrypted frames are still received until the transition is executed
1325
- if (this._daveDowngraded) {
1326
- this.daveSession.setPassthroughMode(true);
1327
- }
1328
- this.sendWSBinary(VoiceOPCodes.DAVE_MLS_KEY_PACKAGE, this.daveSession.getSerializedKeyPackage());
1329
- } else if (this.daveSession) {
1330
- this.daveSession.reset();
1331
- this.daveSession.setPassthroughMode(true);
1332
- this.emit("debug", "DAVE session reset");
1333
- }
1334
- }
1335
-
1336
- _send() {
1337
- if (!this.piper.encoding && this.piper.dataPacketCount === 0) {
1338
- return this.stopPlaying();
1339
- }
1340
-
1341
- if ((this.current.buffer = this.piper.getDataPacket())) {
1342
- if (this.current.startTime === 0) {
1343
- this.current.startTime = Date.now();
1344
- }
1345
- if (this.current.bufferingTicks > 0) {
1346
- this.current.bufferingTicks = 0;
1347
- this.setSpeaking(1);
1348
- }
1349
- } else if (this.current.options.voiceDataTimeout === -1 || this.current.bufferingTicks < this.current.options.voiceDataTimeout / (4 * this.current.options.frameDuration)) { // wait for data
1350
- if (++this.current.bufferingTicks === 1) {
1351
- this.setSpeaking(0);
1352
- }
1353
- this.current.pausedTime += 4 * this.current.options.frameDuration;
1354
- this.timestamp = (this.timestamp + 3 * this.current.options.frameSize) >>> 0;
1355
- this.current.timeout = setTimeout(this._send, 4 * this.current.options.frameDuration);
1356
- return;
1357
- } else {
1358
- return this.stopPlaying();
1359
- }
1360
-
1361
- this.sendAudioFrame(this.current.buffer, this.current.options.frameSize);
1362
- this.current.playTime += this.current.options.frameDuration;
1363
- this.current.timeout = setTimeout(this._send, Math.max(0, this.current.startTime + this.current.pausedTime + this.current.playTime - Date.now()));
1364
- }
1365
-
1366
- _sendAudioFrame(frame) {
1367
- if (!this._sendNonce) {
1368
- return;
1369
- }
1370
- if (this.daveProtocolVersion !== 0 && !this._daveDowngraded && this.daveSession && !isSilenceFrame(frame)) {
1371
- // In an end-to-end encrypted call, frames are dropped until they can be encrypted (MLS group joined and transition executed) to never leak unencrypted audio
1372
- if (!this.daveSession.ready || !this.daveSession.canEncrypt) {
1373
- return;
1374
- }
1375
- try {
1376
- frame = this.daveSession.encryptOpus(frame);
1377
- } catch (err) {
1378
- this.emit("warn", `Failed to end-to-end encrypt audio frame: ${err.message}`);
1379
- return;
1380
- }
1381
- }
1382
-
1383
- const header = this.sendHeader;
1384
- header.writeUInt16BE(this.sequence, 2);
1385
- header.writeUInt32BE(this.timestamp, 4);
1386
- this._nonce = (this._nonce + 1) >>> 0;
1387
- this._sendNonce.writeUInt32BE(this._nonce, 0);
1388
-
1389
- // UDP sends are asynchronous, each packet needs its own buffer (small allocations are taken from Node's buffer pool)
1390
- const packet = Buffer.allocUnsafe(RTP_HEADER_SIZE + frame.length + AUTH_TAG_SIZE + NONCE_SUFFIX_SIZE);
1391
- header.copy(packet, 0);
1392
- const end = RTP_HEADER_SIZE + frame.length + AUTH_TAG_SIZE;
1393
- if (this.mode === ENCRYPTION_MODE_AES256) {
1394
- const cipher = NodeCrypto.createCipheriv("aes-256-gcm", this.secret, this._sendNonce);
1395
- cipher.setAAD(header);
1396
- cipher.update(frame).copy(packet, RTP_HEADER_SIZE);
1397
- cipher.final();
1398
- cipher.getAuthTag().copy(packet, end - AUTH_TAG_SIZE);
1399
- } else if (Sodium) {
1400
- Sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(packet.subarray(RTP_HEADER_SIZE, end), frame, header, null, this._sendNonce, this.secret);
1401
- } else {
1402
- this._stablelib.seal(this._sendNonce, frame, header, packet.subarray(RTP_HEADER_SIZE, end));
1403
- }
1404
- this._sendNonce.copy(packet, end, 0, NONCE_SUFFIX_SIZE);
1405
- return this.sendUDPPacket(packet);
1406
- }
1407
-
1408
- /** @deprecated */
1409
- _sendAudioPacket(audio) {
1410
- return this._sendAudioFrame(audio);
1411
- }
1412
-
1413
- [util.inspect.custom]() {
1414
- return Base.prototype[util.inspect.custom].call(this);
1415
- }
1416
-
1417
- toString() {
1418
- return `[VoiceConnection ${this.channelID}]`;
1419
- }
1420
-
1421
- toJSON(props = []) {
1422
- return Base.prototype.toJSON.call(this, [
1423
- "channelID",
1424
- "connecting",
1425
- "current",
1426
- "daveProtocolVersion",
1427
- "id",
1428
- "mode",
1429
- "paused",
1430
- "playing",
1431
- "ready",
1432
- "volume",
1433
- ...props,
1434
- ]);
1435
- }
1436
- }
1437
-
1438
- VoiceConnection._converterCommand = converterCommand;
1439
-
1440
- module.exports = VoiceConnection;
1
+ "use strict";
2
+
3
+ const util = require("util");
4
+ const Base = require("../structures/Base");
5
+ const ChildProcess = require("child_process");
6
+ const { GatewayOPCodes, VOICE_VERSION, VoiceOPCodes } = require("../Constants");
7
+ const Dgram = require("dgram");
8
+ const Net = require("net");
9
+ const Piper = require("./Piper");
10
+ const VoiceDataStream = require("./VoiceDataStream");
11
+ const { createOpus } = require("../util/Opus");
12
+
13
+ const WebSocket = typeof window !== "undefined" ? require("../util/BrowserWebSocket") : require("ws");
14
+
15
+ let EventEmitter;
16
+ try {
17
+ EventEmitter = require("eventemitter3");
18
+ } catch {
19
+ EventEmitter = require("events").EventEmitter;
20
+ }
21
+
22
+ let NodeCrypto = null;
23
+ let Davey = null;
24
+ let Sodium = null;
25
+ let StableLib = null;
26
+ let aes256Available = false;
27
+ let librariesLoaded = false;
28
+
29
+ const ENCRYPTION_MODE_AES256 = "aead_aes256_gcm_rtpsize";
30
+ const ENCRYPTION_MODE_XCHACHA20 = "aead_xchacha20_poly1305_rtpsize";
31
+ const DAVE_MEDIA_TYPE_AUDIO = 0;
32
+ const DAVE_RECOVERY_INTERVAL = 10000;
33
+ const AUTH_TAG_SIZE = 16;
34
+ const IP_DISCOVERY_TIMEOUT = 10000;
35
+ const NONCE_SUFFIX_SIZE = 4;
36
+ const RTP_HEADER_SIZE = 12;
37
+ const SILENCE_FRAME = Buffer.from([0xF8, 0xFF, 0xFE]);
38
+ const UDP_KEEP_ALIVE = Buffer.from([0x80, 0xC8, 0x0, 0x0]);
39
+
40
+ function loadLibraries() {
41
+ if (librariesLoaded) {
42
+ return;
43
+ }
44
+ librariesLoaded = true;
45
+ try {
46
+ NodeCrypto = require("crypto");
47
+ aes256Available = NodeCrypto.getCiphers().includes("aes-256-gcm");
48
+ } catch {} // eslint-disable-line no-empty
49
+ try {
50
+ Sodium = require("sodium-native");
51
+ if (typeof Sodium.crypto_aead_xchacha20poly1305_ietf_encrypt !== "function") {
52
+ Sodium = null;
53
+ }
54
+ } catch {} // eslint-disable-line no-empty
55
+ if (!Sodium) {
56
+ try {
57
+ StableLib = require("@stablelib/xchacha20poly1305");
58
+ } catch {} // eslint-disable-line no-empty
59
+ }
60
+ try {
61
+ Davey = require("@snazzah/davey");
62
+ } catch {} // eslint-disable-line no-empty
63
+ }
64
+
65
+ // Sorted by preference
66
+ function getAvailableEncryptionModes() {
67
+ const modes = [];
68
+ if (aes256Available) {
69
+ modes.push(ENCRYPTION_MODE_AES256);
70
+ }
71
+ if (Sodium || StableLib) {
72
+ modes.push(ENCRYPTION_MODE_XCHACHA20);
73
+ }
74
+ return modes;
75
+ }
76
+
77
+ // DAVE encrypted frames end with the 0xFAFA magic marker
78
+ function isDaveFrame(frame) {
79
+ return frame.length > 2 && frame[frame.length - 1] === 0xFA && frame[frame.length - 2] === 0xFA;
80
+ }
81
+
82
+ // Opus silence frames are never end-to-end encrypted
83
+ function isSilenceFrame(frame) {
84
+ return frame.length === 3 && frame[0] === 0xF8 && frame[1] === 0xFF && frame[2] === 0xFE;
85
+ }
86
+
87
+ const converterCommand = {
88
+ cmd: null,
89
+ libopus: false,
90
+ };
91
+
92
+ converterCommand.pickCommand = function pickCommand() {
93
+ let tenative;
94
+ for (const command of ["./ffmpeg", "./avconv", "ffmpeg", "avconv"]) {
95
+ const res = ChildProcess.spawnSync(command, ["-encoders"]);
96
+ if (!res.error) {
97
+ if (!res.stdout.toString().includes("libopus")) {
98
+ tenative = command;
99
+ continue;
100
+ }
101
+ converterCommand.cmd = command;
102
+ converterCommand.libopus = true;
103
+ return;
104
+ }
105
+ }
106
+ if (tenative) {
107
+ converterCommand.cmd = tenative;
108
+ return;
109
+ }
110
+ };
111
+
112
+ /**
113
+ * Represents a voice connection
114
+ * Transport encryption uses AES-256-GCM through Node.js' crypto module, or XChaCha20-Poly1305 through `sodium-native` or `@stablelib/xchacha20poly1305`.
115
+ * End-to-end encryption (DAVE protocol, required by Discord for voice channels) needs the optional `@snazzah/davey` dependency
116
+ * @extends EventEmitter
117
+ * @prop {String} channelID The ID of the voice connection's current channel
118
+ * @prop {Boolean} connecting Whether the voice connection is connecting
119
+ * @prop {Object?} current The state of the currently playing stream
120
+ * @prop {Object} current.options The custom options for the current stream
121
+ * @prop {Array<String>?} current.options.encoderArgs Additional encoder parameters to pass to ffmpeg/avconv (after -i)
122
+ * @prop {String?} current.options.format The format of the resource. If null, FFmpeg will attempt to guess and play the format. Available options: "dca", "ogg", "webm", "pcm", "opusPackets", null
123
+ * @prop {Number?} current.options.frameDuration The resource opus frame duration (required for DCA/Ogg)
124
+ * @prop {Number?} current.options.frameSize The resource opus frame size
125
+ * @prop {Boolean?} current.options.inlineVolume Whether to enable on-the-fly volume changing. Note that enabling this leads to increased CPU usage
126
+ * @prop {Array<String>?} current.options.inputArgs Additional input parameters to pass to ffmpeg/avconv (before -i)
127
+ * @prop {Number?} current.options.sampleRate The resource audio sampling rate
128
+ * @prop {Number?} current.options.voiceDataTimeout Timeout when waiting for voice data (-1 for no timeout)
129
+ * @prop {Number} current.pausedTime How long the current stream has been paused for, in milliseconds
130
+ * @prop {Number} current.pausedTimestamp The timestamp of the most recent pause
131
+ * @prop {Number} current.playTime How long the current stream has been playing for, in milliseconds
132
+ * @prop {Number} current.startTime The timestamp of the start of the current stream
133
+ * @prop {Boolean} daveEnabled Whether the connection supports end-to-end encryption (DAVE protocol). Requires the `@snazzah/davey` package
134
+ * @prop {Number} daveProtocolVersion The DAVE protocol version used by the call. `0` means the call is not end-to-end encrypted
135
+ * @prop {Object?} daveSession The `@snazzah/davey` DAVE session, if the call is end-to-end encrypted
136
+ * @prop {Number} decryptionFailureTolerance The number of consecutive end-to-end decryption failures from a single user after which the DAVE session is recovered (0 to never recover). Recoveries are at least 10 seconds apart, and skipped while packets from other users still decrypt
137
+ * @prop {String} id The ID of the voice connection (guild ID)
138
+ * @prop {String?} mode The transport encryption mode of the connection
139
+ * @prop {Boolean} paused Whether the voice connection is paused
140
+ * @prop {Boolean} playing Whether the voice connection is playing something
141
+ * @prop {Boolean} ready Whether the voice connection is ready
142
+ * @prop {Boolean} resuming Whether the voice connection is waiting for resuming
143
+ * @prop {String?} voicePrivacyCode The voice privacy code of the call, if it is end-to-end encrypted. It matches the code displayed in the Discord client
144
+ * @prop {Number} volume The current volume level of the connection
145
+ * @prop {Number} wsSequence The sequence number of the last numbered message received from the voice gateway
146
+ */
147
+ class VoiceConnection extends EventEmitter {
148
+ constructor(id, options = {}) {
149
+ super();
150
+
151
+ if (typeof window !== "undefined") {
152
+ throw new Error("Voice is not supported in browsers at this time");
153
+ }
154
+
155
+ loadLibraries();
156
+ if (getAvailableEncryptionModes().length === 0) {
157
+ throw new Error("No voice encryption available. Use a Node.js build supporting AES-256-GCM, or install sodium-native or @stablelib/xchacha20poly1305");
158
+ }
159
+
160
+ this.id = id;
161
+ this.samplingRate = 48000;
162
+ this.channels = 2;
163
+ this.frameDuration = 20;
164
+ this.frameSize = this.samplingRate * this.frameDuration / 1000;
165
+ this.pcmSize = this.frameSize * this.channels * 2;
166
+ this.bitrate = 64000;
167
+ this.shared = !!options.shared;
168
+ this.shard = options.shard || {};
169
+ this.opusOnly = !!options.opusOnly;
170
+ this.daveEnabled = options.daveEncryption !== false && !!Davey;
171
+ this.decryptionFailureTolerance = options.decryptionFailureTolerance !== undefined ? options.decryptionFailureTolerance : 36;
172
+
173
+ if (!this.opusOnly && !this.shared) {
174
+ this.opus = {};
175
+ }
176
+
177
+ this.channelID = null;
178
+ this.paused = true;
179
+ this.speaking = false;
180
+ this.sequence = 0;
181
+ this.timestamp = 0;
182
+ this.ssrcUserMap = {};
183
+ this.connectionTimeout = null;
184
+ this.connecting = false;
185
+ this.reconnecting = false;
186
+ this.resuming = false;
187
+ this.ready = false;
188
+ this.sessionID = null;
189
+ this.token = null;
190
+ this.wsSequence = -1;
191
+
192
+ this.daveProtocolVersion = 0;
193
+ this.daveSession = null;
194
+ this._connectedUsers = new Set();
195
+ this._daveDecryptionFailures = new Map();
196
+ this._daveDowngraded = false;
197
+ this._daveExternalSender = null;
198
+ this._daveLastDecryption = 0;
199
+ this._daveLastDecryptionUserID = null;
200
+ this._daveLastRecovery = 0;
201
+ this._davePendingTransitions = new Map();
202
+ this._daveReinitializing = false;
203
+ this._daveWarned = false;
204
+ this._ipDiscoveryTimeout = null;
205
+ this._lastTransitionID = null;
206
+ this._nonce = 0;
207
+ this._receiveNonce = null;
208
+ this._receiveSocket = null;
209
+ this._sendNonce = null;
210
+ this._stablelib = null;
211
+ this._userID = null;
212
+
213
+ this.sendHeader = Buffer.alloc(RTP_HEADER_SIZE);
214
+ this.sendHeader[0] = 0x80;
215
+ this.sendHeader[1] = 0x78;
216
+
217
+ if (!options.shared) {
218
+ if (!converterCommand.cmd) {
219
+ converterCommand.pickCommand();
220
+ }
221
+
222
+ this.piper = new Piper(converterCommand.cmd, () => createOpus(this.samplingRate, this.channels, this.bitrate));
223
+ /**
224
+ * Fired when the voice connection encounters an error. This event should be handled by users
225
+ * @event VoiceConnection#error
226
+ * @prop {Error} err The error object
227
+ */
228
+ this.piper.on("error", (e) => this.emit("error", e));
229
+ if (!converterCommand.libopus) {
230
+ this.piper.libopus = false;
231
+ }
232
+ }
233
+
234
+ this._send = this._send.bind(this);
235
+ }
236
+
237
+ get voicePrivacyCode() {
238
+ return (this.daveSession && this.daveSession.voicePrivacyCode) || null;
239
+ }
240
+
241
+ get volume() {
242
+ return this.piper.volumeLevel;
243
+ }
244
+
245
+ connect(data) {
246
+ this.connecting = true;
247
+ if (this.ws && this.ws.readyState !== WebSocket.CLOSED) {
248
+ this.disconnect(undefined, true);
249
+ setTimeout(() => {
250
+ if (!this.connecting && !this.ready) {
251
+ this.connect(data);
252
+ }
253
+ }, 500).unref();
254
+ return;
255
+ }
256
+ clearTimeout(this.connectionTimeout);
257
+ this.connectionTimeout = setTimeout(() => {
258
+ if (this.connecting) {
259
+ this.disconnect(new Error("Voice connection timeout"));
260
+ }
261
+ this.connectionTimeout = null;
262
+ }, this.shard.client ? this.shard.client.options.connectionTimeout : 30000).unref();
263
+ if (!data.endpoint) {
264
+ return; // Endpoint null, wait next update.
265
+ }
266
+ if (!data.token || !data.session_id || !data.user_id) {
267
+ this.disconnect(new Error("Malformed voice server update: " + JSON.stringify(data)));
268
+ return;
269
+ }
270
+ this.channelID = data.channel_id;
271
+ this._userID = data.user_id;
272
+ const lastEndpoint = this.endpoint ? this.endpoint.hostname : null;
273
+ this.endpoint = new URL(`wss://${data.endpoint}`);
274
+ if (this.endpoint.port === "80") {
275
+ this.endpoint.port = "";
276
+ }
277
+ this.endpoint.searchParams.set("v", VOICE_VERSION);
278
+ this.resuming = this.reconnecting && !!this.udpSocket && data.session_id === this.sessionID && data.token === this.token && lastEndpoint === this.endpoint.hostname;
279
+ const ws = this.ws = new WebSocket(this.endpoint.href);
280
+ /**
281
+ * Fired when stuff happens and gives more info
282
+ * @event VoiceConnection#debug
283
+ * @prop {String} message The debug message
284
+ */
285
+ this.emit("debug", "Connection: " + JSON.stringify(data));
286
+ ws.on("open", () => {
287
+ if (this.ws !== ws) {
288
+ return;
289
+ }
290
+ /**
291
+ * Fired when the voice connection connects
292
+ * @event VoiceConnection#connect
293
+ */
294
+ this.emit("connect");
295
+ if (this.connectionTimeout) {
296
+ clearTimeout(this.connectionTimeout);
297
+ this.connectionTimeout = null;
298
+ }
299
+ if (this.resuming) {
300
+ this.emit("debug", `Resuming session (sequence ${this.wsSequence})`);
301
+ this.sendWS(VoiceOPCodes.RESUME, {
302
+ server_id: this.id,
303
+ session_id: data.session_id,
304
+ token: data.token,
305
+ seq_ack: this.wsSequence,
306
+ });
307
+ } else {
308
+ this._closeUDP();
309
+ this._connectedUsers.clear();
310
+ this._daveDecryptionFailures.clear();
311
+ this.wsSequence = -1;
312
+ if (!this.daveEnabled && !this._daveWarned) {
313
+ this._daveWarned = true;
314
+ /**
315
+ * Fired to warn of something weird but non-breaking happening
316
+ * @event VoiceConnection#warn
317
+ * @prop {String} message The warning message
318
+ */
319
+ this.emit("warn", "End-to-end encryption (DAVE protocol) is not available" + (Davey ? "" : ", install @snazzah/davey to enable it") + ". Discord will refuse the connection for channels requiring it");
320
+ }
321
+ this.sendWS(VoiceOPCodes.IDENTIFY, {
322
+ server_id: this.id,
323
+ user_id: data.user_id,
324
+ session_id: data.session_id,
325
+ token: data.token,
326
+ max_dave_protocol_version: this.daveEnabled ? Davey.DAVE_PROTOCOL_VERSION : 0,
327
+ });
328
+ }
329
+ });
330
+ ws.on("message", (m, isBinary) => {
331
+ if (this.ws !== ws) {
332
+ return;
333
+ }
334
+ if (isBinary) {
335
+ if (m instanceof ArrayBuffer) {
336
+ m = Buffer.from(m);
337
+ } else if (Array.isArray(m)) {
338
+ m = Buffer.concat(m);
339
+ }
340
+ return this._handleBinaryMessage(m);
341
+ }
342
+ const packet = JSON.parse(m);
343
+ if (this.listeners("debug").length > 0) {
344
+ this.emit("debug", "Rec: " + JSON.stringify(packet));
345
+ }
346
+ if (packet.seq !== undefined) {
347
+ this.wsSequence = packet.seq;
348
+ }
349
+ switch (packet.op) {
350
+ case VoiceOPCodes.READY: {
351
+ this.ssrc = packet.d.ssrc;
352
+ this.sendHeader.writeUInt32BE(this.ssrc, 8);
353
+
354
+ this.modes = packet.d.modes;
355
+ const mode = getAvailableEncryptionModes().find((mode) => packet.d.modes.includes(mode));
356
+ if (!mode) {
357
+ this.disconnect(new Error("No supported voice encryption mode found. Available modes: " + packet.d.modes.join(", ")));
358
+ return;
359
+ }
360
+
361
+ this.udpIP = packet.d.ip;
362
+ this.udpPort = packet.d.port;
363
+ this.sessionID = data.session_id;
364
+ this.token = data.token;
365
+
366
+ this.emit("debug", "Connecting to UDP: " + this.udpIP + ":" + this.udpPort);
367
+
368
+ const udpSocket = this.udpSocket = Dgram.createSocket(Net.isIPv6(this.udpIP) ? "udp6" : "udp4");
369
+ udpSocket.on("error", (err, msg) => {
370
+ if (this.udpSocket !== udpSocket) {
371
+ return;
372
+ }
373
+ this.emit("error", err);
374
+ if (msg) {
375
+ this.emit("debug", "Voice UDP error: " + msg);
376
+ }
377
+ if (this.ready || this.connecting) {
378
+ this.disconnect(err);
379
+ }
380
+ });
381
+ udpSocket.once("message", (packet) => {
382
+ if (this.udpSocket !== udpSocket) {
383
+ return;
384
+ }
385
+ clearTimeout(this._ipDiscoveryTimeout);
386
+ this._ipDiscoveryTimeout = null;
387
+ let i = 8;
388
+ while (packet[i] !== 0) {
389
+ i++;
390
+ }
391
+ const localIP = packet.toString("ascii", 8, i);
392
+ const localPort = packet.readUInt16BE(packet.length - 2);
393
+ this.emit("debug", `Discovered IP: ${localIP}:${localPort} (${packet.toString("hex")})`);
394
+
395
+ this.sendWS(VoiceOPCodes.SELECT_PROTOCOL, {
396
+ protocol: "udp",
397
+ data: {
398
+ address: localIP,
399
+ port: localPort,
400
+ mode: mode,
401
+ },
402
+ });
403
+ });
404
+ udpSocket.on("close", (err) => {
405
+ if (this.udpSocket !== udpSocket) {
406
+ return;
407
+ }
408
+ if (err) {
409
+ this.emit("warn", "Voice UDP close: " + err);
410
+ }
411
+ if (this.ready || this.connecting) {
412
+ this.disconnect(err);
413
+ }
414
+ });
415
+ clearTimeout(this._ipDiscoveryTimeout);
416
+ this._ipDiscoveryTimeout = setTimeout(() => {
417
+ this._ipDiscoveryTimeout = null;
418
+ if (this.udpSocket === udpSocket && !this.ready) {
419
+ this.disconnect(new Error("Voice IP discovery timeout"));
420
+ }
421
+ }, IP_DISCOVERY_TIMEOUT).unref();
422
+ const udpMessage = Buffer.alloc(74);
423
+ udpMessage.writeUInt16BE(0x1, 0);
424
+ udpMessage.writeUInt16BE(70, 2);
425
+ udpMessage.writeUInt32BE(this.ssrc, 4);
426
+ this.sendUDPPacket(udpMessage);
427
+ break;
428
+ }
429
+ case VoiceOPCodes.RESUMED: {
430
+ this.connecting = false;
431
+ this.reconnecting = false;
432
+ this.resuming = false;
433
+ this.ready = true;
434
+ /**
435
+ * Fired when the voice connection resumes its session
436
+ * @event VoiceConnection#resumed
437
+ */
438
+ this.emit("resumed");
439
+ this.resume();
440
+ break;
441
+ }
442
+ case VoiceOPCodes.SESSION_DESCRIPTION: {
443
+ this.mode = packet.d.mode;
444
+ this.secret = Buffer.from(packet.d.secret_key);
445
+ const nonceSize = this.mode === ENCRYPTION_MODE_AES256 ? 12 : 24;
446
+ this._nonce = 0;
447
+ this._receiveNonce = Buffer.alloc(nonceSize);
448
+ this._sendNonce = Buffer.alloc(nonceSize);
449
+ this._stablelib = this.mode === ENCRYPTION_MODE_XCHACHA20 && !Sodium ? new StableLib.XChaCha20Poly1305(this.secret) : null;
450
+ this.daveProtocolVersion = packet.d.dave_protocol_version || 0;
451
+ this._daveDowngraded = this.daveProtocolVersion === 0;
452
+ this.connecting = false;
453
+ this.reconnecting = false;
454
+ this.resuming = false;
455
+ this.ready = true;
456
+ this._reinitDaveSession();
457
+ // Send audio to properly establish the socket (e.g. for voice receive)
458
+ this.sendAudioFrame(SILENCE_FRAME, this.frameSize);
459
+ /**
460
+ * Fired when the voice connection turns ready
461
+ * @event VoiceConnection#ready
462
+ */
463
+ this.emit("ready");
464
+ this.resume();
465
+ if (this.receiveStreamOpus || this.receiveStreamPCM) {
466
+ this.registerReceiveEventHandler();
467
+ }
468
+ break;
469
+ }
470
+ case VoiceOPCodes.HEARTBEAT_ACK: {
471
+ /**
472
+ * Fired when the voice connection receives a pong
473
+ * @event VoiceConnection#pong
474
+ * @prop {Number} latency The current latency in milliseconds
475
+ */
476
+ this.emit("pong", Date.now() - (packet.d && typeof packet.d === "object" ? packet.d.t : packet.d));
477
+ break;
478
+ }
479
+ case VoiceOPCodes.SPEAKING: {
480
+ this.ssrcUserMap[packet.d.ssrc] = packet.d.user_id;
481
+ /**
482
+ * Fired when a user begins speaking
483
+ * @event VoiceConnection#speakingStart
484
+ * @prop {String} userID The ID of the user that began speaking
485
+ */
486
+ /**
487
+ * Fired when a user stops speaking
488
+ * @event VoiceConnection#speakingStop
489
+ * @prop {String} userID The ID of the user that stopped speaking
490
+ */
491
+ this.emit(packet.d.speaking ? "speakingStart" : "speakingStop", packet.d.user_id);
492
+ break;
493
+ }
494
+ case VoiceOPCodes.HELLO: {
495
+ if (this.heartbeatInterval) {
496
+ clearInterval(this.heartbeatInterval);
497
+ }
498
+ this.heartbeatInterval = setInterval(() => {
499
+ this.heartbeat();
500
+ }, packet.d.heartbeat_interval);
501
+
502
+ this.heartbeat();
503
+ break;
504
+ }
505
+ case VoiceOPCodes.CLIENTS_CONNECT: {
506
+ for (const userID of packet.d.user_ids) {
507
+ this._connectedUsers.add(userID);
508
+ }
509
+ /**
510
+ * Fired when one or more clients connect to the voice channel
511
+ * @event VoiceConnection#usersConnect
512
+ * @prop {String[]} userIDs The IDs of the users that connected
513
+ */
514
+ this.emit("usersConnect", packet.d.user_ids);
515
+ break;
516
+ }
517
+ case VoiceOPCodes.CLIENT_DISCONNECT: {
518
+ if (this.opus) {
519
+ // opusscript requires manual cleanup
520
+ if (this.opus[packet.d.user_id] && this.opus[packet.d.user_id].delete) {
521
+ this.opus[packet.d.user_id].delete();
522
+ }
523
+
524
+ delete this.opus[packet.d.user_id];
525
+ }
526
+
527
+ this._connectedUsers.delete(packet.d.user_id);
528
+ this._daveDecryptionFailures.delete(packet.d.user_id);
529
+ for (const ssrc in this.ssrcUserMap) {
530
+ if (this.ssrcUserMap[ssrc] === packet.d.user_id) {
531
+ delete this.ssrcUserMap[ssrc];
532
+ }
533
+ }
534
+
535
+ /**
536
+ * Fired when a user disconnects from the voice server
537
+ * @event VoiceConnection#userDisconnect
538
+ * @prop {String} userID The ID of the user that disconnected
539
+ */
540
+ this.emit("userDisconnect", packet.d.user_id);
541
+ break;
542
+ }
543
+ case VoiceOPCodes.DAVE_PREPARE_TRANSITION: {
544
+ this.emit("debug", `Preparing DAVE transition ${packet.d.transition_id} (protocol version ${packet.d.protocol_version})`);
545
+ this._davePendingTransitions.set(packet.d.transition_id, packet.d.protocol_version);
546
+ if (this.daveSession) {
547
+ this.daveSession.prepareTransition(packet.d.transition_id, packet.d.protocol_version);
548
+ // Downgrading to transport-only encryption, unencrypted frames can be received right away
549
+ if (packet.d.protocol_version === 0) {
550
+ this.daveSession.setPassthroughMode(true);
551
+ }
552
+ }
553
+ // Transition ID 0 is a (re)initialization and is executed immediately
554
+ if (packet.d.transition_id === 0) {
555
+ this._executeDaveTransition(0);
556
+ } else {
557
+ this.sendWS(VoiceOPCodes.DAVE_TRANSITION_READY, {
558
+ transition_id: packet.d.transition_id,
559
+ });
560
+ }
561
+ break;
562
+ }
563
+ case VoiceOPCodes.DAVE_EXECUTE_TRANSITION: {
564
+ this._executeDaveTransition(packet.d.transition_id);
565
+ break;
566
+ }
567
+ case VoiceOPCodes.DAVE_PREPARE_EPOCH: {
568
+ this.emit("debug", `Preparing DAVE epoch ${packet.d.epoch} (protocol version ${packet.d.protocol_version})`);
569
+ // Epoch 1 means a new MLS group is being created
570
+ if (packet.d.epoch === 1) {
571
+ this.daveProtocolVersion = packet.d.protocol_version;
572
+ this._reinitDaveSession();
573
+ }
574
+ break;
575
+ }
576
+ default: {
577
+ this.emit("unknown", packet);
578
+ break;
579
+ }
580
+ }
581
+ });
582
+ ws.on("error", (err) => {
583
+ if (this.ws !== ws) {
584
+ return;
585
+ }
586
+ this.emit("error", err);
587
+ });
588
+ ws.on("close", (code, reason) => {
589
+ if (this.ws !== ws) {
590
+ return;
591
+ }
592
+ let err = !code || code === 1000 ? null : new Error(code + ": " + reason);
593
+ this.emit("warn", `Voice WS close ${code}: ${reason}`);
594
+ if (this.connecting || this.ready) {
595
+ let reconnecting = true;
596
+ const resumable = !code || code < 4000 || code === 4015;
597
+ if (code === 1000 || code === 4004 || code === 4006 || code === 4016 || code === 4021) {
598
+ reconnecting = false;
599
+ } else if (code === 4017) {
600
+ reconnecting = false;
601
+ err = new Error(code + ": " + reason + (this.daveEnabled ? "" : Davey ? " (end-to-end encryption is disabled by the daveEncryption option)" : " (end-to-end encryption requires the @snazzah/davey package)"));
602
+ } else if (code === 4014 || code === 4022) {
603
+ if (this.channelID) {
604
+ data.endpoint = null;
605
+ err = null;
606
+ } else {
607
+ reconnecting = false;
608
+ }
609
+ } else if (resumable) {
610
+ err = null; // Already reported by the warn event, the session is resumed
611
+ }
612
+ this.disconnect(err, reconnecting);
613
+ if (reconnecting) {
614
+ if (!resumable) {
615
+ // The session can't be resumed
616
+ this.sessionID = null;
617
+ this.token = null;
618
+ this.wsSequence = -1;
619
+ this._closeUDP();
620
+ }
621
+ setTimeout(() => {
622
+ if (!this.connecting && !this.ready) {
623
+ this.connect(data);
624
+ }
625
+ }, 500).unref();
626
+ }
627
+ }
628
+ });
629
+ }
630
+
631
+ disconnect(error, reconnecting) {
632
+ this.connecting = false;
633
+ this.reconnecting = reconnecting;
634
+ this.resuming = false;
635
+ this.ready = false;
636
+
637
+ if (this.connectionTimeout) {
638
+ clearTimeout(this.connectionTimeout);
639
+ this.connectionTimeout = null;
640
+ }
641
+ if (this._ipDiscoveryTimeout) {
642
+ clearTimeout(this._ipDiscoveryTimeout);
643
+ this._ipDiscoveryTimeout = null;
644
+ }
645
+
646
+ try {
647
+ if (reconnecting) {
648
+ this.pause();
649
+ } else {
650
+ this.stopPlaying();
651
+ }
652
+ } catch (err) {
653
+ this.emit("error", err);
654
+ }
655
+ if (this.heartbeatInterval) {
656
+ clearInterval(this.heartbeatInterval);
657
+ this.heartbeatInterval = null;
658
+ }
659
+ if (!reconnecting) {
660
+ this.speaking = false;
661
+ this.timestamp = 0;
662
+ this.sequence = 0;
663
+ this._closeUDP();
664
+ }
665
+ if (this.ws) {
666
+ const ws = this.ws;
667
+ this.ws = null;
668
+ try {
669
+ if (reconnecting) {
670
+ if (ws.readyState === WebSocket.OPEN) {
671
+ ws.close(4901, "Eris: reconnect");
672
+ } else {
673
+ this.emit("debug", `Terminating websocket (state: ${ws.readyState})`);
674
+ ws.terminate();
675
+ }
676
+ } else {
677
+ ws.close(1000, "Eris: normal");
678
+ }
679
+ } catch (err) {
680
+ this.emit("error", err);
681
+ }
682
+ }
683
+ if (reconnecting) {
684
+ if (error) {
685
+ this.emit("error", error);
686
+ }
687
+ } else {
688
+ this.channelID = null;
689
+ this.sessionID = null;
690
+ this.token = null;
691
+ this.wsSequence = -1;
692
+ this.daveProtocolVersion = 0;
693
+ this.daveSession = null;
694
+ this._connectedUsers.clear();
695
+ this._daveDecryptionFailures.clear();
696
+ this._daveExternalSender = null;
697
+ this._daveLastDecryption = 0;
698
+ this._daveLastDecryptionUserID = null;
699
+ this._daveLastRecovery = 0;
700
+ this._davePendingTransitions.clear();
701
+ this._lastTransitionID = null;
702
+ this._stablelib = null;
703
+ this.updateVoiceState();
704
+ /**
705
+ * Fired when the voice connection disconnects
706
+ * @event VoiceConnection#disconnect
707
+ * @prop {Error?} error The error, if any
708
+ */
709
+ this.emit("disconnect", error);
710
+ }
711
+ }
712
+
713
+ /**
714
+ * Get the verification code of a user in the end-to-end encrypted call. It matches the code displayed in the Discord client
715
+ * @arg {String} userID The ID of the user
716
+ * @returns {Promise<String>}
717
+ */
718
+ getVerificationCode(userID) {
719
+ if (!this.daveSession) {
720
+ return Promise.reject(new Error("The call is not end-to-end encrypted"));
721
+ }
722
+ return this.daveSession.getVerificationCode(userID);
723
+ }
724
+
725
+ heartbeat() {
726
+ this.sendWS(VoiceOPCodes.HEARTBEAT, {
727
+ t: Date.now(),
728
+ seq_ack: this.wsSequence,
729
+ });
730
+ if (this.udpSocket) {
731
+ // NAT/connection table keep-alive
732
+ this.sendUDPPacket(UDP_KEEP_ALIVE);
733
+ }
734
+ }
735
+
736
+ /**
737
+ * Pause sending audio (if playing)
738
+ */
739
+ pause() {
740
+ this.paused = true;
741
+ this.setSpeaking(0);
742
+ if (this.current) {
743
+ if (!this.current.pausedTimestamp) {
744
+ this.current.pausedTimestamp = Date.now();
745
+ }
746
+ if (this.current.timeout) {
747
+ clearTimeout(this.current.timeout);
748
+ this.current.timeout = null;
749
+ }
750
+ }
751
+ }
752
+
753
+ /**
754
+ * Play an audio or video resource. If playing from a non-opus resource, FFMPEG should be compiled with --enable-libopus for best performance. If playing from HTTPS, FFMPEG must be compiled with --enable-openssl
755
+ * @arg {ReadableStream | String} resource The audio or video resource, either a ReadableStream, URL, or file path
756
+ * @arg {Object} [options] Music options
757
+ * @arg {Array<String>} [options.encoderArgs] Additional encoder parameters to pass to ffmpeg/avconv (after -i)
758
+ * @arg {String} [options.format] The format of the resource. If null, FFmpeg will attempt to guess and play the format. Available options: "dca", "ogg", "webm", "pcm", null
759
+ * @arg {Number} [options.frameDuration=20] The resource opus frame duration (required for DCA/Ogg)
760
+ * @arg {Number} [options.frameSize=2880] The resource opus frame size
761
+ * @arg {Boolean} [options.inlineVolume=false] Whether to enable on-the-fly volume changing. Note that enabling this leads to increased CPU usage
762
+ * @arg {Array<String>} [options.inputArgs] Additional input parameters to pass to ffmpeg/avconv (before -i)
763
+ * @arg {Number} [options.pcmSize=options.frameSize*2*this.channels] The PCM size if the "pcm" format is used
764
+ * @arg {Number} [options.samplingRate=48000] The resource audio sampling rate
765
+ * @arg {Number} [options.voiceDataTimeout=2000] Timeout when waiting for voice data (-1 for no timeout)
766
+ */
767
+ play(source, options = {}) {
768
+ if (this.shared) {
769
+ throw new Error("Cannot play stream on shared voice connection");
770
+ }
771
+ if (!this.ready) {
772
+ throw new Error("Not ready yet");
773
+ }
774
+
775
+ options.format = options.format || null;
776
+ options.voiceDataTimeout = !isNaN(options.voiceDataTimeout) ? options.voiceDataTimeout : 2000;
777
+ options.inlineVolume = !!options.inlineVolume;
778
+ options.inputArgs = options.inputArgs || [];
779
+ options.encoderArgs = options.encoderArgs || [];
780
+
781
+ options.samplingRate = options.samplingRate || this.samplingRate;
782
+ options.frameDuration = options.frameDuration || this.frameDuration;
783
+ options.frameSize = options.frameSize || options.samplingRate * options.frameDuration / 1000;
784
+ options.pcmSize = options.pcmSize || options.frameSize * 2 * this.channels;
785
+
786
+ if (!this.piper.encode(source, options)) {
787
+ this.emit("error", new Error("Unable to encode source"));
788
+ return;
789
+ }
790
+
791
+ this.ended = false;
792
+ this.current = {
793
+ startTime: 0, // later
794
+ playTime: 0,
795
+ pausedTimestamp: 0,
796
+ pausedTime: 0,
797
+ bufferingTicks: 0,
798
+ options: options,
799
+ timeout: null,
800
+ buffer: null,
801
+ };
802
+
803
+ this.playing = true;
804
+
805
+ /**
806
+ * Fired when the voice connection starts playing a stream
807
+ * @event VoiceConnection#start
808
+ */
809
+ this.emit("start");
810
+
811
+ this._send();
812
+ }
813
+
814
+ /**
815
+ * Generate a receive stream for the voice connection.
816
+ * @arg {String} [type="pcm"] The desired voice data type, either "opus" or "pcm"
817
+ * @returns {VoiceDataStream}
818
+ */
819
+ receive(type) {
820
+ if (type === "pcm") {
821
+ if (!this.receiveStreamPCM) {
822
+ this.receiveStreamPCM = new VoiceDataStream(type);
823
+ if (!this.receiveStreamOpus) {
824
+ this.registerReceiveEventHandler();
825
+ }
826
+ }
827
+ } else if (type === "opus") {
828
+ if (!this.receiveStreamOpus) {
829
+ this.receiveStreamOpus = new VoiceDataStream(type);
830
+ if (!this.receiveStreamPCM) {
831
+ this.registerReceiveEventHandler();
832
+ }
833
+ }
834
+ } else {
835
+ throw new Error(`Unsupported voice data type: ${type}`);
836
+ }
837
+ return type === "pcm" ? this.receiveStreamPCM : this.receiveStreamOpus;
838
+ }
839
+
840
+ registerReceiveEventHandler() {
841
+ const udpSocket = this.udpSocket;
842
+ if (!udpSocket || this._receiveSocket === udpSocket) {
843
+ return;
844
+ }
845
+ this._receiveSocket = udpSocket;
846
+ udpSocket.on("message", (msg) => {
847
+ if (this.udpSocket === udpSocket) {
848
+ this._onUDPMessage(msg);
849
+ }
850
+ });
851
+ }
852
+
853
+ /**
854
+ * Resume sending audio (if paused)
855
+ */
856
+ resume() {
857
+ this.paused = false;
858
+ if (this.current) {
859
+ this.setSpeaking(1);
860
+ if (this.current.pausedTimestamp) {
861
+ this.current.pausedTime += Date.now() - this.current.pausedTimestamp;
862
+ this.current.pausedTimestamp = 0;
863
+ }
864
+ this._send();
865
+ } else {
866
+ this.setSpeaking(0);
867
+ }
868
+ }
869
+
870
+ /**
871
+ * Send a packet containing an Opus audio frame
872
+ * @arg {Buffer} frame The Opus audio frame
873
+ * @arg {Number} [frameSize] The size (in samples) of the Opus audio frame
874
+ */
875
+ sendAudioFrame(frame, frameSize = this.frameSize) {
876
+ this.timestamp = (this.timestamp + frameSize) >>> 0;
877
+ this.sequence = (this.sequence + 1) & 0xFFFF;
878
+
879
+ return this._sendAudioFrame(frame);
880
+ }
881
+
882
+ /**
883
+ * Send a packet through the connection's UDP socket. The packet is dropped if the socket isn't established
884
+ * @arg {Buffer} packet The packet data
885
+ */
886
+ sendUDPPacket(packet) {
887
+ if (this.udpSocket) {
888
+ try {
889
+ this.udpSocket.send(packet, 0, packet.length, this.udpPort, this.udpIP);
890
+ } catch (e) {
891
+ this.emit("error", e);
892
+ }
893
+ }
894
+ }
895
+
896
+ sendWS(op, data) {
897
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
898
+ data = JSON.stringify({ op: op, d: data });
899
+ this.ws.send(data);
900
+ this.emit("debug", data);
901
+ }
902
+ }
903
+
904
+ /**
905
+ * Send a binary message through the voice gateway (used by the DAVE protocol)
906
+ * @arg {Number} op The opcode of the message
907
+ * @arg {Buffer} data The payload of the message
908
+ */
909
+ sendWSBinary(op, data) {
910
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
911
+ const packet = Buffer.allocUnsafe(data.length + 1);
912
+ packet[0] = op;
913
+ data.copy(packet, 1);
914
+ this.ws.send(packet);
915
+ this.emit("debug", `Sent binary opcode ${op} (${data.length} bytes)`);
916
+ }
917
+ }
918
+
919
+ setSpeaking(value, delay = 0) {
920
+ this.speaking = value === true ? 1 : value === false ? 0 : value;
921
+ this.sendWS(VoiceOPCodes.SPEAKING, {
922
+ speaking: value,
923
+ delay: delay,
924
+ ssrc: this.ssrc,
925
+ });
926
+ }
927
+
928
+ /**
929
+ * Modify the output volume of the current stream (if inlineVolume is enabled for the current stream)
930
+ * @arg {Number} [volume=1.0] The desired volume. 0.0 is 0%, 1.0 is 100%, 2.0 is 200%, etc. It is not recommended to go above 2.0
931
+ */
932
+ setVolume(volume) {
933
+ this.piper.setVolume(volume);
934
+ }
935
+
936
+ /**
937
+ * Stop the bot from sending audio
938
+ */
939
+ stopPlaying() {
940
+ if (this.ended) {
941
+ return;
942
+ }
943
+ this.ended = true;
944
+ if (this.current && this.current.timeout) {
945
+ clearTimeout(this.current.timeout);
946
+ this.current.timeout = null;
947
+ }
948
+ this.current = null;
949
+ if (this.piper) {
950
+ this.piper.stop();
951
+ this.piper.resetPackets();
952
+ }
953
+
954
+ if (this.secret) {
955
+ for (let i = 0; i < 5; i++) {
956
+ this.sendAudioFrame(SILENCE_FRAME, this.frameSize);
957
+ }
958
+ }
959
+ this.playing = false;
960
+ this.setSpeaking(0);
961
+
962
+ /**
963
+ * Fired when the voice connection finishes playing a stream
964
+ * @event VoiceConnection#end
965
+ */
966
+ this.emit("end");
967
+ }
968
+
969
+ /**
970
+ * Switch the voice channel the bot is in. The channel to switch to must be in the same guild as the current voice channel
971
+ * @arg {String} channelID The ID of the voice channel
972
+ */
973
+ switchChannel(channelID, reactive) {
974
+ if (this.channelID === channelID) {
975
+ return;
976
+ }
977
+
978
+ this.channelID = channelID;
979
+ if (reactive) {
980
+ if (this.reconnecting && !channelID) {
981
+ this.disconnect();
982
+ }
983
+ } else {
984
+ this.updateVoiceState();
985
+ }
986
+ }
987
+
988
+ /**
989
+ * Update the bot's voice state
990
+ * @arg {Boolean} selfMute Whether the bot muted itself or not (audio receiving is unaffected)
991
+ * @arg {Boolean} selfDeaf Whether the bot deafened itself or not (audio sending is unaffected)
992
+ */
993
+ updateVoiceState(selfMute, selfDeaf) {
994
+ if (this.shard.sendWS) {
995
+ this.shard.sendWS(GatewayOPCodes.VOICE_STATE_UPDATE, {
996
+ guild_id: this.id === "call" ? null : this.id,
997
+ channel_id: this.channelID || null,
998
+ self_mute: !!selfMute,
999
+ self_deaf: !!selfDeaf,
1000
+ });
1001
+ }
1002
+ }
1003
+
1004
+ _closeUDP() {
1005
+ if (this.udpSocket) {
1006
+ const udpSocket = this.udpSocket;
1007
+ this.udpSocket = null;
1008
+ try {
1009
+ udpSocket.close();
1010
+ } catch (err) {
1011
+ if (err.message !== "Not running") {
1012
+ this.emit("error", err);
1013
+ }
1014
+ }
1015
+ }
1016
+ }
1017
+
1018
+ _daveDecrypt(userID, data) {
1019
+ const session = this.daveSession;
1020
+ if (!session.ready) {
1021
+ if (this.daveProtocolVersion !== 0 && !this._daveDowngraded) {
1022
+ return null; // The session isn't established yet
1023
+ }
1024
+ return data;
1025
+ }
1026
+ if (!userID) {
1027
+ return null; // Unknown sender, can't be decrypted
1028
+ }
1029
+ try {
1030
+ if (this._isDaveActive() || session.canPassthrough(userID)) {
1031
+ data = session.decrypt(userID, DAVE_MEDIA_TYPE_AUDIO, data);
1032
+ if (this._daveDecryptionFailures.size !== 0) {
1033
+ // Only tracked while a user fails, so that the common case costs nothing
1034
+ this._daveDecryptionFailures.delete(userID);
1035
+ this._daveLastDecryption = Date.now();
1036
+ this._daveLastDecryptionUserID = userID;
1037
+ }
1038
+ } else if (isDaveFrame(data)) {
1039
+ return null;
1040
+ }
1041
+ return data;
1042
+ } catch (err) {
1043
+ if (!this._isDaveActive()) {
1044
+ this.emit("debug", `Failed to decrypt end-to-end encrypted packet from ${userID} (session downgraded)`);
1045
+ } else if (this._daveReinitializing || this._davePendingTransitions.size > 0) {
1046
+ this.emit("debug", `Failed to decrypt end-to-end encrypted packet from ${userID} (session transitioning)`);
1047
+ } else {
1048
+ // Failures are counted per user, so that the packets of one user can't reset the count of another
1049
+ const failures = (this._daveDecryptionFailures.get(userID) || 0) + 1;
1050
+ this._daveDecryptionFailures.set(userID, failures);
1051
+ this.emit("debug", `Failed to decrypt end-to-end encrypted packet from ${userID} (${failures} consecutive failures): ${err.message}`);
1052
+ if (this.decryptionFailureTolerance > 0 && this._lastTransitionID !== null && failures > this.decryptionFailureTolerance) {
1053
+ const now = Date.now();
1054
+ // Packets from other users still decrypting means the session is fine and only this user's packets are broken
1055
+ const othersDecrypt = this._daveLastDecryptionUserID !== userID && now - this._daveLastDecryption < DAVE_RECOVERY_INTERVAL;
1056
+ if (!othersDecrypt && now - this._daveLastRecovery >= DAVE_RECOVERY_INTERVAL) {
1057
+ this.emit("warn", `Failed to decrypt ${failures} consecutive end-to-end encrypted packets from ${userID}: ${err.message}`);
1058
+ this._daveLastRecovery = now;
1059
+ this._recoverFromInvalidTransition(this._lastTransitionID);
1060
+ }
1061
+ }
1062
+ }
1063
+ return null;
1064
+ }
1065
+ }
1066
+
1067
+ _decryptPacket(msg, headerSize) {
1068
+ const end = msg.length - NONCE_SUFFIX_SIZE;
1069
+ if (end - headerSize < AUTH_TAG_SIZE) {
1070
+ return null;
1071
+ }
1072
+ const nonce = this._receiveNonce;
1073
+ msg.copy(nonce, 0, end);
1074
+ try {
1075
+ if (this.mode === ENCRYPTION_MODE_AES256) {
1076
+ const decipher = NodeCrypto.createDecipheriv("aes-256-gcm", this.secret, nonce);
1077
+ decipher.setAAD(msg.subarray(0, headerSize));
1078
+ decipher.setAuthTag(msg.subarray(end - AUTH_TAG_SIZE, end));
1079
+ const data = decipher.update(msg.subarray(headerSize, end - AUTH_TAG_SIZE));
1080
+ decipher.final();
1081
+ return data;
1082
+ }
1083
+ if (Sodium) {
1084
+ const data = Buffer.allocUnsafe(end - headerSize - AUTH_TAG_SIZE);
1085
+ Sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(data, null, msg.subarray(headerSize, end), msg.subarray(0, headerSize), nonce, this.secret);
1086
+ return data;
1087
+ }
1088
+ const data = this._stablelib.open(nonce, msg.subarray(headerSize, end), msg.subarray(0, headerSize));
1089
+ return data && Buffer.from(data.buffer, data.byteOffset, data.byteLength);
1090
+ } catch {
1091
+ return null;
1092
+ }
1093
+ }
1094
+
1095
+ _destroy() {
1096
+ if (this.opus) {
1097
+ for (const key in this.opus) {
1098
+ if (this.opus[key].delete) {
1099
+ this.opus[key].delete();
1100
+ }
1101
+ delete this.opus[key];
1102
+ }
1103
+ }
1104
+ delete this.piper;
1105
+ if (this.receiveStreamOpus) {
1106
+ this.receiveStreamOpus.removeAllListeners();
1107
+ this.receiveStreamOpus = null;
1108
+ }
1109
+ if (this.receiveStreamPCM) {
1110
+ this.receiveStreamPCM.removeAllListeners();
1111
+ this.receiveStreamPCM = null;
1112
+ }
1113
+ }
1114
+
1115
+ _executeDaveTransition(transitionID) {
1116
+ if (!this._davePendingTransitions.has(transitionID)) {
1117
+ this.emit("warn", `Received DAVE execute transition ${transitionID}, but it was not prepared`);
1118
+ return false;
1119
+ }
1120
+ // Transition 0 is executed by the DAVE session itself
1121
+ if (transitionID !== 0 && this.daveSession) {
1122
+ let executed = false;
1123
+ try {
1124
+ executed = this.daveSession.executeTransition(transitionID);
1125
+ } catch (err) {
1126
+ this.emit("warn", `Failed to execute DAVE transition ${transitionID}: ${err.message}`);
1127
+ }
1128
+ if (!executed) {
1129
+ this._davePendingTransitions.delete(transitionID);
1130
+ return false;
1131
+ }
1132
+ }
1133
+
1134
+ const oldVersion = this.daveProtocolVersion;
1135
+ this.daveProtocolVersion = this._davePendingTransitions.get(transitionID);
1136
+ this._davePendingTransitions.delete(transitionID);
1137
+ if (oldVersion !== this.daveProtocolVersion && this.daveProtocolVersion === 0) {
1138
+ this._daveDowngraded = true;
1139
+ this.emit("debug", "DAVE protocol downgraded");
1140
+ } else if (transitionID > 0 && this._daveDowngraded) {
1141
+ this._daveDowngraded = false;
1142
+ if (this.daveSession) {
1143
+ this.daveSession.setPassthroughMode(false, 10);
1144
+ }
1145
+ this.emit("debug", "DAVE protocol upgraded");
1146
+ }
1147
+ this._daveReinitializing = false;
1148
+ this._lastTransitionID = transitionID;
1149
+ this.emit("debug", `DAVE transition ${transitionID} executed (protocol version ${oldVersion} -> ${this.daveProtocolVersion})`);
1150
+ /**
1151
+ * Fired when the end-to-end encryption of the call transitions to a new state (new participants, protocol version change...)
1152
+ * @event VoiceConnection#daveTransition
1153
+ * @prop {Number} transitionID The ID of the transition
1154
+ * @prop {Number} protocolVersion The DAVE protocol version of the call after the transition. `0` means the call is not end-to-end encrypted anymore
1155
+ */
1156
+ this.emit("daveTransition", transitionID, this.daveProtocolVersion);
1157
+ return true;
1158
+ }
1159
+
1160
+ _handleBinaryMessage(message) {
1161
+ if (message.length < 3) {
1162
+ return;
1163
+ }
1164
+ // Server binary messages: sequence (uint16) | opcode (uint8) | payload
1165
+ this.wsSequence = message.readUInt16BE(0);
1166
+ const op = message[2];
1167
+ if (this.listeners("debug").length > 0) {
1168
+ this.emit("debug", `Rec binary opcode ${op} (${message.length - 3} bytes)`);
1169
+ }
1170
+ if (op === VoiceOPCodes.DAVE_MLS_EXTERNAL_SENDER) {
1171
+ this._daveExternalSender = message.subarray(3);
1172
+ if (this.daveSession) {
1173
+ try {
1174
+ this.daveSession.setExternalSender(this._daveExternalSender);
1175
+ this.emit("debug", "Set DAVE MLS external sender");
1176
+ } catch (err) {
1177
+ this.emit("warn", `Failed to set DAVE MLS external sender: ${err.message}`);
1178
+ }
1179
+ }
1180
+ return;
1181
+ }
1182
+ if (!this.daveSession) {
1183
+ return;
1184
+ }
1185
+ switch (op) {
1186
+ case VoiceOPCodes.DAVE_MLS_PROPOSALS: {
1187
+ try {
1188
+ const result = this.daveSession.processProposals(message[3], message.subarray(4), this._recognizedUsers());
1189
+ if (result.commit) {
1190
+ this.sendWSBinary(VoiceOPCodes.DAVE_MLS_COMMIT_WELCOME, result.welcome ? Buffer.concat([result.commit, result.welcome]) : result.commit);
1191
+ }
1192
+ } catch (err) {
1193
+ this.emit("warn", `Failed to process DAVE MLS proposals: ${err.message}`);
1194
+ if (this._lastTransitionID !== null) {
1195
+ if (!this._daveReinitializing) {
1196
+ this._recoverFromInvalidTransition(this._lastTransitionID);
1197
+ }
1198
+ } else {
1199
+ this.disconnect(new Error("Failed to process DAVE MLS proposals"));
1200
+ }
1201
+ }
1202
+ break;
1203
+ }
1204
+ case VoiceOPCodes.DAVE_MLS_ANNOUNCE_COMMIT_TRANSITION:
1205
+ case VoiceOPCodes.DAVE_MLS_WELCOME: {
1206
+ const transitionID = message.readUInt16BE(3);
1207
+ try {
1208
+ if (op === VoiceOPCodes.DAVE_MLS_WELCOME) {
1209
+ this.daveSession.processWelcome(message.subarray(5), this._recognizedUsers());
1210
+ } else if (!this.daveSession.processCommit(message.subarray(5))) {
1211
+ this.emit("debug", `DAVE MLS commit ignored (transition ${transitionID})`);
1212
+ break;
1213
+ }
1214
+ this.daveSession.prepareTransition(transitionID, this.daveSession.protocolVersion);
1215
+ this._davePendingTransitions.set(transitionID, this.daveSession.protocolVersion);
1216
+ // Transition ID 0 is a (re)initialization and is executed immediately
1217
+ if (transitionID === 0) {
1218
+ this._executeDaveTransition(0);
1219
+ } else {
1220
+ this.sendWS(VoiceOPCodes.DAVE_TRANSITION_READY, {
1221
+ transition_id: transitionID,
1222
+ });
1223
+ }
1224
+ } catch (err) {
1225
+ this.emit("warn", `Failed to process DAVE MLS ${op === VoiceOPCodes.DAVE_MLS_WELCOME ? "welcome" : "commit"} (transition ${transitionID}): ${err.message}`);
1226
+ this._recoverFromInvalidTransition(transitionID);
1227
+ }
1228
+ break;
1229
+ }
1230
+ }
1231
+ }
1232
+
1233
+ _isDaveActive() {
1234
+ return this.daveProtocolVersion !== 0 && !this._daveDowngraded && !!this.daveSession && this.daveSession.ready;
1235
+ }
1236
+
1237
+ _onUDPMessage(msg) {
1238
+ // RTP version 2 and Opus payload type only
1239
+ if (!this._receiveNonce || msg.length < RTP_HEADER_SIZE + AUTH_TAG_SIZE + NONCE_SUFFIX_SIZE || msg[1] !== 0x78 || (msg[0] >> 6) !== 2) {
1240
+ return;
1241
+ }
1242
+ const hasPadding = !!(msg[0] & 0b100000);
1243
+ const hasExtension = !!(msg[0] & 0b10000);
1244
+ // With rtpsize modes, the header, the CSRCs and the extension header are unencrypted, and the extension data is encrypted
1245
+ const headerSize = RTP_HEADER_SIZE + (msg[0] & 0b1111) * 4 + (hasExtension ? 4 : 0);
1246
+ let data = this._decryptPacket(msg, headerSize);
1247
+ if (!data) {
1248
+ this.emit("warn", "Failed to decrypt received packet");
1249
+ return;
1250
+ }
1251
+ if (hasPadding && data.length > 0 && data[data.length - 1] <= data.length) {
1252
+ data = data.subarray(0, data.length - data[data.length - 1]);
1253
+ }
1254
+ if (hasExtension) { // RFC3550 5.3.1: RTP Header Extension, length in 32-bit words
1255
+ data = data.subarray(msg.readUInt16BE(headerSize - 2) * 4);
1256
+ }
1257
+ if (data.length === 0) {
1258
+ return;
1259
+ }
1260
+
1261
+ const userID = this.ssrcUserMap[msg.readUInt32BE(8)];
1262
+ if (this.daveSession && !isSilenceFrame(data)) {
1263
+ data = this._daveDecrypt(userID, data);
1264
+ if (!data) {
1265
+ return;
1266
+ }
1267
+ }
1268
+ const timestamp = msg.readUInt32BE(4);
1269
+ const sequence = msg.readUInt16BE(2);
1270
+ if (this.receiveStreamOpus) {
1271
+ /**
1272
+ * Fired when a voice data packet is received
1273
+ * @event VoiceDataStream#data
1274
+ * @prop {Buffer} data The voice data
1275
+ * @prop {String} userID The user who sent the voice packet
1276
+ * @prop {Number} timestamp The intended timestamp of the packet
1277
+ * @prop {Number} sequence The intended sequence number of the packet
1278
+ */
1279
+ this.receiveStreamOpus.emit("data", data, userID, timestamp, sequence);
1280
+ }
1281
+ if (this.receiveStreamPCM) {
1282
+ if (!this.opus[userID]) {
1283
+ this.opus[userID] = createOpus(this.samplingRate, this.channels, this.bitrate);
1284
+ }
1285
+
1286
+ data = this.opus[userID].decode(data, this.frameSize);
1287
+ if (!data) {
1288
+ return this.emit("warn", "Failed to decode received packet");
1289
+ }
1290
+ this.receiveStreamPCM.emit("data", data, userID, timestamp, sequence);
1291
+ }
1292
+ }
1293
+
1294
+ _recognizedUsers() {
1295
+ return Array.from(this._connectedUsers).concat(this._userID);
1296
+ }
1297
+
1298
+ _recoverFromInvalidTransition(transitionID) {
1299
+ this.emit("warn", `Invalidating DAVE transition ${transitionID}`);
1300
+ this._daveReinitializing = true;
1301
+ this._daveDecryptionFailures.clear();
1302
+ this.sendWS(VoiceOPCodes.DAVE_MLS_INVALID_COMMIT_WELCOME, {
1303
+ transition_id: transitionID,
1304
+ });
1305
+ this._reinitDaveSession();
1306
+ }
1307
+
1308
+ _reinitDaveSession() {
1309
+ // Resetting the session drops its prepared transitions
1310
+ this._davePendingTransitions.clear();
1311
+ if (this.daveProtocolVersion > 0 && this.daveEnabled) {
1312
+ if (this.daveSession) {
1313
+ this.daveSession.reinit(this.daveProtocolVersion, this._userID, this.channelID);
1314
+ this.emit("debug", `DAVE session reinitialized (protocol version ${this.daveProtocolVersion})`);
1315
+ } else {
1316
+ this.daveSession = new Davey.DAVESession(this.daveProtocolVersion, this._userID, this.channelID);
1317
+ this.emit("debug", `DAVE session initialized (protocol version ${this.daveProtocolVersion})`);
1318
+ }
1319
+ if (this._daveExternalSender) {
1320
+ try {
1321
+ this.daveSession.setExternalSender(this._daveExternalSender);
1322
+ } catch {} // eslint-disable-line no-empty
1323
+ }
1324
+ // When upgrading, unencrypted frames are still received until the transition is executed
1325
+ if (this._daveDowngraded) {
1326
+ this.daveSession.setPassthroughMode(true);
1327
+ }
1328
+ this.sendWSBinary(VoiceOPCodes.DAVE_MLS_KEY_PACKAGE, this.daveSession.getSerializedKeyPackage());
1329
+ } else if (this.daveSession) {
1330
+ this.daveSession.reset();
1331
+ this.daveSession.setPassthroughMode(true);
1332
+ this.emit("debug", "DAVE session reset");
1333
+ }
1334
+ }
1335
+
1336
+ _send() {
1337
+ if (!this.piper.encoding && this.piper.dataPacketCount === 0) {
1338
+ return this.stopPlaying();
1339
+ }
1340
+
1341
+ if ((this.current.buffer = this.piper.getDataPacket())) {
1342
+ if (this.current.startTime === 0) {
1343
+ this.current.startTime = Date.now();
1344
+ }
1345
+ if (this.current.bufferingTicks > 0) {
1346
+ this.current.bufferingTicks = 0;
1347
+ this.setSpeaking(1);
1348
+ }
1349
+ } else if (this.current.options.voiceDataTimeout === -1 || this.current.bufferingTicks < this.current.options.voiceDataTimeout / (4 * this.current.options.frameDuration)) { // wait for data
1350
+ if (++this.current.bufferingTicks === 1) {
1351
+ this.setSpeaking(0);
1352
+ }
1353
+ this.current.pausedTime += 4 * this.current.options.frameDuration;
1354
+ this.timestamp = (this.timestamp + 3 * this.current.options.frameSize) >>> 0;
1355
+ this.current.timeout = setTimeout(this._send, 4 * this.current.options.frameDuration);
1356
+ return;
1357
+ } else {
1358
+ return this.stopPlaying();
1359
+ }
1360
+
1361
+ this.sendAudioFrame(this.current.buffer, this.current.options.frameSize);
1362
+ this.current.playTime += this.current.options.frameDuration;
1363
+ this.current.timeout = setTimeout(this._send, Math.max(0, this.current.startTime + this.current.pausedTime + this.current.playTime - Date.now()));
1364
+ }
1365
+
1366
+ _sendAudioFrame(frame) {
1367
+ if (!this._sendNonce) {
1368
+ return;
1369
+ }
1370
+ if (this.daveProtocolVersion !== 0 && !this._daveDowngraded && this.daveSession && !isSilenceFrame(frame)) {
1371
+ // In an end-to-end encrypted call, frames are dropped until they can be encrypted (MLS group joined and transition executed) to never leak unencrypted audio
1372
+ if (!this.daveSession.ready || !this.daveSession.canEncrypt) {
1373
+ return;
1374
+ }
1375
+ try {
1376
+ frame = this.daveSession.encryptOpus(frame);
1377
+ } catch (err) {
1378
+ this.emit("warn", `Failed to end-to-end encrypt audio frame: ${err.message}`);
1379
+ return;
1380
+ }
1381
+ }
1382
+
1383
+ const header = this.sendHeader;
1384
+ header.writeUInt16BE(this.sequence, 2);
1385
+ header.writeUInt32BE(this.timestamp, 4);
1386
+ this._nonce = (this._nonce + 1) >>> 0;
1387
+ this._sendNonce.writeUInt32BE(this._nonce, 0);
1388
+
1389
+ // UDP sends are asynchronous, each packet needs its own buffer (small allocations are taken from Node's buffer pool)
1390
+ const packet = Buffer.allocUnsafe(RTP_HEADER_SIZE + frame.length + AUTH_TAG_SIZE + NONCE_SUFFIX_SIZE);
1391
+ header.copy(packet, 0);
1392
+ const end = RTP_HEADER_SIZE + frame.length + AUTH_TAG_SIZE;
1393
+ if (this.mode === ENCRYPTION_MODE_AES256) {
1394
+ const cipher = NodeCrypto.createCipheriv("aes-256-gcm", this.secret, this._sendNonce);
1395
+ cipher.setAAD(header);
1396
+ cipher.update(frame).copy(packet, RTP_HEADER_SIZE);
1397
+ cipher.final();
1398
+ cipher.getAuthTag().copy(packet, end - AUTH_TAG_SIZE);
1399
+ } else if (Sodium) {
1400
+ Sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(packet.subarray(RTP_HEADER_SIZE, end), frame, header, null, this._sendNonce, this.secret);
1401
+ } else {
1402
+ this._stablelib.seal(this._sendNonce, frame, header, packet.subarray(RTP_HEADER_SIZE, end));
1403
+ }
1404
+ this._sendNonce.copy(packet, end, 0, NONCE_SUFFIX_SIZE);
1405
+ return this.sendUDPPacket(packet);
1406
+ }
1407
+
1408
+ /** @deprecated */
1409
+ _sendAudioPacket(audio) {
1410
+ return this._sendAudioFrame(audio);
1411
+ }
1412
+
1413
+ [util.inspect.custom]() {
1414
+ return Base.prototype[util.inspect.custom].call(this);
1415
+ }
1416
+
1417
+ toString() {
1418
+ return `[VoiceConnection ${this.channelID}]`;
1419
+ }
1420
+
1421
+ toJSON(props = []) {
1422
+ return Base.prototype.toJSON.call(this, [
1423
+ "channelID",
1424
+ "connecting",
1425
+ "current",
1426
+ "daveProtocolVersion",
1427
+ "id",
1428
+ "mode",
1429
+ "paused",
1430
+ "playing",
1431
+ "ready",
1432
+ "volume",
1433
+ ...props,
1434
+ ]);
1435
+ }
1436
+ }
1437
+
1438
+ VoiceConnection._converterCommand = converterCommand;
1439
+
1440
+ module.exports = VoiceConnection;