From e501fc62fb5050987b45381b0883ea2eb07a7683 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Fri, 20 Nov 2026 15:09:18 +0300 Subject: [PATCH] feat(music): implement instant track transitions via next-up pre-fetching - Queue: add peek() to inspect the upcoming track while respecting loop modes - PlaybackMixin: schedule pre-fetch 15s before the current track finishes - PlaybackMixin: pre-resolve Lavalink tracks and NodeLink trackstream URLs in background - Player: trigger pre-fetching on queue add events near track completion and clear timers on stop - FluxerAudioBridge: consume cached direct stream URLs for 0ms track transition latency --- src/music/audio/FluxerAudioBridge.mjs | 8 ++- src/music/player/PlaybackMixin.mjs | 96 +++++++++++++++++++++++++++ src/music/player/Player.mjs | 11 ++- src/music/player/Queue.mjs | 15 +++++ 4 files changed, 128 insertions(+), 2 deletions(-) diff --git a/src/music/audio/FluxerAudioBridge.mjs b/src/music/audio/FluxerAudioBridge.mjs index 8ef16dd..7579611 100644 --- a/src/music/audio/FluxerAudioBridge.mjs +++ b/src/music/audio/FluxerAudioBridge.mjs @@ -437,7 +437,13 @@ export class FluxerAudioBridge extends EventEmitter { let direct; try { - direct = await this._getTrackstreamUrl(trackInfo); + if (trackInfo._prefetchedDirect && (Date.now() - (trackInfo._prefetchedDirect.cachedAt || 0) < 60_000)) { + direct = trackInfo._prefetchedDirect; + trackInfo._prefetchedDirect = null; + logger.player("[AudioBridge] Using pre-fetched trackstream direct URL: " + (trackInfo.title || "unknown")); + } else { + direct = await this._getTrackstreamUrl(trackInfo); + } if (!direct?.url) throw new Error("trackstream returned no URL"); } catch (e) { if (stale()) return "stopped"; diff --git a/src/music/player/PlaybackMixin.mjs b/src/music/player/PlaybackMixin.mjs index 0190459..bf88881 100644 --- a/src/music/player/PlaybackMixin.mjs +++ b/src/music/player/PlaybackMixin.mjs @@ -413,6 +413,17 @@ const PlaybackMixin = { const myPlayGen = (this._playSessionGen = (this._playSessionGen ?? 0) + 1); + this._clearPrefetchTimer(); + if (durationMs > 20_000) { + this._prefetchTimer = setTimeout(() => { + this._prefetchNextTrack().catch(() => {}); + }, Math.max(2_000, durationMs - 15_000)); + } else if (durationMs > 0) { + this._prefetchTimer = setTimeout(() => { + this._prefetchNextTrack().catch(() => {}); + }, 1_000); + } + const result = await this._audioBridge.play(this._voiceConn, { encoded: songData.encoded, url: bridgeUrl, @@ -425,6 +436,8 @@ const PlaybackMixin = { filterPayload: this.activeFilterPayload || null, }); + this._clearPrefetchTimer(); + if (myPlayGen !== this._playSessionGen) { /* Another track was started or stopped while this was playing — drop stale completion */ return; @@ -505,6 +518,89 @@ const PlaybackMixin = { this._trackEndTimer = null; } this._trackEndRemainingMs = null; + this._clearPrefetchTimer(); + }, + + /** + * @private Clear the next-up pre-fetch timer. + * @this {import('./Player.mjs').Player} + */ + _clearPrefetchTimer() { + if (this._prefetchTimer) { + clearTimeout(this._prefetchTimer); + this._prefetchTimer = null; + } + }, + + /** + * @private Pre-fetch the upcoming track in the queue: pre-resolves Lavalink + * encoded payload if missing, and queries NodeLink /v4/trackstream in advance + * so the next track begins with 0ms transition latency. + * @this {import('./Player.mjs').Player} + * @returns {Promise} + */ + async _prefetchNextTrack() { + this._clearPrefetchTimer(); + if (this._destroyed || this.leaving || !this.queue) return; + const nextTrack = typeof this.queue.peek === "function" ? this.queue.peek() : (this.queue.data?.[0] || null); + if (!nextTrack || nextTrack.type === "radio" || nextTrack.type === "livestream") return; + if (nextTrack._prefetchedDirect && Date.now() - (nextTrack._prefetchedDirect.cachedAt || 0) < 60_000) return; + + try { + if (!nextTrack.encoded && nextTrack.url && nextTrack.url.startsWith("http") && this._lavalink && nextTrack.type !== "external" && nextTrack.type !== "attachment") { + const nlInfo = this._lavalink.getNodeLinkInfo?.(); + if (nlInfo) { + const protocol = nlInfo.secure ? "https" : "http"; + const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port; + const headers = { "Authorization": nlInfo.password }; + if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId; + if (this._guildId) headers["Guild-Id"] = this._guildId; + + const loadtracksUrl = baseUrl + "/v4/loadtracks?identifier=" + encodeURIComponent(nextTrack.url); + const body = await this._request(loadtracksUrl, { headers }).catch(() => null); + const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data; + const encoded = track?.encoded ?? track?.data; + if (encoded && typeof encoded === "string") { + nextTrack.encoded = encoded; + logger.player(`[Player] Next track pre-resolved encoded payload: ${nextTrack.title || nextTrack.url}`); + } + } + } + + if (nextTrack.encoded && this._audioBridge && typeof this._audioBridge._getTrackstreamUrl === "function") { + const direct = await this._audioBridge._getTrackstreamUrl({ + encoded: nextTrack.encoded, + guildId: this._guildId, + }).catch(() => null); + + if (direct?.url) { + nextTrack._prefetchedDirect = { + url: direct.url, + format: direct.format || "", + cachedAt: Date.now(), + }; + logger.player(`[Player] Next-up pre-fetch ready for: ${nextTrack.title || nextTrack.url} (format=${direct.format})`); + } + } + } catch (e) { + logger.player("[Player] Next-up pre-fetch ignored error: " + (e?.message || e)); + } + }, + + /** + * @private Trigger pre-fetching if the current track is already near completion. + * @this {import('./Player.mjs').Player} + */ + _maybePrefetchNext() { + if (!this.startedPlaying || this._paused || !this.queue?.getCurrent()) return; + const current = this.queue.getCurrent(); + const totalMs = this._getTrackDurationMs(current); + if (totalMs <= 0) return; + const elapsedMs = Math.max(0, Date.now() - this.startedPlaying); + const remainingMs = totalMs - elapsedMs; + if (remainingMs <= 20_000) { + this._prefetchNextTrack().catch(() => {}); + } }, /** diff --git a/src/music/player/Player.mjs b/src/music/player/Player.mjs index 6c95e7f..932faf8 100644 --- a/src/music/player/Player.mjs +++ b/src/music/player/Player.mjs @@ -74,6 +74,8 @@ class Player extends EventEmitter { _lastConnectedAt = null; /** @private @type {string|null} The home channel of a 24/7 spawn. */ _home247Channel = null; + /** @private @type {NodeJS.Timeout|null} */ + _prefetchTimer = null; /** @private @type {Set} User IDs who have voted to skip the current track. Reset whenever a new track starts. */ _skipVotes = new Set(); @@ -150,7 +152,13 @@ class Player extends EventEmitter { super(); this.queue = new Queue(); - this.queue.on("queue", (...args) => this.emit("queue", ...args)); + this.queue.on("queue", (...args) => { + this.emit("queue", ...args); + const ev = args[0]; + if (ev?.type === "add" || ev?.type === "addMany") { + this._maybePrefetchNext?.(); + } + }); this.client = opts.client; this.config = opts.config ?? {}; this.settings = opts.settings ?? null; @@ -1078,6 +1086,7 @@ class Player extends EventEmitter { /** @private Stop the audio bridge if currently playing. */ _bridgeStop() { this._playSessionGen = (this._playSessionGen ?? 0) + 1; + this._clearPrefetchTimer?.(); if (this._audioBridge) { try { this._audioBridge.stop(); } catch (_) {} } diff --git a/src/music/player/Queue.mjs b/src/music/player/Queue.mjs index 5c8867b..ed4e854 100644 --- a/src/music/player/Queue.mjs +++ b/src/music/player/Queue.mjs @@ -41,6 +41,21 @@ export class Queue extends EventEmitter { /** @returns {number} Number of tracks in the queue (excluding current). */ size() { return this.data.length; } + /** + * Peek at the track that will play next without modifying the queue. + * @param {object} [options] + * @param {boolean} [options.ignoreSongLoop=false] + * @returns {object|null} + */ + peek({ ignoreSongLoop = false } = {}) { + if (!ignoreSongLoop && this.songLoop && this.current) return this.current; + if (this.isEmpty()) { + if (this.loop && this.current) return this.current; + return null; + } + return this.data[0] ?? null; + } + /** * Advance to the next track in the queue. If songLoop is active, returns * the current track. If queue loop is active, re-appends the current track.