diff --git a/index.mjs b/index.mjs index 9c8f8e2..176d28a 100644 --- a/index.mjs +++ b/index.mjs @@ -5,9 +5,6 @@ * graceful shutdown. All boot logic lives in src/core/Bot.mjs. */ -import { EventEmitter } from "node:events"; -EventEmitter.defaultMaxListeners = 100; - import { logger } from "./src/core/Logger.mjs"; import Remix from "./src/core/Bot.mjs"; import { initErrorChannel, reportCrash } from "./src/core/ErrorChannel.mjs"; diff --git a/src/music/audio/FluxerAudioBridge.mjs b/src/music/audio/FluxerAudioBridge.mjs index 7ea4eeb..d5a6a86 100644 --- a/src/music/audio/FluxerAudioBridge.mjs +++ b/src/music/audio/FluxerAudioBridge.mjs @@ -17,23 +17,6 @@ const pendingUnpublishSids = new WeakMap(); /** @type {number} @description Max time to wait for a stale-track unpublish to settle before publishing anyway (defensive — an unpublish should resolve almost instantly; this only guards against a hung/never-resolving LiveKit promise blocking playback indefinitely). */ const UNPUBLISH_WAIT_TIMEOUT_MS = 1200; -/** - * Trackstream circuit breaker (shared by all bridges — they all talk to the - * same NodeLink). When /v4/trackstream keeps timing out and loadstream is - * enabled, every track used to burn ~15s (timeout) + ~13s (loadtracks retry) - * before reaching the route that actually works. After TS_BREAKER_THRESHOLD - * consecutive failures we skip trackstream for TS_BREAKER_COOLDOWN_MS, then - * probe it once again. - */ -const TS_BREAKER_THRESHOLD = 2; -const TS_BREAKER_COOLDOWN_MS = 5 * 60_000; -const _tsBreaker = { failures: 0, openUntil: 0 }; -const tsBreakerOpen = () => _tsBreaker.failures >= TS_BREAKER_THRESHOLD && Date.now() < _tsBreaker.openUntil; -const tsBreakerFail = () => { _tsBreaker.failures++; if (_tsBreaker.failures >= TS_BREAKER_THRESHOLD) _tsBreaker.openUntil = Date.now() + TS_BREAKER_COOLDOWN_MS; }; -const tsBreakerOk = () => { _tsBreaker.failures = 0; _tsBreaker.openUntil = 0; }; -/** Timeouts/connection errors mean the node is slow — a fresh encoded track will not help. */ -const isSlowNodeError = (e) => /timeout|ECONNRESET|ECONNREFUSED|EAI_AGAIN/i.test(String(e?.message || e)); - /** @extends {EventEmitter} */ export class FluxerAudioBridge extends EventEmitter { _conn = null; @@ -62,10 +45,6 @@ export class FluxerAudioBridge extends EventEmitter { /** @type {boolean} @description Whether the current track was served via /v4/trackstream. */ get usedTrackstream() { return this._usedTrackstream; } - /** Called by prefetch on success: a working trackstream closes the circuit breaker. */ - _tsOk() { tsBreakerOk(); } - _tsBreakerOpen() { return tsBreakerOpen(); } - /** @param {LavalinkManager|null} lavalinkManager - LavalinkManager for trackstream/loadstream. */ constructor(lavalinkManager = null) { super(); @@ -131,9 +110,7 @@ export class FluxerAudioBridge extends EventEmitter { const trackstreamGate = loadstreamEnabled ? (seekMs === 0 && !filterPayload) // loadstream owns seek/filter cases when enabled : true; - const skipTrackstream = loadstreamEnabled && tsBreakerOpen(); - if (skipTrackstream) logger.player("[AudioBridge] Trackstream circuit open (recent timeouts) — going straight to loadstream."); - if (trackstreamGate && !skipTrackstream && trackInfo.encoded && this._lavalink) { + if (trackstreamGate && trackInfo.encoded && this._lavalink) { const result = await this._playViaTrackstream(conn, trackInfo, { seekMs, durationMs, generation }); if (result !== null) return result; // Trackstream could not serve this track (returned null for a LIVE play). @@ -400,11 +377,6 @@ export class FluxerAudioBridge extends EventEmitter { if (stale()) return "stopped"; // The encoded payload may be stale (expired googlevideo URL → HTTP 403) // — resolve a fresh one once and retry before giving up. - if (isSlowNodeError(e)) { - tsBreakerFail(); - logger.warn("[AudioBridge] Trackstream failed (" + e.message + ") — node is slow, skipping fresh-encoded retry."); - return null; - } logger.warn("[AudioBridge] Trackstream failed (" + e.message + ") — trying one fresh-encoded retry..."); const freshEncoded = trackInfo.url && trackInfo.url.startsWith("http") ? await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId).catch(() => null) @@ -424,21 +396,9 @@ export class FluxerAudioBridge extends EventEmitter { if (stale()) return "stopped"; - if (/mpegts|m3u8|hls/i.test(String(direct.format || "")) || /\.m3u8(\?|$)/i.test(direct.url)) { - // HLS/MPEG-TS can never be positioned/passed through in-process, and a - // fresh loadtracks resolve returns the same HLS — skip the ~13s detour. - logger.player("[AudioBridge] trackstream returned HLS (" + (direct.format || "m3u8") + ") — not playable in-process."); - return null; - } - if (!/webm|opus/i.test(String(direct.format || ""))) { - // A fresh resolve only helps when YouTube handed us a non-WebM itag (googlevideo). - // Mirror sources (JioSaavn/Deezer/SoundCloud... AAC/MP3/MP4) return the same thing - // again, so skip the ~7-13s loadtracks round-trip for them. - const refreshable = /googlevideo\.com|youtube\.com|ytimg/i.test(String(direct.url || "")); - logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct.format || "?") + ")" + - (refreshable ? ", refreshing encoded track once..." : " from a non-YouTube source, skipping refresh.")); - const freshEncoded = refreshable && trackInfo.url && trackInfo.url.startsWith("http") + logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct.format || "?") + "), refreshing encoded track once..."); + const freshEncoded = trackInfo.url && trackInfo.url.startsWith("http") ? await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId) : null; if (stale()) return "stopped"; @@ -475,7 +435,6 @@ export class FluxerAudioBridge extends EventEmitter { } // WebM/Opus direct URL — play with zero re-encode. - tsBreakerOk(); this._usedTrackstream = true; logger.player("[AudioBridge] Passthrough webm/opus via trackstream" + (seekMs > 0 ? " [positioned seek " + seekMs + "ms]" : " (zero-copy)") + ": " + diff --git a/src/music/audio/StreamPipeline.mjs b/src/music/audio/StreamPipeline.mjs index 9e27ea2..54baba9 100644 --- a/src/music/audio/StreamPipeline.mjs +++ b/src/music/audio/StreamPipeline.mjs @@ -10,7 +10,6 @@ * FluxerAudioBridge instance. */ -import { isLoadstreamEnabled } from "./AudioSettings.mjs"; import { logger } from "../../core/Logger.mjs"; import { WebMOpusMuxer, OPUS_FRAME_MS } from "./WebMOpusMuxer.mjs"; import { StreamPositioner } from "./StreamPositioner.mjs"; @@ -18,11 +17,6 @@ import prismMedia from "prism-media"; const { Encoder: PrismOpusEncoder, OggDemuxer: PrismOggDemuxer } = prismMedia.opus; -/** Prefetched trackstream results keyed by encoded track (shared across players). */ -const _tsCache = new Map(); -const TS_CACHE_TTL_MS = 4 * 60_000; -let _lastProbeAt = 0; - /** @type {number} @description PCM sample rate expected from NodeLink loadstream (48kHz stereo s16le). */ const PCM_RATE = 48000; /** @type {number} @description PCM channel count expected from NodeLink loadstream. */ @@ -279,67 +273,6 @@ const StreamPipeline = { * @private */ async _getTrackstreamUrl(trackInfo) { - const key = trackInfo.encoded; - const hit = _tsCache.get(key); - if (hit) { - // One-shot: a prefetched URL is consumed by the play that needs it (a replay - // or loop re-queries, so we never reuse an expired direct URL). - if (hit.result && Date.now() - hit.at < TS_CACHE_TTL_MS) { - _tsCache.delete(key); - logger.player("[AudioBridge] trackstream: using prefetched URL (instant start)"); - return hit.result; - } - if (hit.promise) { - logger.player("[AudioBridge] trackstream: joining in-flight prefetch..."); - return hit.promise; - } - _tsCache.delete(key); - } - return this._queryTrackstream(trackInfo); - }, - - /** - * Warm the next track: resolve its encoded payload (if missing) and its - * trackstream URL in the background so the track change is near-instant. - * Never throws. Doubles as a free health probe for the trackstream circuit - * breaker (success closes it, so playback returns to the fast route). - * @param {object} song - Queue track object (its .encoded is filled in when resolved). - * @param {string} [guildId] - * @returns {Promise} - */ - async prefetchTrack(song, guildId) { - try { - if (!this._lavalink || !song || song.type === "bilibili" || song.type === "external") return; - if (!song.encoded && song.url && String(song.url).startsWith("http")) { - const enc = await this._resolveUrlViaLavalink(song.url, guildId); - if (enc) song.encoded = enc; - } - if (!song.encoded || _tsCache.has(song.encoded)) return; - // While trackstream is known-bad, probe at most once a minute (each probe is a hung request on the node). - if (this._tsBreakerOpen?.()) { - if (Date.now() - _lastProbeAt < 60_000) return; - _lastProbeAt = Date.now(); - } - const info = { encoded: song.encoded, guildId }; - const entry = { at: Date.now(), result: null, promise: null }; - entry.promise = this._queryTrackstream(info).then( - (r) => { entry.result = r; entry.at = Date.now(); entry.promise = null; this._tsOk?.(); return r; }, - (e) => { _tsCache.delete(song.encoded); throw e; }, - ); - entry.promise.catch(() => {}); // prefetch failures are silent - _tsCache.set(song.encoded, entry); - while (_tsCache.size > 40) _tsCache.delete(_tsCache.keys().next().value); - await entry.promise.catch(() => {}); - if (entry.result) logger.player("[AudioBridge] Prefetched next track: " + (song.title || "unknown")); - } catch (_) { /* never block playback */ } - }, - - /** - * @param {object} trackInfo - * @returns {Promise<{url: string, format: string}>} - * @private - */ - async _queryTrackstream(trackInfo) { const nlInfo = this._lavalink.getNodeLinkInfo?.(); if (!nlInfo) throw new Error("NodeLink info not available"); @@ -355,9 +288,7 @@ const StreamPipeline = { logger.player("[AudioBridge] Querying /v4/trackstream..."); - // A healthy trackstream answers in a few seconds. When loadstream can take over, - // fail fast (8s) instead of making the listener wait the full 15s. - const body = await this._httpGetJson(url, headers, 0, isLoadstreamEnabled() ? 8_000 : 15_000); + const body = await this._httpGetJson(url, headers); const directUrl = body?.url; if (!directUrl || typeof directUrl !== "string") { diff --git a/src/music/player/PlaybackMixin.mjs b/src/music/player/PlaybackMixin.mjs index 89256ae..cd515df 100644 --- a/src/music/player/PlaybackMixin.mjs +++ b/src/music/player/PlaybackMixin.mjs @@ -253,26 +253,6 @@ const PlaybackMixin = { } }, - /** - * @private Shortly after a track starts, warm the NEXT queued track (resolve + - * trackstream URL) so the transition does not wait on NodeLink. - * @this {import('./Player.mjs').Player} - */ - _schedulePrefetchNext() { - if (this._prefetchTimer) clearTimeout(this._prefetchTimer); - this._prefetchTimer = setTimeout(() => { - this._prefetchTimer = null; - try { - if (this._destroyed || this.leaving || !this._audioBridge?.prefetchTrack) return; - if (this.queue.songLoop) return; // next track is the same one - const next = this.queue.data?.[0]; - if (!next) return; - this._audioBridge.prefetchTrack(next, this._guildId); - } catch (_) {} - }, 6_000); - this._prefetchTimer.unref?.(); - }, - /** * @private @async Play a track through the FluxerAudioBridge. For * radio/external tracks without an encoded payload, attempts Lavalink URL @@ -338,8 +318,6 @@ const PlaybackMixin = { const totalMs = this._getTrackDurationMs(songData); const durationMs = totalMs > 0 ? Math.max(0, totalMs - seekMs) : 0; - this._schedulePrefetchNext(); - const result = await this._audioBridge.play(this._voiceConn, { encoded: songData.encoded, url: bridgeUrl,