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.
Files changed (45) hide show
  1. package/README.md +279 -11
  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 +419 -290
  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/src/structures/Guild.js +5 -2
  44. package/typings/index.d.mts +256 -4
  45. package/typings/index.d.ts +256 -4
@@ -0,0 +1,245 @@
1
+ 'use strict';
2
+
3
+ // Публичный приём чужого звука поверх `RemoteAudio` вложенного слоя. Приём включается только по запросу:
4
+ // recv-транспорт создаётся, когда на соединении появился слушатель 'track', вызван `receiver.subscribe()`
5
+ // или передан `receive: true`. Ядро отдаёт Opus-пакеты пачками раз в ≤ 40 мс и только тем трекам, у которых
6
+ // есть читатель ('packet', поток, подписка по userId): без читателя JS не просыпается вообще.
7
+
8
+ const EventEmitter = require('node:events');
9
+ const { Readable } = require('node:stream');
10
+
11
+ const STREAM_HIGH_WATER_MARK = 100;
12
+
13
+ /**
14
+ * Входящий звук одного участника (одного продюсера): Opus-пакеты как есть.
15
+ * @extends {EventEmitter}
16
+ * События: 'packet' `(opus: Buffer, { sequence, timestamp, ssrc })`, 'ended'. `opus` – часть общего буфера
17
+ * пачки, не изменяй его.
18
+ */
19
+ class RemoteAudioTrack extends EventEmitter {
20
+ /** @param {import('../_lolka_voice').RemoteAudio} remote */
21
+ constructor(remote) {
22
+ super();
23
+ this.userId = remote.userId;
24
+ this.producerId = remote.producerId;
25
+ this.readyState = 'live';
26
+ this._remote = remote;
27
+ this._streams = new Set();
28
+ this._overflow = 0;
29
+ remote.onPackets = packets => {
30
+ for (const { payload, sequence, timestamp, ssrc } of packets) this._push(payload, { sequence, timestamp, ssrc });
31
+ };
32
+ this._installHooks();
33
+ }
34
+
35
+ // Без читателя ядро не будит JS: слушаем, только пока есть слушатель 'packet' или поток. Хуки – обычные слушатели
36
+ // служебных событий EventEmitter, их снимает removeAllListeners(), поэтому он переопределён (см. ниже).
37
+ _installHooks() {
38
+ this._onNewListener ??= event => {
39
+ if (event === 'packet') this._remote.setListening(true);
40
+ };
41
+ this._onRemoveListener ??= event => {
42
+ if (event === 'packet') this._syncListening();
43
+ };
44
+ // идемпотентно: переустановка не множит хуки, если один из них уцелел
45
+ this.off('newListener', this._onNewListener);
46
+ this.off('removeListener', this._onRemoveListener);
47
+ this.on('newListener', this._onNewListener);
48
+ this.on('removeListener', this._onRemoveListener);
49
+ }
50
+
51
+ // removeAllListeners() без аргумента снимает и хуки, а внутри себя вызывает removeAllListeners(тип) для каждого типа:
52
+ // переустанавливаем хуки один раз, после внешнего вызова. Аргументы передаём как есть: у `(undefined)` и `()` разный смысл.
53
+ removeAllListeners(...args) {
54
+ if (this._removingAll) return super.removeAllListeners(...args);
55
+ this._removingAll = true;
56
+ try {
57
+ super.removeAllListeners(...args);
58
+ } finally {
59
+ this._removingAll = false;
60
+ }
61
+ const [event] = args;
62
+ if (args.length === 0 || event === 'newListener' || event === 'removeListener') this._installHooks();
63
+ this._syncListening();
64
+ return this;
65
+ }
66
+
67
+ /** Консьюмер на сервере: меняется, когда recv-транспорт пересоздаётся. */
68
+ get consumerId() {
69
+ return this._remote.consumerId;
70
+ }
71
+
72
+ /** SSRC консьюмера: меняется, когда recv-транспорт пересоздаётся. */
73
+ get ssrc() {
74
+ return this._remote.ssrc;
75
+ }
76
+
77
+ /** Сколько пакетов отброшено: переполнение очереди ядра и потоков. */
78
+ get dropped() {
79
+ return this._remote.dropped + this._overflow;
80
+ }
81
+
82
+ /** Поток Opus-пакетов (objectMode): один Buffer — один пакет. Закрывается вместе с треком. */
83
+ createReadStream() {
84
+ const stream = new Readable({
85
+ objectMode: true,
86
+ highWaterMark: STREAM_HIGH_WATER_MARK,
87
+ read() {},
88
+ destroy: (error, callback) => {
89
+ this._streams.delete(stream);
90
+ this._syncListening();
91
+ callback(error);
92
+ },
93
+ });
94
+ if (this.readyState === 'ended') stream.push(null);
95
+ else {
96
+ this._streams.add(stream);
97
+ this._syncListening();
98
+ }
99
+ return stream;
100
+ }
101
+
102
+ /** Перестать получать звук этого участника: трек завершается, сервер консьюмер не закрывает. */
103
+ stop() {
104
+ this._end();
105
+ }
106
+
107
+ _syncListening() {
108
+ this._remote.setListening(this.readyState === 'live' && (this.listenerCount('packet') > 0 || this._streams.size > 0));
109
+ }
110
+
111
+ _push(opus, info) {
112
+ if (this.readyState !== 'live') return;
113
+ this.emit('packet', opus, info);
114
+ for (const stream of this._streams) {
115
+ if (stream.readableLength >= STREAM_HIGH_WATER_MARK * 2) this._overflow++;
116
+ else stream.push(opus);
117
+ }
118
+ }
119
+
120
+ _end() {
121
+ if (this.readyState === 'ended') return;
122
+ this.readyState = 'ended';
123
+ this._remote.setListening(false);
124
+ this._remote.onPackets = null;
125
+ for (const stream of this._streams) stream.push(null);
126
+ this._streams.clear();
127
+ this.emit('ended');
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Приёмник соединения: треки участников и подписки по userId. Живёт всё время соединения;
133
+ * подписки переживают переезд на другой голосовой сервер (треки переподключаются).
134
+ */
135
+ class Receiver {
136
+ /** @param {{ _enableReceive: () => void }} connection */
137
+ constructor(connection) {
138
+ this._connection = connection;
139
+ this._tracks = new Map(); // producerId -> RemoteAudioTrack
140
+ this._subscriptions = new Map(); // userId -> Set<Readable>
141
+ this._destroyed = false;
142
+ }
143
+
144
+ /** Живые треки по producerId. */
145
+ get tracks() {
146
+ return this._tracks;
147
+ }
148
+
149
+ /**
150
+ * Opus-пакеты участника (objectMode), `stream.dropped` — сколько пакетов отброшено при
151
+ * переполнении. Включает приём. Поток закрывается, когда закрывается продюсер участника или
152
+ * уничтожено соединение; после destroy() возвращается сразу закрытый поток.
153
+ * @param {string} userId
154
+ * @returns {import('node:stream').Readable}
155
+ */
156
+ subscribe(userId) {
157
+ userId = String(userId);
158
+ const stream = new Readable({
159
+ objectMode: true,
160
+ highWaterMark: STREAM_HIGH_WATER_MARK,
161
+ read() {},
162
+ destroy: (error, callback) => {
163
+ this._unlink(userId, stream);
164
+ callback(error);
165
+ },
166
+ });
167
+ stream.dropped = 0;
168
+ stream._ended = false;
169
+ if (this._destroyed) {
170
+ stream._ended = true;
171
+ stream.push(null);
172
+ return stream;
173
+ }
174
+ this._connection._enableReceive();
175
+ let set = this._subscriptions.get(userId);
176
+ if (!set) {
177
+ set = new Set();
178
+ this._subscriptions.set(userId, set);
179
+ }
180
+ set.add(stream);
181
+ for (const track of this._tracks.values()) if (track.userId === userId) this._attach(track, stream);
182
+ return stream;
183
+ }
184
+
185
+ _unlink(userId, stream) {
186
+ const set = this._subscriptions.get(userId);
187
+ set?.delete(stream);
188
+ if (set?.size === 0) this._subscriptions.delete(userId);
189
+ stream._detach?.();
190
+ stream._detach = null;
191
+ }
192
+
193
+ // Заканчиваем поток один раз: после push(null) писать в него нельзя (ERR_STREAM_PUSH_AFTER_EOF).
194
+ _endStream(userId, stream) {
195
+ if (stream._ended) return;
196
+ stream._ended = true;
197
+ this._unlink(userId, stream);
198
+ stream.push(null);
199
+ }
200
+
201
+ _attach(track, stream) {
202
+ const onPacket = opus => {
203
+ if (stream._ended || stream.destroyed) return;
204
+ if (stream.readableLength >= STREAM_HIGH_WATER_MARK * 2) stream.dropped++;
205
+ else stream.push(opus);
206
+ };
207
+ track.on('packet', onPacket);
208
+ const previous = stream._detach;
209
+ stream._detach = () => {
210
+ previous?.();
211
+ track.off('packet', onPacket);
212
+ };
213
+ }
214
+
215
+ _trackAdded(track) {
216
+ this._tracks.set(track.producerId, track);
217
+ for (const stream of this._subscriptions.get(track.userId) ?? []) this._attach(track, stream);
218
+ }
219
+
220
+ // Закрылся продюсер: поток подписки заканчивается, если у участника не осталось живых треков.
221
+ _trackClosed(track) {
222
+ if (this._tracks.get(track.producerId) === track) this._tracks.delete(track.producerId);
223
+ track._end();
224
+ const alive = [...this._tracks.values()].some(t => t.userId === track.userId && t.readyState === 'live');
225
+ if (alive) return;
226
+ for (const stream of [...(this._subscriptions.get(track.userId) ?? [])]) this._endStream(track.userId, stream);
227
+ }
228
+
229
+ // Сессия закрыта (переезд): треки заканчиваются, подписки остаются и подключатся к новым трекам.
230
+ _sessionClosed() {
231
+ for (const track of [...this._tracks.values()]) {
232
+ track._end();
233
+ this._tracks.delete(track.producerId);
234
+ }
235
+ }
236
+
237
+ _destroy() {
238
+ this._destroyed = true;
239
+ this._sessionClosed();
240
+ for (const [userId, set] of [...this._subscriptions]) for (const stream of [...set]) this._endStream(userId, stream);
241
+ this._subscriptions.clear();
242
+ }
243
+ }
244
+
245
+ module.exports = { Receiver, RemoteAudioTrack };
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+
3
+ // Зависимости голоса подгружаются лениво: `require('lolka.js')` не тянет ни нативное ядро, ни `ws`,
4
+ // ни `prism-media`, пока голос реально не используется. Ядро (`core.node`) грузит только вложенный слой
5
+ // `_lolka_voice`; ошибка загрузчика пробрасывается как есть (`code = 'LOLKA_VOICE_UNSUPPORTED'`).
6
+
7
+ let loaded = null;
8
+
9
+ /**
10
+ * Загрузить зависимости голоса (один раз на процесс).
11
+ * @returns {{ WebSocket: Function, prism: Object, voice: Object }} `voice` – вложенный слой, ядро загружено
12
+ * (`loadCore()`), но не запущено: его запускает `getRuntime()` при первом голосовом объекте.
13
+ * @throws {Error} `LOLKA_VOICE_UNSUPPORTED`, если для платформы нет бинаря
14
+ */
15
+ function ensureVoiceDeps() {
16
+ if (loaded) return loaded;
17
+ const voice = require('../_lolka_voice');
18
+ voice.loadCore();
19
+ loaded = {
20
+ voice,
21
+ WebSocket: require('ws'),
22
+ prism: require('prism-media'),
23
+ };
24
+ return loaded;
25
+ }
26
+
27
+ module.exports = { ensureVoiceDeps };
package/src/index.js CHANGED
@@ -16,6 +16,17 @@ exports.WebhookClient = require('./client/WebhookClient');
16
16
  // Voice (WebRTC)
17
17
  exports.joinVoiceChannel = require('./client/voice/VoiceConnection').joinVoiceChannel;
18
18
  exports.VoiceConnection = require('./client/voice/VoiceConnection').VoiceConnection;
19
+ exports.VoiceReceiver = require('./client/voice/media/Receiver').Receiver;
20
+ exports.RemoteAudioTrack = require('./client/voice/media/Receiver').RemoteAudioTrack;
21
+ exports.createAudioPlayer = require('./client/voice/AudioPlayer').createAudioPlayer;
22
+ exports.AudioPlayer = require('./client/voice/AudioPlayer').AudioPlayer;
23
+ exports.AudioPlayerError = require('./client/voice/AudioPlayer').AudioPlayerError;
24
+ exports.AudioPlayerStatus = require('./client/voice/AudioPlayer').AudioPlayerStatus;
25
+ exports.NoSubscriberBehavior = require('./client/voice/AudioPlayer').NoSubscriberBehavior;
26
+ exports.PlayerSubscription = require('./client/voice/AudioPlayer').PlayerSubscription;
27
+ exports.createAudioResource = require('./client/voice/AudioResource').createAudioResource;
28
+ exports.AudioResource = require('./client/voice/AudioResource').AudioResource;
29
+ exports.StreamType = require('./client/voice/AudioResource').StreamType;
19
30
 
20
31
  // Errors
21
32
  exports.DiscordjsError = require('./errors/DJSError').DiscordjsError;
@@ -1457,7 +1457,7 @@ class Guild extends AnonymousGuild {
1457
1457
  * @readonly
1458
1458
  */
1459
1459
  get voiceAdapterCreator() {
1460
- return methods => {
1460
+ const creator = methods => {
1461
1461
  this.client.voice.adapters.set(this.id, methods);
1462
1462
  return {
1463
1463
  sendPayload: data => {
@@ -1466,10 +1466,13 @@ class Guild extends AnonymousGuild {
1466
1466
  return true;
1467
1467
  },
1468
1468
  destroy: () => {
1469
- this.client.voice.adapters.delete(this.id);
1469
+ if (this.client.voice.adapters.get(this.id) === methods) this.client.voice.adapters.delete(this.id);
1470
1470
  },
1471
1471
  };
1472
1472
  };
1473
+ // Метка владельца: voice-соединения разных клиентов в одной гильдии не пересекаются.
1474
+ creator.voiceManager = this.client.voice;
1475
+ return creator;
1473
1476
  }
1474
1477
 
1475
1478
  /**
@@ -229,7 +229,7 @@ import {
229
229
  } from 'discord-api-types/v10';
230
230
  import { ChildProcess } from 'node:child_process';
231
231
  import { EventEmitter } from 'node:events';
232
- import { Stream } from 'node:stream';
232
+ import { Readable, Stream } from 'node:stream';
233
233
  import { MessagePort, Worker } from 'node:worker_threads';
234
234
  import {
235
235
  RawActivityData,
@@ -8134,11 +8134,81 @@ export interface VoiceConnectionOptions {
8134
8134
  adapterCreator: InternalDiscordGatewayAdapterCreator;
8135
8135
  selfMute?: boolean;
8136
8136
  selfDeaf?: boolean;
8137
+ /** Сразу включить приём чужого звука (иначе его включают слушатель `'track'` или `receiver.subscribe()`). */
8138
+ receive?: boolean;
8139
+ }
8140
+
8141
+ export interface VoiceConnectionRejoinOptions {
8142
+ channelId?: string;
8143
+ selfMute?: boolean;
8144
+ selfDeaf?: boolean;
8137
8145
  }
8138
8146
 
8139
8147
  export type VoiceConnectionState = 'connecting' | 'ready' | 'error' | 'destroyed';
8140
8148
 
8149
+ export type VoiceInputType = 'arbitrary' | 'raw' | 'ogg/opus' | 'webm/opus' | 'opus';
8150
+
8151
+ export interface VoicePlayOptions {
8152
+ /** `'arbitrary'` (по умолчанию) – любой формат через ffmpeg; `'raw'` – PCM s16le 48 кГц стерео без заголовка через ffmpeg; `'ogg/opus'` и `'webm/opus'` – без ffmpeg; `'opus'` – объектный поток готовых Opus-пакетов. */
8153
+ inputType?: VoiceInputType;
8154
+ /** Битрейт кодирования в кбит/с, только для `'arbitrary'` и `'raw'` (по умолчанию 128). */
8155
+ bitrate?: number;
8156
+ }
8157
+
8158
+ export interface VoiceConnectionStats {
8159
+ state: VoiceConnectionState;
8160
+ playing: boolean;
8161
+ paused: boolean;
8162
+ queuedFrames: number;
8163
+ transportState: string | null;
8164
+ receiving: boolean;
8165
+ consumers: number;
8166
+ packetsSent: number;
8167
+ bytesSent: number;
8168
+ underruns: number;
8169
+ lateTicks: number;
8170
+ bursts: number;
8171
+ resyncs: number;
8172
+ silentSkipped: number;
8173
+ drops: number;
8174
+ /** Кадры плеера, пропущенные соединением из-за отставания. */
8175
+ skipped: number;
8176
+ /** Соединение подписано на плеер. */
8177
+ subscribed: boolean;
8178
+ }
8179
+
8180
+ export interface RemoteAudioPacketInfo {
8181
+ sequence: number;
8182
+ timestamp: number;
8183
+ ssrc: number;
8184
+ }
8185
+
8186
+ export class RemoteAudioTrack extends EventEmitter {
8187
+ private constructor();
8188
+ public readonly userId: string;
8189
+ public readonly producerId: string;
8190
+ public readonly consumerId: string;
8191
+ public readonly ssrc: number;
8192
+ public readonly readyState: 'live' | 'ended';
8193
+ public createReadStream(): Readable;
8194
+ public stop(): void;
8195
+ public on(event: 'packet', listener: (opus: Buffer, info: RemoteAudioPacketInfo) => void): this;
8196
+ public on(event: 'ended', listener: () => void): this;
8197
+ public once(event: 'packet', listener: (opus: Buffer, info: RemoteAudioPacketInfo) => void): this;
8198
+ public once(event: 'ended', listener: () => void): this;
8199
+ }
8200
+
8201
+ export type VoiceSubscriptionStream = Readable & { dropped: number };
8202
+
8203
+ export class VoiceReceiver {
8204
+ private constructor();
8205
+ public readonly tracks: ReadonlyMap<string, RemoteAudioTrack>;
8206
+ public subscribe(userId: string): VoiceSubscriptionStream;
8207
+ }
8208
+
8141
8209
  export class VoiceConnection extends EventEmitter {
8210
+ public static kickGraceMs: number;
8211
+ public static recvRebuildThreshold: number;
8142
8212
  private constructor(options: VoiceConnectionOptions);
8143
8213
  public channelId: string;
8144
8214
  public guildId: string;
@@ -8146,20 +8216,202 @@ export class VoiceConnection extends EventEmitter {
8146
8216
  public sessionId: string | null;
8147
8217
  public token: string | null;
8148
8218
  public endpoint: string | null;
8219
+ public readonly receiver: VoiceReceiver;
8220
+ public readonly paused: boolean;
8149
8221
  public awaitReady(timeout?: number): Promise<void>;
8150
- public play(input: string | NodeJS.ReadableStream): void;
8222
+ public rejoin(options?: VoiceConnectionRejoinOptions): boolean;
8223
+ public play(input: string | NodeJS.ReadableStream, options?: VoicePlayOptions): void;
8151
8224
  public stop(): void;
8225
+ public pause(): boolean;
8226
+ public resume(): boolean;
8227
+ public unpause(): boolean;
8228
+ public stats(): VoiceConnectionStats;
8229
+ /** Подписка на плеер. `state` здесь строка, поэтому подписка лежит отдельно, а не в `state.subscription`. */
8230
+ public readonly subscription: PlayerSubscription | undefined;
8231
+ /** Подписаться на плеер; `undefined` у уничтоженного соединения. Новая подписка снимает прежнюю. */
8232
+ public subscribe(player: AudioPlayer): PlayerSubscription | undefined;
8152
8233
  public destroy(): void;
8153
8234
  public on(event: 'ready' | 'playing' | 'idle' | 'destroyed', listener: () => void): this;
8154
8235
  public on(event: 'error', listener: (error: Error) => void): this;
8155
- public on(event: 'track', listener: (track: unknown, userId: string, producerId: string) => void): this;
8236
+ public on(event: 'track', listener: (track: RemoteAudioTrack, userId: string, producerId: string) => void): this;
8237
+ public on(event: 'speaking', listener: (userId: string, speaking: boolean) => void): this;
8156
8238
  public once(event: 'ready' | 'playing' | 'idle' | 'destroyed', listener: () => void): this;
8157
8239
  public once(event: 'error', listener: (error: Error) => void): this;
8158
- public once(event: 'track', listener: (track: unknown, userId: string, producerId: string) => void): this;
8240
+ public once(event: 'track', listener: (track: RemoteAudioTrack, userId: string, producerId: string) => void): this;
8241
+ public once(event: 'speaking', listener: (userId: string, speaking: boolean) => void): this;
8159
8242
  }
8160
8243
 
8161
8244
  export function joinVoiceChannel(options: VoiceConnectionOptions): VoiceConnection;
8162
8245
 
8246
+ export enum AudioPlayerStatus {
8247
+ AutoPaused = 'autopaused',
8248
+ Buffering = 'buffering',
8249
+ Idle = 'idle',
8250
+ Paused = 'paused',
8251
+ Playing = 'playing',
8252
+ }
8253
+
8254
+ export enum NoSubscriberBehavior {
8255
+ Pause = 'pause',
8256
+ Play = 'play',
8257
+ Stop = 'stop',
8258
+ }
8259
+
8260
+ /** `Raw` – PCM s16le 48 кГц стерео без заголовка: ffmpeg кодирует его в Opus, громкость меняют в ffmpeg. */
8261
+ export enum StreamType {
8262
+ Arbitrary = 'arbitrary',
8263
+ OggOpus = 'ogg/opus',
8264
+ Opus = 'opus',
8265
+ Raw = 'raw',
8266
+ WebmOpus = 'webm/opus',
8267
+ }
8268
+
8269
+ export interface AudioPlayerBehaviors {
8270
+ /** Что делать, когда некому слать звук (по умолчанию `Pause`). */
8271
+ noSubscriber: NoSubscriberBehavior;
8272
+ /** Сколько кадров подряд плеер может не получить из ресурса, прежде чем остановиться (по умолчанию 5). */
8273
+ maxMissedFrames: number;
8274
+ }
8275
+
8276
+ export interface CreateAudioPlayerOptions {
8277
+ /** `false` отключает событие `'debug'`. */
8278
+ debug?: boolean;
8279
+ behaviors?: Partial<AudioPlayerBehaviors>;
8280
+ }
8281
+
8282
+ export interface CreateAudioResourceOptions<T> {
8283
+ /** Для строки по умолчанию `Arbitrary`, для потока тип выводится по классу потока prism-media, иначе `Arbitrary`. */
8284
+ inputType?: StreamType;
8285
+ metadata?: T;
8286
+ /** Принимается для совместимости: хвост тишины у каждого канала свой, всегда 5 кадров. */
8287
+ silencePaddingFrames?: number;
8288
+ /** Битрейт кодирования в кбит/с, только для `Arbitrary` и `Raw` (по умолчанию 128). */
8289
+ bitrate?: number;
8290
+ /** Не поддержано: громкость меняют в ffmpeg (`-af volume=…`). `true` даёт `TypeError`. */
8291
+ inlineVolume?: false;
8292
+ }
8293
+
8294
+ export class AudioResource<T = unknown> {
8295
+ private constructor();
8296
+ public readonly edges: readonly never[];
8297
+ public readonly playStream: Readable;
8298
+ public readonly metadata: T;
8299
+ /** Всегда `undefined`: громкость меняют в ffmpeg. */
8300
+ public readonly volume?: undefined;
8301
+ /** Всегда `undefined`: звук в процессе не кодируется. */
8302
+ public readonly encoder?: undefined;
8303
+ public audioPlayer?: AudioPlayer;
8304
+ public readonly playbackDuration: number;
8305
+ public readonly started: boolean;
8306
+ public readonly silencePaddingFrames: number;
8307
+ public readonly readable: boolean;
8308
+ public readonly ended: boolean;
8309
+ }
8310
+
8311
+ export function createAudioResource<T>(
8312
+ input: string | Readable,
8313
+ options: CreateAudioResourceOptions<T> & Required<Pick<CreateAudioResourceOptions<T>, 'metadata'>>,
8314
+ ): AudioResource<T>;
8315
+ export function createAudioResource(
8316
+ input: string | Readable,
8317
+ options?: Omit<CreateAudioResourceOptions<null>, 'metadata'>,
8318
+ ): AudioResource<null>;
8319
+
8320
+ export interface AudioPlayerIdleState {
8321
+ status: AudioPlayerStatus.Idle;
8322
+ }
8323
+
8324
+ export interface AudioPlayerBufferingState {
8325
+ status: AudioPlayerStatus.Buffering;
8326
+ resource: AudioResource;
8327
+ }
8328
+
8329
+ export interface AudioPlayerPlayingState {
8330
+ status: AudioPlayerStatus.Playing;
8331
+ missedFrames: number;
8332
+ playbackDuration: number;
8333
+ resource: AudioResource;
8334
+ }
8335
+
8336
+ export interface AudioPlayerPausedState {
8337
+ status: AudioPlayerStatus.Paused | AudioPlayerStatus.AutoPaused;
8338
+ missedFrames: number;
8339
+ playbackDuration: number;
8340
+ resource: AudioResource;
8341
+ }
8342
+
8343
+ export type AudioPlayerState =
8344
+ | AudioPlayerBufferingState
8345
+ | AudioPlayerIdleState
8346
+ | AudioPlayerPausedState
8347
+ | AudioPlayerPlayingState;
8348
+
8349
+ export interface AudioPlayerStats {
8350
+ status: AudioPlayerStatus;
8351
+ subscribers: number;
8352
+ /** Подписки, которым плеер может слать звук прямо сейчас. */
8353
+ activeSubscribers: number;
8354
+ queuedFrames: number;
8355
+ framesPublished: number;
8356
+ underruns: number;
8357
+ resyncs: number;
8358
+ }
8359
+
8360
+ export class AudioPlayerError extends Error {
8361
+ public constructor(error: Error, resource: AudioResource);
8362
+ public resource: AudioResource;
8363
+ }
8364
+
8365
+ export class PlayerSubscription {
8366
+ private constructor();
8367
+ public readonly connection: VoiceConnection;
8368
+ public readonly player: AudioPlayer;
8369
+ /** Отписать только это соединение. */
8370
+ public unsubscribe(): void;
8371
+ }
8372
+
8373
+ export class AudioPlayer extends EventEmitter {
8374
+ public constructor(options?: CreateAudioPlayerOptions);
8375
+ public readonly behaviors: AudioPlayerBehaviors;
8376
+ public readonly debug: ((message: string) => void) | null;
8377
+ public readonly subscribers: PlayerSubscription[];
8378
+ /** Соединения, которым плеер может слать звук прямо сейчас. */
8379
+ public readonly playable: VoiceConnection[];
8380
+ public readonly state: AudioPlayerState;
8381
+ public play<T>(resource: AudioResource<T>): void;
8382
+ public pause(interpolateSilence?: boolean): boolean;
8383
+ public unpause(): boolean;
8384
+ public stop(force?: boolean): boolean;
8385
+ public checkPlayable(): boolean;
8386
+ public stats(): AudioPlayerStats;
8387
+ public on(event: 'error', listener: (error: AudioPlayerError) => void): this;
8388
+ public on(event: 'debug', listener: (message: string) => void): this;
8389
+ public on(event: 'stateChange', listener: (oldState: AudioPlayerState, newState: AudioPlayerState) => void): this;
8390
+ public on(event: 'subscribe' | 'unsubscribe', listener: (subscription: PlayerSubscription) => void): this;
8391
+ public on<T extends AudioPlayerStatus>(
8392
+ event: T,
8393
+ listener: (oldState: AudioPlayerState, newState: AudioPlayerState & { status: T }) => void,
8394
+ ): this;
8395
+ public once(event: 'error', listener: (error: AudioPlayerError) => void): this;
8396
+ public once(event: 'debug', listener: (message: string) => void): this;
8397
+ public once(event: 'stateChange', listener: (oldState: AudioPlayerState, newState: AudioPlayerState) => void): this;
8398
+ public once(event: 'subscribe' | 'unsubscribe', listener: (subscription: PlayerSubscription) => void): this;
8399
+ public once<T extends AudioPlayerStatus>(
8400
+ event: T,
8401
+ listener: (oldState: AudioPlayerState, newState: AudioPlayerState & { status: T }) => void,
8402
+ ): this;
8403
+ public off(event: 'error', listener: (error: AudioPlayerError) => void): this;
8404
+ public off(event: 'debug', listener: (message: string) => void): this;
8405
+ public off(event: 'stateChange', listener: (oldState: AudioPlayerState, newState: AudioPlayerState) => void): this;
8406
+ public off(event: 'subscribe' | 'unsubscribe', listener: (subscription: PlayerSubscription) => void): this;
8407
+ public off<T extends AudioPlayerStatus>(
8408
+ event: T,
8409
+ listener: (oldState: AudioPlayerState, newState: AudioPlayerState & { status: T }) => void,
8410
+ ): this;
8411
+ }
8412
+
8413
+ export function createAudioPlayer(options?: CreateAudioPlayerOptions): AudioPlayer;
8414
+
8163
8415
  //#endregion
8164
8416
 
8165
8417
  // Lolka