Resume interrupted tracks where they stopped
A track cut off without anyone asking (voice connection lost, bot leaving an empty channel, restart) used to start over from the beginning; on an hour-long mix, a drop near the end replayed it all. - The requeued track keeps resumeAt and ffmpeg seeks to it (-ss before -i, so it jumps there without decoding the start). It resumes 2 s before the cut; a track cut in its first 2 s starts over. - The player keeps playing without a connection (NoSubscriberBehavior.Play), so the position of a voice drop is taken when the connection drops, not 5 s later when it is given up. - The saved queue holds the current position, and it is saved every 30 s while playing: after a crash the track resumes at most 30 s earlier. - Loop mode replays a resumed track from the beginning; skip and stop are unchanged. - The web page and /queue show "Reprise à 49:15" for such a track, and the progress bar counts from the resume point. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
11ee972636
commit
793765fb79
8 changed files with 141 additions and 24 deletions
|
|
@ -1,5 +1,6 @@
|
|||
/**
|
||||
* @file Formate un morceau pour les messages Discord : titre et durée lisible.
|
||||
* @file Formate un morceau pour les messages Discord : titre, durée lisible et, pour un morceau
|
||||
* interrompu, sa position de reprise.
|
||||
*
|
||||
* Utilisé par : les commandes /play, /queue et /skip.
|
||||
* Attention : la page web a son propre formatDuration (public/scripts/common.js).
|
||||
|
|
@ -17,8 +18,12 @@ function formatDuration(seconds) {
|
|||
|
||||
function trackLabel(track) {
|
||||
const title = track.title || track.originalName || "Sans titre";
|
||||
const duration = formatDuration(track.duration);
|
||||
return duration ? `${title} (${duration})` : title;
|
||||
const details = [formatDuration(track.duration)];
|
||||
if (track.resumeAt > 0) {
|
||||
details.push(`reprise à ${formatDuration(track.resumeAt)}`);
|
||||
}
|
||||
const text = details.filter(Boolean).join(", ");
|
||||
return text ? `${title} (${text})` : title;
|
||||
}
|
||||
|
||||
export { formatDuration, trackLabel };
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
/**
|
||||
* @file Vérifie avec ffprobe qu'un fichier est de l'audio (durée, titre, artiste), et le convertit
|
||||
* avec ffmpeg en Ogg Opus au volume normalisé, prêt pour Discord.
|
||||
* avec ffmpeg en Ogg Opus au volume normalisé, prêt pour Discord (depuis le début ou depuis une
|
||||
* position donnée).
|
||||
*
|
||||
* Utilisé par : music/ingest.js et storage/libraryMetadata.js (probeAudioFile), music/queue.js
|
||||
* (createOpusStream).
|
||||
|
|
@ -81,13 +82,16 @@ function invalidAudioError(cause) {
|
|||
|
||||
// Décode le fichier, normalise le volume et encode en Ogg Opus avec le ffmpeg natif : Discord
|
||||
// reçoit l'Opus tel quel, sans réencodage en JavaScript. Fermer le flux arrête ffmpeg.
|
||||
function createOpusStream(filePath, { spawnProcess = spawn } = {}) {
|
||||
// startAt : position de départ en secondes, pour reprendre un morceau interrompu.
|
||||
function createOpusStream(filePath, { spawnProcess = spawn, startAt = 0 } = {}) {
|
||||
const ffmpeg = spawnProcess(
|
||||
"ffmpeg",
|
||||
[
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
// Placé avant -i : ffmpeg saute directement à la position au lieu de tout décoder.
|
||||
...(startAt > 0 ? ["-ss", String(startAt)] : []),
|
||||
"-i",
|
||||
filePath,
|
||||
"-map",
|
||||
|
|
|
|||
|
|
@ -13,6 +13,10 @@
|
|||
* - Sans morceau ou sans auditeur pendant 5 min, le bot quitte le salon. Parti faute d'auditeurs,
|
||||
* il revient dès que quelqu'un le rejoint.
|
||||
* - Un morceau temporaire est supprimé une fois joué, retiré ou en erreur, sauf en mode boucle.
|
||||
* - Un morceau interrompu sans qu'on l'ait demandé (connexion vocale perdue, bot seul dans le
|
||||
* salon, redémarrage) revient en tête de file avec `resumeAt` : il reprend 2 s avant l'endroit
|
||||
* où il s'était arrêté. Le lecteur joue même sans connexion (NoSubscriberBehavior.Play) : la
|
||||
* position d'une coupure est donc relevée dès la déconnexion, pas quand on abandonne.
|
||||
* - Toute modification de la file émet « queueUpdate » : c'est aussi ce qui l'enregistre.
|
||||
* @see README.md#jukebox
|
||||
*/
|
||||
|
|
@ -44,6 +48,12 @@ const AUTO_DISCONNECT_DELAY = 5 * 60 * 1000;
|
|||
// file attend une action (ajout d'un morceau, bouton Play).
|
||||
const CONNECT_RETRY_DELAYS = [5_000, 15_000, 30_000, 60_000, 60_000];
|
||||
|
||||
// Secondes rejouées à la reprise d'un morceau interrompu, pour retrouver le fil.
|
||||
const RESUME_REWIND = 2;
|
||||
// Pendant la lecture, la position est enregistrée à cet intervalle : après un arrêt brutal du
|
||||
// bot (sans arrêt propre), le morceau reprend à peu près où il en était.
|
||||
const POSITION_SAVE_INTERVAL = 30_000;
|
||||
|
||||
class MusicQueue extends EventEmitter {
|
||||
// persistence : { load() → état | null, save(état) } pour garder la file d'un démarrage à
|
||||
// l'autre (voir queuePersistence.js). Sans elle, la file est perdue à l'arrêt.
|
||||
|
|
@ -92,8 +102,8 @@ class MusicQueue extends EventEmitter {
|
|||
this.currentTrack = null;
|
||||
if (finished) {
|
||||
if (this.loop && !this.discardCurrent && !this.shuttingDown) {
|
||||
// Mode boucle : le morceau repart en fin de file, fichier conservé.
|
||||
const { startedAt: _startedAt, ...track } = finished;
|
||||
// Mode boucle : le morceau repart en fin de file, du début, fichier conservé.
|
||||
const { startedAt: _startedAt, resumeAt: _resumeAt, ...track } = finished;
|
||||
this.queue.push({ ...track, id: randomUUID() });
|
||||
} else {
|
||||
handleTrackCompletion(finished);
|
||||
|
|
@ -114,6 +124,12 @@ class MusicQueue extends EventEmitter {
|
|||
|
||||
this.on("queueUpdate", () => this.scheduleSave());
|
||||
this.restore();
|
||||
if (this.persistence) {
|
||||
this.positionSaveInterval = setInterval(() => {
|
||||
if (this.playbackStatus === AudioPlayerStatus.Playing) this.scheduleSave();
|
||||
}, POSITION_SAVE_INTERVAL);
|
||||
this.positionSaveInterval.unref?.();
|
||||
}
|
||||
|
||||
this.audioPlayer.on("stateChange", (oldState, newState) => {
|
||||
this.playbackStatus = newState.status;
|
||||
|
|
@ -127,11 +143,27 @@ class MusicQueue extends EventEmitter {
|
|||
upcoming: serializeTracks(this.queue),
|
||||
status: this.playbackStatus,
|
||||
loop: this.loop,
|
||||
// Millisecondes déjà jouées du morceau en cours (pauses exclues).
|
||||
position: this.audioPlayer?.state?.resource?.playbackDuration ?? 0,
|
||||
// Position dans le morceau en cours, en millisecondes (pauses exclues).
|
||||
position: this.currentPosition(),
|
||||
};
|
||||
}
|
||||
|
||||
// Position dans le fichier du morceau en cours (ms), reprise comprise : playbackDuration ne
|
||||
// compte que ce qui a été joué depuis le départ du flux.
|
||||
currentPosition() {
|
||||
if (!this.currentTrack) return 0;
|
||||
const played = this.audioPlayer?.state?.resource?.playbackDuration ?? 0;
|
||||
return (this.currentTrack.resumeAt ?? 0) * 1000 + played;
|
||||
}
|
||||
|
||||
// Copie d'un morceau interrompu à `position` (ms), à remettre en file pour qu'il reprenne un
|
||||
// peu avant cet endroit.
|
||||
resumableTrack(track, position) {
|
||||
const { startedAt: _startedAt, resumeAt: _resumeAt, ...rest } = track;
|
||||
const resumeAt = Math.floor(position / 1000) - RESUME_REWIND;
|
||||
return resumeAt > 0 ? { ...rest, resumeAt } : rest;
|
||||
}
|
||||
|
||||
// Fichiers encore utiles (file d'attente et morceau en cours), à ne pas nettoyer.
|
||||
inUsePaths() {
|
||||
return new Set(
|
||||
|
|
@ -183,6 +215,8 @@ class MusicQueue extends EventEmitter {
|
|||
this.connection = connection;
|
||||
connection.subscribe(this.audioPlayer);
|
||||
connection.on(VoiceConnectionStatus.Disconnected, async () => {
|
||||
// Le lecteur continue sans connexion : la reprise se fera depuis l'instant de la coupure.
|
||||
const position = this.currentPosition();
|
||||
try {
|
||||
await Promise.race([
|
||||
entersState(connection, VoiceConnectionStatus.Signalling, 5_000),
|
||||
|
|
@ -190,7 +224,7 @@ class MusicQueue extends EventEmitter {
|
|||
]);
|
||||
} catch {
|
||||
if (this.connection === connection) {
|
||||
this.destroyConnection("voice connection lost", { requeue: true });
|
||||
this.destroyConnection("voice connection lost", { requeue: true, position });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
@ -294,7 +328,7 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
|
||||
createResource(track) {
|
||||
return createAudioResource(createOpusStream(track.path), {
|
||||
return createAudioResource(createOpusStream(track.path, { startAt: track.resumeAt }), {
|
||||
inputType: StreamType.OggOpus,
|
||||
});
|
||||
}
|
||||
|
|
@ -445,9 +479,10 @@ class MusicQueue extends EventEmitter {
|
|||
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 } = {}) {
|
||||
// requeue : remet le morceau interrompu en tête de file, pour qu'il reprenne où il en était
|
||||
// (à `position` ms si elle est donnée, sinon à la position actuelle), au lieu de le perdre,
|
||||
// quand la coupure ne vient pas d'une demande d'arrêt.
|
||||
destroyConnection(reason, { suspend = false, requeue = false, position } = {}) {
|
||||
if (!this.connection && this.playbackStatus === AudioPlayerStatus.Idle) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -460,11 +495,11 @@ class MusicQueue extends EventEmitter {
|
|||
this.cancelAloneDisconnect();
|
||||
|
||||
const interruptedTrack = this.currentTrack;
|
||||
const interruptedAt = position ?? this.currentPosition();
|
||||
this.currentTrack = null;
|
||||
const requeued = Boolean(requeue && interruptedTrack);
|
||||
if (requeued) {
|
||||
const { startedAt: _startedAt, ...track } = interruptedTrack;
|
||||
this.queue.unshift(track);
|
||||
this.queue.unshift(this.resumableTrack(interruptedTrack, interruptedAt));
|
||||
}
|
||||
|
||||
if (this.connection) {
|
||||
|
|
@ -594,6 +629,7 @@ class MusicQueue extends EventEmitter {
|
|||
this.cancelAloneDisconnect();
|
||||
this.cancelConnectRetry();
|
||||
clearTimeout(this.saveTimeout);
|
||||
clearInterval(this.positionSaveInterval);
|
||||
this.client.off(Events.VoiceStateUpdate, this.voiceStateListener);
|
||||
|
||||
if (this.persistence) {
|
||||
|
|
@ -608,11 +644,12 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
|
||||
persistedState() {
|
||||
const current = this.currentTrack
|
||||
? this.resumableTrack(this.currentTrack, this.currentPosition())
|
||||
: null;
|
||||
return {
|
||||
// Le morceau en cours reprendra du début, en tête de file.
|
||||
queue: [this.currentTrack, ...this.queue]
|
||||
.filter(Boolean)
|
||||
.map(({ startedAt: _startedAt, ...track }) => track),
|
||||
// Le morceau en cours reprendra en tête de file, à peu près où il en était.
|
||||
queue: [current, ...this.queue].filter(Boolean),
|
||||
loop: this.loop,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue