palico-bot/src/music/queue.js
Shinuwa 98f4d29ac7 Encode jukebox audio with native ffmpeg, normalise loudness, read metadata
- Play every track through an ffmpeg process that normalises loudness
  (EBU R128) and outputs Ogg Opus, handed to Discord as is: no more Opus
  encoding in JavaScript with opusscript. Measured at over 40x real time,
  about 2% of a core while playing. Closing the stream kills ffmpeg.
- Encoding at upload instead was ruled out: over two minutes for an 85-minute
  mix, during which the upload would hang.
- Read duration, title and artist with ffprobe at upload; default the title
  to "Artist - Title" or the file name without extension.
- Fill the duration of existing library entries at startup.
- Expose the position of the current track in queue snapshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:10:49 +01:00

530 lines
14 KiB
JavaScript

import { EventEmitter } from "events";
import {
AudioPlayerStatus,
NoSubscriberBehavior,
StreamType,
VoiceConnectionStatus,
createAudioPlayer,
createAudioResource,
entersState,
joinVoiceChannel,
} from "@discordjs/voice";
import { Events } from "discord.js";
import { config } from "../config.js";
import { createOpusStream } from "../media/validateAudioFile.js";
import { serializeTrack, serializeTracks } from "../web/serializers.js";
import {
deleteTrackFile,
handleTrackCompletion,
} from "../web/storage/storageManager.js";
const AUTO_DISCONNECT_DELAY = 5 * 60 * 1000;
// Délais entre les nouvelles tentatives quand le salon vocal est injoignable. Au-delà, la
// file attend une action (ajout d'un morceau, bouton Play).
const CONNECT_RETRY_DELAYS = [5_000, 15_000, 30_000, 60_000, 60_000];
class MusicQueue extends EventEmitter {
constructor(client, { retryDelays = CONNECT_RETRY_DELAYS } = {}) {
super();
this.client = client;
this.queue = [];
this.currentTrack = null;
this.connection = null;
this.playbackStatus = AudioPlayerStatus.Idle;
this.idleDisconnectTimeout = null;
this.aloneDisconnectTimeout = null;
this.connectRetryTimeout = null;
this.connectFailures = 0;
this.retryDelays = retryDelays;
this.suspendedForAlone = false;
this.playNextPromise = null;
this.shuttingDown = false;
this.audioPlayer = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Play,
},
});
this.voiceStateListener = (oldState, newState) => {
if (
oldState.channelId === config.voiceChannelId ||
newState.channelId === config.voiceChannelId
) {
this.evaluateAloneStatus();
}
};
this.client.on(Events.VoiceStateUpdate, this.voiceStateListener);
this.audioPlayer.on(AudioPlayerStatus.Idle, () => {
if (this.currentTrack) {
handleTrackCompletion(this.currentTrack);
}
this.currentTrack = null;
if (!this.shuttingDown) {
void this.playNext();
}
});
// Après une erreur, le player passe toujours en Idle : le gestionnaire ci-dessus
// termine le morceau et lance le suivant.
this.audioPlayer.on("error", (error) => {
console.error("Audio player encountered an error", error);
});
this.audioPlayer.on("stateChange", (oldState, newState) => {
this.playbackStatus = newState.status;
this.emit("queueUpdate", this.snapshot());
});
}
snapshot() {
return {
current: serializeTrack(this.currentTrack),
upcoming: serializeTracks(this.queue),
status: this.playbackStatus,
// Millisecondes déjà jouées du morceau en cours (pauses exclues).
position: this.audioPlayer?.state?.resource?.playbackDuration ?? 0,
};
}
// Fichiers encore utiles (file d'attente et morceau en cours), à ne pas nettoyer.
inUsePaths() {
return new Set(
[this.currentTrack, ...this.queue]
.map((track) => track?.path)
.filter(Boolean)
);
}
async ensureConnection() {
if (this.connection) {
if (
this.connection.joinConfig.channelId === config.voiceChannelId &&
this.connection.state.status === VoiceConnectionStatus.Ready
) {
return this.connection;
}
try {
this.connection.destroy();
} catch {
// The connection may already be destroyed.
}
this.connection = null;
}
let channel = this.client.channels.cache.get(config.voiceChannelId);
if (!channel) {
try {
channel = await this.client.channels.fetch(config.voiceChannelId);
} catch (error) {
console.error("Unable to fetch voice channel", error);
throw error;
}
}
if (!channel) {
throw new Error("Voice channel configured for music playback was not found");
}
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: false,
});
this.connection = connection;
connection.subscribe(this.audioPlayer);
connection.on(VoiceConnectionStatus.Disconnected, async () => {
try {
await Promise.race([
entersState(connection, VoiceConnectionStatus.Signalling, 5_000),
entersState(connection, VoiceConnectionStatus.Connecting, 5_000),
]);
} catch {
if (this.connection === connection) {
this.destroyConnection("voice connection lost", { requeue: true });
}
}
});
try {
await entersState(connection, VoiceConnectionStatus.Ready, 30_000);
} catch (error) {
if (this.connection === connection) {
try {
connection.destroy();
} catch {
// The connection may have been destroyed by the voice adapter.
}
this.connection = null;
}
throw error;
}
this.evaluateAloneStatus();
return connection;
}
enqueue(track) {
this.queue.push(track);
// Ajouter un morceau est une demande de lecture explicite : elle lève la suspension
// (bot parti faute d'auditeurs) et relance les tentatives de connexion.
this.suspendedForAlone = false;
this.connectFailures = 0;
this.cancelIdleDisconnect();
this.emit("queueUpdate", this.snapshot());
if (!this.currentTrack) {
void this.playNext();
}
return track;
}
playNext() {
if (this.playNextPromise) {
return this.playNextPromise;
}
this.playNextPromise = this.runPlayNext().finally(() => {
this.playNextPromise = null;
});
return this.playNextPromise;
}
async runPlayNext() {
this.cancelConnectRetry();
if (this.shuttingDown || this.suspendedForAlone) {
return;
}
if (this.queue.length === 0) {
this.scheduleIdleDisconnect();
this.emit("queueUpdate", this.snapshot());
return;
}
this.cancelIdleDisconnect();
const nextTrack = this.queue[0];
try {
await this.ensureConnection();
this.connectFailures = 0;
} catch (error) {
console.error("Unable to connect to the configured voice channel", error);
this.currentTrack = null;
this.scheduleConnectRetry();
return;
}
if (this.shuttingDown || this.suspendedForAlone) {
return;
}
// La file a pu changer pendant la connexion (morceau retiré ou déplacé) : on repart
// de la nouvelle tête de file au lieu d'abandonner.
if (this.queue[0]?.id !== nextTrack.id) {
return this.runPlayNext();
}
try {
this.queue.shift();
const resource = this.createResource(nextTrack);
this.currentTrack = {
...nextTrack,
startedAt: new Date().toISOString(),
};
this.audioPlayer.play(resource);
this.emit("trackStart", this.currentTrack);
this.emit("queueUpdate", this.snapshot());
} catch (error) {
console.error("Unable to play track", error);
deleteTrackFile(nextTrack);
this.currentTrack = null;
return this.runPlayNext();
}
}
createResource(track) {
return createAudioResource(createOpusStream(track.path), {
inputType: StreamType.OggOpus,
});
}
scheduleConnectRetry() {
if (this.shuttingDown || this.queue.length === 0 || this.connectRetryTimeout) {
return;
}
if (this.connectFailures >= this.retryDelays.length) {
console.error(
`[${new Date().toLocaleString()}] MusicQueue gave up connecting after ${this.connectFailures} retries; the next enqueue or Play will try again`
);
return;
}
const delay = this.retryDelays[this.connectFailures];
this.connectFailures += 1;
this.connectRetryTimeout = setTimeout(() => {
this.connectRetryTimeout = null;
void this.playNext();
}, delay);
}
cancelConnectRetry() {
if (this.connectRetryTimeout) {
clearTimeout(this.connectRetryTimeout);
this.connectRetryTimeout = null;
}
}
async remove(trackId) {
const index = this.queue.findIndex((track) => track.id === trackId);
if (index === -1) {
if (this.currentTrack && this.currentTrack.id === trackId) {
// skip() repasse le player en Idle tout de suite, ce qui efface currentTrack.
const removed = this.currentTrack;
this.skip();
return removed;
}
return null;
}
const [removed] = this.queue.splice(index, 1);
deleteTrackFile(removed);
this.emit("queueUpdate", this.snapshot());
if (this.queue.length === 0 && !this.currentTrack) {
this.scheduleIdleDisconnect();
}
return removed;
}
move(trackId, newPosition) {
const index = this.queue.findIndex((track) => track.id === trackId);
if (index === -1) {
return null;
}
const [track] = this.queue.splice(index, 1);
const boundedPosition = Math.max(0, Math.min(newPosition, this.queue.length));
this.queue.splice(boundedPosition, 0, track);
this.emit("queueUpdate", this.snapshot());
return this.snapshot();
}
skip() {
return this.audioPlayer.stop(true);
}
stop() {
this.cancelConnectRetry();
this.queue.forEach((track) => deleteTrackFile(track));
this.queue = [];
this.audioPlayer.stop(true);
this.emit("queueUpdate", this.snapshot());
}
pause() {
this.audioPlayer.pause(true);
}
resume() {
this.audioPlayer.unpause();
}
start() {
this.suspendedForAlone = false;
this.connectFailures = 0;
this.cancelIdleDisconnect();
if (!this.currentTrack) {
return this.playNext();
}
return this.currentTrack;
}
removeByLibraryId(libraryTrackId) {
if (!libraryTrackId) {
return [];
}
const removed = this.queue.filter(
(track) => track.libraryTrackId === libraryTrackId
);
this.queue = this.queue.filter(
(track) => track.libraryTrackId !== libraryTrackId
);
removed.forEach((track) => deleteTrackFile(track));
if (
this.currentTrack &&
this.currentTrack.libraryTrackId === libraryTrackId
) {
this.skip();
}
if (removed.length > 0) {
this.emit("queueUpdate", this.snapshot());
}
return removed;
}
// requeue : remet le morceau interrompu en tête de file (il reprendra du début) au lieu
// de le perdre, quand la coupure ne vient pas d'une demande d'arrêt.
destroyConnection(reason, { suspend = false, requeue = false } = {}) {
if (!this.connection && this.playbackStatus === AudioPlayerStatus.Idle) {
return;
}
if (suspend) {
this.suspendedForAlone = true;
}
this.cancelIdleDisconnect();
this.cancelAloneDisconnect();
const interruptedTrack = this.currentTrack;
this.currentTrack = null;
const requeued = Boolean(requeue && interruptedTrack);
if (requeued) {
const { startedAt: _startedAt, ...track } = interruptedTrack;
this.queue.unshift(track);
}
if (this.connection) {
try {
this.connection.destroy();
} catch (error) {
console.error("Failed to destroy voice connection", error);
}
this.connection = null;
}
try {
this.audioPlayer.stop(true);
} catch (error) {
console.error("Failed to stop audio player", error);
}
if (!requeued) {
handleTrackCompletion(interruptedTrack);
}
this.emit("queueUpdate", this.snapshot());
console.log(
`[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})`
);
}
scheduleIdleDisconnect() {
if (
this.idleDisconnectTimeout ||
this.queue.length > 0 ||
this.currentTrack ||
!this.connection
) {
return;
}
this.idleDisconnectTimeout = setTimeout(() => {
this.idleDisconnectTimeout = null;
if (!this.currentTrack && this.queue.length === 0 && this.connection) {
this.destroyConnection("idle timeout");
}
}, AUTO_DISCONNECT_DELAY);
}
cancelIdleDisconnect() {
if (this.idleDisconnectTimeout) {
clearTimeout(this.idleDisconnectTimeout);
this.idleDisconnectTimeout = null;
}
}
scheduleAloneDisconnect() {
if (this.aloneDisconnectTimeout || !this.connection) {
return;
}
this.aloneDisconnectTimeout = setTimeout(() => {
this.aloneDisconnectTimeout = null;
if (this.connection && this.isBotAlone()) {
this.destroyConnection("alone timeout", { suspend: true, requeue: true });
}
}, AUTO_DISCONNECT_DELAY);
}
cancelAloneDisconnect() {
if (this.aloneDisconnectTimeout) {
clearTimeout(this.aloneDisconnectTimeout);
this.aloneDisconnectTimeout = null;
}
}
evaluateAloneStatus() {
if (!this.connection) {
this.cancelAloneDisconnect();
// Parti faute d'auditeurs : revenir dès que quelqu'un rejoint le salon.
if (this.suspendedForAlone && this.queue.length > 0 && this.hasListeners()) {
this.suspendedForAlone = false;
void this.playNext();
}
return;
}
if (this.isBotAlone()) {
this.scheduleAloneDisconnect();
} else {
const wasSuspended = this.suspendedForAlone;
this.suspendedForAlone = false;
this.cancelAloneDisconnect();
if (wasSuspended && !this.currentTrack && this.queue.length > 0) {
void this.playNext();
}
}
}
// Membres humains du salon configuré, sans le bot lui-même ni les autres bots.
listeners() {
const channel = this.client.channels.cache.get(config.voiceChannelId);
const clientId = this.client.user?.id;
if (!channel || !clientId) {
return null;
}
return [...channel.members.values()].filter(
(member) => member.id !== clientId && !member.user?.bot
);
}
hasListeners() {
return (this.listeners()?.length ?? 0) > 0;
}
isBotAlone() {
const channel = this.client.channels.cache.get(config.voiceChannelId);
const clientId = this.client.user?.id;
if (!channel || !clientId || !channel.members.has(clientId)) {
return false;
}
return this.listeners().length === 0;
}
shutdown() {
this.shuttingDown = true;
this.cancelIdleDisconnect();
this.cancelAloneDisconnect();
this.cancelConnectRetry();
this.client.off(Events.VoiceStateUpdate, this.voiceStateListener);
this.queue.forEach((track) => deleteTrackFile(track));
this.queue = [];
this.destroyConnection("shutdown");
}
}
export { MusicQueue };