lolka.js 0.4.4 → 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.
Files changed (44) hide show
  1. package/README.md +242 -12
  2. package/package.json +3 -5
  3. package/src/client/voice/AudioPlayer.js +358 -0
  4. package/src/client/voice/AudioResource.js +137 -0
  5. package/src/client/voice/VoiceConnection.js +296 -383
  6. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libdatachannel.txt +373 -0
  7. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libjuice.txt +373 -0
  8. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libsrtp.txt +35 -0
  9. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-nlohmann-json.txt +21 -0
  10. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-node-addon-api.txt +9 -0
  11. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-node-api-headers.txt +21 -0
  12. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-openssl.txt +177 -0
  13. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-opus.txt +44 -0
  14. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-plog.txt +21 -0
  15. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-usrsctp.txt +27 -0
  16. package/src/client/voice/_lolka_voice/LICENSES/THIRD-PARTY.txt +16 -0
  17. package/src/client/voice/_lolka_voice/MANIFEST.json +47 -0
  18. package/src/client/voice/_lolka_voice/_loader.js +103 -0
  19. package/src/client/voice/_lolka_voice/_native/linux-aarch64/core.node +0 -0
  20. package/src/client/voice/_lolka_voice/_native/linux-aarch64-musl/core.node +0 -0
  21. package/src/client/voice/_lolka_voice/_native/linux-x86_64/core.node +0 -0
  22. package/src/client/voice/_lolka_voice/_native/linux-x86_64-musl/core.node +0 -0
  23. package/src/client/voice/_lolka_voice/_native/macos-arm64/core.node +0 -0
  24. package/src/client/voice/_lolka_voice/_native/macos-x86_64/core.node +0 -0
  25. package/src/client/voice/_lolka_voice/_native/windows-x86_64/core.node +0 -0
  26. package/src/client/voice/_lolka_voice/_version.js +4 -0
  27. package/src/client/voice/_lolka_voice/caps.js +56 -0
  28. package/src/client/voice/_lolka_voice/core.d.ts +200 -0
  29. package/src/client/voice/_lolka_voice/errors.js +22 -0
  30. package/src/client/voice/_lolka_voice/events.js +119 -0
  31. package/src/client/voice/_lolka_voice/index.d.ts +226 -0
  32. package/src/client/voice/_lolka_voice/index.js +35 -0
  33. package/src/client/voice/_lolka_voice/player.js +606 -0
  34. package/src/client/voice/_lolka_voice/receive.js +387 -0
  35. package/src/client/voice/_lolka_voice/sdp.js +137 -0
  36. package/src/client/voice/_lolka_voice/session.js +335 -0
  37. package/src/client/voice/_lolka_voice/signaling.js +120 -0
  38. package/src/client/voice/_lolka_voice/transport.js +260 -0
  39. package/src/client/voice/media/OpusPlayback.js +199 -0
  40. package/src/client/voice/media/Receiver.js +245 -0
  41. package/src/client/voice/media/deps.js +27 -0
  42. package/src/index.js +11 -0
  43. package/typings/index.d.mts +248 -4
  44. package/typings/index.d.ts +248 -4
@@ -2,50 +2,41 @@
2
2
 
3
3
  // WebRTC-голос для lolka.js.
4
4
  //
5
- // lolka voice работает через WebRTC (как клиенты lolka), а не через Discord UDP.
6
- // Использует официальный WebRTC-клиент поверх @roamhq/wrtc для Node
7
- // и говорит с голосовым сервером по простому JSON-RPC поверх WebSocket.
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'); // путь к файлу или Readable-поток
13
- // conn.on('track', (track, userId) => {}); // приём чужого звука (wrtc MediaStreamTrack)
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');
22
+ const { ensureVoiceDeps } = require('./media/deps');
23
+ const { OpusPlayback } = require('./media/OpusPlayback');
24
+ const { Receiver, RemoteAudioTrack } = require('./media/Receiver');
17
25
 
18
- // Зависимости голоса подгружаются лениво: `require('lolka.js')` не тянет WebRTC,
19
- // пока голос реально не используется.
20
- let wrtc;
21
- let rtcClient;
22
- let WebSocketImpl;
23
- let FFmpeg;
24
- let depsReady = false;
25
-
26
- function ensureVoiceDeps() {
27
- if (depsReady) return;
28
- wrtc = require('@roamhq/wrtc');
29
- rtcClient = require('mediasoup-client');
30
- WebSocketImpl = require('ws');
31
- FFmpeg = require('prism-media').FFmpeg;
32
- // WebRTC-клиент браузерный, ему нужны WebRTC-глобалы.
33
- for (const key of [
34
- 'RTCPeerConnection', 'RTCSessionDescription', 'RTCIceCandidate', 'MediaStream',
35
- 'MediaStreamTrack', 'RTCRtpSender', 'RTCRtpReceiver', 'RTCRtpTransceiver',
36
- 'RTCDtlsTransport', 'RTCIceTransport', 'RTCDataChannel', 'RTCSctpTransport',
37
- ]) {
38
- if (wrtc[key] && !global[key]) global[key] = wrtc[key];
39
- }
40
- depsReady = true;
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
26
  const DEFAULT_KICK_GRACE_MS = 5000;
48
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
+
49
40
  // Живые соединения: owner (голосовой менеджер клиента) -> guildId -> соединение. Повторный
50
41
  // joinVoiceChannel переиспользует соединение через rejoin(); разные клиенты не пересекаются.
51
42
  const defaultOwner = {};
@@ -55,99 +46,12 @@ function ownerOf(adapterCreator) {
55
46
  return adapterCreator?.voiceManager ?? defaultOwner;
56
47
  }
57
48
 
58
- // JSON-RPC поверх WebSocket к голосовому серверу.
59
- // request: { id, method, data }
60
- // response: { id, response: true, data } | { id, response: true, error }
61
- // notification: { notification: true, method, data }
62
- class VoiceSignaling {
63
- constructor(url, onNotification, onClose) {
64
- this.url = url;
65
- this.onNotification = onNotification;
66
- this.onClose = onClose;
67
- this.closing = false;
68
- this.ws = null;
69
- this.pending = new Map();
70
- this.nextId = 1;
71
- }
72
-
73
- connect() {
74
- return new Promise((resolve, reject) => {
75
- this.ws = new WebSocketImpl(this.url);
76
- this.ws.on('open', resolve);
77
- this.ws.on('error', reject);
78
- this.ws.on('close', () => {
79
- for (const [id, p] of this.pending) {
80
- this.pending.delete(id);
81
- p.reject(new Error('voice signaling closed'));
82
- }
83
- if (!this.closing) this.onClose?.();
84
- });
85
- this.ws.on('message', buffer => {
86
- let obj;
87
- try {
88
- obj = JSON.parse(buffer.toString());
89
- } catch {
90
- return;
91
- }
92
- if (obj.response) {
93
- const p = this.pending.get(obj.id);
94
- if (p) {
95
- this.pending.delete(obj.id);
96
- if (obj.error) p.reject(new Error(String(obj.error)));
97
- else p.resolve(obj.data ?? {});
98
- }
99
- } else if (obj.notification) {
100
- Promise.resolve(this.onNotification(obj.method, obj.data ?? {})).catch(() => {});
101
- }
102
- });
103
- });
104
- }
105
-
106
- request(method, data = {}, timeout = 15000) {
107
- return new Promise((resolve, reject) => {
108
- const id = this.nextId++;
109
- const timer = setTimeout(() => {
110
- if (this.pending.has(id)) {
111
- this.pending.delete(id);
112
- reject(new Error(`voice signaling timeout: ${method}`));
113
- }
114
- }, timeout);
115
- this.pending.set(id, {
116
- resolve: value => {
117
- clearTimeout(timer);
118
- resolve(value);
119
- },
120
- reject: error => {
121
- clearTimeout(timer);
122
- reject(error);
123
- },
124
- });
125
- try {
126
- this.ws.send(JSON.stringify({ id, method, data }));
127
- } catch (error) {
128
- this.pending.delete(id);
129
- clearTimeout(timer);
130
- reject(error);
131
- }
132
- });
133
- }
134
-
135
- close() {
136
- this.closing = true;
137
- try {
138
- this.ws?.close();
139
- } catch {
140
- // ignore
141
- }
142
- }
143
- }
144
-
145
49
  /**
146
50
  * Активное голосовое соединение в канале.
147
51
  * @extends {EventEmitter}
148
52
  */
149
53
  class VoiceConnection extends EventEmitter {
150
- constructor({ channelId, guildId, adapterCreator, selfMute = false, selfDeaf = false }) {
54
+ constructor({ channelId, guildId, adapterCreator, selfMute = false, selfDeaf = false, receive = false }) {
151
55
  super();
152
56
  if (!channelId || !guildId || typeof adapterCreator !== 'function') {
153
57
  throw new TypeError('joinVoiceChannel requires { channelId, guildId, adapterCreator }');
@@ -163,18 +67,23 @@ class VoiceConnection extends EventEmitter {
163
67
  this.token = null;
164
68
  this.endpoint = null;
165
69
 
166
- this._signaling = null;
167
- this._device = null;
168
- this._sendTransport = null;
169
- this._recvTransport = null;
170
- this._audioSource = null;
171
- this._audioTrack = null;
172
- this._producer = null;
173
- this._consumers = new Map();
174
-
175
- this._playToken = null;
176
- this._playTimer = null;
177
- this._playFF = null;
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
+ });
178
87
 
179
88
  this._kickTimer = null;
180
89
  this._started = false;
@@ -197,47 +106,53 @@ class VoiceConnection extends EventEmitter {
197
106
  this._selfMute = Boolean(selfMute);
198
107
  this._selfDeaf = Boolean(selfDeaf);
199
108
 
200
- this._adapter = adapterCreator({
201
- onVoiceStateUpdate: data => {
202
- this.sessionId = data.session_id;
203
- if (data.channel_id === null || data.channel_id === undefined) {
204
- if (this._stateReceived) this.destroy();
205
- return;
206
- }
207
- this._stateReceived = true;
208
- const channelId = String(data.channel_id);
209
- if (channelId !== String(this.channelId)) {
210
- this.channelId = channelId;
211
- if (this._started) this._roomChanged = true;
212
- }
213
- },
214
- onVoiceServerUpdate: data => {
215
- // Повторный Voice Server Update у уже поднятого соединения приходит, когда голосовой сервер
216
- // канала сменили вручную (SetChannelVoiceServer -> migrateBotParticipant) или назначенный
217
- // сервер нездоров и бот повторил op 4; также после перемещения бота в другой канал (тот же
218
- // endpoint, но новая комната). Failover мёртвого сервера сюда не приходит — он только кикает.
219
- // Смена одного лишь токена сессию не трогает: бэкенд перевыпускает его на каждый
220
- // Voice State Update (например, при self_mute).
221
- const serverChanged =
222
- this._started && Boolean(data.endpoint) && (data.endpoint !== this.endpoint || this._roomChanged);
223
- this.token = data.token;
224
- if (data.endpoint || !this._started) this.endpoint = data.endpoint;
225
- if (serverChanged) {
226
- this._roomChanged = false;
227
- this._migrate();
228
- } else {
229
- this._maybeStart();
230
- }
231
- },
232
- // Шард отключился безвозвратно: полный локальный teardown без op 4 и без adapter.destroy().
233
- destroy: () => {
234
- if (this._destroyed) return;
235
- this._destroyed = true;
236
- this.state = 'destroyed';
237
- this._finalize();
238
- this.emit('destroyed');
239
- },
240
- });
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
+ }
241
156
 
242
157
  this._sendState(channelId);
243
158
  }
@@ -301,12 +216,6 @@ class VoiceConnection extends EventEmitter {
301
216
  this._readyResolve();
302
217
  }
303
218
 
304
- _signalingUrl() {
305
- let ep = this.endpoint || '';
306
- if (!ep.includes('://')) ep = `ws://${ep}`;
307
- return `${ep}${ep.includes('?') ? '&' : '?'}token=${this.token}`;
308
- }
309
-
310
219
  /**
311
220
  * Голосовой сервер сменился — пересобираем сессию на новом endpoint. Исходящий трек
312
221
  * сохраняется, поэтому текущее воспроизведение не прерывается.
@@ -327,120 +236,71 @@ class VoiceConnection extends EventEmitter {
327
236
  this.destroy();
328
237
  }
329
238
  }
330
-
331
239
  async _start(migration) {
332
- const check = () => {
333
- if (migration !== this._migration || this._destroyed) throw new Error('voice session superseded');
334
- };
335
- const signaling = new VoiceSignaling(
336
- this._signalingUrl(),
337
- (method, data) => {
338
- // Уведомления от уже заменённого сигналинга (прежний голосовой сервер) игнорируем —
339
- // иначе его запоздалый `kicked` уничтожил бы переехавшее соединение.
340
- if (this._signaling !== signaling) return undefined;
341
- return this._onNotification(method, data);
342
- },
343
- () => {
344
- if (this._signaling === signaling) this._scheduleKickDestroy();
345
- },
346
- );
347
- this._signaling = signaling;
348
- await signaling.connect();
349
- check();
350
-
351
- const routerRtpCapabilities = await signaling.request('getRouterRtpCapabilities', {});
352
- check();
353
- const device = new rtcClient.Device({ handlerName: 'Chrome111' });
354
- await device.load({ routerRtpCapabilities });
355
- check();
356
- this._device = device;
357
-
358
- await this._createSendTransport(check);
359
- await this._createRecvTransport(check);
360
- check();
361
-
362
- // Постоянный исходящий трек; play() подаёт в него PCM. Создаётся один раз и переживает
363
- // смену голосового сервера (stopTracks: false — закрытие продюсера трек не останавливает).
364
- if (!this._audioSource) {
365
- this._audioSource = new wrtc.nonstandard.RTCAudioSource();
366
- this._audioTrack = this._audioSource.createTrack();
367
- }
368
- this._producer = await this._sendTransport.produce({ track: this._audioTrack, stopTracks: false });
369
-
370
- check();
371
- const { producers } = await signaling.request('getProducers', {});
372
- check();
373
- for (const p of producers) await this._consume(p.producerId, p.userId, p.kind);
374
- }
375
-
376
- async _createSendTransport(check) {
377
- const params = await this._signaling.request('createWebRtcTransport', { direction: 'send' });
378
- check();
379
- this._sendTransport = this._device.createSendTransport(params);
380
- const signaling = this._signaling;
381
- const transport = this._sendTransport;
382
- transport.on('connect', ({ dtlsParameters }, callback, errback) =>
383
- signaling
384
- .request('connectTransport', { transportId: transport.id, dtlsParameters })
385
- .then(() => callback())
386
- .catch(errback),
387
- );
388
- transport.on('produce', ({ kind, rtpParameters, appData }, callback, errback) =>
389
- signaling
390
- .request('produce', { transportId: transport.id, kind, rtpParameters, appData })
391
- .then(({ id }) => callback({ id }))
392
- .catch(errback),
393
- );
394
- }
395
-
396
- async _createRecvTransport(check) {
397
- const params = await this._signaling.request('createWebRtcTransport', { direction: 'recv' });
398
- check();
399
- this._recvTransport = this._device.createRecvTransport(params);
400
- const signaling = this._signaling;
401
- const transport = this._recvTransport;
402
- transport.on('connect', ({ dtlsParameters }, callback, errback) =>
403
- signaling
404
- .request('connectTransport', { transportId: transport.id, dtlsParameters })
405
- .then(() => callback())
406
- .catch(errback),
407
- );
408
- }
409
-
410
- async _consume(producerId, userId, kind) {
411
- const recv = this._recvTransport;
412
- const signaling = this._signaling;
413
- if (kind !== 'audio' || !recv || !signaling || this._consumers.has(producerId)) return;
240
+ const session = this._createSession();
241
+ this._session = session;
414
242
  try {
415
- const params = await signaling.request('consume', {
416
- transportId: recv.id,
417
- producerId,
418
- rtpCapabilities: this._device.rtpCapabilities,
419
- });
420
- if (this._recvTransport !== recv) return;
421
- const consumer = await recv.consume(params);
422
- if (this._recvTransport !== recv) return;
423
- await signaling.request('resumeConsumer', { consumerId: consumer.id });
424
- if (this._recvTransport !== recv) return;
425
- this._consumers.set(producerId, consumer);
426
- this.emit('track', consumer.track, userId, producerId);
243
+ await session.start();
427
244
  } catch (error) {
428
- if (this._recvTransport === recv && this.listenerCount('error') > 0) this.emit('error', error);
245
+ // сессия при сбое старта закрылась сама; устаревшая (переезд, destroy) уже закрыта нами
246
+ if (this._session === session) {
247
+ this._session = null;
248
+ this.receiver._sessionClosed();
249
+ }
250
+ throw error;
429
251
  }
252
+ if (migration !== this._migration || this._destroyed) throw new Error('voice session superseded');
253
+ // проигрывать можно, как только есть send-сессия; отправитель переживает смену голосового сервера
254
+ this._canPlay = true;
430
255
  }
431
256
 
432
- async _onNotification(method, data) {
433
- if (method === 'newProducer') {
434
- await this._consume(data.producerId, data.userId, data.kind);
435
- } else if (method === 'producerClosed') {
436
- if (data.producerId) this._consumers.delete(data.producerId);
437
- } else if (method === 'consumerClosed') {
438
- for (const [producerId, consumer] of this._consumers) {
439
- if (consumer.id === data.consumerId) this._consumers.delete(producerId);
440
- }
441
- } else if (method === 'kicked') {
442
- this._scheduleKickDestroy();
443
- }
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
+ }
294
+
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();
444
304
  }
445
305
 
446
306
  /**
@@ -459,88 +319,144 @@ class VoiceConnection extends EventEmitter {
459
319
  }
460
320
 
461
321
  /**
462
- * Проиграть аудио в канал.
463
- * @param {string|import('node:stream').Readable} input Путь к файлу или Readable-поток (любой формат — через ffmpeg).
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'`).
464
330
  */
465
- play(input) {
466
- if (!this._audioSource) throw new Error('voice connection is not ready');
331
+ play(input, { inputType, bitrate } = {}) {
332
+ if (!this._canPlay || this._destroyed) throw new Error('voice connection is not ready');
467
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');
338
+ }
468
339
 
469
- const args =
470
- typeof input === 'string'
471
- ? ['-i', input]
472
- : ['-i', 'pipe:0'];
473
- const ff = new FFmpeg({
474
- args: [...args, '-analyzeduration', '0', '-loglevel', '0', '-f', 's16le', '-ar', String(SAMPLE_RATE), '-ac', String(CHANNELS)],
475
- });
476
- if (typeof input !== 'string' && input && typeof input.pipe === 'function') input.pipe(ff);
340
+ // Источник доигран (после хвоста) или сломался; не вызывается после stop() и play() поверх.
341
+ _onPlayEnd(playback, error) {
342
+ if (this._playback !== playback) return;
343
+ this._playback = null;
344
+ try {
345
+ if (error && this.listenerCount('error') > 0) this.emit('error', error);
346
+ } finally {
347
+ this.emit('idle');
348
+ }
349
+ }
477
350
 
478
- let ended = false;
479
- ff.on('end', () => {
480
- ended = true;
481
- });
482
- ff.on('error', error => {
483
- ended = true;
484
- this.emit('error', error);
485
- });
351
+ /**
352
+ * Остановить текущее воспроизведение и снять подписку на плеер.
353
+ * Хвост тишины уходит как при паузе; события `'idle'` нет.
354
+ */
355
+ stop() {
356
+ this._subscription?.unsubscribe();
357
+ this._player.stop();
358
+ this._playback = null;
359
+ }
486
360
 
487
- const token = {};
488
- this._playToken = token;
489
- this._playFF = ff;
490
- const start = performance.now();
491
- let frame = 0;
492
- this.emit('playing');
361
+ /**
362
+ * Подписаться на плеер (`createAudioPlayer()`): канал играет то, что играет плеер, с текущего места.
363
+ * Один плеер можно подписать на сколько угодно соединений, у соединения подписка одна: новая снимает
364
+ * прежнюю. Собственное проигрывание (`play()`) останавливается без события `'idle'`.
365
+ * @param {import('./AudioPlayer').AudioPlayer} player
366
+ * @returns {import('./AudioPlayer').PlayerSubscription|undefined} `undefined` у уничтоженного соединения
367
+ */
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
+ }
493
382
 
494
- const tick = () => {
495
- if (this._playToken !== token) return;
496
- let chunk = ff.read(FRAME_BYTES);
497
- if (ended && !chunk) {
498
- this._playToken = null;
499
- this.emit('idle');
500
- return;
501
- }
502
- // wrtc требует Int16Array в отдельном ArrayBuffer ровно нужного размера.
503
- const ab = new ArrayBuffer(FRAME_BYTES);
504
- if (chunk) {
505
- if (chunk.length < FRAME_BYTES) {
506
- const padded = Buffer.alloc(FRAME_BYTES);
507
- chunk.copy(padded);
508
- chunk = padded;
509
- }
510
- new Uint8Array(ab).set(chunk.subarray(0, FRAME_BYTES));
511
- }
512
- // Если данных нет (джиттер) — кадр остаётся тишиной, расписание не сбиваем.
513
- this._audioSource.onData({
514
- samples: new Int16Array(ab),
515
- sampleRate: SAMPLE_RATE,
516
- bitsPerSample: 16,
517
- channelCount: CHANNELS,
518
- numberOfFrames: FRAME_SAMPLES,
519
- });
520
- frame += 1;
521
- const target = start + frame * 10;
522
- this._playTimer = setTimeout(tick, Math.max(0, target - performance.now()));
523
- };
383
+ /**
384
+ * Текущая подписка на плеер. Состояние соединения (`state`) здесь строка, поэтому подписка лежит
385
+ * отдельно, а не в `state.subscription`, как в @discordjs/voice.
386
+ * @type {import('./AudioPlayer').PlayerSubscription|undefined}
387
+ */
388
+ get subscription() {
389
+ return this._subscription ?? undefined;
390
+ }
524
391
 
525
- // preroll ~400 мс: даём ffmpeg наполнить буфер, чтобы не было стартовых пропусков.
526
- this._playTimer = setTimeout(tick, 400);
392
+ /** @internal Вызывает `PlayerSubscription#unsubscribe()`. */
393
+ _onSubscriptionRemoved(subscription) {
394
+ if (this._subscription !== subscription) return;
395
+ this._subscription = null;
396
+ this._player.leave();
527
397
  }
528
398
 
529
- /** Остановить текущее воспроизведение. */
530
- stop() {
531
- this._playToken = null;
532
- if (this._playTimer) {
533
- clearTimeout(this._playTimer);
534
- this._playTimer = null;
535
- }
536
- if (this._playFF) {
537
- try {
538
- this._playFF.destroy();
539
- } catch {
540
- // ignore
541
- }
542
- this._playFF = null;
543
- }
399
+ /** Отправитель может сейчас слать звук трансляции: открыт транспорт, нет паузы соединения. @internal */
400
+ get _canSend() {
401
+ return this._player.playable;
402
+ }
403
+
404
+ /**
405
+ * Поставить воспроизведение на паузу: в эфир не уходит ни одного пакета. При подписке на плеер
406
+ * пауза касается только этого соединения.
407
+ * @returns {boolean} Изменилось ли состояние
408
+ */
409
+ pause() {
410
+ return !this._player.closed && this._player.pause();
411
+ }
412
+
413
+ /**
414
+ * Продолжить воспроизведение с того же места (при подписке на плеер – с текущего места плеера).
415
+ * @returns {boolean} Изменилось ли состояние
416
+ */
417
+ resume() {
418
+ return !this._player.closed && this._player.resume();
419
+ }
420
+
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
+ };
544
460
  }
545
461
 
546
462
  /** Выйти из канала и освободить ресурсы. */
@@ -570,33 +486,20 @@ class VoiceConnection extends EventEmitter {
570
486
  this._kickTimer = null;
571
487
  this.stop();
572
488
  this._closeSession();
573
- try {
574
- this._audioTrack?.stop();
575
- } catch {
576
- // ignore
577
- }
578
- this._audioTrack = null;
579
- this._audioSource = null;
489
+ this._player.close();
490
+ this._canPlay = false;
491
+ this.receiver._destroy();
580
492
  if (!this._readyAnnounced) this._readyReject(new Error('voice connection destroyed'));
581
493
  const byGuild = connections.get(this._owner);
582
494
  if (byGuild?.get(this.guildId) === this) byGuild.delete(this.guildId);
583
495
  }
584
496
 
585
- /** Закрыть сессию с текущим голосовым сервером, не трогая исходящий трек. */
497
+ /** Закрыть сессию с текущим голосовым сервером, не трогая отправитель: к нему подключится новая сессия. */
586
498
  _closeSession() {
587
- this._consumers.clear();
588
- for (const transport of [this._sendTransport, this._recvTransport]) {
589
- try {
590
- transport?.close();
591
- } catch {
592
- // ignore
593
- }
594
- }
595
- this._sendTransport = null;
596
- this._recvTransport = null;
597
- this._producer = null;
598
- this._signaling?.close();
599
- this._signaling = null;
499
+ const session = this._session;
500
+ this._session = null;
501
+ session?.close().catch(() => {});
502
+ this.receiver._sessionClosed();
600
503
  }
601
504
  }
602
505
 
@@ -608,6 +511,8 @@ class VoiceConnection extends EventEmitter {
608
511
  * @param {Function} options.adapterCreator `guild.voiceAdapterCreator`
609
512
  * @param {boolean} [options.selfMute=false]
610
513
  * @param {boolean} [options.selfDeaf=false]
514
+ * @param {boolean} [options.receive=false] Сразу включить приём чужого звука (иначе он включается
515
+ * слушателем 'track' или `receiver.subscribe()`)
611
516
  * @returns {VoiceConnection}
612
517
  */
613
518
  function joinVoiceChannel(options) {
@@ -616,6 +521,7 @@ function joinVoiceChannel(options) {
616
521
  const existing = byGuild?.get(options.guildId);
617
522
  if (existing && !existing._destroyed) {
618
523
  existing.rejoin({ channelId: options.channelId, selfMute: options.selfMute, selfDeaf: options.selfDeaf });
524
+ if (options.receive) existing._enableReceive();
619
525
  return existing;
620
526
  }
621
527
  const connection = new VoiceConnection(options);
@@ -633,4 +539,11 @@ function joinVoiceChannel(options) {
633
539
  */
634
540
  VoiceConnection.kickGraceMs = DEFAULT_KICK_GRACE_MS;
635
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
+
636
549
  module.exports = { VoiceConnection, joinVoiceChannel };