lolka.js 0.4.3 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +279 -11
- package/package.json +3 -5
- package/src/client/voice/AudioPlayer.js +358 -0
- package/src/client/voice/AudioResource.js +137 -0
- package/src/client/voice/VoiceConnection.js +419 -290
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libdatachannel.txt +373 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libjuice.txt +373 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libsrtp.txt +35 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-nlohmann-json.txt +21 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-node-addon-api.txt +9 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-node-api-headers.txt +21 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-openssl.txt +177 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-opus.txt +44 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-plog.txt +21 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-usrsctp.txt +27 -0
- package/src/client/voice/_lolka_voice/LICENSES/THIRD-PARTY.txt +16 -0
- package/src/client/voice/_lolka_voice/MANIFEST.json +47 -0
- package/src/client/voice/_lolka_voice/_loader.js +103 -0
- package/src/client/voice/_lolka_voice/_native/linux-aarch64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/linux-aarch64-musl/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/linux-x86_64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/linux-x86_64-musl/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/macos-arm64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/macos-x86_64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/windows-x86_64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_version.js +4 -0
- package/src/client/voice/_lolka_voice/caps.js +56 -0
- package/src/client/voice/_lolka_voice/core.d.ts +200 -0
- package/src/client/voice/_lolka_voice/errors.js +22 -0
- package/src/client/voice/_lolka_voice/events.js +119 -0
- package/src/client/voice/_lolka_voice/index.d.ts +226 -0
- package/src/client/voice/_lolka_voice/index.js +35 -0
- package/src/client/voice/_lolka_voice/player.js +606 -0
- package/src/client/voice/_lolka_voice/receive.js +387 -0
- package/src/client/voice/_lolka_voice/sdp.js +137 -0
- package/src/client/voice/_lolka_voice/session.js +335 -0
- package/src/client/voice/_lolka_voice/signaling.js +120 -0
- package/src/client/voice/_lolka_voice/transport.js +260 -0
- package/src/client/voice/media/OpusPlayback.js +199 -0
- package/src/client/voice/media/Receiver.js +245 -0
- package/src/client/voice/media/deps.js +27 -0
- package/src/index.js +11 -0
- package/src/structures/Guild.js +5 -2
- package/typings/index.d.mts +256 -4
- package/typings/index.d.ts +256 -4
|
@@ -2,109 +2,48 @@
|
|
|
2
2
|
|
|
3
3
|
// WebRTC-голос для lolka.js.
|
|
4
4
|
//
|
|
5
|
-
// lolka voice работает через WebRTC (как клиенты lolka), а не через Discord UDP.
|
|
6
|
-
//
|
|
7
|
-
// и
|
|
5
|
+
// lolka voice работает через WebRTC (как клиенты lolka), а не через Discord UDP. Транспорт – встроенное
|
|
6
|
+
// нативное ядро lolka-voice (libdatachannel + Opus, бинари внутри пакета): ffmpeg -> Ogg/Opus -> RTP -> SRTP.
|
|
7
|
+
// Пейсинг, RTP и отправка идут в нативном потоке, JS на пакет не выполняется. Сигналинг (JSON-RPC поверх
|
|
8
|
+
// WebSocket), SDP для mediasoup, транспорты и приём – во вложенном слое `_lolka_voice` (VoiceSession); здесь
|
|
9
|
+
// остаётся то, что видит пользователь: адаптер и op 4, rejoin, переезды, kick grace, `play`/`subscribe`, события.
|
|
8
10
|
//
|
|
9
11
|
// Публичный API в духе @discordjs/voice:
|
|
10
12
|
// const conn = joinVoiceChannel({ channelId, guildId, adapterCreator });
|
|
11
13
|
// await conn.awaitReady();
|
|
12
|
-
// conn.play('song.mp3');
|
|
13
|
-
// conn.
|
|
14
|
+
// conn.play('song.mp3'); // путь к файлу или Readable-поток
|
|
15
|
+
// conn.pause(); conn.resume(); // после короткого хвоста тишины пакетов нет
|
|
16
|
+
// conn.subscribe(player); // один трек из createAudioPlayer() во многих каналах
|
|
17
|
+
// conn.on('track', (track, userId) => {}); // приём чужого звука (RemoteAudioTrack), включает приём
|
|
18
|
+
// conn.receiver.subscribe(userId); // Readable с Opus-пакетами участника, включает приём
|
|
14
19
|
// conn.destroy();
|
|
15
20
|
|
|
16
21
|
const EventEmitter = require('node:events');
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const SAMPLE_RATE = 48000;
|
|
44
|
-
const CHANNELS = 2;
|
|
45
|
-
const FRAME_SAMPLES = 480; // 10 мс
|
|
46
|
-
const FRAME_BYTES = FRAME_SAMPLES * CHANNELS * 2;
|
|
47
|
-
|
|
48
|
-
// JSON-RPC поверх WebSocket к голосовому серверу.
|
|
49
|
-
// request: { id, method, data }
|
|
50
|
-
// response: { id, response: true, data } | { id, response: true, error }
|
|
51
|
-
// notification: { notification: true, method, data }
|
|
52
|
-
class VoiceSignaling {
|
|
53
|
-
constructor(url, onNotification) {
|
|
54
|
-
this.url = url;
|
|
55
|
-
this.onNotification = onNotification;
|
|
56
|
-
this.ws = null;
|
|
57
|
-
this.pending = new Map();
|
|
58
|
-
this.nextId = 1;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
connect() {
|
|
62
|
-
return new Promise((resolve, reject) => {
|
|
63
|
-
this.ws = new WebSocketImpl(this.url);
|
|
64
|
-
this.ws.on('open', resolve);
|
|
65
|
-
this.ws.on('error', reject);
|
|
66
|
-
this.ws.on('message', buffer => {
|
|
67
|
-
let obj;
|
|
68
|
-
try {
|
|
69
|
-
obj = JSON.parse(buffer.toString());
|
|
70
|
-
} catch {
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
if (obj.response) {
|
|
74
|
-
const p = this.pending.get(obj.id);
|
|
75
|
-
if (p) {
|
|
76
|
-
this.pending.delete(obj.id);
|
|
77
|
-
if (obj.error) p.reject(new Error(String(obj.error)));
|
|
78
|
-
else p.resolve(obj.data ?? {});
|
|
79
|
-
}
|
|
80
|
-
} else if (obj.notification) {
|
|
81
|
-
Promise.resolve(this.onNotification(obj.method, obj.data ?? {})).catch(() => {});
|
|
82
|
-
}
|
|
83
|
-
});
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
request(method, data = {}, timeout = 15000) {
|
|
88
|
-
return new Promise((resolve, reject) => {
|
|
89
|
-
const id = this.nextId++;
|
|
90
|
-
this.pending.set(id, { resolve, reject });
|
|
91
|
-
this.ws.send(JSON.stringify({ id, method, data }));
|
|
92
|
-
setTimeout(() => {
|
|
93
|
-
if (this.pending.has(id)) {
|
|
94
|
-
this.pending.delete(id);
|
|
95
|
-
reject(new Error(`voice signaling timeout: ${method}`));
|
|
96
|
-
}
|
|
97
|
-
}, timeout);
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
close() {
|
|
102
|
-
try {
|
|
103
|
-
this.ws?.close();
|
|
104
|
-
} catch {
|
|
105
|
-
// ignore
|
|
106
|
-
}
|
|
107
|
-
}
|
|
22
|
+
const { ensureVoiceDeps } = require('./media/deps');
|
|
23
|
+
const { OpusPlayback } = require('./media/OpusPlayback');
|
|
24
|
+
const { Receiver, RemoteAudioTrack } = require('./media/Receiver');
|
|
25
|
+
|
|
26
|
+
const DEFAULT_KICK_GRACE_MS = 5000;
|
|
27
|
+
|
|
28
|
+
const NO_COUNTERS = Object.freeze({
|
|
29
|
+
packetsSent: 0,
|
|
30
|
+
bytesSent: 0,
|
|
31
|
+
underruns: 0,
|
|
32
|
+
lateTicks: 0,
|
|
33
|
+
bursts: 0,
|
|
34
|
+
resyncs: 0,
|
|
35
|
+
silentSkipped: 0,
|
|
36
|
+
drops: 0,
|
|
37
|
+
skipped: 0,
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// Живые соединения: owner (голосовой менеджер клиента) -> guildId -> соединение. Повторный
|
|
41
|
+
// joinVoiceChannel переиспользует соединение через rejoin(); разные клиенты не пересекаются.
|
|
42
|
+
const defaultOwner = {};
|
|
43
|
+
const connections = new WeakMap();
|
|
44
|
+
|
|
45
|
+
function ownerOf(adapterCreator) {
|
|
46
|
+
return adapterCreator?.voiceManager ?? defaultOwner;
|
|
108
47
|
}
|
|
109
48
|
|
|
110
49
|
/**
|
|
@@ -112,13 +51,14 @@ class VoiceSignaling {
|
|
|
112
51
|
* @extends {EventEmitter}
|
|
113
52
|
*/
|
|
114
53
|
class VoiceConnection extends EventEmitter {
|
|
115
|
-
constructor({ channelId, guildId, adapterCreator, selfMute = false, selfDeaf = false }) {
|
|
54
|
+
constructor({ channelId, guildId, adapterCreator, selfMute = false, selfDeaf = false, receive = false }) {
|
|
116
55
|
super();
|
|
117
56
|
if (!channelId || !guildId || typeof adapterCreator !== 'function') {
|
|
118
57
|
throw new TypeError('joinVoiceChannel requires { channelId, guildId, adapterCreator }');
|
|
119
58
|
}
|
|
120
59
|
ensureVoiceDeps();
|
|
121
60
|
|
|
61
|
+
this._owner = ownerOf(adapterCreator);
|
|
122
62
|
this.channelId = channelId;
|
|
123
63
|
this.guildId = guildId;
|
|
124
64
|
this.state = 'connecting';
|
|
@@ -127,21 +67,31 @@ class VoiceConnection extends EventEmitter {
|
|
|
127
67
|
this.token = null;
|
|
128
68
|
this.endpoint = null;
|
|
129
69
|
|
|
130
|
-
this.
|
|
131
|
-
this.
|
|
132
|
-
this.
|
|
133
|
-
|
|
134
|
-
this.
|
|
135
|
-
this.
|
|
136
|
-
this.
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
70
|
+
this._session = null; // VoiceSession текущего голосового сервера
|
|
71
|
+
this._wantReceive = Boolean(receive);
|
|
72
|
+
this._canPlay = false;
|
|
73
|
+
// отправитель в ядре: часы и RTP-состояние переживают play() и переезд на другой голосовой сервер
|
|
74
|
+
this._player = new (ensureVoiceDeps().voice.SendPlayer)();
|
|
75
|
+
this._playback = null; // текущий собственный источник (OpusPlayback)
|
|
76
|
+
this._subscription = null; // подписка на плеер (PlayerSubscription), вместо собственного источника
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Приёмник чужого звука: `subscribe(userId)` и треки участников. Пока приём не запрошен
|
|
80
|
+
* (`receive: true`, слушатель 'track' или `subscribe`), recv-транспорта и consume нет.
|
|
81
|
+
* @type {Receiver}
|
|
82
|
+
*/
|
|
83
|
+
this.receiver = new Receiver(this);
|
|
84
|
+
this.on('newListener', event => {
|
|
85
|
+
if (event === 'track') this._enableReceive();
|
|
86
|
+
});
|
|
142
87
|
|
|
88
|
+
this._kickTimer = null;
|
|
143
89
|
this._started = false;
|
|
144
90
|
this._destroyed = false;
|
|
91
|
+
this._migration = 0; // счётчик переездов: результат устаревшего старта/переезда игнорируется
|
|
92
|
+
this._readyAnnounced = false;
|
|
93
|
+
this._roomChanged = false;
|
|
94
|
+
this._stateReceived = false;
|
|
145
95
|
|
|
146
96
|
let readyResolve;
|
|
147
97
|
let readyReject;
|
|
@@ -153,215 +103,360 @@ class VoiceConnection extends EventEmitter {
|
|
|
153
103
|
this._readyResolve = readyResolve;
|
|
154
104
|
this._readyReject = readyReject;
|
|
155
105
|
|
|
156
|
-
this.
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
106
|
+
this._selfMute = Boolean(selfMute);
|
|
107
|
+
this._selfDeaf = Boolean(selfDeaf);
|
|
108
|
+
|
|
109
|
+
try {
|
|
110
|
+
this._adapter = adapterCreator({
|
|
111
|
+
onVoiceStateUpdate: data => {
|
|
112
|
+
this.sessionId = data.session_id;
|
|
113
|
+
if (data.channel_id === null || data.channel_id === undefined) {
|
|
114
|
+
if (this._stateReceived) this.destroy();
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
this._stateReceived = true;
|
|
118
|
+
const channelId = String(data.channel_id);
|
|
119
|
+
if (channelId !== String(this.channelId)) {
|
|
120
|
+
this.channelId = channelId;
|
|
121
|
+
if (this._started) this._roomChanged = true;
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
onVoiceServerUpdate: data => {
|
|
125
|
+
// Повторный Voice Server Update у уже поднятого соединения приходит, когда голосовой сервер
|
|
126
|
+
// канала сменили вручную (SetChannelVoiceServer -> migrateBotParticipant) или назначенный
|
|
127
|
+
// сервер нездоров и бот повторил op 4; также после перемещения бота в другой канал (тот же
|
|
128
|
+
// endpoint, но новая комната). Failover мёртвого сервера сюда не приходит — он только кикает.
|
|
129
|
+
// Смена одного лишь токена сессию не трогает: бэкенд перевыпускает его на каждый
|
|
130
|
+
// Voice State Update (например, при self_mute).
|
|
131
|
+
const serverChanged =
|
|
132
|
+
this._started && Boolean(data.endpoint) && (data.endpoint !== this.endpoint || this._roomChanged);
|
|
133
|
+
this.token = data.token;
|
|
134
|
+
if (data.endpoint || !this._started) this.endpoint = data.endpoint;
|
|
135
|
+
if (serverChanged) {
|
|
136
|
+
this._roomChanged = false;
|
|
137
|
+
this._migrate();
|
|
138
|
+
} else {
|
|
139
|
+
this._maybeStart();
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
// Шард отключился безвозвратно: полный локальный teardown без op 4 и без adapter.destroy().
|
|
143
|
+
destroy: () => {
|
|
144
|
+
if (this._destroyed) return;
|
|
145
|
+
this._destroyed = true;
|
|
146
|
+
this.state = 'destroyed';
|
|
147
|
+
this._finalize();
|
|
148
|
+
this.emit('destroyed');
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
} catch (error) {
|
|
152
|
+
// адаптер не создался: отправитель в ядре уже есть и без владельца не закроется
|
|
153
|
+
this._player.close();
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
170
156
|
|
|
157
|
+
this._sendState(channelId);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
_sendState(channelId) {
|
|
171
161
|
// Op 4 — Voice State Update (просим сервер подключить нас к каналу).
|
|
172
|
-
this._adapter.sendPayload({
|
|
162
|
+
return this._adapter.sendPayload({
|
|
173
163
|
op: 4,
|
|
174
|
-
d: { guild_id: guildId, channel_id: channelId, self_mute:
|
|
164
|
+
d: { guild_id: this.guildId, channel_id: channelId, self_mute: this._selfMute, self_deaf: this._selfDeaf },
|
|
175
165
|
});
|
|
176
166
|
}
|
|
177
167
|
|
|
168
|
+
/**
|
|
169
|
+
* Переместить соединение в другой канал (или обновить mute/deaf) без пересоздания.
|
|
170
|
+
* @param {Object} options
|
|
171
|
+
* @param {string} [options.channelId] ID нового голосового канала
|
|
172
|
+
* @param {boolean} [options.selfMute]
|
|
173
|
+
* @param {boolean} [options.selfDeaf]
|
|
174
|
+
* @returns {boolean} Удалось ли отправить op 4
|
|
175
|
+
*/
|
|
176
|
+
rejoin({ channelId = this.channelId, selfMute = this._selfMute, selfDeaf = this._selfDeaf } = {}) {
|
|
177
|
+
if (this._destroyed) throw new Error('voice connection is destroyed');
|
|
178
|
+
this._selfMute = Boolean(selfMute);
|
|
179
|
+
this._selfDeaf = Boolean(selfDeaf);
|
|
180
|
+
return this._sendState(channelId);
|
|
181
|
+
}
|
|
182
|
+
|
|
178
183
|
/** Дождаться готовности соединения (WebRTC поднят). */
|
|
179
184
|
awaitReady(timeout = 30000) {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
185
|
+
let timer;
|
|
186
|
+
const timeoutPromise = new Promise((_, rej) => {
|
|
187
|
+
timer = setTimeout(() => rej(new Error('voice connection timeout')), timeout);
|
|
188
|
+
});
|
|
189
|
+
return Promise.race([this._ready, timeoutPromise]).finally(() => clearTimeout(timer));
|
|
184
190
|
}
|
|
185
191
|
|
|
186
192
|
async _maybeStart() {
|
|
187
193
|
if (this._started || this._destroyed || !this.token || !this.endpoint) return;
|
|
188
194
|
this._started = true;
|
|
195
|
+
const migration = this._migration;
|
|
189
196
|
try {
|
|
190
|
-
await this._start();
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
this.
|
|
197
|
+
await this._start(migration);
|
|
198
|
+
// Пока поднимались, голосовой сервер сменился — исход этого старта уже не важен,
|
|
199
|
+
// готовность объявит _migrate.
|
|
200
|
+
if (migration !== this._migration) return;
|
|
201
|
+
this._markReady();
|
|
194
202
|
} catch (error) {
|
|
195
|
-
this.
|
|
196
|
-
this.emit('error', error);
|
|
203
|
+
if (migration !== this._migration || this._destroyed) return;
|
|
197
204
|
this._readyReject(error);
|
|
205
|
+
if (this.listenerCount('error') > 0) this.emit('error', error);
|
|
206
|
+
this.destroy();
|
|
198
207
|
}
|
|
199
208
|
}
|
|
200
209
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
210
|
+
/** Соединение поднято: `ready` и awaitReady() срабатывают один раз, даже после переездов. */
|
|
211
|
+
_markReady() {
|
|
212
|
+
this.state = 'ready';
|
|
213
|
+
if (this._readyAnnounced) return;
|
|
214
|
+
this._readyAnnounced = true;
|
|
215
|
+
this.emit('ready');
|
|
216
|
+
this._readyResolve();
|
|
205
217
|
}
|
|
206
218
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
this.
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
219
|
+
/**
|
|
220
|
+
* Голосовой сервер сменился — пересобираем сессию на новом endpoint. Исходящий трек
|
|
221
|
+
* сохраняется, поэтому текущее воспроизведение не прерывается.
|
|
222
|
+
*/
|
|
223
|
+
async _migrate() {
|
|
224
|
+
if (this._destroyed) return;
|
|
225
|
+
const migration = ++this._migration;
|
|
226
|
+
this.state = 'connecting';
|
|
227
|
+
this._closeSession();
|
|
228
|
+
try {
|
|
229
|
+
await this._start(migration);
|
|
230
|
+
if (migration !== this._migration || this._destroyed) return;
|
|
231
|
+
this._markReady();
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if (migration !== this._migration || this._destroyed) return;
|
|
234
|
+
this._readyReject(error);
|
|
235
|
+
if (this.listenerCount('error') > 0) this.emit('error', error);
|
|
236
|
+
this.destroy();
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async _start(migration) {
|
|
240
|
+
const session = this._createSession();
|
|
241
|
+
this._session = session;
|
|
242
|
+
try {
|
|
243
|
+
await session.start();
|
|
244
|
+
} catch (error) {
|
|
245
|
+
// сессия при сбое старта закрылась сама; устаревшая (переезд, destroy) уже закрыта нами
|
|
246
|
+
if (this._session === session) {
|
|
247
|
+
this._session = null;
|
|
248
|
+
this.receiver._sessionClosed();
|
|
249
|
+
}
|
|
250
|
+
throw error;
|
|
251
|
+
}
|
|
252
|
+
if (migration !== this._migration || this._destroyed) throw new Error('voice session superseded');
|
|
253
|
+
// проигрывать можно, как только есть send-сессия; отправитель переживает смену голосового сервера
|
|
254
|
+
this._canPlay = true;
|
|
255
|
+
}
|
|
217
256
|
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
257
|
+
/**
|
|
258
|
+
* Сессия с текущим голосовым сервером: сигналинг, транспорты, produce, приём (во вложенном слое). Колбэки
|
|
259
|
+
* устаревшей сессии (уже закрытой переездом) игнорируются.
|
|
260
|
+
*/
|
|
261
|
+
_createSession() {
|
|
262
|
+
const { voice } = ensureVoiceDeps();
|
|
263
|
+
const current = () => this._session === session && !this._destroyed;
|
|
264
|
+
const session = new voice.VoiceSession({
|
|
265
|
+
endpoint: this.endpoint,
|
|
266
|
+
token: this.token,
|
|
267
|
+
name: `lolka-${this.guildId}`,
|
|
268
|
+
player: this._player,
|
|
269
|
+
receive: this._wantReceive,
|
|
270
|
+
recvRebuildThreshold: VoiceConnection.recvRebuildThreshold,
|
|
271
|
+
// кик или обрыв сигналинга: при переезде за ним сразу следует новый Voice Server Update
|
|
272
|
+
onClosed: () => {
|
|
273
|
+
if (current()) this._scheduleKickDestroy();
|
|
274
|
+
},
|
|
275
|
+
onTrack: remote => {
|
|
276
|
+
if (!current()) return;
|
|
277
|
+
const track = new RemoteAudioTrack(remote);
|
|
278
|
+
this.receiver._trackAdded(track);
|
|
279
|
+
this.emit('track', track, track.userId, track.producerId);
|
|
280
|
+
},
|
|
281
|
+
onTrackEnded: remote => {
|
|
282
|
+
const track = this.receiver.tracks.get(remote.producerId);
|
|
283
|
+
if (track && track._remote === remote) this.receiver._trackClosed(track);
|
|
284
|
+
},
|
|
285
|
+
onSpeaking: (userId, speaking) => {
|
|
286
|
+
if (current()) this.emit('speaking', userId, speaking);
|
|
287
|
+
},
|
|
288
|
+
onError: error => {
|
|
289
|
+
if (current() && this.listenerCount('error') > 0) this.emit('error', error);
|
|
290
|
+
},
|
|
291
|
+
});
|
|
292
|
+
return session;
|
|
293
|
+
}
|
|
222
294
|
|
|
223
|
-
|
|
224
|
-
|
|
295
|
+
/**
|
|
296
|
+
* Включить приём (идемпотентно): recv-транспорт, getProducers и consume всех аудио-продюсеров, дальше consume
|
|
297
|
+
* на каждый newProducer. Раз включённый, приём живёт до конца сессии: закрыть консьюмер на сервере нельзя.
|
|
298
|
+
* Пока сессия не поднялась, запрос запоминается и выполняется при старте.
|
|
299
|
+
*/
|
|
300
|
+
_enableReceive() {
|
|
301
|
+
if (this._destroyed) return;
|
|
302
|
+
this._wantReceive = true;
|
|
303
|
+
this._session?.requestReceive();
|
|
225
304
|
}
|
|
226
305
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
)
|
|
236
|
-
|
|
237
|
-
this.
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
.catch(errback),
|
|
241
|
-
);
|
|
306
|
+
/**
|
|
307
|
+
* Сервер кикнул нас (или сигналинг оборвался). При перемещении бота в другой канал за киком сразу
|
|
308
|
+
* следует переезд, поэтому уничтожаем соединение только если за grace-период переезда не было.
|
|
309
|
+
*/
|
|
310
|
+
_scheduleKickDestroy() {
|
|
311
|
+
if (this._destroyed) return;
|
|
312
|
+
const migration = this._migration;
|
|
313
|
+
clearTimeout(this._kickTimer);
|
|
314
|
+
this._kickTimer = setTimeout(() => {
|
|
315
|
+
this._kickTimer = null;
|
|
316
|
+
if (!this._destroyed && migration === this._migration) this.destroy();
|
|
317
|
+
}, VoiceConnection.kickGraceMs);
|
|
318
|
+
this._kickTimer.unref?.();
|
|
242
319
|
}
|
|
243
320
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
321
|
+
/**
|
|
322
|
+
* Проиграть аудио в канал. Opus уходит в SFU без декодирования и повторного кодирования
|
|
323
|
+
* (для `'arbitrary'` ffmpeg один раз кодирует вход в Opus).
|
|
324
|
+
* @param {string|import('node:stream').Readable} input Путь к файлу или Readable-поток.
|
|
325
|
+
* @param {Object} [options]
|
|
326
|
+
* @param {'arbitrary'|'raw'|'ogg/opus'|'webm/opus'|'opus'} [options.inputType='arbitrary'] Формат входа:
|
|
327
|
+
* любой через ffmpeg, PCM s16le 48 кГц стерео без заголовка через ffmpeg, Ogg/Opus или WebM/Opus без ffmpeg,
|
|
328
|
+
* объектный поток готовых Opus-пакетов.
|
|
329
|
+
* @param {number} [options.bitrate=128] Битрейт кодирования в кбит/с (только для `'arbitrary'` и `'raw'`).
|
|
330
|
+
*/
|
|
331
|
+
play(input, { inputType, bitrate } = {}) {
|
|
332
|
+
if (!this._canPlay || this._destroyed) throw new Error('voice connection is not ready');
|
|
333
|
+
this.stop();
|
|
334
|
+
const playback = new OpusPlayback(input, { inputType, bitrate });
|
|
335
|
+
this._playback = playback;
|
|
336
|
+
this._player.play(playback.pump, error => this._onPlayEnd(playback, error));
|
|
337
|
+
this.emit('playing');
|
|
253
338
|
}
|
|
254
339
|
|
|
255
|
-
|
|
256
|
-
|
|
340
|
+
// Источник доигран (после хвоста) или сломался; не вызывается после stop() и play() поверх.
|
|
341
|
+
_onPlayEnd(playback, error) {
|
|
342
|
+
if (this._playback !== playback) return;
|
|
343
|
+
this._playback = null;
|
|
257
344
|
try {
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
rtpCapabilities: this._device.rtpCapabilities,
|
|
262
|
-
});
|
|
263
|
-
const consumer = await this._recvTransport.consume(params);
|
|
264
|
-
await this._signaling.request('resumeConsumer', { consumerId: consumer.id });
|
|
265
|
-
this._consumers.set(producerId, consumer);
|
|
266
|
-
this.emit('track', consumer.track, userId, producerId);
|
|
267
|
-
} catch (error) {
|
|
268
|
-
this.emit('error', error);
|
|
345
|
+
if (error && this.listenerCount('error') > 0) this.emit('error', error);
|
|
346
|
+
} finally {
|
|
347
|
+
this.emit('idle');
|
|
269
348
|
}
|
|
270
349
|
}
|
|
271
350
|
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
351
|
+
/**
|
|
352
|
+
* Остановить текущее воспроизведение и снять подписку на плеер.
|
|
353
|
+
* Хвост тишины уходит как при паузе; события `'idle'` нет.
|
|
354
|
+
*/
|
|
355
|
+
stop() {
|
|
356
|
+
this._subscription?.unsubscribe();
|
|
357
|
+
this._player.stop();
|
|
358
|
+
this._playback = null;
|
|
280
359
|
}
|
|
281
360
|
|
|
282
361
|
/**
|
|
283
|
-
*
|
|
284
|
-
*
|
|
362
|
+
* Подписаться на плеер (`createAudioPlayer()`): канал играет то, что играет плеер, с текущего места.
|
|
363
|
+
* Один плеер можно подписать на сколько угодно соединений, у соединения подписка одна: новая снимает
|
|
364
|
+
* прежнюю. Собственное проигрывание (`play()`) останавливается без события `'idle'`.
|
|
365
|
+
* @param {import('./AudioPlayer').AudioPlayer} player
|
|
366
|
+
* @returns {import('./AudioPlayer').PlayerSubscription|undefined} `undefined` у уничтоженного соединения
|
|
285
367
|
*/
|
|
286
|
-
|
|
287
|
-
if (!
|
|
288
|
-
this.
|
|
368
|
+
subscribe(player) {
|
|
369
|
+
if (!player || typeof player._subscribe !== 'function') throw new TypeError('subscribe() requires an audio player');
|
|
370
|
+
if (this._destroyed) return undefined;
|
|
371
|
+
const existing = this._subscription;
|
|
372
|
+
if (existing && existing.player === player) return existing;
|
|
373
|
+
const feed = player._ensureFeed();
|
|
374
|
+
existing?.unsubscribe();
|
|
375
|
+
this._player.stop();
|
|
376
|
+
this._playback = null;
|
|
377
|
+
this._player.follow(feed);
|
|
378
|
+
const subscription = player._subscribe(this);
|
|
379
|
+
this._subscription = subscription;
|
|
380
|
+
return subscription;
|
|
381
|
+
}
|
|
289
382
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
383
|
+
/**
|
|
384
|
+
* Текущая подписка на плеер. Состояние соединения (`state`) здесь строка, поэтому подписка лежит
|
|
385
|
+
* отдельно, а не в `state.subscription`, как в @discordjs/voice.
|
|
386
|
+
* @type {import('./AudioPlayer').PlayerSubscription|undefined}
|
|
387
|
+
*/
|
|
388
|
+
get subscription() {
|
|
389
|
+
return this._subscription ?? undefined;
|
|
390
|
+
}
|
|
298
391
|
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
this.emit('error', error);
|
|
306
|
-
});
|
|
392
|
+
/** @internal Вызывает `PlayerSubscription#unsubscribe()`. */
|
|
393
|
+
_onSubscriptionRemoved(subscription) {
|
|
394
|
+
if (this._subscription !== subscription) return;
|
|
395
|
+
this._subscription = null;
|
|
396
|
+
this._player.leave();
|
|
397
|
+
}
|
|
307
398
|
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
this.
|
|
311
|
-
|
|
312
|
-
let frame = 0;
|
|
313
|
-
this.emit('playing');
|
|
399
|
+
/** Отправитель может сейчас слать звук трансляции: открыт транспорт, нет паузы соединения. @internal */
|
|
400
|
+
get _canSend() {
|
|
401
|
+
return this._player.playable;
|
|
402
|
+
}
|
|
314
403
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
// wrtc требует Int16Array в отдельном ArrayBuffer ровно нужного размера.
|
|
324
|
-
const ab = new ArrayBuffer(FRAME_BYTES);
|
|
325
|
-
if (chunk) {
|
|
326
|
-
if (chunk.length < FRAME_BYTES) {
|
|
327
|
-
const padded = Buffer.alloc(FRAME_BYTES);
|
|
328
|
-
chunk.copy(padded);
|
|
329
|
-
chunk = padded;
|
|
330
|
-
}
|
|
331
|
-
new Uint8Array(ab).set(chunk.subarray(0, FRAME_BYTES));
|
|
332
|
-
}
|
|
333
|
-
// Если данных нет (джиттер) — кадр остаётся тишиной, расписание не сбиваем.
|
|
334
|
-
this._audioSource.onData({
|
|
335
|
-
samples: new Int16Array(ab),
|
|
336
|
-
sampleRate: SAMPLE_RATE,
|
|
337
|
-
bitsPerSample: 16,
|
|
338
|
-
channelCount: CHANNELS,
|
|
339
|
-
numberOfFrames: FRAME_SAMPLES,
|
|
340
|
-
});
|
|
341
|
-
frame += 1;
|
|
342
|
-
const target = start + frame * 10;
|
|
343
|
-
this._playTimer = setTimeout(tick, Math.max(0, target - performance.now()));
|
|
344
|
-
};
|
|
404
|
+
/**
|
|
405
|
+
* Поставить воспроизведение на паузу: в эфир не уходит ни одного пакета. При подписке на плеер
|
|
406
|
+
* пауза касается только этого соединения.
|
|
407
|
+
* @returns {boolean} Изменилось ли состояние
|
|
408
|
+
*/
|
|
409
|
+
pause() {
|
|
410
|
+
return !this._player.closed && this._player.pause();
|
|
411
|
+
}
|
|
345
412
|
|
|
346
|
-
|
|
347
|
-
|
|
413
|
+
/**
|
|
414
|
+
* Продолжить воспроизведение с того же места (при подписке на плеер – с текущего места плеера).
|
|
415
|
+
* @returns {boolean} Изменилось ли состояние
|
|
416
|
+
*/
|
|
417
|
+
resume() {
|
|
418
|
+
return !this._player.closed && this._player.resume();
|
|
348
419
|
}
|
|
349
420
|
|
|
350
|
-
/**
|
|
351
|
-
|
|
352
|
-
this.
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
421
|
+
/** Алиас {@link VoiceConnection#resume}. */
|
|
422
|
+
unpause() {
|
|
423
|
+
return this.resume();
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** Воспроизведение на паузе. */
|
|
427
|
+
get paused() {
|
|
428
|
+
return !this._player.closed && this._player.paused;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Счётчики отправки и состояние: packetsSent, bytesSent, underruns, lateTicks, bursts, resyncs,
|
|
433
|
+
* silentSkipped, drops, skipped (кадры плеера, пропущенные из-за отставания), а также playing, paused,
|
|
434
|
+
* subscribed, queuedFrames, transportState, receiving, consumers.
|
|
435
|
+
* @returns {Object}
|
|
436
|
+
*/
|
|
437
|
+
stats() {
|
|
438
|
+
const session = this._session;
|
|
439
|
+
const closed = this._player.closed;
|
|
440
|
+
const counters = closed ? NO_COUNTERS : this._player.stats();
|
|
441
|
+
return {
|
|
442
|
+
state: this.state,
|
|
443
|
+
playing: !closed && this._player.playing,
|
|
444
|
+
paused: this.paused,
|
|
445
|
+
subscribed: Boolean(this._subscription),
|
|
446
|
+
queuedFrames: counters.queuedFrames ?? 0,
|
|
447
|
+
transportState: session?.transportState ?? null,
|
|
448
|
+
receiving: Boolean(session?.receiving),
|
|
449
|
+
consumers: session?.consumers.size ?? 0,
|
|
450
|
+
packetsSent: counters.packetsSent,
|
|
451
|
+
bytesSent: counters.bytesSent,
|
|
452
|
+
underruns: counters.underruns,
|
|
453
|
+
lateTicks: counters.lateTicks,
|
|
454
|
+
bursts: counters.bursts,
|
|
455
|
+
resyncs: counters.resyncs,
|
|
456
|
+
silentSkipped: counters.silentSkipped,
|
|
457
|
+
drops: counters.drops,
|
|
458
|
+
skipped: counters.skipped,
|
|
459
|
+
};
|
|
365
460
|
}
|
|
366
461
|
|
|
367
462
|
/** Выйти из канала и освободить ресурсы. */
|
|
@@ -369,7 +464,6 @@ class VoiceConnection extends EventEmitter {
|
|
|
369
464
|
if (this._destroyed) return;
|
|
370
465
|
this._destroyed = true;
|
|
371
466
|
this.state = 'destroyed';
|
|
372
|
-
this.stop();
|
|
373
467
|
try {
|
|
374
468
|
this._adapter?.sendPayload({
|
|
375
469
|
op: 4,
|
|
@@ -378,7 +472,7 @@ class VoiceConnection extends EventEmitter {
|
|
|
378
472
|
} catch {
|
|
379
473
|
// ignore
|
|
380
474
|
}
|
|
381
|
-
this.
|
|
475
|
+
this._finalize();
|
|
382
476
|
try {
|
|
383
477
|
this._adapter?.destroy();
|
|
384
478
|
} catch {
|
|
@@ -387,19 +481,25 @@ class VoiceConnection extends EventEmitter {
|
|
|
387
481
|
this.emit('destroyed');
|
|
388
482
|
}
|
|
389
483
|
|
|
390
|
-
|
|
391
|
-
this.
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
this.
|
|
401
|
-
|
|
402
|
-
|
|
484
|
+
_finalize() {
|
|
485
|
+
clearTimeout(this._kickTimer);
|
|
486
|
+
this._kickTimer = null;
|
|
487
|
+
this.stop();
|
|
488
|
+
this._closeSession();
|
|
489
|
+
this._player.close();
|
|
490
|
+
this._canPlay = false;
|
|
491
|
+
this.receiver._destroy();
|
|
492
|
+
if (!this._readyAnnounced) this._readyReject(new Error('voice connection destroyed'));
|
|
493
|
+
const byGuild = connections.get(this._owner);
|
|
494
|
+
if (byGuild?.get(this.guildId) === this) byGuild.delete(this.guildId);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** Закрыть сессию с текущим голосовым сервером, не трогая отправитель: к нему подключится новая сессия. */
|
|
498
|
+
_closeSession() {
|
|
499
|
+
const session = this._session;
|
|
500
|
+
this._session = null;
|
|
501
|
+
session?.close().catch(() => {});
|
|
502
|
+
this.receiver._sessionClosed();
|
|
403
503
|
}
|
|
404
504
|
}
|
|
405
505
|
|
|
@@ -411,10 +511,39 @@ class VoiceConnection extends EventEmitter {
|
|
|
411
511
|
* @param {Function} options.adapterCreator `guild.voiceAdapterCreator`
|
|
412
512
|
* @param {boolean} [options.selfMute=false]
|
|
413
513
|
* @param {boolean} [options.selfDeaf=false]
|
|
514
|
+
* @param {boolean} [options.receive=false] Сразу включить приём чужого звука (иначе он включается
|
|
515
|
+
* слушателем 'track' или `receiver.subscribe()`)
|
|
414
516
|
* @returns {VoiceConnection}
|
|
415
517
|
*/
|
|
416
518
|
function joinVoiceChannel(options) {
|
|
417
|
-
|
|
519
|
+
const owner = ownerOf(options.adapterCreator);
|
|
520
|
+
let byGuild = connections.get(owner);
|
|
521
|
+
const existing = byGuild?.get(options.guildId);
|
|
522
|
+
if (existing && !existing._destroyed) {
|
|
523
|
+
existing.rejoin({ channelId: options.channelId, selfMute: options.selfMute, selfDeaf: options.selfDeaf });
|
|
524
|
+
if (options.receive) existing._enableReceive();
|
|
525
|
+
return existing;
|
|
526
|
+
}
|
|
527
|
+
const connection = new VoiceConnection(options);
|
|
528
|
+
if (!byGuild) {
|
|
529
|
+
byGuild = new Map();
|
|
530
|
+
connections.set(owner, byGuild);
|
|
531
|
+
}
|
|
532
|
+
byGuild.set(options.guildId, connection);
|
|
533
|
+
return connection;
|
|
418
534
|
}
|
|
419
535
|
|
|
536
|
+
/**
|
|
537
|
+
* How long (ms) the connection survives a kick or a lost signaling socket waiting for a move.
|
|
538
|
+
* @type {number}
|
|
539
|
+
*/
|
|
540
|
+
VoiceConnection.kickGraceMs = DEFAULT_KICK_GRACE_MS;
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* How many closed (`m=audio 0`) receive sections a connection tolerates before it rebuilds its receive
|
|
544
|
+
* transport (consuming the active participants again; tracks and subscriptions survive).
|
|
545
|
+
* @type {number}
|
|
546
|
+
*/
|
|
547
|
+
VoiceConnection.recvRebuildThreshold = 128;
|
|
548
|
+
|
|
420
549
|
module.exports = { VoiceConnection, joinVoiceChannel };
|