1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
|
import {VoiceChannel, Snowflake} from 'discord.js';
import {Readable} from 'stream';
import hasha from 'hasha';
import ytdl, {videoFormat} from '@distube/ytdl-core';
import {WriteStream} from 'fs-capacitor';
import ffmpeg from 'fluent-ffmpeg';
import shuffle from 'array-shuffle';
import {
AudioPlayer,
AudioPlayerState,
AudioPlayerStatus, AudioResource,
createAudioPlayer,
createAudioResource, DiscordGatewayAdapterCreator,
joinVoiceChannel,
StreamType,
VoiceConnection,
VoiceConnectionStatus,
} from '@discordjs/voice';
import FileCacheProvider from './file-cache.js';
import debug from '../utils/debug.js';
import {getGuildSettings} from '../utils/get-guild-settings.js';
import {buildPlayingMessageEmbed} from '../utils/build-embed.js';
import {Setting} from '@prisma/client';
export enum MediaSource {
Youtube,
HLS,
}
export interface QueuedPlaylist {
title: string;
source: string;
}
export interface SongMetadata {
title: string;
artist: string;
url: string; // For YT, it's the video ID (not the full URI)
length: number;
offset: number;
playlist: QueuedPlaylist | null;
isLive: boolean;
thumbnailUrl: string | null;
source: MediaSource;
}
export interface QueuedSong extends SongMetadata {
addedInChannelId: Snowflake;
requestedBy: string;
}
export enum STATUS {
PLAYING,
PAUSED,
IDLE,
}
export interface PlayerEvents {
statusChange: (oldStatus: STATUS, newStatus: STATUS) => void;
}
type YTDLVideoFormat = videoFormat & {loudnessDb?: number};
export const DEFAULT_VOLUME = 100;
export default class {
public voiceConnection: VoiceConnection | null = null;
public status = STATUS.PAUSED;
public guildId: string;
public loopCurrentSong = false;
public loopCurrentQueue = false;
private currentChannel: VoiceChannel | undefined;
private queue: QueuedSong[] = [];
private queuePosition = 0;
private audioPlayer: AudioPlayer | null = null;
private audioResource: AudioResource | null = null;
private volume?: number;
private defaultVolume: number = DEFAULT_VOLUME;
private nowPlaying: QueuedSong | null = null;
private playPositionInterval: NodeJS.Timeout | undefined;
private lastSongURL = '';
private positionInSeconds = 0;
private readonly fileCache: FileCacheProvider;
private disconnectTimer: NodeJS.Timeout | null = null;
private readonly channelToSpeakingUsers: Map<string, Set<string>> = new Map();
constructor(fileCache: FileCacheProvider, guildId: string) {
this.fileCache = fileCache;
this.guildId = guildId;
}
async connect(channel: VoiceChannel): Promise<void> {
// Always get freshest default volume setting value
const settings = await getGuildSettings(this.guildId);
const {defaultVolume = DEFAULT_VOLUME} = settings;
this.defaultVolume = defaultVolume;
this.voiceConnection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
selfDeaf: false,
adapterCreator: channel.guild.voiceAdapterCreator as DiscordGatewayAdapterCreator,
});
const guildSettings = await getGuildSettings(this.guildId);
// Workaround to disable keepAlive
this.voiceConnection.on('stateChange', (oldState, newState) => {
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */
const oldNetworking = Reflect.get(oldState, 'networking');
const newNetworking = Reflect.get(newState, 'networking');
const networkStateChangeHandler = (_: any, newNetworkState: any) => {
const newUdp = Reflect.get(newNetworkState, 'udp');
clearInterval(newUdp?.keepAliveInterval);
};
oldNetworking?.off('stateChange', networkStateChangeHandler);
newNetworking?.on('stateChange', networkStateChangeHandler);
/* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */
this.currentChannel = channel;
if (newState.status === VoiceConnectionStatus.Ready) {
this.registerVoiceActivityListener(guildSettings);
}
});
}
disconnect(): void {
if (this.voiceConnection) {
if (this.status === STATUS.PLAYING) {
this.pause();
}
this.loopCurrentSong = false;
this.voiceConnection.destroy();
this.audioPlayer?.stop(true);
this.voiceConnection = null;
this.audioPlayer = null;
this.audioResource = null;
}
}
async seek(positionSeconds: number): Promise<void> {
this.status = STATUS.PAUSED;
if (this.voiceConnection === null) {
throw new Error('Not connected to a voice channel.');
}
const currentSong = this.getCurrent();
if (!currentSong) {
throw new Error('No song currently playing');
}
if (positionSeconds > currentSong.length) {
throw new Error('Seek position is outside the range of the song.');
}
let realPositionSeconds = positionSeconds;
let to: number | undefined;
if (currentSong.offset !== undefined) {
realPositionSeconds += currentSong.offset;
to = currentSong.length + currentSong.offset;
}
const stream = await this.getStream(currentSong, {seek: realPositionSeconds, to});
this.audioPlayer = createAudioPlayer({
behaviors: {
// Needs to be somewhat high for livestreams
maxMissedFrames: 50,
},
});
this.voiceConnection.subscribe(this.audioPlayer);
this.playAudioPlayerResource(this.createAudioStream(stream));
this.attachListeners();
this.startTrackingPosition(positionSeconds);
this.status = STATUS.PLAYING;
}
async forwardSeek(positionSeconds: number): Promise<void> {
return this.seek(this.positionInSeconds + positionSeconds);
}
getPosition(): number {
return this.positionInSeconds;
}
async play(): Promise<void> {
if (this.voiceConnection === null) {
throw new Error('Not connected to a voice channel.');
}
const currentSong = this.getCurrent();
if (!currentSong) {
throw new Error('Queue empty.');
}
// Cancel any pending idle disconnection
if (this.disconnectTimer) {
clearInterval(this.disconnectTimer);
this.disconnectTimer = null;
}
// Resume from paused state
if (this.status === STATUS.PAUSED && currentSong.url === this.nowPlaying?.url) {
if (this.audioPlayer) {
this.audioPlayer.unpause();
this.status = STATUS.PLAYING;
this.startTrackingPosition();
return;
}
// Was disconnected, need to recreate stream
if (!currentSong.isLive) {
return this.seek(this.getPosition());
}
}
try {
let positionSeconds: number | undefined;
let to: number | undefined;
if (currentSong.offset !== undefined) {
positionSeconds = currentSong.offset;
to = currentSong.length + currentSong.offset;
}
const stream = await this.getStream(currentSong, {seek: positionSeconds, to});
this.audioPlayer = createAudioPlayer({
behaviors: {
// Needs to be somewhat high for livestreams
maxMissedFrames: 50,
},
});
this.voiceConnection.subscribe(this.audioPlayer);
this.playAudioPlayerResource(this.createAudioStream(stream));
this.attachListeners();
this.status = STATUS.PLAYING;
this.nowPlaying = currentSong;
if (currentSong.url === this.lastSongURL) {
this.startTrackingPosition();
} else {
// Reset position counter
this.startTrackingPosition(0);
this.lastSongURL = currentSong.url;
}
} catch (error: unknown) {
await this.forward(1);
if ((error as {statusCode: number}).statusCode === 410 && currentSong) {
const channelId = currentSong.addedInChannelId;
if (channelId) {
debug(`${currentSong.title} is unavailable`);
return;
}
}
throw error;
}
}
pause(): void {
if (this.status !== STATUS.PLAYING) {
throw new Error('Not currently playing.');
}
this.status = STATUS.PAUSED;
if (this.audioPlayer) {
this.audioPlayer.pause();
}
this.stopTrackingPosition();
}
async forward(skip: number): Promise<void> {
this.manualForward(skip);
try {
if (this.getCurrent() && this.status !== STATUS.PAUSED) {
await this.play();
} else {
this.status = STATUS.IDLE;
this.audioPlayer?.stop(true);
const settings = await getGuildSettings(this.guildId);
const {secondsToWaitAfterQueueEmpties} = settings;
if (secondsToWaitAfterQueueEmpties !== 0) {
this.disconnectTimer = setTimeout(() => {
// Make sure we are not accidentally playing
// when disconnecting
if (this.status === STATUS.IDLE) {
this.disconnect();
}
}, secondsToWaitAfterQueueEmpties * 1000);
}
}
} catch (error: unknown) {
this.queuePosition--;
throw error;
}
}
registerVoiceActivityListener(guildSettings: Setting) {
const {turnDownVolumeWhenPeopleSpeak, turnDownVolumeWhenPeopleSpeakTarget} = guildSettings;
if (!turnDownVolumeWhenPeopleSpeak || !this.voiceConnection) {
return;
}
this.voiceConnection.receiver.speaking.on('start', (userId: string) => {
if (!this.currentChannel) {
return;
}
const member = this.currentChannel.members.get(userId);
const channelId = this.currentChannel?.id;
if (member) {
if (!this.channelToSpeakingUsers.has(channelId)) {
this.channelToSpeakingUsers.set(channelId, new Set());
}
this.channelToSpeakingUsers.get(channelId)?.add(member.id);
}
this.suppressVoiceWhenPeopleAreSpeaking(turnDownVolumeWhenPeopleSpeakTarget);
});
this.voiceConnection.receiver.speaking.on('end', (userId: string) => {
if (!this.currentChannel) {
return;
}
const member = this.currentChannel.members.get(userId);
const channelId = this.currentChannel.id;
if (member) {
if (!this.channelToSpeakingUsers.has(channelId)) {
this.channelToSpeakingUsers.set(channelId, new Set());
}
this.channelToSpeakingUsers.get(channelId)?.delete(member.id);
}
this.suppressVoiceWhenPeopleAreSpeaking(turnDownVolumeWhenPeopleSpeakTarget);
});
}
suppressVoiceWhenPeopleAreSpeaking(turnDownVolumeWhenPeopleSpeakTarget: number): void {
if (!this.currentChannel) {
return;
}
const speakingUsers = this.channelToSpeakingUsers.get(this.currentChannel.id);
if (speakingUsers && speakingUsers.size > 0) {
this.setVolume(turnDownVolumeWhenPeopleSpeakTarget);
} else {
this.setVolume(this.defaultVolume);
}
}
canGoForward(skip: number) {
return (this.queuePosition + skip - 1) < this.queue.length;
}
manualForward(skip: number): void {
if (this.canGoForward(skip)) {
this.queuePosition += skip;
this.positionInSeconds = 0;
this.stopTrackingPosition();
} else {
throw new Error('No songs in queue to forward to.');
}
}
canGoBack() {
return this.queuePosition - 1 >= 0;
}
async back(): Promise<void> {
if (this.canGoBack()) {
this.queuePosition--;
this.positionInSeconds = 0;
this.stopTrackingPosition();
if (this.status !== STATUS.PAUSED) {
await this.play();
}
} else {
throw new Error('No songs in queue to go back to.');
}
}
getCurrent(): QueuedSong | null {
if (this.queue[this.queuePosition]) {
return this.queue[this.queuePosition];
}
return null;
}
/**
* Returns queue, not including the current song.
* @returns {QueuedSong[]}
*/
getQueue(): QueuedSong[] {
return this.queue.slice(this.queuePosition + 1);
}
add(song: QueuedSong, {immediate = false} = {}): void {
if (song.playlist || !immediate) {
// Add to end of queue
this.queue.push(song);
} else {
// Add as the next song to be played
const insertAt = this.queuePosition + 1;
this.queue = [...this.queue.slice(0, insertAt), song, ...this.queue.slice(insertAt)];
}
}
shuffle(): void {
const shuffledSongs = shuffle(this.queue.slice(this.queuePosition + 1));
this.queue = [...this.queue.slice(0, this.queuePosition + 1), ...shuffledSongs];
}
clear(): void {
const newQueue = [];
// Don't clear curently playing song
const current = this.getCurrent();
if (current) {
newQueue.push(current);
}
this.queuePosition = 0;
this.queue = newQueue;
}
removeFromQueue(index: number, amount = 1): void {
this.queue.splice(this.queuePosition + index, amount);
}
removeCurrent(): void {
this.queue = [...this.queue.slice(0, this.queuePosition), ...this.queue.slice(this.queuePosition + 1)];
}
queueSize(): number {
return this.getQueue().length;
}
isQueueEmpty(): boolean {
return this.queueSize() === 0;
}
stop(): void {
this.disconnect();
this.queuePosition = 0;
this.queue = [];
}
move(from: number, to: number): QueuedSong {
if (from > this.queueSize() || to > this.queueSize()) {
throw new Error('Move index is outside the range of the queue.');
}
this.queue.splice(this.queuePosition + to, 0, this.queue.splice(this.queuePosition + from, 1)[0]);
return this.queue[this.queuePosition + to];
}
setVolume(level: number): void {
// Level should be a number between 0 and 100 = 0% => 100%
this.volume = level;
this.setAudioPlayerVolume(level);
}
getVolume(): number {
// Only use default volume if player volume is not already set (in the event of a reconnect we shouldn't reset)
return this.volume ?? this.defaultVolume;
}
private getHashForCache(url: string): string {
return hasha(url);
}
private async getStream(song: QueuedSong, options: {seek?: number; to?: number} = {}): Promise<Readable> {
if (this.status === STATUS.PLAYING) {
this.audioPlayer?.stop();
} else if (this.status === STATUS.PAUSED) {
this.audioPlayer?.stop(true);
}
if (song.source === MediaSource.HLS) {
return this.createReadStream({url: song.url, cacheKey: song.url});
}
let ffmpegInput: string | null;
const ffmpegInputOptions: string[] = [];
let shouldCacheVideo = false;
let format: YTDLVideoFormat | undefined;
ffmpegInput = await this.fileCache.getPathFor(this.getHashForCache(song.url));
if (!ffmpegInput) {
// Not yet cached, must download
const info = await ytdl.getInfo(song.url);
const formats = info.formats as YTDLVideoFormat[];
const filter = (format: ytdl.videoFormat): boolean => format.codecs === 'opus' && format.container === 'webm' && format.audioSampleRate !== undefined && parseInt(format.audioSampleRate, 10) === 48000;
format = formats.find(filter);
const nextBestFormat = (formats: ytdl.videoFormat[]): ytdl.videoFormat | undefined => {
if (formats[0].isLive) {
formats = formats.sort((a, b) => (b as unknown as {audioBitrate: number}).audioBitrate - (a as unknown as {audioBitrate: number}).audioBitrate); // Bad typings
return formats.find(format => [128, 127, 120, 96, 95, 94, 93].includes(parseInt(format.itag as unknown as string, 10))); // Bad typings
}
formats = formats
.filter(format => format.averageBitrate)
.sort((a, b) => {
if (a && b) {
return b.averageBitrate! - a.averageBitrate!;
}
return 0;
});
return formats.find(format => !format.bitrate) ?? formats[0];
};
if (!format) {
format = nextBestFormat(info.formats);
if (!format) {
// If still no format is found, throw
throw new Error('Can\'t find suitable format.');
}
}
debug('Using format', format);
ffmpegInput = format.url;
// Don't cache livestreams or long videos
const MAX_CACHE_LENGTH_SECONDS = 30 * 60; // 30 minutes
shouldCacheVideo = !info.player_response.videoDetails.isLiveContent && parseInt(info.videoDetails.lengthSeconds, 10) < MAX_CACHE_LENGTH_SECONDS && !options.seek;
debug(shouldCacheVideo ? 'Caching video' : 'Not caching video');
ffmpegInputOptions.push(...[
'-reconnect',
'1',
'-reconnect_streamed',
'1',
'-reconnect_delay_max',
'5',
]);
}
if (options.seek) {
ffmpegInputOptions.push('-ss', options.seek.toString());
}
if (options.to) {
ffmpegInputOptions.push('-to', options.to.toString());
}
return this.createReadStream({
url: ffmpegInput,
cacheKey: song.url,
ffmpegInputOptions,
cache: shouldCacheVideo,
volumeAdjustment: format?.loudnessDb ? `${-format.loudnessDb}dB` : undefined,
});
}
private startTrackingPosition(initalPosition?: number): void {
if (initalPosition !== undefined) {
this.positionInSeconds = initalPosition;
}
if (this.playPositionInterval) {
clearInterval(this.playPositionInterval);
}
this.playPositionInterval = setInterval(() => {
this.positionInSeconds++;
}, 1000);
}
private stopTrackingPosition(): void {
if (this.playPositionInterval) {
clearInterval(this.playPositionInterval);
}
}
private attachListeners(): void {
if (!this.voiceConnection) {
return;
}
if (this.voiceConnection.listeners(VoiceConnectionStatus.Disconnected).length === 0) {
this.voiceConnection.on(VoiceConnectionStatus.Disconnected, this.onVoiceConnectionDisconnect.bind(this));
}
if (!this.audioPlayer) {
return;
}
if (this.audioPlayer.listeners('stateChange').length === 0) {
this.audioPlayer.on(AudioPlayerStatus.Idle, this.onAudioPlayerIdle.bind(this));
}
}
private onVoiceConnectionDisconnect(): void {
this.disconnect();
}
private async onAudioPlayerIdle(_oldState: AudioPlayerState, newState: AudioPlayerState): Promise<void> {
// Automatically advance queued song at end
if (this.loopCurrentSong && newState.status === AudioPlayerStatus.Idle && this.status === STATUS.PLAYING) {
await this.seek(0);
return;
}
// Automatically re-add current song to queue
if (this.loopCurrentQueue && newState.status === AudioPlayerStatus.Idle && this.status === STATUS.PLAYING) {
const currentSong = this.getCurrent();
if (currentSong) {
this.add(currentSong);
} else {
throw new Error('No song currently playing.');
}
}
if (newState.status === AudioPlayerStatus.Idle && this.status === STATUS.PLAYING) {
await this.forward(1);
// Auto announce the next song if configured to
const settings = await getGuildSettings(this.guildId);
const {autoAnnounceNextSong} = settings;
if (autoAnnounceNextSong && this.currentChannel) {
await this.currentChannel.send({
embeds: this.getCurrent() ? [buildPlayingMessageEmbed(this)] : [],
});
}
}
}
private async createReadStream(options: {url: string; cacheKey: string; ffmpegInputOptions?: string[]; cache?: boolean; volumeAdjustment?: string}): Promise<Readable> {
return new Promise((resolve, reject) => {
const capacitor = new WriteStream();
if (options?.cache) {
const cacheStream = this.fileCache.createWriteStream(this.getHashForCache(options.cacheKey));
capacitor.createReadStream().pipe(cacheStream);
}
const returnedStream = capacitor.createReadStream();
let hasReturnedStreamClosed = false;
const stream = ffmpeg(options.url)
.inputOptions(options?.ffmpegInputOptions ?? ['-re'])
.noVideo()
.audioCodec('libopus')
.outputFormat('webm')
.addOutputOption(['-filter:a', `volume=${options?.volumeAdjustment ?? '1'}`])
.on('error', error => {
if (!hasReturnedStreamClosed) {
reject(error);
}
})
.on('start', command => {
debug(`Spawned ffmpeg with ${command as string}`);
});
stream.pipe(capacitor);
returnedStream.on('close', () => {
if (!options.cache) {
stream.kill('SIGKILL');
}
hasReturnedStreamClosed = true;
});
resolve(returnedStream);
});
}
private createAudioStream(stream: Readable) {
return createAudioResource(stream, {
inputType: StreamType.WebmOpus,
inlineVolume: true,
});
}
private playAudioPlayerResource(resource: AudioResource) {
if (this.audioPlayer !== null) {
this.audioResource = resource;
this.setAudioPlayerVolume();
this.audioPlayer.play(this.audioResource);
}
}
private setAudioPlayerVolume(level?: number) {
// Audio resource expects a float between 0 and 1 to represent level percentage
this.audioResource?.volume?.setVolume((level ?? this.getVolume()) / 100);
}
}
|