discord-player 5.4.0 → 5.4.1-dev.0

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/dist/index.js CHANGED
@@ -1,38 +1,2074 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.version = exports.Util = exports.StreamDispatcher = exports.VoiceUtils = exports.Track = exports.Queue = exports.QueryResolver = exports.ErrorStatusCode = exports.PlayerError = exports.Player = exports.Playlist = exports.ExtractorModel = exports.AudioFilters = void 0;
4
- const tslib_1 = require("tslib");
5
- // try applying smooth volume patch on load
6
- require("./smoothVolume");
7
- const discord_js_1 = require("discord.js");
8
- var AudioFilters_1 = require("./utils/AudioFilters");
9
- Object.defineProperty(exports, "AudioFilters", { enumerable: true, get: function () { return AudioFilters_1.AudioFilters; } });
10
- var ExtractorModel_1 = require("./Structures/ExtractorModel");
11
- Object.defineProperty(exports, "ExtractorModel", { enumerable: true, get: function () { return ExtractorModel_1.ExtractorModel; } });
12
- var Playlist_1 = require("./Structures/Playlist");
13
- Object.defineProperty(exports, "Playlist", { enumerable: true, get: function () { return Playlist_1.Playlist; } });
14
- var Player_1 = require("./Player");
15
- Object.defineProperty(exports, "Player", { enumerable: true, get: function () { return Player_1.Player; } });
16
- var PlayerError_1 = require("./Structures/PlayerError");
17
- Object.defineProperty(exports, "PlayerError", { enumerable: true, get: function () { return PlayerError_1.PlayerError; } });
18
- Object.defineProperty(exports, "ErrorStatusCode", { enumerable: true, get: function () { return PlayerError_1.ErrorStatusCode; } });
19
- var QueryResolver_1 = require("./utils/QueryResolver");
20
- Object.defineProperty(exports, "QueryResolver", { enumerable: true, get: function () { return QueryResolver_1.QueryResolver; } });
21
- var Queue_1 = require("./Structures/Queue");
22
- Object.defineProperty(exports, "Queue", { enumerable: true, get: function () { return Queue_1.Queue; } });
23
- var Track_1 = require("./Structures/Track");
24
- Object.defineProperty(exports, "Track", { enumerable: true, get: function () { return Track_1.Track; } });
25
- var VoiceUtils_1 = require("./VoiceInterface/VoiceUtils");
26
- Object.defineProperty(exports, "VoiceUtils", { enumerable: true, get: function () { return VoiceUtils_1.VoiceUtils; } });
27
- var StreamDispatcher_1 = require("./VoiceInterface/StreamDispatcher");
28
- Object.defineProperty(exports, "StreamDispatcher", { enumerable: true, get: function () { return StreamDispatcher_1.StreamDispatcher; } });
29
- tslib_1.__exportStar(require("./VoiceInterface/VolumeTransformer"), exports);
30
- var Util_1 = require("./utils/Util");
31
- Object.defineProperty(exports, "Util", { enumerable: true, get: function () { return Util_1.Util; } });
32
- tslib_1.__exportStar(require("./types/types"), exports);
33
- tslib_1.__exportStar(require("./utils/FFmpegStream"), exports);
34
- // eslint-disable-next-line @typescript-eslint/no-var-requires
35
- exports.version = require(`${__dirname}/../package.json`).version;
36
- if (!discord_js_1.version.startsWith("14")) {
37
- process.emitWarning(`Discord.js v${discord_js_1.version} is incompatible with Discord Player v${exports.version}! Please use >=v14.x of Discord.js`);
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+ var __accessCheck = (obj, member, msg) => {
27
+ if (!member.has(obj))
28
+ throw TypeError("Cannot " + msg);
29
+ };
30
+ var __privateGet = (obj, member, getter) => {
31
+ __accessCheck(obj, member, "read from private field");
32
+ return getter ? getter.call(obj) : member.get(obj);
33
+ };
34
+ var __privateAdd = (obj, member, value) => {
35
+ if (member.has(obj))
36
+ throw TypeError("Cannot add the same private member more than once");
37
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
38
+ };
39
+ var __privateSet = (obj, member, value, setter) => {
40
+ __accessCheck(obj, member, "write to private field");
41
+ setter ? setter.call(obj, value) : member.set(obj, value);
42
+ return value;
43
+ };
44
+ var __privateMethod = (obj, member, method) => {
45
+ __accessCheck(obj, member, "access private method");
46
+ return method;
47
+ };
48
+
49
+ // src/index.ts
50
+ var src_exports = {};
51
+ __export(src_exports, {
52
+ AudioFilters: () => AudioFilters,
53
+ BaseExtractor: () => BaseExtractor,
54
+ ErrorStatusCode: () => ErrorStatusCode,
55
+ ExtractorExecutionContext: () => ExtractorExecutionContext,
56
+ FFMPEG_ARGS_PIPED: () => FFMPEG_ARGS_PIPED,
57
+ FFMPEG_ARGS_STRING: () => FFMPEG_ARGS_STRING,
58
+ Player: () => Player,
59
+ PlayerError: () => PlayerError,
60
+ Playlist: () => Playlist,
61
+ QueryResolver: () => QueryResolver,
62
+ QueryType: () => QueryType,
63
+ Queue: () => Queue,
64
+ QueueRepeatMode: () => QueueRepeatMode,
65
+ StreamDispatcher: () => StreamDispatcher,
66
+ Track: () => Track,
67
+ Util: () => Util,
68
+ VoiceUtils: () => VoiceUtils,
69
+ VolumeTransformer: () => VolumeTransformer,
70
+ createFFmpegStream: () => createFFmpegStream,
71
+ version: () => version
72
+ });
73
+ module.exports = __toCommonJS(src_exports);
74
+
75
+ // src/VoiceInterface/VolumeTransformer.ts
76
+ var import_stream = require("stream");
77
+ var VolumeTransformer = class extends import_stream.Transform {
78
+ constructor(options = {}) {
79
+ super(options);
80
+ switch (options.type) {
81
+ case "s16le":
82
+ this._readInt = (buffer, index) => buffer.readInt16LE(index);
83
+ this._writeInt = (buffer, int, index) => buffer.writeInt16LE(int, index);
84
+ this._bits = 16;
85
+ break;
86
+ case "s16be":
87
+ this._readInt = (buffer, index) => buffer.readInt16BE(index);
88
+ this._writeInt = (buffer, int, index) => buffer.writeInt16BE(int, index);
89
+ this._bits = 16;
90
+ break;
91
+ case "s32le":
92
+ this._readInt = (buffer, index) => buffer.readInt32LE(index);
93
+ this._writeInt = (buffer, int, index) => buffer.writeInt32LE(int, index);
94
+ this._bits = 32;
95
+ break;
96
+ case "s32be":
97
+ this._readInt = (buffer, index) => buffer.readInt32BE(index);
98
+ this._writeInt = (buffer, int, index) => buffer.writeInt32BE(int, index);
99
+ this._bits = 32;
100
+ break;
101
+ default:
102
+ throw new Error("VolumeTransformer type should be one of s16le, s16be, s32le, s32be");
103
+ }
104
+ this.type = options.type;
105
+ this._bytes = this._bits / 8;
106
+ this._extremum = Math.pow(2, this._bits - 1);
107
+ this.volume = Number.isNaN(options.volume) ? 1 : Number(options.volume);
108
+ if (!Number.isFinite(this.volume))
109
+ this.volume = 1;
110
+ this._targetVolume = this.volume;
111
+ this._chunk = Buffer.alloc(0);
112
+ this._smoothing = options.smoothness || 0;
113
+ }
114
+ _readInt(buffer, index) {
115
+ return index;
116
+ }
117
+ _writeInt(buffer, int, index) {
118
+ return index;
119
+ }
120
+ _applySmoothness() {
121
+ if (this.volume < this._targetVolume) {
122
+ this.volume = this.volume + this._smoothing >= this._targetVolume ? this._targetVolume : this.volume + this._smoothing;
123
+ } else if (this.volume > this._targetVolume) {
124
+ this.volume = this.volume - this._smoothing <= this._targetVolume ? this._targetVolume : this.volume - this._smoothing;
125
+ }
126
+ }
127
+ _transform(chunk, encoding, done) {
128
+ if (this.smoothingEnabled() && this.volume !== this._targetVolume)
129
+ this._applySmoothness();
130
+ if (this.volume === 1) {
131
+ this.push(chunk);
132
+ return done();
133
+ }
134
+ const { _bytes, _extremum } = this;
135
+ chunk = this._chunk = Buffer.concat([this._chunk, chunk]);
136
+ if (chunk.length < _bytes)
137
+ return done();
138
+ const complete = Math.floor(chunk.length / _bytes) * _bytes;
139
+ for (let i = 0; i < complete; i += _bytes) {
140
+ const int = Math.min(_extremum - 1, Math.max(-_extremum, Math.floor(this.volume * this._readInt(chunk, i))));
141
+ this._writeInt(chunk, int, i);
142
+ }
143
+ this._chunk = chunk.slice(complete);
144
+ this.push(chunk.slice(0, complete));
145
+ return done();
146
+ }
147
+ _destroy(err, cb) {
148
+ super._destroy(err, cb);
149
+ this._chunk = null;
150
+ }
151
+ setVolume(volume) {
152
+ if (Number.isNaN(volume))
153
+ volume = 1;
154
+ if (typeof volume !== "number")
155
+ volume = Number(volume);
156
+ if (!Number.isFinite(volume))
157
+ volume = volume < 0 ? 0 : 1;
158
+ this._targetVolume = volume;
159
+ if (this._smoothing <= 0)
160
+ this.volume = volume;
161
+ }
162
+ setVolumeDecibels(db) {
163
+ this.setVolume(Math.pow(10, db / 20));
164
+ }
165
+ setVolumeLogarithmic(value) {
166
+ this.setVolume(Math.pow(value, 1.660964));
167
+ }
168
+ get volumeDecibels() {
169
+ return Math.log10(this.volume) * 20;
170
+ }
171
+ get volumeLogarithmic() {
172
+ return Math.pow(this.volume, 1 / 1.660964);
173
+ }
174
+ get smoothness() {
175
+ return this._smoothing;
176
+ }
177
+ setSmoothness(smoothness) {
178
+ this._smoothing = smoothness;
179
+ }
180
+ smoothingEnabled() {
181
+ return typeof this._smoothing === "number" && !Number.isNaN(this._smoothing) && Number.isFinite(this._smoothing) && this._smoothing > 0;
182
+ }
183
+ get hasSmoothness() {
184
+ return true;
185
+ }
186
+ static get hasSmoothing() {
187
+ return true;
188
+ }
189
+ };
190
+ __name(VolumeTransformer, "VolumeTransformer");
191
+
192
+ // src/smoothVolume.ts
193
+ if (!("DISABLE_DISCORD_PLAYER_SMOOTH_VOLUME" in process.env)) {
194
+ try {
195
+ const mod = require("prism-media");
196
+ if (typeof mod.VolumeTransformer.hasSmoothing !== "boolean") {
197
+ Reflect.set(mod, "VolumeTransformer", VolumeTransformer);
198
+ }
199
+ } catch {
200
+ }
38
201
  }
202
+
203
+ // src/index.ts
204
+ var import_discord4 = require("discord.js");
205
+
206
+ // src/utils/AudioFilters.ts
207
+ var bass = /* @__PURE__ */ __name((g) => `bass=g=${g}:f=110:w=0.3`, "bass");
208
+ var _AudioFilters = class {
209
+ constructor() {
210
+ return _AudioFilters;
211
+ }
212
+ static get(name) {
213
+ return this.filters[name];
214
+ }
215
+ static has(name) {
216
+ return name in this.filters;
217
+ }
218
+ static *[Symbol.iterator]() {
219
+ for (const [k, v] of Object.entries(this.filters)) {
220
+ yield { name: k, value: v };
221
+ }
222
+ }
223
+ static get names() {
224
+ return Object.keys(this.filters);
225
+ }
226
+ static get length() {
227
+ return this.names.length;
228
+ }
229
+ static toString() {
230
+ return this.names.map((m) => this[m]).join(",");
231
+ }
232
+ static create(filters) {
233
+ if (!filters || !Array.isArray(filters))
234
+ return this.toString();
235
+ return filters.filter((predicate) => typeof predicate === "string").map((m) => this.get(m)).join(",");
236
+ }
237
+ static define(filterName, value) {
238
+ this.filters[filterName] = value;
239
+ }
240
+ static defineBulk(filtersArray) {
241
+ filtersArray.forEach((arr) => this.define(arr.name, arr.value));
242
+ }
243
+ };
244
+ var AudioFilters = _AudioFilters;
245
+ __name(AudioFilters, "AudioFilters");
246
+ AudioFilters.filters = {
247
+ bassboost_low: bass(15),
248
+ bassboost: bass(20),
249
+ bassboost_high: bass(30),
250
+ "8D": "apulsator=hz=0.09",
251
+ vaporwave: "aresample=48000,asetrate=48000*0.8",
252
+ nightcore: "aresample=48000,asetrate=48000*1.25",
253
+ phaser: "aphaser=in_gain=0.4",
254
+ tremolo: "tremolo",
255
+ vibrato: "vibrato=f=6.5",
256
+ reverse: "areverse",
257
+ treble: "treble=g=5",
258
+ normalizer2: "dynaudnorm=g=101",
259
+ normalizer: "acompressor",
260
+ surrounding: "surround",
261
+ pulsator: "apulsator=hz=1",
262
+ subboost: "asubboost",
263
+ karaoke: "stereotools=mlev=0.03",
264
+ flanger: "flanger",
265
+ gate: "agate",
266
+ haas: "haas",
267
+ mcompand: "mcompand",
268
+ mono: "pan=mono|c0=.5*c0+.5*c1",
269
+ mstlr: "stereotools=mode=ms>lr",
270
+ mstrr: "stereotools=mode=ms>rr",
271
+ compressor: "compand=points=-80/-105|-62/-80|-15.4/-15.4|0/-12|20/-7.6",
272
+ expander: "compand=attacks=0:points=-80/-169|-54/-80|-49.5/-64.6|-41.1/-41.1|-25.8/-15|-10.8/-4.5|0/0|20/8.3",
273
+ softlimiter: "compand=attacks=0:points=-80/-80|-12.4/-12.4|-6/-8|0/-6.8|20/-2.8",
274
+ chorus: "chorus=0.7:0.9:55:0.4:0.25:2",
275
+ chorus2d: "chorus=0.6:0.9:50|60:0.4|0.32:0.25|0.4:2|1.3",
276
+ chorus3d: "chorus=0.5:0.9:50|60|40:0.4|0.32|0.3:0.25|0.4|0.3:2|2.3|1.3",
277
+ fadein: "afade=t=in:ss=0:d=10",
278
+ dim: `afftfilt="'real=re * (1-clip((b/nb)*b,0,1))':imag='im * (1-clip((b/nb)*b,0,1))'"`,
279
+ earrape: "channelsplit,sidechaingate=level_in=64"
280
+ };
281
+ var AudioFilters_default = AudioFilters;
282
+
283
+ // src/extractors/BaseExtractor.ts
284
+ var BaseExtractor = class {
285
+ constructor(context) {
286
+ this.context = context;
287
+ }
288
+ get identifier() {
289
+ return this.constructor.identifier;
290
+ }
291
+ async activate() {
292
+ return;
293
+ }
294
+ async deactivate() {
295
+ return;
296
+ }
297
+ async validate(query, type) {
298
+ return false;
299
+ }
300
+ async stream(info) {
301
+ throw new Error("Not Implemented");
302
+ }
303
+ async handle(query, context) {
304
+ throw new Error("Not Implemented");
305
+ }
306
+ handlePostStream(stream, next) {
307
+ return next(null, stream);
308
+ }
309
+ emit(event, ...args) {
310
+ return this.context.player.emit(event, ...args);
311
+ }
312
+ };
313
+ __name(BaseExtractor, "BaseExtractor");
314
+ BaseExtractor.identifier = "com.discord-player.extractor";
315
+
316
+ // src/extractors/ExtractorExecutionContext.ts
317
+ var import_utils = require("@discord-player/utils");
318
+ var ExtractorExecutionContext = class {
319
+ constructor(player) {
320
+ this.player = player;
321
+ this.store = new import_utils.Collection();
322
+ }
323
+ isRegistered(identifier) {
324
+ return this.store.has(identifier);
325
+ }
326
+ get size() {
327
+ return this.store.size;
328
+ }
329
+ get(identifier) {
330
+ return this.store.get(identifier);
331
+ }
332
+ async register(_extractor) {
333
+ if (typeof _extractor.identifier !== "string" || this.store.has(_extractor.identifier))
334
+ return;
335
+ const extractor = new _extractor(this);
336
+ try {
337
+ this.store.set(_extractor.identifier, extractor);
338
+ await extractor.activate();
339
+ } catch {
340
+ this.store.delete(_extractor.identifier);
341
+ }
342
+ }
343
+ async unregister(_extractor) {
344
+ const extractor = typeof _extractor === "string" ? this.store.get(_extractor) : this.store.find((r) => r === _extractor);
345
+ if (!extractor)
346
+ return;
347
+ try {
348
+ const key = extractor.identifier || this.store.findKey((e) => e === extractor);
349
+ this.store.delete(key);
350
+ await extractor.deactivate();
351
+ } catch {
352
+ }
353
+ }
354
+ async unregisterAll() {
355
+ try {
356
+ await Promise.all(
357
+ this.store.map((e, k) => {
358
+ this.store.delete(k);
359
+ return e.deactivate();
360
+ })
361
+ );
362
+ } catch {
363
+ }
364
+ }
365
+ async run(fn) {
366
+ for (const ext of this.store.values()) {
367
+ const result = await fn(ext).catch(() => {
368
+ return false;
369
+ });
370
+ if (result)
371
+ return {
372
+ extractor: ext,
373
+ result
374
+ };
375
+ }
376
+ return null;
377
+ }
378
+ };
379
+ __name(ExtractorExecutionContext, "ExtractorExecutionContext");
380
+
381
+ // src/Structures/Playlist.ts
382
+ var Playlist = class {
383
+ constructor(player, data) {
384
+ this.player = player;
385
+ this.tracks = data.tracks ?? [];
386
+ this.author = data.author;
387
+ this.description = data.description;
388
+ this.thumbnail = data.thumbnail;
389
+ this.type = data.type;
390
+ this.source = data.source;
391
+ this.id = data.id;
392
+ this.url = data.url;
393
+ this.title = data.title;
394
+ }
395
+ *[Symbol.iterator]() {
396
+ yield* this.tracks;
397
+ }
398
+ toJSON(withTracks = true) {
399
+ const payload = {
400
+ id: this.id,
401
+ url: this.url,
402
+ title: this.title,
403
+ description: this.description,
404
+ thumbnail: this.thumbnail,
405
+ type: this.type,
406
+ source: this.source,
407
+ author: this.author,
408
+ tracks: []
409
+ };
410
+ if (withTracks)
411
+ payload.tracks = this.tracks.map((m) => m.toJSON(true));
412
+ return payload;
413
+ }
414
+ };
415
+ __name(Playlist, "Playlist");
416
+
417
+ // src/Player.ts
418
+ var import_discord3 = require("discord.js");
419
+ var import_tiny_typed_emitter2 = require("tiny-typed-emitter");
420
+
421
+ // src/Structures/Queue.ts
422
+ var import_discord2 = require("discord.js");
423
+
424
+ // src/Structures/Track.ts
425
+ var import_discord = require("discord.js");
426
+ var Track = class {
427
+ constructor(player, data) {
428
+ this.requestedBy = null;
429
+ this.queryType = null;
430
+ this.raw = {};
431
+ this.id = import_discord.SnowflakeUtil.generate().toString();
432
+ Object.defineProperty(this, "player", { value: player, enumerable: false });
433
+ void this._patch(data);
434
+ }
435
+ _patch(data) {
436
+ this.title = (0, import_discord.escapeMarkdown)(data.title ?? "");
437
+ this.author = data.author ?? "";
438
+ this.url = data.url ?? "";
439
+ this.thumbnail = data.thumbnail ?? "";
440
+ this.duration = data.duration ?? "";
441
+ this.views = data.views ?? 0;
442
+ this.queryType = data.queryType;
443
+ this.requestedBy = data.requestedBy || null;
444
+ this.playlist = data.playlist;
445
+ Object.defineProperty(this, "raw", { value: Object.assign({}, { source: data.raw?.source ?? data.source }, data.raw ?? data), enumerable: false });
446
+ }
447
+ get queue() {
448
+ return this.player.queues.find((q) => q.tracks.some((ab) => ab.id === this.id));
449
+ }
450
+ get durationMS() {
451
+ const times = /* @__PURE__ */ __name((n, t) => {
452
+ let tn = 1;
453
+ for (let i = 0; i < t; i++)
454
+ tn *= n;
455
+ return t <= 0 ? 1e3 : tn * 1e3;
456
+ }, "times");
457
+ return this.duration.split(":").reverse().map((m, i) => parseInt(m) * times(60, i)).reduce((a, c) => a + c, 0);
458
+ }
459
+ get source() {
460
+ return this.raw.source ?? "arbitrary";
461
+ }
462
+ toString() {
463
+ return `${this.title} by ${this.author}`;
464
+ }
465
+ toJSON(hidePlaylist) {
466
+ return {
467
+ id: this.id,
468
+ title: this.title,
469
+ description: this.description,
470
+ author: this.author,
471
+ url: this.url,
472
+ thumbnail: this.thumbnail,
473
+ duration: this.duration,
474
+ durationMS: this.durationMS,
475
+ views: this.views,
476
+ requestedBy: this.requestedBy?.id || null,
477
+ playlist: hidePlaylist ? null : this.playlist?.toJSON() ?? null
478
+ };
479
+ }
480
+ };
481
+ __name(Track, "Track");
482
+ var Track_default = Track;
483
+
484
+ // src/types/types.ts
485
+ var QueryType = {
486
+ AUTO: "auto",
487
+ YOUTUBE: "youtube",
488
+ YOUTUBE_PLAYLIST: "youtubePlaylist",
489
+ SOUNDCLOUD_TRACK: "soundcloudTrack",
490
+ SOUNDCLOUD_PLAYLIST: "soundcloudPlaylist",
491
+ SOUNDCLOUD: "soundcloud",
492
+ SPOTIFY_SONG: "spotifySong",
493
+ SPOTIFY_ALBUM: "spotifyAlbum",
494
+ SPOTIFY_PLAYLIST: "spotifyPlaylist",
495
+ FACEBOOK: "facebook",
496
+ VIMEO: "vimeo",
497
+ ARBITRARY: "arbitrary",
498
+ REVERBNATION: "reverbnation",
499
+ YOUTUBE_SEARCH: "youtubeSearch",
500
+ YOUTUBE_VIDEO: "youtubeVideo",
501
+ SOUNDCLOUD_SEARCH: "soundcloudSearch",
502
+ APPLE_MUSIC_SONG: "appleMusicSong",
503
+ APPLE_MUSIC_ALBUM: "appleMusicAlbum",
504
+ APPLE_MUSIC_PLAYLIST: "appleMusicPlaylist",
505
+ FILE: "file"
506
+ };
507
+ var QueueRepeatMode = /* @__PURE__ */ ((QueueRepeatMode2) => {
508
+ QueueRepeatMode2[QueueRepeatMode2["OFF"] = 0] = "OFF";
509
+ QueueRepeatMode2[QueueRepeatMode2["TRACK"] = 1] = "TRACK";
510
+ QueueRepeatMode2[QueueRepeatMode2["QUEUE"] = 2] = "QUEUE";
511
+ QueueRepeatMode2[QueueRepeatMode2["AUTOPLAY"] = 3] = "AUTOPLAY";
512
+ return QueueRepeatMode2;
513
+ })(QueueRepeatMode || {});
514
+
515
+ // src/Structures/Queue.ts
516
+ var import_voice = require("@discordjs/voice");
517
+
518
+ // src/utils/Util.ts
519
+ var import_promises = require("timers/promises");
520
+ var Util = class {
521
+ constructor() {
522
+ }
523
+ static durationString(durObj) {
524
+ return Object.values(durObj).map((m) => isNaN(m) ? 0 : m).join(":");
525
+ }
526
+ static parseMS(milliseconds) {
527
+ if (isNaN(milliseconds))
528
+ milliseconds = 0;
529
+ const round = milliseconds > 0 ? Math.floor : Math.ceil;
530
+ return {
531
+ days: round(milliseconds / 864e5),
532
+ hours: round(milliseconds / 36e5) % 24,
533
+ minutes: round(milliseconds / 6e4) % 60,
534
+ seconds: round(milliseconds / 1e3) % 60
535
+ };
536
+ }
537
+ static buildTimeCode(duration) {
538
+ const items = Object.keys(duration);
539
+ const required = ["days", "hours", "minutes", "seconds"];
540
+ const parsed = items.filter((x) => required.includes(x)).map((m) => duration[m]);
541
+ const final = parsed.slice(parsed.findIndex((x) => x !== 0)).map((x) => x.toString().padStart(2, "0")).join(":");
542
+ return final.length <= 3 ? `0:${final.padStart(2, "0") || 0}` : final;
543
+ }
544
+ static last(arr) {
545
+ if (!Array.isArray(arr))
546
+ return arr;
547
+ return arr[arr.length - 1];
548
+ }
549
+ static isVoiceEmpty(channel) {
550
+ return channel.members.filter((member) => !member.user.bot).size === 0;
551
+ }
552
+ static require(id) {
553
+ try {
554
+ return require(id);
555
+ } catch {
556
+ return null;
557
+ }
558
+ }
559
+ static wait(time) {
560
+ return (0, import_promises.setTimeout)(time, void 0, { ref: false });
561
+ }
562
+ static noop() {
563
+ }
564
+ static async getFetch() {
565
+ if ("fetch" in globalThis)
566
+ return globalThis.fetch;
567
+ for (const lib of ["node-fetch", "undici"]) {
568
+ try {
569
+ return await import(lib).then((res) => res.fetch || res.default?.fetch || res.default);
570
+ } catch {
571
+ try {
572
+ const res = require(lib);
573
+ if (res)
574
+ return res.fetch || res.default?.fetch || res.default;
575
+ } catch {
576
+ }
577
+ }
578
+ }
579
+ }
580
+ };
581
+ __name(Util, "Util");
582
+
583
+ // src/Structures/PlayerError.ts
584
+ var ErrorStatusCode = /* @__PURE__ */ ((ErrorStatusCode2) => {
585
+ ErrorStatusCode2["STREAM_ERROR"] = "StreamError";
586
+ ErrorStatusCode2["AUDIO_PLAYER_ERROR"] = "AudioPlayerError";
587
+ ErrorStatusCode2["PLAYER_ERROR"] = "PlayerError";
588
+ ErrorStatusCode2["NO_AUDIO_RESOURCE"] = "NoAudioResource";
589
+ ErrorStatusCode2["UNKNOWN_GUILD"] = "UnknownGuild";
590
+ ErrorStatusCode2["INVALID_ARG_TYPE"] = "InvalidArgType";
591
+ ErrorStatusCode2["UNKNOWN_EXTRACTOR"] = "UnknownExtractor";
592
+ ErrorStatusCode2["INVALID_EXTRACTOR"] = "InvalidExtractor";
593
+ ErrorStatusCode2["INVALID_CHANNEL_TYPE"] = "InvalidChannelType";
594
+ ErrorStatusCode2["INVALID_TRACK"] = "InvalidTrack";
595
+ ErrorStatusCode2["UNKNOWN_REPEAT_MODE"] = "UnknownRepeatMode";
596
+ ErrorStatusCode2["TRACK_NOT_FOUND"] = "TrackNotFound";
597
+ ErrorStatusCode2["NO_CONNECTION"] = "NoConnection";
598
+ ErrorStatusCode2["DESTROYED_QUEUE"] = "DestroyedQueue";
599
+ return ErrorStatusCode2;
600
+ })(ErrorStatusCode || {});
601
+ var PlayerError = class extends Error {
602
+ constructor(message, code = "PlayerError" /* PLAYER_ERROR */) {
603
+ super();
604
+ this.createdAt = new Date();
605
+ this.message = `[${code}] ${message}`;
606
+ this.statusCode = code;
607
+ this.name = code;
608
+ Error.captureStackTrace(this);
609
+ }
610
+ get createdTimestamp() {
611
+ return this.createdAt.getTime();
612
+ }
613
+ valueOf() {
614
+ return this.statusCode;
615
+ }
616
+ toJSON() {
617
+ return {
618
+ stack: this.stack,
619
+ code: this.statusCode,
620
+ message: this.message,
621
+ created: this.createdTimestamp
622
+ };
623
+ }
624
+ toString() {
625
+ return this.stack;
626
+ }
627
+ };
628
+ __name(PlayerError, "PlayerError");
629
+
630
+ // src/utils/FFmpegStream.ts
631
+ var import_prism_media = require("prism-media");
632
+ function FFMPEG_ARGS_STRING(stream, fmt) {
633
+ return [
634
+ "-reconnect",
635
+ "1",
636
+ "-reconnect_streamed",
637
+ "1",
638
+ "-reconnect_delay_max",
639
+ "5",
640
+ "-i",
641
+ stream,
642
+ "-analyzeduration",
643
+ "0",
644
+ "-loglevel",
645
+ "0",
646
+ "-f",
647
+ `${typeof fmt === "string" ? fmt : "s16le"}`,
648
+ "-ar",
649
+ "48000",
650
+ "-ac",
651
+ "2"
652
+ ];
653
+ }
654
+ __name(FFMPEG_ARGS_STRING, "FFMPEG_ARGS_STRING");
655
+ function FFMPEG_ARGS_PIPED(fmt) {
656
+ return [
657
+ "-analyzeduration",
658
+ "0",
659
+ "-loglevel",
660
+ "0",
661
+ "-f",
662
+ `${typeof fmt === "string" ? fmt : "s16le"}`,
663
+ "-ar",
664
+ "48000",
665
+ "-ac",
666
+ "2"
667
+ ];
668
+ }
669
+ __name(FFMPEG_ARGS_PIPED, "FFMPEG_ARGS_PIPED");
670
+ function createFFmpegStream(stream, options) {
671
+ if (options?.skip && typeof stream !== "string")
672
+ return stream;
673
+ options ?? (options = {});
674
+ const args = typeof stream === "string" ? FFMPEG_ARGS_STRING(stream, options.fmt) : FFMPEG_ARGS_PIPED(options.fmt);
675
+ if (!Number.isNaN(options.seek))
676
+ args.unshift("-ss", String(options.seek));
677
+ if (Array.isArray(options.encoderArgs))
678
+ args.push(...options.encoderArgs);
679
+ const transcoder = new import_prism_media.FFmpeg({ shell: false, args });
680
+ transcoder.on("close", () => transcoder.destroy());
681
+ if (typeof stream !== "string") {
682
+ stream.on("error", () => transcoder.destroy());
683
+ stream.pipe(transcoder);
684
+ }
685
+ return transcoder;
686
+ }
687
+ __name(createFFmpegStream, "createFFmpegStream");
688
+
689
+ // src/Structures/Queue.ts
690
+ var import_os = __toESM(require("os"));
691
+ var import_worker_threads = require("worker_threads");
692
+ var import_utils2 = require("@discord-player/utils");
693
+
694
+ // src/utils/QueryResolver.ts
695
+ var import_youtube_sr = require("youtube-sr");
696
+ var import_soundcloud_scraper = require("soundcloud-scraper");
697
+ var spotifySongRegex = /^https?:\/\/(?:embed\.|open\.)(?:spotify\.com\/)(?:track\/|\?uri=spotify:track:)((\w|-){22})(\?si=.+)?$/;
698
+ var spotifyPlaylistRegex = /^https?:\/\/(?:embed\.|open\.)(?:spotify\.com\/)(?:playlist\/|\?uri=spotify:playlist:)((\w|-){22})(\?si=.+)?$/;
699
+ var spotifyAlbumRegex = /^https?:\/\/(?:embed\.|open\.)(?:spotify\.com\/)(?:album\/|\?uri=spotify:album:)((\w|-){22})(\?si=.+)?$/;
700
+ var vimeoRegex = /^(http|https)?:\/\/(www\.|player\.)?vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/([^/]*)\/videos\/|video\/|)(\d+)(?:|\/\?)$/;
701
+ var reverbnationRegex = /^https:\/\/(www.)?reverbnation.com\/(.+)\/song\/(.+)$/;
702
+ var attachmentRegex = /^https?:\/\/.+$/;
703
+ var appleMusicSongRegex = /^https?:\/\/music\.apple\.com\/.+?\/(song|album)\/.+?(\/.+?\?i=|\/)([0-9]+)$/;
704
+ var appleMusicPlaylistRegex = /^https?:\/\/music\.apple\.com\/.+?\/playlist\/.+\/pl\.[a-f0-9]+$/;
705
+ var appleMusicAlbumRegex = /^https?:\/\/music\.apple\.com\/.+?\/album\/.+\/([0-9]+)$/;
706
+ var QueryResolver = class {
707
+ constructor() {
708
+ }
709
+ static get regex() {
710
+ return {
711
+ spotifyAlbumRegex,
712
+ spotifyPlaylistRegex,
713
+ spotifySongRegex,
714
+ vimeoRegex,
715
+ reverbnationRegex,
716
+ attachmentRegex,
717
+ appleMusicAlbumRegex,
718
+ appleMusicPlaylistRegex,
719
+ appleMusicSongRegex
720
+ };
721
+ }
722
+ static resolve(query) {
723
+ query = query.trim();
724
+ if ((0, import_soundcloud_scraper.validateURL)(query, "track"))
725
+ return QueryType.SOUNDCLOUD_TRACK;
726
+ if ((0, import_soundcloud_scraper.validateURL)(query, "playlist") || query.includes("/sets/"))
727
+ return QueryType.SOUNDCLOUD_PLAYLIST;
728
+ if (import_youtube_sr.YouTube.isPlaylist(query))
729
+ return QueryType.YOUTUBE_PLAYLIST;
730
+ if (QueryResolver.validateId(query) || QueryResolver.validateURL(query))
731
+ return QueryType.YOUTUBE_VIDEO;
732
+ if (spotifySongRegex.test(query))
733
+ return QueryType.SPOTIFY_SONG;
734
+ if (spotifyPlaylistRegex.test(query))
735
+ return QueryType.SPOTIFY_PLAYLIST;
736
+ if (spotifyAlbumRegex.test(query))
737
+ return QueryType.SPOTIFY_ALBUM;
738
+ if (vimeoRegex.test(query))
739
+ return QueryType.VIMEO;
740
+ if (reverbnationRegex.test(query))
741
+ return QueryType.REVERBNATION;
742
+ if (appleMusicAlbumRegex.test(query))
743
+ return QueryType.APPLE_MUSIC_ALBUM;
744
+ if (appleMusicPlaylistRegex.test(query))
745
+ return QueryType.APPLE_MUSIC_PLAYLIST;
746
+ if (appleMusicSongRegex.test(query))
747
+ return QueryType.APPLE_MUSIC_SONG;
748
+ if (attachmentRegex.test(query))
749
+ return QueryType.ARBITRARY;
750
+ return QueryType.YOUTUBE_SEARCH;
751
+ }
752
+ static getVimeoID(query) {
753
+ return QueryResolver.resolve(query) === QueryType.VIMEO ? query.split("/").filter((x) => !!x).pop() : null;
754
+ }
755
+ static validateId(q) {
756
+ return import_youtube_sr.YouTube.Regex.VIDEO_ID.test(q);
757
+ }
758
+ static validateURL(q) {
759
+ return import_youtube_sr.YouTube.Regex.VIDEO_URL.test(q);
760
+ }
761
+ };
762
+ __name(QueryResolver, "QueryResolver");
763
+
764
+ // src/Structures/Queue.ts
765
+ var import_youtube_sr2 = require("youtube-sr");
766
+ var OBCS_DEFAULT = /* @__PURE__ */ __name(async () => {
767
+ return void 0;
768
+ }, "OBCS_DEFAULT");
769
+ var _destroyed, _watchDestroyed, watchDestroyed_fn, _getBufferingTimeout, getBufferingTimeout_fn;
770
+ var Queue = class {
771
+ constructor(player, guild, options = {}) {
772
+ __privateAdd(this, _watchDestroyed);
773
+ __privateAdd(this, _getBufferingTimeout);
774
+ this.tracks = [];
775
+ this.previousTracks = [];
776
+ this.playing = false;
777
+ this.metadata = null;
778
+ this.repeatMode = 0;
779
+ this.id = import_discord2.SnowflakeUtil.generate().toString();
780
+ this._streamTime = 0;
781
+ this._cooldownsTimeout = new import_utils2.Collection();
782
+ this._activeFilters = [];
783
+ this._filtersUpdate = false;
784
+ this._lastEQBands = [];
785
+ this._lastAudioFilters = [];
786
+ __privateAdd(this, _destroyed, false);
787
+ this.onBeforeCreateStream = OBCS_DEFAULT;
788
+ this.player = player;
789
+ this.guild = guild;
790
+ this.options = {};
791
+ Object.assign(
792
+ this.options,
793
+ {
794
+ leaveOnEnd: true,
795
+ leaveOnStop: true,
796
+ leaveOnEmpty: true,
797
+ leaveOnEndCooldown: 1e3,
798
+ leaveOnEmptyCooldown: 1e3,
799
+ autoSelfDeaf: true,
800
+ ytdlOptions: {
801
+ highWaterMark: 1 << 25
802
+ },
803
+ initialVolume: 100,
804
+ bufferingTimeout: 3e3,
805
+ spotifyBridge: true,
806
+ disableVolume: false,
807
+ disableEqualizer: false,
808
+ equalizerBands: [],
809
+ disableBiquad: false,
810
+ disableFilters: false,
811
+ defaultFilters: []
812
+ },
813
+ options
814
+ );
815
+ if (Array.isArray(options.equalizerBands))
816
+ this._lastEQBands = options.equalizerBands;
817
+ if (Array.isArray(options.defaultFilters))
818
+ this._lastAudioFilters = options.defaultFilters;
819
+ if (options.biquadFilter != null)
820
+ this._lastBiquadFilter = options.biquadFilter;
821
+ if ("onBeforeCreateStream" in this.options)
822
+ this.onBeforeCreateStream = this.options.onBeforeCreateStream;
823
+ this.player.emit("debug", this, `Queue initialized:
824
+
825
+ ${this.player.scanDeps()}`);
826
+ }
827
+ isFiltersAvailable() {
828
+ return this.connection.audioFilters != null;
829
+ }
830
+ get filters() {
831
+ return this.connection.audioFilters;
832
+ }
833
+ isBiquadEnabled() {
834
+ return this.connection.biquad != null;
835
+ }
836
+ isBiquadOff() {
837
+ return this.isBiquadEnabled() && !this.connection.biquad.disabled;
838
+ }
839
+ toggleBiquad() {
840
+ const eq = this.connection.biquad;
841
+ if (!eq)
842
+ return false;
843
+ eq.toggle();
844
+ return !eq.disabled;
845
+ }
846
+ enableBiquad() {
847
+ const eq = this.connection.biquad;
848
+ if (!eq)
849
+ return false;
850
+ eq.enable();
851
+ return !eq.disabled;
852
+ }
853
+ disableBiquad() {
854
+ const eq = this.connection.biquad;
855
+ if (!eq)
856
+ return false;
857
+ eq.disable();
858
+ return eq.disabled;
859
+ }
860
+ setBiquadFilter(filter) {
861
+ if (!this.isBiquadEnabled())
862
+ return;
863
+ this.connection.biquad.setFilter(filter);
864
+ this._lastBiquadFilter = filter;
865
+ }
866
+ getBiquadFilterName() {
867
+ return this.connection.biquad?.getFilterName();
868
+ }
869
+ getBiquadFilter() {
870
+ return this.connection.biquad?.filter;
871
+ }
872
+ setBiquadGain(gain) {
873
+ return this.connection.biquad?.setGain(gain);
874
+ }
875
+ setBiquadCutoff(val) {
876
+ return this.connection.biquad?.setCutoff(val);
877
+ }
878
+ setBiquadSampleRate(val) {
879
+ return this.connection.biquad?.setSample(val);
880
+ }
881
+ setBiquadQ(val) {
882
+ return this.connection.biquad?.setQ(val);
883
+ }
884
+ setEqualizer(bands) {
885
+ if (!this.connection.equalizer)
886
+ return false;
887
+ if (!Array.isArray(bands) || !bands.length) {
888
+ this.connection.equalizer.resetEQ();
889
+ this._lastEQBands = this.getEqualizer();
890
+ } else {
891
+ this.connection.equalizer.setEQ(bands);
892
+ this._lastEQBands = this.getEqualizer();
893
+ }
894
+ return true;
895
+ }
896
+ setEqualizerBand(band, gain) {
897
+ if (!this.connection.equalizer)
898
+ return null;
899
+ this.connection.equalizer.equalizer.setGain(band, gain);
900
+ this._lastEQBands = this.getEqualizer();
901
+ return true;
902
+ }
903
+ getEqualizerBand(band) {
904
+ if (!this.connection.equalizer)
905
+ return null;
906
+ return this.connection.equalizer.equalizer.getGain(band);
907
+ }
908
+ getEqualizer() {
909
+ if (!this.connection.equalizer)
910
+ return [];
911
+ return this.connection.equalizer.getEQ();
912
+ }
913
+ isEqualizerEnabled() {
914
+ return this.connection.equalizer != null;
915
+ }
916
+ isEqualizerOff() {
917
+ return this.isEqualizerEnabled() && !this.connection.equalizer.disabled;
918
+ }
919
+ toggleEqualizer() {
920
+ const eq = this.connection.equalizer;
921
+ if (!eq)
922
+ return false;
923
+ eq.toggle();
924
+ return !eq.disabled;
925
+ }
926
+ enableEqualizer() {
927
+ const eq = this.connection.equalizer;
928
+ if (!eq)
929
+ return false;
930
+ eq.enable();
931
+ return !eq.disabled;
932
+ }
933
+ disableEqualizer() {
934
+ const eq = this.connection.equalizer;
935
+ if (!eq)
936
+ return false;
937
+ eq.disable();
938
+ return eq.disabled;
939
+ }
940
+ async forceNext() {
941
+ if (this.connection.audioResource) {
942
+ this.connection.emit("finish", this.connection.audioResource);
943
+ } else if (this.tracks.length) {
944
+ await this.play();
945
+ }
946
+ }
947
+ get current() {
948
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
949
+ return;
950
+ return this.connection.audioResource?.metadata ?? this.tracks[0];
951
+ }
952
+ get destroyed() {
953
+ return __privateGet(this, _destroyed);
954
+ }
955
+ nowPlaying() {
956
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
957
+ return;
958
+ return this.current;
959
+ }
960
+ async connect(channel) {
961
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
962
+ return;
963
+ const _channel = this.guild.channels.resolve(channel);
964
+ if (![import_discord2.ChannelType.GuildStageVoice, import_discord2.ChannelType.GuildVoice].includes(_channel?.type))
965
+ throw new PlayerError(`Channel type must be GuildVoice or GuildStageVoice, got ${_channel?.type}!`, "InvalidArgType" /* INVALID_ARG_TYPE */);
966
+ const connection = await this.player.voiceUtils.connect(_channel, {
967
+ deaf: this.options.autoSelfDeaf
968
+ });
969
+ this.connection = connection;
970
+ if (_channel.type === import_discord2.ChannelType.GuildStageVoice) {
971
+ await _channel.guild.members.me.voice.setSuppressed(false).catch(async () => {
972
+ return await _channel.guild.members.me.voice.setRequestToSpeak(true).catch(Util.noop);
973
+ });
974
+ }
975
+ this.connection.on("audioFilters", (filters) => {
976
+ this._lastAudioFilters = filters;
977
+ });
978
+ this.connection.on("error", (err) => {
979
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this, false))
980
+ return;
981
+ this.player.emit("connectionError", this, err);
982
+ });
983
+ this.connection.on("debug", (msg) => {
984
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this, false))
985
+ return;
986
+ this.player.emit("debug", this, msg);
987
+ });
988
+ this.player.emit("connectionCreate", this, this.connection);
989
+ this.connection.on("start", (resource) => {
990
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this, false))
991
+ return;
992
+ this.playing = true;
993
+ if (!this._filtersUpdate)
994
+ this.player.emit("trackStart", this, resource?.metadata ?? this.current);
995
+ this._filtersUpdate = false;
996
+ });
997
+ this.connection.on("finish", async (resource) => {
998
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this, false))
999
+ return;
1000
+ this.playing = false;
1001
+ if (this._filtersUpdate)
1002
+ return;
1003
+ this._streamTime = 0;
1004
+ this.player.emit("trackEnd", this, resource.metadata);
1005
+ if (!this.tracks.length && this.repeatMode === 0 /* OFF */) {
1006
+ this.emitEnd();
1007
+ } else if (!this.tracks.length && this.repeatMode === 3 /* AUTOPLAY */) {
1008
+ this._handleAutoplay(Util.last(this.previousTracks));
1009
+ } else {
1010
+ if (this.repeatMode === 1 /* TRACK */)
1011
+ return void this.play(Util.last(this.previousTracks), { immediate: true });
1012
+ if (this.repeatMode === 2 /* QUEUE */)
1013
+ this.tracks.push(Util.last(this.previousTracks));
1014
+ const nextTrack = this.tracks.shift();
1015
+ this.play(nextTrack, { immediate: true });
1016
+ return;
1017
+ }
1018
+ });
1019
+ return this;
1020
+ }
1021
+ emitEnd() {
1022
+ const timeout = setTimeout(() => {
1023
+ if (!this.player.queues.has(this.guild.id))
1024
+ return;
1025
+ if (this.tracks.length || this.current)
1026
+ return;
1027
+ if (this.options.leaveOnEnd)
1028
+ this.destroy();
1029
+ this.player.emit("queueEnd", this);
1030
+ }, this.options.leaveOnEndCooldown || 0).unref();
1031
+ this._cooldownsTimeout.set(`queueEnd_${this.guild.id}`, timeout);
1032
+ }
1033
+ refreshEndCooldown() {
1034
+ const existingTimeout = this._cooldownsTimeout.get(`queueEnd_${this.guild.id}`);
1035
+ if (this.tracks.length || this.current) {
1036
+ clearTimeout(existingTimeout);
1037
+ this._cooldownsTimeout.delete(`queueEnd_${this.guild.id}`);
1038
+ }
1039
+ }
1040
+ destroy(disconnect = this.options.leaveOnStop) {
1041
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1042
+ return;
1043
+ if (this.connection)
1044
+ this.connection.end();
1045
+ if (disconnect)
1046
+ this.connection?.disconnect();
1047
+ this.player.queues.delete(this.guild.id);
1048
+ this.player.voiceUtils.cache.delete(this.guild.id);
1049
+ __privateSet(this, _destroyed, true);
1050
+ }
1051
+ skip() {
1052
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1053
+ return;
1054
+ if (!this.connection)
1055
+ return false;
1056
+ this._filtersUpdate = false;
1057
+ this.connection.end();
1058
+ return true;
1059
+ }
1060
+ addTrack(track) {
1061
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1062
+ return;
1063
+ if (!(track instanceof Track_default))
1064
+ throw new PlayerError("invalid track", "InvalidTrack" /* INVALID_TRACK */);
1065
+ this.tracks.push(track);
1066
+ this.refreshEndCooldown();
1067
+ this.player.emit("trackAdd", this, track);
1068
+ }
1069
+ addTracks(tracks) {
1070
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1071
+ return;
1072
+ if (!tracks.every((y) => y instanceof Track_default))
1073
+ throw new PlayerError("invalid track", "InvalidTrack" /* INVALID_TRACK */);
1074
+ this.tracks.push(...tracks);
1075
+ this.refreshEndCooldown();
1076
+ this.player.emit("tracksAdd", this, tracks);
1077
+ }
1078
+ setPaused(paused) {
1079
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1080
+ return false;
1081
+ if (!this.connection)
1082
+ return false;
1083
+ return paused ? this.connection.pause(true) : this.connection.resume();
1084
+ }
1085
+ get paused() {
1086
+ return this.connection.paused;
1087
+ }
1088
+ set paused(val) {
1089
+ this.setPaused(val);
1090
+ }
1091
+ pause() {
1092
+ return this.setPaused(true);
1093
+ }
1094
+ resume() {
1095
+ return this.setPaused(false);
1096
+ }
1097
+ setBitrate(bitrate) {
1098
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1099
+ return;
1100
+ if (!this.connection?.audioResource?.encoder)
1101
+ return;
1102
+ if (bitrate === "auto")
1103
+ bitrate = this.connection.channel?.bitrate ?? 64e3;
1104
+ this.connection.audioResource.encoder.setBitrate(bitrate);
1105
+ }
1106
+ setVolume(amount) {
1107
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1108
+ return;
1109
+ if (!this.connection)
1110
+ return false;
1111
+ this.options.initialVolume = amount;
1112
+ return this.connection.setVolume(amount);
1113
+ }
1114
+ setRepeatMode(mode) {
1115
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1116
+ return;
1117
+ if (![0 /* OFF */, 2 /* QUEUE */, 1 /* TRACK */, 3 /* AUTOPLAY */].includes(mode))
1118
+ throw new PlayerError(`Unknown repeat mode "${mode}"!`, "UnknownRepeatMode" /* UNKNOWN_REPEAT_MODE */);
1119
+ if (mode === this.repeatMode)
1120
+ return false;
1121
+ this.repeatMode = mode;
1122
+ return true;
1123
+ }
1124
+ get volume() {
1125
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1126
+ return 100;
1127
+ if (!this.connection)
1128
+ return 100;
1129
+ return this.connection.volume;
1130
+ }
1131
+ set volume(amount) {
1132
+ this.setVolume(amount);
1133
+ }
1134
+ get streamTime() {
1135
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1136
+ return 0;
1137
+ if (!this.connection)
1138
+ return 0;
1139
+ const playbackTime = this._streamTime + this.connection.streamTime;
1140
+ const NC = this._activeFilters.includes("nightcore") ? 1.25 : null;
1141
+ const VW = this._activeFilters.includes("vaporwave") ? 0.8 : null;
1142
+ if (NC && VW)
1143
+ return playbackTime * (NC + VW);
1144
+ return NC ? playbackTime * NC : VW ? playbackTime * VW : playbackTime;
1145
+ }
1146
+ set streamTime(time) {
1147
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1148
+ return;
1149
+ this.seek(time);
1150
+ }
1151
+ getFiltersEnabled() {
1152
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1153
+ return;
1154
+ return AudioFilters_default.names.filter((x) => this._activeFilters.includes(x));
1155
+ }
1156
+ getFiltersDisabled() {
1157
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1158
+ return;
1159
+ return AudioFilters_default.names.filter((x) => !this._activeFilters.includes(x));
1160
+ }
1161
+ async setFilters(filters) {
1162
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1163
+ return;
1164
+ if (!filters || !Object.keys(filters).length) {
1165
+ const streamTime2 = this.streamTime;
1166
+ this._activeFilters = [];
1167
+ return await this.play(this.current, {
1168
+ immediate: true,
1169
+ filtersUpdate: true,
1170
+ seek: streamTime2,
1171
+ encoderArgs: []
1172
+ });
1173
+ }
1174
+ const _filters = [];
1175
+ for (const filter in filters) {
1176
+ if (filters[filter] === true)
1177
+ _filters.push(filter);
1178
+ }
1179
+ if (this._activeFilters.join("") === _filters.join(""))
1180
+ return;
1181
+ const newFilters = AudioFilters_default.create(_filters).trim();
1182
+ const streamTime = this.streamTime;
1183
+ this._activeFilters = _filters;
1184
+ return await this.play(this.current, {
1185
+ immediate: true,
1186
+ filtersUpdate: true,
1187
+ seek: streamTime,
1188
+ encoderArgs: !_filters.length ? void 0 : ["-af", newFilters]
1189
+ });
1190
+ }
1191
+ async seek(position) {
1192
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1193
+ return;
1194
+ if (!this.playing || !this.current)
1195
+ return false;
1196
+ if (position < 1)
1197
+ position = 0;
1198
+ if (position >= this.current.durationMS)
1199
+ return this.skip();
1200
+ await this.play(this.current, {
1201
+ immediate: true,
1202
+ filtersUpdate: true,
1203
+ seek: position
1204
+ });
1205
+ return true;
1206
+ }
1207
+ async back() {
1208
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1209
+ return;
1210
+ const prev = this.previousTracks[this.previousTracks.length - 2];
1211
+ if (!prev)
1212
+ throw new PlayerError("Could not find previous track", "TrackNotFound" /* TRACK_NOT_FOUND */);
1213
+ return await this.play(prev, { immediate: true });
1214
+ }
1215
+ clear() {
1216
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1217
+ return;
1218
+ this.tracks = [];
1219
+ this.previousTracks = [];
1220
+ }
1221
+ stop() {
1222
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1223
+ return;
1224
+ return this.destroy();
1225
+ }
1226
+ shuffle() {
1227
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1228
+ return;
1229
+ if (!this.tracks.length || this.tracks.length < 2)
1230
+ return false;
1231
+ for (let i = this.tracks.length - 1; i > 0; i--) {
1232
+ const j = Math.floor(Math.random() * (i + 1));
1233
+ [this.tracks[i], this.tracks[j]] = [this.tracks[j], this.tracks[i]];
1234
+ }
1235
+ return true;
1236
+ }
1237
+ remove(track) {
1238
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1239
+ return;
1240
+ let trackFound = null;
1241
+ if (typeof track === "number") {
1242
+ trackFound = this.tracks[track];
1243
+ if (trackFound) {
1244
+ this.tracks = this.tracks.filter((t) => t.id !== trackFound.id);
1245
+ }
1246
+ } else {
1247
+ trackFound = this.tracks.find((s) => s.id === (track instanceof Track_default ? track.id : track));
1248
+ if (trackFound) {
1249
+ this.tracks = this.tracks.filter((s) => s.id !== trackFound.id);
1250
+ }
1251
+ }
1252
+ return trackFound;
1253
+ }
1254
+ getTrackPosition(track) {
1255
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1256
+ return;
1257
+ if (typeof track === "number")
1258
+ return this.tracks[track] != null ? track : -1;
1259
+ return this.tracks.findIndex((pred) => pred.id === (track instanceof Track_default ? track.id : track));
1260
+ }
1261
+ jump(track) {
1262
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1263
+ return;
1264
+ const foundTrack = this.remove(track);
1265
+ if (!foundTrack)
1266
+ throw new PlayerError("Track not found", "TrackNotFound" /* TRACK_NOT_FOUND */);
1267
+ this.tracks.splice(0, 0, foundTrack);
1268
+ return void this.skip();
1269
+ }
1270
+ skipTo(track) {
1271
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1272
+ return;
1273
+ const trackIndex = this.getTrackPosition(track);
1274
+ const removedTrack = this.remove(track);
1275
+ if (!removedTrack)
1276
+ throw new PlayerError("Track not found", "TrackNotFound" /* TRACK_NOT_FOUND */);
1277
+ this.tracks.splice(0, trackIndex, removedTrack);
1278
+ return void this.skip();
1279
+ }
1280
+ insert(track, index = 0) {
1281
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1282
+ return;
1283
+ if (!track || !(track instanceof Track_default))
1284
+ throw new PlayerError("track must be the instance of Track", "InvalidTrack" /* INVALID_TRACK */);
1285
+ if (typeof index !== "number" || index < 0 || !Number.isFinite(index))
1286
+ throw new PlayerError(`Invalid index "${index}"`, "InvalidArgType" /* INVALID_ARG_TYPE */);
1287
+ this.tracks.splice(index, 0, track);
1288
+ this.player.emit("trackAdd", this, track);
1289
+ }
1290
+ getPlayerTimestamp() {
1291
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1292
+ return;
1293
+ const currentStreamTime = this.streamTime;
1294
+ const totalTime = this.current.durationMS;
1295
+ const currentTimecode = Util.buildTimeCode(Util.parseMS(currentStreamTime));
1296
+ const endTimecode = Util.buildTimeCode(Util.parseMS(totalTime));
1297
+ return {
1298
+ current: currentTimecode,
1299
+ end: endTimecode,
1300
+ progress: Math.round(currentStreamTime / totalTime * 100)
1301
+ };
1302
+ }
1303
+ createProgressBar(options = { timecodes: true }) {
1304
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1305
+ return;
1306
+ const length = typeof options.length === "number" ? options.length <= 0 || options.length === Infinity ? 15 : options.length : 15;
1307
+ const index = Math.round(this.streamTime / this.current.durationMS * length);
1308
+ const indicator = typeof options.indicator === "string" && options.indicator.length > 0 ? options.indicator : "\u{1F518}";
1309
+ const line = typeof options.line === "string" && options.line.length > 0 ? options.line : "\u25AC";
1310
+ if (index >= 1 && index <= length) {
1311
+ const bar = line.repeat(length - 1).split("");
1312
+ bar.splice(index, 0, indicator);
1313
+ if (options.timecodes) {
1314
+ const timestamp = this.getPlayerTimestamp();
1315
+ return `${timestamp.current} \u2503 ${bar.join("")} \u2503 ${timestamp.end}`;
1316
+ } else {
1317
+ return `${bar.join("")}`;
1318
+ }
1319
+ } else {
1320
+ if (options.timecodes) {
1321
+ const timestamp = this.getPlayerTimestamp();
1322
+ return `${timestamp.current} \u2503 ${indicator}${line.repeat(length - 1)} \u2503 ${timestamp.end}`;
1323
+ } else {
1324
+ return `${indicator}${line.repeat(length - 1)}`;
1325
+ }
1326
+ }
1327
+ }
1328
+ get totalTime() {
1329
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1330
+ return 0;
1331
+ return this.tracks.length > 0 ? this.tracks.map((t) => t.durationMS).reduce((p, c) => p + c) : 0;
1332
+ }
1333
+ generateStatistics() {
1334
+ return {
1335
+ guild: this.guild.id,
1336
+ memory: process.memoryUsage(),
1337
+ tracks: this.tracks.length,
1338
+ os: {
1339
+ cpuCount: import_os.default.cpus().length,
1340
+ totalMem: import_os.default.totalmem(),
1341
+ freeMem: import_os.default.freemem(),
1342
+ platform: process.platform
1343
+ },
1344
+ isShard: typeof process.send === "function" || import_worker_threads.parentPort != null,
1345
+ latency: {
1346
+ client: this.player.client.ws.ping,
1347
+ udp: this.connection.voiceConnection.ping.udp,
1348
+ ws: this.connection.voiceConnection.ping.ws,
1349
+ eventLoop: this.player.eventLoopLag
1350
+ },
1351
+ subscribers: this.player.queues.size,
1352
+ connections: this.player.queues.filter((x) => x.connection?.voiceConnection != null).size,
1353
+ extractors: this.player.extractors.size
1354
+ };
1355
+ }
1356
+ get ping() {
1357
+ return this.connection.voiceConnection.ping.udp;
1358
+ }
1359
+ async play(src, options = {}) {
1360
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this, false))
1361
+ return;
1362
+ if (!this.connection || !this.connection.voiceConnection)
1363
+ throw new PlayerError("Voice connection is not available, use <Queue>.connect()!", "NoConnection" /* NO_CONNECTION */);
1364
+ if (src && (this.playing || this.tracks.length) && !options.immediate)
1365
+ return this.addTrack(src);
1366
+ const track = options.filtersUpdate && !options.immediate ? src || this.current : src ?? this.tracks.shift();
1367
+ if (!track)
1368
+ return;
1369
+ this.player.emit("debug", this, "Received play request");
1370
+ if (!options.filtersUpdate) {
1371
+ this.previousTracks = this.previousTracks.filter((x) => x.id !== track.id);
1372
+ this.previousTracks.push(track);
1373
+ }
1374
+ let stream = null;
1375
+ const hasCustomDownloader = typeof this.onBeforeCreateStream === "function";
1376
+ if (hasCustomDownloader) {
1377
+ const qt = track.queryType || (track.raw.source === "spotify" ? "spotifySong" : track.raw.source === "apple_music" ? "appleMusicSong" : track.raw.source) || "arbitrary";
1378
+ stream = await this.onBeforeCreateStream(track, qt, this) || null;
1379
+ }
1380
+ if (!stream) {
1381
+ const streamInfo = await this.player.extractors.run(async (extractor) => {
1382
+ const canStream = await extractor.validate(track.url, track.queryType || QueryResolver.resolve(track.url));
1383
+ if (!canStream)
1384
+ return false;
1385
+ return await extractor.stream(track);
1386
+ });
1387
+ if (!streamInfo || !streamInfo.result) {
1388
+ this.player.emit("error", this, new Error("No stream extractors are available for this track"));
1389
+ return void this.play(this.tracks.shift(), { immediate: true });
1390
+ }
1391
+ stream = streamInfo.result;
1392
+ }
1393
+ const ffmpegStream = createFFmpegStream(stream, {
1394
+ encoderArgs: options.encoderArgs || this._activeFilters.length ? ["-af", AudioFilters_default.create(this._activeFilters)] : [],
1395
+ seek: options.seek ? options.seek / 1e3 : 0,
1396
+ fmt: "s16le"
1397
+ }).on("error", (err) => {
1398
+ if (!`${err}`.toLowerCase().includes("premature close"))
1399
+ this.player.emit("error", this, err);
1400
+ });
1401
+ const resource = this.connection.createStream(ffmpegStream, {
1402
+ type: import_voice.StreamType.Raw,
1403
+ data: track,
1404
+ disableVolume: Boolean(this.options.disableVolume),
1405
+ disableEqualizer: Boolean(this.options.disableEqualizer),
1406
+ eq: this._lastEQBands,
1407
+ disableBiquad: Boolean(this.options.disableBiquad),
1408
+ biquadFilter: this._lastBiquadFilter,
1409
+ defaultFilters: this._lastAudioFilters,
1410
+ disableFilters: Boolean(this.options.disableFilters)
1411
+ });
1412
+ if (options.seek)
1413
+ this._streamTime = options.seek;
1414
+ this._filtersUpdate = options.filtersUpdate;
1415
+ const volumeTransformer = resource.volume;
1416
+ if (volumeTransformer && typeof this.options.initialVolume === "number")
1417
+ volumeTransformer.setVolume(Math.pow(this.options.initialVolume / 100, 1.660964));
1418
+ if (volumeTransformer?.hasSmoothness && typeof this.options.volumeSmoothness === "number") {
1419
+ if (typeof volumeTransformer.setSmoothness === "function")
1420
+ volumeTransformer.setSmoothness(this.options.volumeSmoothness || 0);
1421
+ }
1422
+ setTimeout(() => {
1423
+ this.connection.playStream(resource);
1424
+ }, __privateMethod(this, _getBufferingTimeout, getBufferingTimeout_fn).call(this)).unref();
1425
+ }
1426
+ async _handleAutoplay(track) {
1427
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1428
+ return;
1429
+ if (!track || ![track.source, track.raw?.source].includes("youtube")) {
1430
+ return this.emitEnd();
1431
+ }
1432
+ let info = await import_youtube_sr2.YouTube.getVideo(track.url).then((x) => x.videos[0]).catch(Util.noop);
1433
+ if (!info)
1434
+ info = await import_youtube_sr2.YouTube.search(track.author).then((x) => x[0]).catch(Util.noop);
1435
+ if (!info) {
1436
+ return this.emitEnd();
1437
+ }
1438
+ const nextTrack = new Track_default(this.player, {
1439
+ title: info.title,
1440
+ url: `https://www.youtube.com/watch?v=${info.id}`,
1441
+ duration: info.durationFormatted || Util.buildTimeCode(Util.parseMS(info.duration * 1e3)),
1442
+ description: "",
1443
+ thumbnail: typeof info.thumbnail === "string" ? info.thumbnail : info.thumbnail.url,
1444
+ views: info.views,
1445
+ author: info.channel.name,
1446
+ requestedBy: track.requestedBy,
1447
+ source: "youtube",
1448
+ queryType: "youtubeVideo"
1449
+ });
1450
+ this.play(nextTrack, { immediate: true });
1451
+ }
1452
+ *[Symbol.iterator]() {
1453
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1454
+ return;
1455
+ yield* this.tracks;
1456
+ }
1457
+ toJSON() {
1458
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1459
+ return;
1460
+ return {
1461
+ id: this.id,
1462
+ guild: this.guild.id,
1463
+ voiceChannel: this.connection?.channel?.id,
1464
+ options: this.options,
1465
+ tracks: this.tracks.map((m) => m.toJSON())
1466
+ };
1467
+ }
1468
+ toString() {
1469
+ if (__privateMethod(this, _watchDestroyed, watchDestroyed_fn).call(this))
1470
+ return;
1471
+ if (!this.tracks.length)
1472
+ return "No songs available to display!";
1473
+ return `**Upcoming Songs:**
1474
+ ${this.tracks.map((m, i) => `${i + 1}. **${m.title}**`).join("\n")}`;
1475
+ }
1476
+ };
1477
+ __name(Queue, "Queue");
1478
+ _destroyed = new WeakMap();
1479
+ _watchDestroyed = new WeakSet();
1480
+ watchDestroyed_fn = /* @__PURE__ */ __name(function(emit = true) {
1481
+ if (__privateGet(this, _destroyed)) {
1482
+ if (emit)
1483
+ this.player.emit("error", this, new PlayerError("Cannot use destroyed queue", "DestroyedQueue" /* DESTROYED_QUEUE */));
1484
+ return true;
1485
+ }
1486
+ return false;
1487
+ }, "#watchDestroyed");
1488
+ _getBufferingTimeout = new WeakSet();
1489
+ getBufferingTimeout_fn = /* @__PURE__ */ __name(function() {
1490
+ const timeout = this.options.bufferingTimeout;
1491
+ if (isNaN(timeout) || timeout < 0 || !Number.isFinite(timeout))
1492
+ return 1e3;
1493
+ return timeout;
1494
+ }, "#getBufferingTimeout");
1495
+
1496
+ // src/VoiceInterface/VoiceUtils.ts
1497
+ var import_voice3 = require("@discordjs/voice");
1498
+
1499
+ // src/VoiceInterface/StreamDispatcher.ts
1500
+ var import_voice2 = require("@discordjs/voice");
1501
+ var import_tiny_typed_emitter = require("tiny-typed-emitter");
1502
+ var import_equalizer = require("@discord-player/equalizer");
1503
+ var StreamDispatcher = class extends import_tiny_typed_emitter.TypedEmitter {
1504
+ constructor(connection, channel, connectionTimeout = 2e4) {
1505
+ super();
1506
+ this.connectionTimeout = connectionTimeout;
1507
+ this.readyLock = false;
1508
+ this.equalizer = null;
1509
+ this.biquad = null;
1510
+ this.audioFilters = null;
1511
+ this.voiceConnection = connection;
1512
+ this.audioPlayer = (0, import_voice2.createAudioPlayer)();
1513
+ this.channel = channel;
1514
+ this.voiceConnection.on("stateChange", async (_, newState) => {
1515
+ if (newState.status === import_voice2.VoiceConnectionStatus.Disconnected) {
1516
+ if (newState.reason === import_voice2.VoiceConnectionDisconnectReason.WebSocketClose && newState.closeCode === 4014) {
1517
+ try {
1518
+ await (0, import_voice2.entersState)(this.voiceConnection, import_voice2.VoiceConnectionStatus.Connecting, this.connectionTimeout);
1519
+ } catch {
1520
+ try {
1521
+ this.voiceConnection.destroy();
1522
+ } catch (err) {
1523
+ this.emit("error", err);
1524
+ }
1525
+ }
1526
+ } else if (this.voiceConnection.rejoinAttempts < 5) {
1527
+ await Util.wait((this.voiceConnection.rejoinAttempts + 1) * 5e3);
1528
+ this.voiceConnection.rejoin();
1529
+ } else {
1530
+ try {
1531
+ this.voiceConnection.destroy();
1532
+ } catch (err) {
1533
+ this.emit("error", err);
1534
+ }
1535
+ }
1536
+ } else if (newState.status === import_voice2.VoiceConnectionStatus.Destroyed) {
1537
+ this.end();
1538
+ } else if (!this.readyLock && (newState.status === import_voice2.VoiceConnectionStatus.Connecting || newState.status === import_voice2.VoiceConnectionStatus.Signalling)) {
1539
+ this.readyLock = true;
1540
+ try {
1541
+ await (0, import_voice2.entersState)(this.voiceConnection, import_voice2.VoiceConnectionStatus.Ready, this.connectionTimeout);
1542
+ } catch {
1543
+ if (this.voiceConnection.state.status !== import_voice2.VoiceConnectionStatus.Destroyed) {
1544
+ try {
1545
+ this.voiceConnection.destroy();
1546
+ } catch (err) {
1547
+ this.emit("error", err);
1548
+ }
1549
+ }
1550
+ } finally {
1551
+ this.readyLock = false;
1552
+ }
1553
+ }
1554
+ });
1555
+ this.audioPlayer.on("stateChange", (oldState, newState) => {
1556
+ if (newState.status === import_voice2.AudioPlayerStatus.Playing) {
1557
+ if (!this.paused)
1558
+ return void this.emit("start", this.audioResource);
1559
+ } else if (newState.status === import_voice2.AudioPlayerStatus.Idle && oldState.status !== import_voice2.AudioPlayerStatus.Idle) {
1560
+ if (!this.paused) {
1561
+ void this.emit("finish", this.audioResource);
1562
+ if (this.equalizer) {
1563
+ this.equalizer.destroy();
1564
+ this.equalizer = null;
1565
+ }
1566
+ if (this.biquad) {
1567
+ this.biquad.destroy();
1568
+ this.biquad = null;
1569
+ }
1570
+ if (this.audioFilters) {
1571
+ this.audioFilters.destroy();
1572
+ this.audioFilters = null;
1573
+ }
1574
+ this.audioResource = null;
1575
+ }
1576
+ }
1577
+ });
1578
+ this.audioPlayer.on("debug", (m) => void this.emit("debug", m));
1579
+ this.audioPlayer.on("error", (error) => void this.emit("error", error));
1580
+ this.voiceConnection.subscribe(this.audioPlayer);
1581
+ }
1582
+ get paused() {
1583
+ return this.audioPlayer.state.status === import_voice2.AudioPlayerStatus.Paused;
1584
+ }
1585
+ set paused(val) {
1586
+ val ? this.pause(true) : this.resume();
1587
+ }
1588
+ isPaused() {
1589
+ return this.paused || this.audioPlayer.state.status === import_voice2.AudioPlayerStatus.AutoPaused;
1590
+ }
1591
+ isBuffering() {
1592
+ return this.audioPlayer.state.status === import_voice2.AudioPlayerStatus.Buffering;
1593
+ }
1594
+ isPlaying() {
1595
+ return this.audioPlayer.state.status === import_voice2.AudioPlayerStatus.Playing;
1596
+ }
1597
+ isIdle() {
1598
+ return this.audioPlayer.state.status === import_voice2.AudioPlayerStatus.Idle;
1599
+ }
1600
+ createStream(src, ops) {
1601
+ if (!ops?.disableEqualizer) {
1602
+ this.equalizer = new import_equalizer.EqualizerStream({
1603
+ channels: 1,
1604
+ disabled: false,
1605
+ bandMultiplier: ops?.eq || []
1606
+ });
1607
+ }
1608
+ if (!ops?.disableBiquad) {
1609
+ this.biquad = new import_equalizer.BiquadStream({
1610
+ filter: ops?.biquadFilter
1611
+ });
1612
+ }
1613
+ if (!ops?.disableFilters) {
1614
+ this.audioFilters = new import_equalizer.AudioFilter({
1615
+ filters: ops?.defaultFilters
1616
+ });
1617
+ this.audioFilters.onUpdate = () => {
1618
+ if (this.audioFilters)
1619
+ this.emit("audioFilters", this.audioFilters.filters);
1620
+ };
1621
+ }
1622
+ let stream = this.equalizer && typeof src !== "string" ? src.pipe(this.equalizer) : src;
1623
+ if (this.biquad && typeof stream !== "string")
1624
+ stream = stream.pipe(this.biquad);
1625
+ if (this.audioFilters && typeof stream !== "string")
1626
+ stream = stream.pipe(this.audioFilters);
1627
+ this.audioResource = (0, import_voice2.createAudioResource)(stream, {
1628
+ inputType: ops?.type ?? import_voice2.StreamType.Arbitrary,
1629
+ metadata: ops?.data,
1630
+ inlineVolume: !ops?.disableVolume
1631
+ });
1632
+ return this.audioResource;
1633
+ }
1634
+ get status() {
1635
+ return this.audioPlayer.state.status;
1636
+ }
1637
+ disconnect() {
1638
+ try {
1639
+ this.audioPlayer.stop(true);
1640
+ this.voiceConnection.destroy();
1641
+ } catch {
1642
+ }
1643
+ }
1644
+ end() {
1645
+ this.audioPlayer.stop();
1646
+ }
1647
+ pause(interpolateSilence) {
1648
+ const success = this.audioPlayer.pause(interpolateSilence);
1649
+ return success;
1650
+ }
1651
+ resume() {
1652
+ const success = this.audioPlayer.unpause();
1653
+ return success;
1654
+ }
1655
+ async playStream(resource = this.audioResource) {
1656
+ if (!resource)
1657
+ throw new PlayerError("Audio resource is not available!", "NoAudioResource" /* NO_AUDIO_RESOURCE */);
1658
+ if (resource.ended) {
1659
+ return void this.emit("finish", resource);
1660
+ }
1661
+ if (!this.audioResource)
1662
+ this.audioResource = resource;
1663
+ if (this.voiceConnection.state.status !== import_voice2.VoiceConnectionStatus.Ready) {
1664
+ try {
1665
+ await (0, import_voice2.entersState)(this.voiceConnection, import_voice2.VoiceConnectionStatus.Ready, this.connectionTimeout);
1666
+ } catch (err) {
1667
+ return void this.emit("error", err);
1668
+ }
1669
+ }
1670
+ try {
1671
+ this.audioPlayer.play(resource);
1672
+ } catch (e) {
1673
+ this.emit("error", e);
1674
+ }
1675
+ return this;
1676
+ }
1677
+ setVolume(value) {
1678
+ if (!this.audioResource?.volume || isNaN(value) || value < 0 || value > Infinity)
1679
+ return false;
1680
+ this.audioResource.volume.setVolumeLogarithmic(value / 100);
1681
+ return true;
1682
+ }
1683
+ get volume() {
1684
+ if (!this.audioResource?.volume)
1685
+ return 100;
1686
+ const currentVol = this.audioResource.volume.volume;
1687
+ return Math.round(Math.pow(currentVol, 1 / 1.660964) * 100);
1688
+ }
1689
+ get streamTime() {
1690
+ if (!this.audioResource)
1691
+ return 0;
1692
+ return this.audioResource.playbackDuration;
1693
+ }
1694
+ };
1695
+ __name(StreamDispatcher, "StreamDispatcher");
1696
+
1697
+ // src/VoiceInterface/VoiceUtils.ts
1698
+ var import_utils3 = require("@discord-player/utils");
1699
+ var VoiceUtils = class {
1700
+ constructor() {
1701
+ this.cache = new import_utils3.Collection();
1702
+ }
1703
+ async connect(channel, options) {
1704
+ const conn = await this.join(channel, options);
1705
+ const sub = new StreamDispatcher(conn, channel, options?.maxTime);
1706
+ this.cache.set(channel.guild.id, sub);
1707
+ return sub;
1708
+ }
1709
+ async join(channel, options) {
1710
+ const conn = (0, import_voice3.joinVoiceChannel)({
1711
+ guildId: channel.guild.id,
1712
+ channelId: channel.id,
1713
+ adapterCreator: channel.guild.voiceAdapterCreator,
1714
+ selfDeaf: Boolean(options?.deaf)
1715
+ });
1716
+ return conn;
1717
+ }
1718
+ disconnect(connection) {
1719
+ if (connection instanceof StreamDispatcher)
1720
+ return connection.voiceConnection.destroy();
1721
+ return connection.destroy();
1722
+ }
1723
+ getConnection(guild) {
1724
+ return this.cache.get(guild);
1725
+ }
1726
+ };
1727
+ __name(VoiceUtils, "VoiceUtils");
1728
+
1729
+ // src/Player.ts
1730
+ var import_voice4 = require("@discordjs/voice");
1731
+ var import_utils4 = require("@discord-player/utils");
1732
+
1733
+ // src/Structures/SearchResult.ts
1734
+ var SearchResult = class {
1735
+ constructor(player, _data) {
1736
+ this.player = player;
1737
+ this._data = _data;
1738
+ }
1739
+ get query() {
1740
+ return this._data.query;
1741
+ }
1742
+ get queryType() {
1743
+ return this._data.queryType || QueryType.AUTO;
1744
+ }
1745
+ get extractor() {
1746
+ return this._data.extractor || null;
1747
+ }
1748
+ get playlist() {
1749
+ return this._data.playlist;
1750
+ }
1751
+ get tracks() {
1752
+ return this._data.tracks || [];
1753
+ }
1754
+ get requestedBy() {
1755
+ return this._data.requestedBy || null;
1756
+ }
1757
+ async execute() {
1758
+ return this.player.search(this.query, {
1759
+ searchEngine: this.queryType,
1760
+ requestedBy: this.requestedBy
1761
+ });
1762
+ }
1763
+ isEmpty() {
1764
+ return !this.tracks.length;
1765
+ }
1766
+ hasPlaylist() {
1767
+ return this.playlist != null;
1768
+ }
1769
+ hasTracks() {
1770
+ return this.tracks.length > 0;
1771
+ }
1772
+ toJSON() {
1773
+ return {
1774
+ query: this.query,
1775
+ queryType: this.queryType,
1776
+ playlist: this.playlist?.toJSON(false) || null,
1777
+ tracks: this.tracks.map((m) => m.toJSON(true)),
1778
+ extractor: this.extractor?.identifier || null,
1779
+ requestedBy: this.requestedBy?.toJSON() || null
1780
+ };
1781
+ }
1782
+ };
1783
+ __name(SearchResult, "SearchResult");
1784
+
1785
+ // src/Player.ts
1786
+ var _lastLatency;
1787
+ var Player = class extends import_tiny_typed_emitter2.TypedEmitter {
1788
+ constructor(client, options = {}) {
1789
+ super();
1790
+ this.options = {
1791
+ autoRegisterExtractor: true,
1792
+ ytdlOptions: {
1793
+ highWaterMark: 1 << 25
1794
+ },
1795
+ connectionTimeout: 2e4,
1796
+ smoothVolume: true,
1797
+ lagMonitor: 3e4
1798
+ };
1799
+ this.queues = new import_utils4.Collection();
1800
+ this.voiceUtils = new VoiceUtils();
1801
+ this.requiredEvents = ["error", "connectionError"];
1802
+ this.extractors = new ExtractorExecutionContext(this);
1803
+ __privateAdd(this, _lastLatency, -1);
1804
+ this.client = client;
1805
+ if (this.client?.options?.intents && !new import_discord3.IntentsBitField(this.client?.options?.intents).has(import_discord3.IntentsBitField.Flags.GuildVoiceStates)) {
1806
+ throw new PlayerError('client is missing "GuildVoiceStates" intent');
1807
+ }
1808
+ this.options = Object.assign(this.options, options);
1809
+ this.client.on("voiceStateUpdate", this._handleVoiceState.bind(this));
1810
+ if (this.options?.autoRegisterExtractor) {
1811
+ let nv;
1812
+ if (nv = Util.require("@discord-player/extractor")) {
1813
+ ["YouTubeExtractor", "SoundCloudExtractor", "ReverbnationExtractor", "VimeoExtractor", "AttachmentExtractor"].forEach((ext) => void this.extractors.register(nv[ext]));
1814
+ }
1815
+ }
1816
+ if (typeof this.options.lagMonitor === "number" && this.options.lagMonitor > 0) {
1817
+ setInterval(() => {
1818
+ const start = performance.now();
1819
+ setTimeout(() => {
1820
+ __privateSet(this, _lastLatency, performance.now() - start);
1821
+ }, 0).unref();
1822
+ }, this.options.lagMonitor).unref();
1823
+ }
1824
+ }
1825
+ get eventLoopLag() {
1826
+ return __privateGet(this, _lastLatency);
1827
+ }
1828
+ generateStatistics() {
1829
+ return this.queues.map((m) => m.generateStatistics());
1830
+ }
1831
+ _handleVoiceState(oldState, newState) {
1832
+ const queue = this.getQueue(oldState.guild.id);
1833
+ if (!queue || !queue.connection)
1834
+ return;
1835
+ this.emit("voiceStateUpdate", queue, oldState, newState);
1836
+ if (oldState.channelId && !newState.channelId && newState.member.id === newState.guild.members.me.id) {
1837
+ try {
1838
+ queue.destroy();
1839
+ } catch {
1840
+ }
1841
+ return void this.emit("botDisconnect", queue);
1842
+ }
1843
+ if (!oldState.channelId && newState.channelId && newState.member.id === newState.guild.members.me.id) {
1844
+ if (newState.serverMute != null && oldState.serverMute !== newState.serverMute) {
1845
+ queue.setPaused(newState.serverMute);
1846
+ } else if (newState.channel?.type === import_discord3.ChannelType.GuildStageVoice && newState.suppress != null && oldState.suppress !== newState.suppress) {
1847
+ queue.setPaused(newState.suppress);
1848
+ if (newState.suppress) {
1849
+ newState.guild.members.me.voice.setRequestToSpeak(true).catch(Util.noop);
1850
+ }
1851
+ }
1852
+ }
1853
+ if (!newState.channelId && oldState.channelId === queue.connection.channel.id) {
1854
+ if (!Util.isVoiceEmpty(queue.connection.channel))
1855
+ return;
1856
+ const timeout = setTimeout(() => {
1857
+ if (!Util.isVoiceEmpty(queue.connection.channel))
1858
+ return;
1859
+ if (!this.queues.has(queue.guild.id))
1860
+ return;
1861
+ if (queue.options.leaveOnEmpty)
1862
+ queue.destroy(true);
1863
+ this.emit("channelEmpty", queue);
1864
+ }, queue.options.leaveOnEmptyCooldown || 0).unref();
1865
+ queue._cooldownsTimeout.set(`empty_${oldState.guild.id}`, timeout);
1866
+ }
1867
+ if (newState.channelId && newState.channelId === queue.connection.channel.id) {
1868
+ const emptyTimeout = queue._cooldownsTimeout.get(`empty_${oldState.guild.id}`);
1869
+ const channelEmpty = Util.isVoiceEmpty(queue.connection.channel);
1870
+ if (!channelEmpty && emptyTimeout) {
1871
+ clearTimeout(emptyTimeout);
1872
+ queue._cooldownsTimeout.delete(`empty_${oldState.guild.id}`);
1873
+ }
1874
+ }
1875
+ if (oldState.channelId && newState.channelId && oldState.channelId !== newState.channelId) {
1876
+ if (newState.member.id === newState.guild.members.me.id) {
1877
+ if (queue.connection && newState.member.id === newState.guild.members.me.id)
1878
+ queue.connection.channel = newState.channel;
1879
+ const emptyTimeout = queue._cooldownsTimeout.get(`empty_${oldState.guild.id}`);
1880
+ const channelEmpty = Util.isVoiceEmpty(queue.connection.channel);
1881
+ if (!channelEmpty && emptyTimeout) {
1882
+ clearTimeout(emptyTimeout);
1883
+ queue._cooldownsTimeout.delete(`empty_${oldState.guild.id}`);
1884
+ } else {
1885
+ const timeout = setTimeout(() => {
1886
+ if (queue.connection && !Util.isVoiceEmpty(queue.connection.channel))
1887
+ return;
1888
+ if (!this.queues.has(queue.guild.id))
1889
+ return;
1890
+ if (queue.options.leaveOnEmpty)
1891
+ queue.destroy(true);
1892
+ this.emit("channelEmpty", queue);
1893
+ }, queue.options.leaveOnEmptyCooldown || 0).unref();
1894
+ queue._cooldownsTimeout.set(`empty_${oldState.guild.id}`, timeout);
1895
+ }
1896
+ } else {
1897
+ if (newState.channelId !== queue.connection.channel.id) {
1898
+ if (!Util.isVoiceEmpty(queue.connection.channel))
1899
+ return;
1900
+ if (queue._cooldownsTimeout.has(`empty_${oldState.guild.id}`))
1901
+ return;
1902
+ const timeout = setTimeout(() => {
1903
+ if (!Util.isVoiceEmpty(queue.connection.channel))
1904
+ return;
1905
+ if (!this.queues.has(queue.guild.id))
1906
+ return;
1907
+ if (queue.options.leaveOnEmpty)
1908
+ queue.destroy(true);
1909
+ this.emit("channelEmpty", queue);
1910
+ }, queue.options.leaveOnEmptyCooldown || 0).unref();
1911
+ queue._cooldownsTimeout.set(`empty_${oldState.guild.id}`, timeout);
1912
+ } else {
1913
+ const emptyTimeout = queue._cooldownsTimeout.get(`empty_${oldState.guild.id}`);
1914
+ const channelEmpty = Util.isVoiceEmpty(queue.connection.channel);
1915
+ if (!channelEmpty && emptyTimeout) {
1916
+ clearTimeout(emptyTimeout);
1917
+ queue._cooldownsTimeout.delete(`empty_${oldState.guild.id}`);
1918
+ }
1919
+ }
1920
+ }
1921
+ }
1922
+ }
1923
+ createQueue(guild, queueInitOptions = {}) {
1924
+ guild = this.client.guilds.resolve(guild);
1925
+ if (!guild)
1926
+ throw new PlayerError("Unknown Guild", "UnknownGuild" /* UNKNOWN_GUILD */);
1927
+ if (this.queues.has(guild.id))
1928
+ return this.queues.get(guild.id);
1929
+ const _meta = queueInitOptions.metadata;
1930
+ delete queueInitOptions["metadata"];
1931
+ queueInitOptions.volumeSmoothness ?? (queueInitOptions.volumeSmoothness = this.options.smoothVolume ? 0.08 : 0);
1932
+ queueInitOptions.ytdlOptions ?? (queueInitOptions.ytdlOptions = this.options.ytdlOptions);
1933
+ const queue = new Queue(this, guild, queueInitOptions);
1934
+ queue.metadata = _meta;
1935
+ this.queues.set(guild.id, queue);
1936
+ return queue;
1937
+ }
1938
+ getQueue(guild) {
1939
+ guild = this.client.guilds.resolve(guild);
1940
+ if (!guild)
1941
+ throw new PlayerError("Unknown Guild", "UnknownGuild" /* UNKNOWN_GUILD */);
1942
+ return this.queues.get(guild.id);
1943
+ }
1944
+ deleteQueue(guild) {
1945
+ guild = this.client.guilds.resolve(guild);
1946
+ if (!guild)
1947
+ throw new PlayerError("Unknown Guild", "UnknownGuild" /* UNKNOWN_GUILD */);
1948
+ const prev = this.getQueue(guild);
1949
+ try {
1950
+ prev.destroy();
1951
+ } catch {
1952
+ }
1953
+ this.queues.delete(guild.id);
1954
+ return prev;
1955
+ }
1956
+ async search(query, options) {
1957
+ if (options.requestedBy != null)
1958
+ options.requestedBy = this.client.users.resolve(options.requestedBy);
1959
+ if (query instanceof Track_default)
1960
+ return new SearchResult(this, {
1961
+ playlist: query.playlist || null,
1962
+ tracks: [query],
1963
+ query: query.toString(),
1964
+ extractor: null,
1965
+ queryType: QueryType.AUTO,
1966
+ requestedBy: options.requestedBy
1967
+ });
1968
+ if (!options)
1969
+ throw new PlayerError("DiscordPlayer#search needs search options!", "InvalidArgType" /* INVALID_ARG_TYPE */);
1970
+ let extractor = null;
1971
+ options.searchEngine ?? (options.searchEngine = QueryType.AUTO);
1972
+ const queryType = options.searchEngine === QueryType.AUTO ? QueryResolver.resolve(query) : options.searchEngine;
1973
+ if (options.searchEngine.startsWith("ext:")) {
1974
+ extractor = this.extractors.get(options.searchEngine.substring(4));
1975
+ if (!extractor)
1976
+ return new SearchResult(this, { query, queryType });
1977
+ }
1978
+ if (!extractor) {
1979
+ extractor = (await this.extractors.run((ext) => ext.validate(query, queryType)))?.extractor || null;
1980
+ }
1981
+ if (!extractor) {
1982
+ return new SearchResult(this, { query, queryType });
1983
+ }
1984
+ const res = await extractor.handle(query, {
1985
+ type: queryType,
1986
+ requestedBy: options.requestedBy
1987
+ }).catch(() => null);
1988
+ if (res) {
1989
+ return new SearchResult(this, {
1990
+ query,
1991
+ queryType,
1992
+ playlist: res.playlist,
1993
+ tracks: res.tracks,
1994
+ extractor
1995
+ });
1996
+ }
1997
+ const result = await this.extractors.run(
1998
+ async (ext) => await ext.validate(query) && ext.handle(query, {
1999
+ type: queryType,
2000
+ requestedBy: options.requestedBy
2001
+ })
2002
+ );
2003
+ if (!result?.result)
2004
+ return new SearchResult(this, { query, queryType });
2005
+ return new SearchResult(this, {
2006
+ query,
2007
+ queryType,
2008
+ playlist: result.result.playlist,
2009
+ tracks: result.result.tracks,
2010
+ extractor: result.extractor
2011
+ });
2012
+ }
2013
+ scanDeps() {
2014
+ const line = "-".repeat(50);
2015
+ const depsReport = (0, import_voice4.generateDependencyReport)();
2016
+ const extractorReport = this.extractors.store.map((m) => {
2017
+ return m.identifier;
2018
+ }).join("\n");
2019
+ return `${depsReport}
2020
+ ${line}
2021
+ Loaded Extractors:
2022
+ ${extractorReport || "None"}`;
2023
+ }
2024
+ emit(eventName, ...args) {
2025
+ if (this.requiredEvents.includes(eventName) && !super.eventNames().includes(eventName)) {
2026
+ console.error(...args);
2027
+ process.emitWarning(`[DiscordPlayerWarning] Unhandled "${eventName}" event! Events ${this.requiredEvents.map((m) => `"${m}"`).join(", ")} must have event listeners!`);
2028
+ return false;
2029
+ } else {
2030
+ return super.emit(eventName, ...args);
2031
+ }
2032
+ }
2033
+ resolveQueue(queueLike) {
2034
+ return this.getQueue(queueLike instanceof Queue ? queueLike.guild : queueLike);
2035
+ }
2036
+ *[Symbol.iterator]() {
2037
+ yield* Array.from(this.queues.values());
2038
+ }
2039
+ createPlaylist(data) {
2040
+ return new Playlist(this, data);
2041
+ }
2042
+ };
2043
+ __name(Player, "Player");
2044
+ _lastLatency = new WeakMap();
2045
+
2046
+ // src/index.ts
2047
+ var version = "5.4.1-dev.0";
2048
+ if (!import_discord4.version.startsWith("14")) {
2049
+ process.emitWarning(`Discord.js v${import_discord4.version} is incompatible with Discord Player v${version}! Please use >=v14.x of Discord.js`);
2050
+ }
2051
+ // Annotate the CommonJS export names for ESM import in node:
2052
+ 0 && (module.exports = {
2053
+ AudioFilters,
2054
+ BaseExtractor,
2055
+ ErrorStatusCode,
2056
+ ExtractorExecutionContext,
2057
+ FFMPEG_ARGS_PIPED,
2058
+ FFMPEG_ARGS_STRING,
2059
+ Player,
2060
+ PlayerError,
2061
+ Playlist,
2062
+ QueryResolver,
2063
+ QueryType,
2064
+ Queue,
2065
+ QueueRepeatMode,
2066
+ StreamDispatcher,
2067
+ Track,
2068
+ Util,
2069
+ VoiceUtils,
2070
+ VolumeTransformer,
2071
+ createFFmpegStream,
2072
+ version
2073
+ });
2074
+ //# sourceMappingURL=index.js.map