This commit is contained in:
NoLogicAlan committed 2026-10-14 03:37:19 +03:00
1 parent 15a84cce69
commit 02b85bad5a
4 files changed
+4 -139

No files matched your search

-3
View File
@@ -5,9 +5,6 @@
* graceful shutdown. All boot logic lives in src/core/Bot.mjs. * 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 { logger } from "./src/core/Logger.mjs";
import Remix from "./src/core/Bot.mjs"; import Remix from "./src/core/Bot.mjs";
import { initErrorChannel, reportCrash } from "./src/core/ErrorChannel.mjs"; import { initErrorChannel, reportCrash } from "./src/core/ErrorChannel.mjs";
+3 -44
View File
@@ -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). */ /** @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; 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} */ /** @extends {EventEmitter} */
export class FluxerAudioBridge extends EventEmitter { export class FluxerAudioBridge extends EventEmitter {
_conn = null; _conn = null;
@@ -62,10 +45,6 @@ export class FluxerAudioBridge extends EventEmitter {
/** @type {boolean} @description Whether the current track was served via /v4/trackstream. */ /** @type {boolean} @description Whether the current track was served via /v4/trackstream. */
get usedTrackstream() { return this._usedTrackstream; } 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. */ /** @param {LavalinkManager|null} lavalinkManager - LavalinkManager for trackstream/loadstream. */
constructor(lavalinkManager = null) { constructor(lavalinkManager = null) {
super(); super();
@@ -131,9 +110,7 @@ export class FluxerAudioBridge extends EventEmitter {
const trackstreamGate = loadstreamEnabled const trackstreamGate = loadstreamEnabled
? (seekMs === 0 && !filterPayload) // loadstream owns seek/filter cases when enabled ? (seekMs === 0 && !filterPayload) // loadstream owns seek/filter cases when enabled
: true; : true;
const skipTrackstream = loadstreamEnabled && tsBreakerOpen(); if (trackstreamGate && trackInfo.encoded && this._lavalink) {
if (skipTrackstream) logger.player("[AudioBridge] Trackstream circuit open (recent timeouts) — going straight to loadstream.");
if (trackstreamGate && !skipTrackstream && trackInfo.encoded && this._lavalink) {
const result = await this._playViaTrackstream(conn, trackInfo, { seekMs, durationMs, generation }); const result = await this._playViaTrackstream(conn, trackInfo, { seekMs, durationMs, generation });
if (result !== null) return result; if (result !== null) return result;
// Trackstream could not serve this track (returned null for a LIVE play). // 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"; if (stale()) return "stopped";
// The encoded payload may be stale (expired googlevideo URL → HTTP 403) // The encoded payload may be stale (expired googlevideo URL → HTTP 403)
// — resolve a fresh one once and retry before giving up. // — 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..."); logger.warn("[AudioBridge] Trackstream failed (" + e.message + ") — trying one fresh-encoded retry...");
const freshEncoded = trackInfo.url && trackInfo.url.startsWith("http") const freshEncoded = trackInfo.url && trackInfo.url.startsWith("http")
? await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId).catch(() => null) ? await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId).catch(() => null)
@@ -424,21 +396,9 @@ export class FluxerAudioBridge extends EventEmitter {
if (stale()) return "stopped"; 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 || ""))) { if (!/webm|opus/i.test(String(direct.format || ""))) {
// A fresh resolve only helps when YouTube handed us a non-WebM itag (googlevideo). logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct.format || "?") + "), refreshing encoded track once...");
// Mirror sources (JioSaavn/Deezer/SoundCloud... AAC/MP3/MP4) return the same thing const freshEncoded = trackInfo.url && trackInfo.url.startsWith("http")
// 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")
? await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId) ? await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId)
: null; : null;
if (stale()) return "stopped"; if (stale()) return "stopped";
@@ -475,7 +435,6 @@ export class FluxerAudioBridge extends EventEmitter {
} }
// WebM/Opus direct URL — play with zero re-encode. // WebM/Opus direct URL — play with zero re-encode.
tsBreakerOk();
this._usedTrackstream = true; this._usedTrackstream = true;
logger.player("[AudioBridge] Passthrough webm/opus via trackstream" + logger.player("[AudioBridge] Passthrough webm/opus via trackstream" +
(seekMs > 0 ? " [positioned seek " + seekMs + "ms]" : " (zero-copy)") + ": " + (seekMs > 0 ? " [positioned seek " + seekMs + "ms]" : " (zero-copy)") + ": " +
+1 -70
View File
@@ -10,7 +10,6 @@
* FluxerAudioBridge instance. * FluxerAudioBridge instance.
*/ */
import { isLoadstreamEnabled } from "./AudioSettings.mjs";
import { logger } from "../../core/Logger.mjs"; import { logger } from "../../core/Logger.mjs";
import { WebMOpusMuxer, OPUS_FRAME_MS } from "./WebMOpusMuxer.mjs"; import { WebMOpusMuxer, OPUS_FRAME_MS } from "./WebMOpusMuxer.mjs";
import { StreamPositioner } from "./StreamPositioner.mjs"; import { StreamPositioner } from "./StreamPositioner.mjs";
@@ -18,11 +17,6 @@ import prismMedia from "prism-media";
const { Encoder: PrismOpusEncoder, OggDemuxer: PrismOggDemuxer } = prismMedia.opus; 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). */ /** @type {number} @description PCM sample rate expected from NodeLink loadstream (48kHz stereo s16le). */
const PCM_RATE = 48000; const PCM_RATE = 48000;
/** @type {number} @description PCM channel count expected from NodeLink loadstream. */ /** @type {number} @description PCM channel count expected from NodeLink loadstream. */
@@ -279,67 +273,6 @@ const StreamPipeline = {
* @private * @private
*/ */
async _getTrackstreamUrl(trackInfo) { 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<void>}
*/
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?.(); const nlInfo = this._lavalink.getNodeLinkInfo?.();
if (!nlInfo) throw new Error("NodeLink info not available"); if (!nlInfo) throw new Error("NodeLink info not available");
@@ -355,9 +288,7 @@ const StreamPipeline = {
logger.player("[AudioBridge] Querying /v4/trackstream..."); logger.player("[AudioBridge] Querying /v4/trackstream...");
// A healthy trackstream answers in a few seconds. When loadstream can take over, const body = await this._httpGetJson(url, headers);
// 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 directUrl = body?.url; const directUrl = body?.url;
if (!directUrl || typeof directUrl !== "string") { if (!directUrl || typeof directUrl !== "string") {
-22
View File
@@ -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 * @private @async Play a track through the FluxerAudioBridge. For
* radio/external tracks without an encoded payload, attempts Lavalink URL * radio/external tracks without an encoded payload, attempts Lavalink URL
@@ -338,8 +318,6 @@ const PlaybackMixin = {
const totalMs = this._getTrackDurationMs(songData); const totalMs = this._getTrackDurationMs(songData);
const durationMs = totalMs > 0 ? Math.max(0, totalMs - seekMs) : 0; const durationMs = totalMs > 0 ? Math.max(0, totalMs - seekMs) : 0;
this._schedulePrefetchNext();
const result = await this._audioBridge.play(this._voiceConn, { const result = await this._audioBridge.play(this._voiceConn, {
encoded: songData.encoded, encoded: songData.encoded,
url: bridgeUrl, url: bridgeUrl,