diff --git a/config_example.json b/config_example.json index 49af163..1c2e405 100644 --- a/config_example.json +++ b/config_example.json @@ -45,6 +45,10 @@ "requestTimeout": 60000, "Comment": "requestTimeout: ms before a NodeLink HTTP request is aborted. Default: 60000 (60s). Raise if you see 'NodeLink request timeout' errors. All audio sources (Spotify, Deezer, Apple Music, etc.) are resolved by NodeLink, so configure source credentials in nodelink.config.json, not here." }, + "audio": { + "allowLoadstream": false, + "Comment": "Playback runs on NodeLink's /v4/trackstream endpoint only: WebM/Opus zero-re-encode passthrough, stale URLs auto-retried with a fresh resolve, and seeks handled in-process by the bot (no FFmpeg anywhere). Leave allowLoadstream = false unless you specifically need the legacy /v4/loadstream route. Set it to true only if your audio node exposes /v4/loadstream — it re-enables: server-side audio filters (bassboost, nightcore, ...), MP3/AAC/PCM sources (radio stations, Bilibili's AAC audio), and NodeLink-side seeking. loadstream is what required FFmpeg in the past." + }, "bilibili": { "enabled": true, "bind": "127.0.0.1", diff --git a/src/core/Bot.mjs b/src/core/Bot.mjs index 230c4a7..0d0d8d8 100644 --- a/src/core/Bot.mjs +++ b/src/core/Bot.mjs @@ -29,6 +29,7 @@ import { LastFmManager } from "../services/lastfm/LastFmManager.mjs"; import { FluxerListManager } from "../services/FluxerListManager.mjs"; import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs"; import { configureBilibili } from "../music/bilibili/index.mjs"; +import { configureAudio } from "../music/audio/AudioSettings.mjs"; import { applyMixins } from "../utils/mixins.mjs"; import BotVoiceMixin from "./BotVoiceMixin.mjs"; @@ -126,6 +127,10 @@ class Remix { remoteSecret: config.bilibili?.remoteSecret ?? null, }); + configureAudio({ + allowLoadstream: config.audio?.allowLoadstream ?? false, + }); + this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%"); this.locale.load(); diff --git a/src/music/audio/AudioSettings.mjs b/src/music/audio/AudioSettings.mjs new file mode 100644 index 0000000..b556028 --- /dev/null +++ b/src/music/audio/AudioSettings.mjs @@ -0,0 +1,36 @@ +/** @module src/music/audio/AudioSettings @description Audio subsystem settings, merged from the config.json `audio` section at startup (see Bot.mjs). Keeps the streaming core free of direct config dependencies — the bridge, player mixins and tests read the effective settings via {@link getAudioSettings}. */ + +/** @type {object} @description Effective audio settings (merged from config.json -> audio). */ +const _settings = { + /** @type {boolean} @description Whether the legacy /v4/loadstream route may be used (server-side seek, filters, MP3/AAC decode). Disabled by default: playback runs on /v4/trackstream only. */ + allowLoadstream: false, +}; + +/** + * Merge the config.json `audio` section into the effective settings. + * @param {object|null} [section] - config.json -> audio + * @param {boolean|string} [section.allowLoadstream] - Opt into the NodeLink + * /v4/loadstream route. Accepts true / "true"; anything else keeps it off. + */ +export function configureAudio(section = null) { + const raw = section?.allowLoadstream; + _settings.allowLoadstream = raw === true || raw === "true"; +} + +/** + * @returns {object} A snapshot of the effective audio settings. + */ +export function getAudioSettings() { + return { ..._settings }; +} + +/** + * @returns {boolean} Whether the /v4/loadstream route is enabled. When false + * the bot never calls /v4/loadstream: playback and seeking run entirely on + * /v4/trackstream plus in-process WebM/Ogg handling. + */ +export function isLoadstreamEnabled() { + return _settings.allowLoadstream === true; +} + +export default { configureAudio, getAudioSettings, isLoadstreamEnabled }; diff --git a/src/music/audio/FluxerAudioBridge.mjs b/src/music/audio/FluxerAudioBridge.mjs index 39bf974..e571f9b 100644 --- a/src/music/audio/FluxerAudioBridge.mjs +++ b/src/music/audio/FluxerAudioBridge.mjs @@ -1,15 +1,19 @@ -/** @module src/music/audio/FluxerAudioBridge @description Audio bridge for streaming Lavalink/NodeLink audio through Fluxer voice connections. 100% in-process — Opus encoding via prism-media (native/WASM), WebM muxing via WebMOpusMuxer. No FFmpeg processes. Supports MP3/AAC/radio streams via Lavalink resolve-through. Base class: lifecycle (play/stop/destroy), state getters, volume and cleanup. Stream pipeline building and Lavalink REST HTTP helpers live in the StreamPipeline/HttpStreams mixin modules applied at the bottom of this file. */ +/** @module src/music/audio/FluxerAudioBridge @description Audio bridge for streaming Lavalink/NodeLink audio through Fluxer voice connections. 100% in-process — Opus encoding via prism-media (native/WASM), WebM muxing via WebMOpusMuxer. No FFmpeg processes. Primary route: /v4/trackstream zero-re-encode passthrough with automatic fresh-URL retry on stale/forbidden direct URLs, and in-process WebM/Ogg byte positioning for ffmpeg-free seeks (StreamPositioner). The legacy /v4/loadstream route (server-side seek, filters, MP3/AAC decode — needs FFmpeg on the audio node) is opt-in via config.json -> audio.allowLoadstream. Base class: lifecycle (play/stop/destroy), state getters, volume and cleanup. Stream pipeline building and Lavalink REST HTTP helpers live in the StreamPipeline/HttpStreams mixin modules applied at the bottom of this file. */ import { logger } from "../../core/Logger.mjs"; import { EventEmitter } from "node:events"; import { Readable } from "node:stream"; import { applyMixins } from "../../utils/mixins.mjs"; +import { isLoadstreamEnabled } from "./AudioSettings.mjs"; import StreamPipeline from "./StreamPipeline.mjs"; import HttpStreams from "./HttpStreams.mjs"; /** @type {number} @description livekit TrackKind.KIND_AUDIO — publications with this kind are managed by the bridge. */ const TRACK_KIND_AUDIO = 1; +/** @type {WeakMap>} @description Audio SIDs already handed to LiveKit for unpublish, keyed per local participant. LiveKit's unpublishTrack() is async — the publication stays listed in trackPublications until the RTC layer completes it, so repeated sweeps (stop() -> play() -> stop()) re-unpublish the same SID, producing duplicate "Unpublished stale audio track" logs and LiveKit "RoomEvent.LocalTrackSubscribed: Publication not found" warnings. The WeakMap GCs itself when the participant is destroyed. */ +const pendingUnpublishSids = new WeakMap(); + /** @extends {EventEmitter} */ export class FluxerAudioBridge extends EventEmitter { _conn = null; @@ -24,6 +28,7 @@ export class FluxerAudioBridge extends EventEmitter { _lavalink = null; _playGeneration = 0; _durationTimer = null; + _durationResolve = null; _endResolve = null; _endReject = null; _usedTrackstream = false; @@ -34,6 +39,8 @@ export class FluxerAudioBridge extends EventEmitter { get startedAt() { return this._startedAt; } /** @type {string|null} @description URI of the currently playing track. */ get currentUri() { return this._currentUri; } + /** @type {boolean} @description Whether the current track was served via /v4/trackstream. */ + get usedTrackstream() { return this._usedTrackstream; } /** @param {LavalinkManager|null} lavalinkManager - LavalinkManager for trackstream/loadstream. */ constructor(lavalinkManager = null) { @@ -43,12 +50,22 @@ export class FluxerAudioBridge extends EventEmitter { /** * Play a track through a Fluxer voice connection, entirely in-process. - * Routing order: - * 1. trackstream passthrough (seek=0, no filters) — NodeLink hands back a WebM/Opus - * direct URL which the voice connection plays natively (zero re-encode). - * 2. loadstream — NodeLink returns raw PCM (48k stereo s16le) with server-side - * seek/filters; PCM is Opus-encoded in-process and muxed to WebM. - * 3. direct URL fallback — magic-byte sniff: WebM passthrough or Ogg/Opus remux. + * Routing order (audio.allowLoadstream defaults to false — trackstream-only): + * 1. trackstream — NodeLink hands back a WebM/Opus direct URL which the + * voice connection plays natively (zero re-encode). Stale/forbidden + * URLs (HTTP 403 etc.) trigger one fresh-encoded retry via Lavalink. + * Seeks are served in-process by StreamPositioner (byte-level cluster/ + * page skip); when the track length is unknown the URL is streamed + * through the bot so end-of-stream can be observed. + * 2. loadstream (only when audio.allowLoadstream is true) — NodeLink + * returns raw audio with server-side seek/filters/decoding; WebM + * passes through, Ogg is remuxed, PCM is Opus-encoded in-process. + * 3. direct URL fallback — only for tracks WITHOUT an encoded payload + * (Bilibili proxy, radio, direct links); magic-byte sniff: WebM + * passthrough or Ogg/Opus remux; other formats need the loadstream + * route or a Lavalink resolve + trackstream retry. + * Every await is followed by a play-generation check so a stop()/new play() + * can never leave a superseded play() publishing audio (double-audio race). * @param {object} conn - Fluxer voice connection * @param {object} trackInfo - Track metadata (encoded, title, url, guildId) * @param {object} [options] @@ -73,70 +90,32 @@ export class FluxerAudioBridge extends EventEmitter { const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000); let durationMs = options.durationMs || 0; + const filterPayload = options.filterPayload ?? null; + const loadstreamEnabled = isLoadstreamEnabled(); + + if (filterPayload && !loadstreamEnabled) { + logger.warn("[AudioBridge] Audio filter ignored — the loadstream route is disabled (config.json -> audio.allowLoadstream). Playing unfiltered."); + } try { - if (seekMs === 0 && !options.filterPayload && trackInfo.encoded && this._lavalink) { - try { - const direct = await this._getTrackstreamUrl(trackInfo); - if (direct?.url && /webm|opus/i.test(direct.format || "")) { - this._usedTrackstream = true; - logger.player("[AudioBridge] Passthrough webm/opus via trackstream (zero-copy): " + (trackInfo.title || "unknown")); - - await conn.play(direct.url); - if (generation !== this._playGeneration) return "stopped"; - - if (durationMs > 0) await this._waitDuration(durationMs); - if (generation !== this._playGeneration) return "stopped"; - - if (this._playing && !this._stopped) { - this._playing = false; - logger.player("[AudioBridge] Track finished naturally (trackstream passthrough)"); - return "finished"; - } - return "stopped"; - } - if (direct?.url && this._lavalink && trackInfo.url && trackInfo.url.startsWith("http")) { - logger.player("[AudioBridge] trackstream format " + (direct.format || "?") + " — resolving original source URL via Lavalink for fresh encoded track..."); - const freshEncoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId); - if (freshEncoded) { - trackInfo.encoded = freshEncoded; - logger.player("[AudioBridge] Fresh encoded track obtained — retrying trackstream for webm/opus..."); - try { - const freshDirect = await this._getTrackstreamUrl(trackInfo); - if (freshDirect?.url && /webm|opus/i.test(freshDirect.format || "")) { - this._usedTrackstream = true; - logger.player("[AudioBridge] Fresh trackstream is webm/opus — zero-copy passthrough: " + (trackInfo.title || "unknown")); - await conn.play(freshDirect.url); - if (generation !== this._playGeneration) return "stopped"; - if (durationMs > 0) await this._waitDuration(durationMs); - if (generation !== this._playGeneration) return "stopped"; - if (this._playing && !this._stopped) { - this._playing = false; - logger.player("[AudioBridge] Track finished naturally (fresh trackstream passthrough)"); - return "finished"; - } - return "stopped"; - } - logger.player("[AudioBridge] Fresh trackstream also " + (freshDirect?.format || "?") + ", falling through to loadstream"); - } catch (e2) { - logger.player("[AudioBridge] Fresh trackstream failed, falling through to loadstream: " + e2.message); - } - } else { - logger.player("[AudioBridge] Could not resolve source URL via Lavalink, using original encoded track for loadstream"); - } - } else { - logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct?.format || "?") + "), falling through to loadstream"); - } - } catch (e) { - logger.warn("[AudioBridge] Trackstream failed, falling back to loadstream: " + e.message); - this._playing = true; - this._stopped = false; - this._startedAt = Date.now(); - } + // ── Route A: /v4/trackstream — primary path, never touches /v4/loadstream. + // In trackstream-only mode it also covers seeks (in-process positioning); + // filters are ignored there because they are NodeLink server-side effects. + const trackstreamGate = loadstreamEnabled + ? (seekMs === 0 && !filterPayload) // loadstream owns seek/filter cases when enabled + : true; + 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). + if (generation !== this._playGeneration) return "stopped"; + durationMs = options.durationMs || 0; // reset in case trackstream consumed it } - if (trackInfo.encoded && this._lavalink) { - const loaded = await this._streamFromLoadstream(trackInfo, seekMs, options.filterPayload); + // ── Route B: /v4/loadstream — opt-in legacy route (server-side seek, + // filters and MP3/AAC/PCM decoding). Unchanged behavior when enabled. + if (loadstreamEnabled && trackInfo.encoded && this._lavalink) { + const loaded = await this._streamFromLoadstream(trackInfo, seekMs, filterPayload); if (generation !== this._playGeneration) { loaded.stream.destroy(); return "stopped"; @@ -160,7 +139,7 @@ export class FluxerAudioBridge extends EventEmitter { } else { logger.player("[AudioBridge] Playing via loadstream PCM -> in-process Opus: " + (trackInfo.title || "unknown") + (seekMs > 0 ? " [seek: " + seekMs + "ms]" : "") + - (options.filterPayload ? " [filters]" : "")); + (filterPayload ? " [filters]" : "")); this._stream = this._buildPcmPipeline(routed.stream); await conn.play(this._stream); } @@ -177,7 +156,11 @@ export class FluxerAudioBridge extends EventEmitter { return "stopped"; } - if (trackInfo.url && trackInfo.url.startsWith("http")) { + // ── Route C: direct URL — only for tracks WITHOUT an encoded payload + // (Bilibili proxy, radio, direct links). Encoded tracks that reached + // this point get the explicit error below instead of fetching their + // source page. + if (!trackInfo.encoded && trackInfo.url && trackInfo.url.startsWith("http")) { logger.player("[AudioBridge] Route 3: Fetching directly: " + trackInfo.url.substring(0, 80) + "..."); const response = await fetch(trackInfo.url, { headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" }, @@ -228,34 +211,39 @@ export class FluxerAudioBridge extends EventEmitter { this._sourceStream = null; logger.player("[AudioBridge] Route 3c: Direct stream is " + routed.kind + " (MP3/AAC?) — resolving through Lavalink..."); - if (this._lavalink) { - const encoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId); - if (encoded) { - trackInfo.encoded = encoded; - logger.player("[AudioBridge] Route 3c: Got encoded track from Lavalink, retrying via loadstream..."); - const loaded = await this._streamFromLoadstream(trackInfo, 0, null); + const encoded = this._lavalink + ? await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId) + : null; + if (encoded) { + trackInfo.encoded = encoded; + logger.player("[AudioBridge] Route 3c: Got encoded track from Lavalink — retrying via trackstream..."); + const result3c = await this._playViaTrackstream(conn, trackInfo, { seekMs, durationMs, generation }); + if (result3c !== null) return result3c; + if (generation !== this._playGeneration) return "stopped"; + // Trackstream could not serve the resolved track either — fall + // through to loadstream when allowed, else the explicit error. + if (loadstreamEnabled) { + const loaded3c = await this._streamFromLoadstream(trackInfo, seekMs, null); if (generation !== this._playGeneration) { - loaded.stream.destroy(); + loaded3c.stream.destroy(); return "stopped"; } - - const routed2 = await this._routeByMagic(loaded.stream); - this._sourceStream = loaded.stream; - this._sourceReq = loaded.req || null; - - if (routed2.kind === "webm") { - logger.player("[AudioBridge] Route 3c (Lavalink): webm/opus passthrough"); - this._stream = routed2.stream; - await conn.play(routed2.stream); - } else if (routed2.kind === "ogg") { - logger.player("[AudioBridge] Route 3c (Lavalink): ogg/opus remux to webm"); - const oggResult3c = await this._remuxOggToWebM(routed2.stream); + const routed3c = await this._routeByMagic(loaded3c.stream); + this._sourceStream = loaded3c.stream; + this._sourceReq = loaded3c.req || null; + if (routed3c.kind === "webm") { + logger.player("[AudioBridge] Route 3c (loadstream): webm/opus passthrough"); + this._stream = routed3c.stream; + await conn.play(routed3c.stream); + } else if (routed3c.kind === "ogg") { + logger.player("[AudioBridge] Route 3c (loadstream): ogg/opus remux to webm"); + const oggResult3c = await this._remuxOggToWebM(routed3c.stream); this._stream = oggResult3c; if (durationMs <= 0) durationMs = oggResult3c.getDurationMs(); await conn.play(this._stream); } else { - logger.player("[AudioBridge] Route 3c (Lavalink): PCM -> Opus -> WebM"); - this._stream = this._buildPcmPipeline(routed2.stream); + logger.player("[AudioBridge] Route 3c (loadstream): PCM -> Opus -> WebM"); + this._stream = this._buildPcmPipeline(routed3c.stream); await conn.play(this._stream); } if (generation !== this._playGeneration) return "stopped"; @@ -273,9 +261,9 @@ export class FluxerAudioBridge extends EventEmitter { } throw new Error( - "[AudioBridge] Direct URL is not WebM/Opus or Ogg/Opus (" + routed.kind + "). " + - "Lavalink resolve also failed or is unavailable. " + - "Make sure your Lavalink/NodeLink node is running and can decode this stream format." + "[AudioBridge] Direct stream is " + routed.kind + " (MP3/AAC/PCM?) — this format needs server-side decoding. " + + "Set audio.allowLoadstream to true in config.json (requires a NodeLink exposing /v4/loadstream), " + + "or play a WebM/Opus source." ); } if (generation !== this._playGeneration) return "stopped"; @@ -291,6 +279,14 @@ export class FluxerAudioBridge extends EventEmitter { return "stopped"; } + if (trackInfo.encoded && this._lavalink && !loadstreamEnabled) { + throw new Error( + "[AudioBridge] NodeLink trackstream could not serve a playable WebM/Opus stream for this track, " + + "and the loadstream route is disabled. Set audio.allowLoadstream to true in config.json " + + "if your audio node can decode this format server-side (MP3/AAC sources need it)." + ); + } + throw new Error("Could not get audio stream for: " + (trackInfo.title || trackInfo.url || "unknown")); } catch (e) { @@ -304,6 +300,173 @@ export class FluxerAudioBridge extends EventEmitter { } } + /** + * Play an already-opened (optionally positioned) stream through the voice + * connection and wait for its end. Shared bookkeeping for the trackstream + * routes. + * @param {object} conn - Fluxer voice connection + * @param {{stream: Readable}} opened - Opened stream wrapper + * @param {number} durationMs - Remaining duration (0 = until stream end) + * @param {number} generation - Play generation guard + * @returns {Promise<"finished"|"stopped"|null>} null when playback failed early + * @private + */ + async _playOpened(conn, opened, durationMs, generation) { + try { + if (generation !== this._playGeneration) { + opened.stream.destroy(); + return "stopped"; + } + this._stream = opened.stream; + await conn.play(opened.stream); + } catch (e) { + if (generation !== this._playGeneration) return "stopped"; + if (this._stopped || !this._playing) return "stopped"; + logger.warn("[AudioBridge] Trackstream playback failed, falling back: " + e.message); + return null; + } + + if (generation !== this._playGeneration) return "stopped"; + + await this._awaitEnd(durationMs); + if (generation !== this._playGeneration) return "stopped"; + + if (this._playing && !this._stopped) { + this._playing = false; + logger.player("[AudioBridge] Track finished naturally (trackstream)"); + return "finished"; + } + return "stopped"; + } + + /** + * Play a track through the /v4/trackstream route (no loadstream involved). + * Resolves the direct URL and plays WebM/Opus with zero re-encode — + * zero-copy URL passthrough for plain playback of known-length tracks, + * in-process byte positioning (StreamPositioner) for seeks, and a streamed + * route whenever the duration is unknown so end-of-stream can be observed. + * A failed or stale direct URL (HTTP 403 from the media host, expired + * googlevideo params, ...) triggers ONE fresh-encoded retry via Lavalink + * before giving up. Non-WebM results get the same fresh-encoded retry, + * then a magic-byte sniff of the direct URL itself (format strings can + * lie). Returns null when trackstream cannot serve the track so the caller + * can decide on a fallback. + * @param {object} conn - Fluxer voice connection + * @param {object} trackInfo - Track metadata (encoded, title, url, guildId) + * @param {object} ctx - { seekMs, durationMs, generation } + * @returns {Promise<"finished"|"stopped"|null>} null when trackstream is unusable + * @private + */ + async _playViaTrackstream(conn, trackInfo, ctx) { + const { seekMs, generation } = ctx; + const durationMs = ctx.durationMs; + + const stale = () => generation !== this._playGeneration; + + let direct; + try { + direct = await this._getTrackstreamUrl(trackInfo); + if (!direct?.url) throw new Error("trackstream returned no URL"); + } catch (e) { + 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. + 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) + : null; + if (stale()) return "stopped"; + if (!freshEncoded) return null; + trackInfo.encoded = freshEncoded; + try { + direct = await this._getTrackstreamUrl(trackInfo); + if (!direct?.url) throw new Error("trackstream returned no URL"); + } catch (e2) { + if (stale()) return "stopped"; + logger.warn("[AudioBridge] Fresh-encoded trackstream retry failed: " + e2.message); + return null; + } + } + + if (stale()) return "stopped"; + + if (!/webm|opus/i.test(String(direct.format || ""))) { + 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"; + if (freshEncoded) { + trackInfo.encoded = freshEncoded; + try { + const freshDirect = await this._getTrackstreamUrl(trackInfo); + if (freshDirect?.url && /webm|opus/i.test(String(freshDirect.format || ""))) { + direct = freshDirect; + logger.player("[AudioBridge] Fresh trackstream is webm/opus: " + (trackInfo.title || "unknown")); + } + } catch (e2) { + if (stale()) return "stopped"; + logger.player("[AudioBridge] Fresh trackstream failed: " + e2.message); + } + } + + if (!/webm|opus/i.test(String(direct.format || ""))) { + // Last chance: sniff the direct URL's actual bytes — format strings + // can lie (e.g. "mp4" that is really a WebM/Opus stream). + try { + const opened = await this._openPositionedStream(direct.url, seekMs); + if (stale()) return "stopped"; + logger.player("[AudioBridge] trackstream direct URL is actually " + opened.kind + " — playing it"); + this._usedTrackstream = true; + const result = await this._playOpened(conn, opened, durationMs, generation); + return result; + } catch (e3) { + if (stale()) return "stopped"; + logger.player("[AudioBridge] trackstream direct URL not playable in-process (" + e3.message + ")"); + return null; + } + } + } + + // WebM/Opus direct URL — play with zero re-encode. + this._usedTrackstream = true; + logger.player("[AudioBridge] Passthrough webm/opus via trackstream" + + (seekMs > 0 ? " [positioned seek " + seekMs + "ms]" : " (zero-copy)") + ": " + + (trackInfo.title || "unknown")); + + try { + if (seekMs > 0 || durationMs <= 0) { + // Streamed route: byte-positioned for seeks; also gives an + // end-of-stream handle when the duration is unknown. + const opened = await this._openPositionedStream(direct.url, seekMs); + if (stale()) { + opened.stream.destroy(); + return "stopped"; + } + return await this._playOpened(conn, opened, durationMs, generation); + } + // Zero-copy: the voice connection fetches the URL itself. + await conn.play(direct.url); + } catch (e) { + if (stale()) return "stopped"; + if (this._stopped || !this._playing) return "stopped"; + logger.warn("[AudioBridge] Trackstream playback failed, falling back: " + e.message); + return null; + } + + if (stale()) return "stopped"; + + await this._waitDuration(durationMs); + if (stale()) return "stopped"; + + if (this._playing && !this._stopped) { + this._playing = false; + logger.player("[AudioBridge] Track finished naturally (trackstream)"); + return "finished"; + } + return "stopped"; + } + /** Stop current playback and clean up resources. */ stop() { const wasPlaying = this._playing; @@ -338,14 +501,36 @@ export class FluxerAudioBridge extends EventEmitter { const publications = participant.trackPublications; if (!publications || typeof publications.entries !== "function") return; + // One guard set per participant, shared by every bridge instance in this + // process: a SID currently being unpublished is skipped by later sweeps. + let seen = pendingUnpublishSids.get(participant); + if (!seen) { + seen = new Set(); + pendingUnpublishSids.set(participant, seen); + } + + // Prune SIDs whose publications are gone (unpublish completed) so the + // guard set cannot grow unbounded across a 24/7 session. + try { + if (typeof publications.has === "function") { + for (const sid of seen) { + if (!publications.has(sid)) seen.delete(sid); + } + } + } catch (_) {} + for (const [sid, pub] of publications.entries()) { if (keepSid && sid === keepSid) continue; if (pub?.kind !== TRACK_KIND_AUDIO) continue; + if (seen.has(sid)) continue; try { + seen.add(sid); const p = participant.unpublishTrack(sid, true); - if (p?.catch) p.catch(() => {}); + if (p?.catch) p.catch(() => seen.delete(sid)); // failed unpublish -> allow retry logger.player("[AudioBridge] Unpublished stale audio track: " + sid); - } catch (_) {} + } catch (_) { + seen.delete(sid); + } } } catch (_) { } @@ -385,6 +570,11 @@ export class FluxerAudioBridge extends EventEmitter { */ _cleanup() { if (this._durationTimer) { clearTimeout(this._durationTimer); this._durationTimer = null; } + if (this._durationResolve) { + const resolve = this._durationResolve; + this._durationResolve = null; + resolve(); + } if (this._endResolve) { const resolve = this._endResolve; this._endResolve = null; diff --git a/src/music/audio/StreamPipeline.mjs b/src/music/audio/StreamPipeline.mjs index b22514f..54baba9 100644 --- a/src/music/audio/StreamPipeline.mjs +++ b/src/music/audio/StreamPipeline.mjs @@ -2,8 +2,8 @@ * @module src/music/audio/StreamPipeline * @description Stream pipeline concern for {@link FluxerAudioBridge}: * end-of-playback waiting, magic-byte routing, the in-process PCM -> Opus -> - * WebM pipeline, Ogg/Opus remuxing, trackstream/loadstream URL handling and - * Lavalink URL resolution. + * WebM pipeline, Ogg/Opus remuxing, positioned trackstream URL streaming, + * trackstream/loadstream URL handling and Lavalink URL resolution. * * These methods are applied onto the FluxerAudioBridge class prototype via * {@link module:src/utils/mixins.applyMixins} — `this` is a @@ -12,6 +12,7 @@ import { logger } from "../../core/Logger.mjs"; import { WebMOpusMuxer, OPUS_FRAME_MS } from "./WebMOpusMuxer.mjs"; +import { StreamPositioner } from "./StreamPositioner.mjs"; import prismMedia from "prism-media"; const { Encoder: PrismOpusEncoder, OggDemuxer: PrismOggDemuxer } = prismMedia.opus; @@ -58,6 +59,13 @@ const StreamPipeline = { const stream = this._stream; if (stream) { + if (stream.readableEnded || stream.destroyed) { + // Stream already finished before the wait started (very short + // sources, or the consumer drained it during conn.play setup). + this._endResolve = null; + this._endReject = null; + return resolve(); + } const onEnd = () => { if (durationMs > 0 && this._playing && !this._stopped) return; resolve(); @@ -84,21 +92,61 @@ const StreamPipeline = { /** * Simple timed wait used by the trackstream passthrough route (no local - * pipeline to watch). Resolves early if stopped. + * pipeline to watch). Resolves early when stop()/cleanup clears the timer — + * the resolve handle lives on the bridge (`_durationResolve`) so a stop can + * never leave this promise pending forever. * @param {number} durationMs * @returns {Promise} * @private */ _waitDuration(durationMs) { return new Promise((resolve) => { + this._durationResolve = resolve; const timer = setTimeout(() => { this._durationTimer = null; + this._durationResolve = null; resolve(); }, durationMs); this._durationTimer = timer; }); }, + /** + * Open a direct media URL (typically the NodeLink trackstream result) as a + * bot-side stream and — for seeks — drop leading WebM clusters / Ogg pages + * so playback starts near the target position without re-encoding + * (StreamPositioner). Also used with seekMs = 0 whenever the caller wants a + * real stream handle (unknown-duration tracks) instead of zero-copy URL + * passthrough. Registers the HTTP stream on the bridge for stop/cleanup. + * @param {string} url - Direct media URL to fetch. + * @param {number} [seekMs=0] - Target position in milliseconds (0 = start). + * @returns {Promise<{stream: Transform, kind: "webm"|"ogg"}>} + * @throws {Error} When the URL does not serve WebM or Ogg (nothing the + * in-process pipeline can position or play without decoding). + * @private + */ + async _openPositionedStream(url, seekMs = 0) { + const loaded = await this._httpRequestStream(url); + this._sourceStream = loaded.stream; + this._sourceReq = loaded.req || null; + + const routed = await this._routeByMagic(loaded.stream); + if (routed.kind !== "webm" && routed.kind !== "ogg") { + loaded.stream.destroy(); + this._sourceStream = null; + this._sourceReq = null; + throw new Error( + "Trackstream URL is not WebM/Ogg (" + (loaded.inputFormat || routed.kind) + ") — " + + "in-process positioning supports WebM/Opus and Ogg/Opus only" + ); + } + + const positioner = new StreamPositioner({ kind: routed.kind, seekMs }); + const out = routed.stream.pipe(positioner); + logger.player("[AudioBridge] Positioned stream open (kind=" + routed.kind + ", seek=" + seekMs + "ms)"); + return { stream: out, kind: routed.kind }; + }, + /** * Peek at the first bytes of a stream and classify it, pushing the peeked * bytes back so nothing is lost. diff --git a/src/music/audio/StreamPositioner.mjs b/src/music/audio/StreamPositioner.mjs new file mode 100644 index 0000000..7917c44 --- /dev/null +++ b/src/music/audio/StreamPositioner.mjs @@ -0,0 +1,512 @@ +/** @module src/music/audio/StreamPositioner @description + * FFmpeg-free stream positioning ("seek") for the trackstream pipeline. + * + * A Transform stream that consumes a WebM/Opus or Ogg/Opus byte stream and + * re-emits it starting as close as possible to a target timestamp — by + * dropping leading EBML clusters (WebM) or Ogg pages (Ogg) whose packets all + * end before the target. Nothing is decoded or re-encoded: the byte layout + * stays a valid WebM/Ogg stream, so @fluxerjs/voice's demuxer (prism-media) + * consumes the output exactly like an unmodified stream. + * + * Precision: WebM ≈ one Opus block (20 ms) — blocks before the target inside + * the first kept cluster are trimmed individually. Ogg ≈ one page (20–60 ms), + * with the two most recently dropped pages re-emitted ahead of the first kept + * page so packets that span page boundaries stay intact. + * + * Used by {@link module:src/music/audio/StreamPipeline} when a seek is + * requested while the legacy /v4/loadstream route is disabled. + */ + +import { Transform } from "node:stream"; + +/** @type {Buffer} @description WebM/Matroska EBML magic bytes. */ +const WEBM_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]); + +/** @type {Buffer} @description Ogg container magic ("OggS"). */ +const OGG_MAGIC = Buffer.from("OggS", "ascii"); + +/** @type {Buffer} @description Matroska Cluster element ID (0x1F43B675). */ +const ID_CLUSTER = Buffer.from("1f43b675", "hex"); + +/** @type {Buffer} @description Matroska SimpleBlock element ID (0xA3). */ +const ID_SIMPLEBLOCK = Buffer.from("a3", "hex"); + +/** @type {Buffer} @description Matroska Cluster Timecode element ID (0xE7). */ +const ID_TIMECODE = Buffer.from("e7", "hex"); + +/** @type {number} @description Hard cap for buffering one known-size cluster before falling back to pass-through. */ +const MAX_KNOWN_CLUSTER_BYTES = 8 * 1024 * 1024; + +/** @type {number} @description Hard cap for buffering an unknown-size cluster's decided prefix. */ +const MAX_UNKNOWN_CLUSTER_BYTES = 4 * 1024 * 1024; + +/** @type {number} @description Hard cap for buffering one Ogg page. */ +const MAX_OGG_PAGE_BYTES = 4 * 1024 * 1024; + +/** @type {number} @description Ogg pages kept back and replayed before the first kept page (packet-continuation safety). */ +const OGG_REPLAY_PAGES = 2; + +/** @type {number} @description Opus sample rate — Ogg granule positions are 48 kHz sample counts. */ +const OPUS_SAMPLE_RATE = 48; + +/** + * Encode a Matroska variable-length size integer (finite size). + * Same layout as WebMOpusMuxer's encoder — needed to rebuild a Cluster + * header after trimming leading blocks. + * @param {number} value - Size to encode (must be >= 0). + * @returns {Buffer} + */ +function encodeSizeVint(value) { + if (value <= 127) { + const buf = Buffer.allocUnsafe(1); + buf[0] = value | 0x80; + return buf; + } + if (value <= 16383) { + const buf = Buffer.allocUnsafe(2); + buf[0] = ((value >> 8) & 0xff) | 0x40; + buf[1] = value & 0xff; + return buf; + } + if (value <= 2097151) { + const buf = Buffer.allocUnsafe(3); + buf[0] = ((value >> 16) & 0xff) | 0x20; + buf[1] = (value >> 8) & 0xff; + buf[2] = value & 0xff; + return buf; + } + let length = 4; + while (value > 2 ** (7 * length) - 1 && length < 8) length++; + const buf = Buffer.alloc(length); + for (let i = length - 1; i >= 0; i--) { + buf[i] = value & 0xff; + value = Math.floor(value / 256); + } + buf[0] |= 1 << (8 - length); + return buf; +} + +/** + * Read an EBML variable-length integer. + * @param {Buffer} buf - Buffer to read from. + * @param {number} off - Byte offset. + * @param {boolean} keepMarker - true for element IDs (keep VINT_MARKER bit), + * false for sizes (strip it). + * @returns {{value: number, length: number, unknown: boolean}|null} Parsed + * vint, or null when more bytes are needed. + */ +function readVint(buf, off, keepMarker) { + const b0 = buf[off]; + if (b0 === undefined) return null; + let len = 0; + for (let i = 0; i < 8; i++) { + if ((b0 >> (7 - i)) & 1) { len = i + 1; break; } + } + if (len === 0 || off + len > buf.length) return null; + let value = keepMarker ? b0 : b0 & ((1 << (8 - len)) - 1); + // Unknown = all VALUE bits set (first byte's value portion + rest 0xFF), + // e.g. Matroska streaming size "01 FF FF FF FF FF FF FF". + let unknown = !keepMarker && (b0 & ((1 << (8 - len)) - 1)) === ((1 << (8 - len)) - 1); + for (let i = 1; i < len; i++) { + if (buf[off + i] !== 0xff) unknown = false; + value = value * 256 + buf[off + i]; + } + return { value, length: len, unknown }; +} + +/** + * Compare an EBML ID read from `buf` against a known ID constant. + * @param {Buffer} buf - Buffer containing the ID bytes. + * @param {number} off - Offset of the ID. + * @param {number} len - ID length. + * @param {Buffer} id - Known ID constant. + * @returns {boolean} + */ +function idEquals(buf, off, len, id) { + if (len !== id.length) return false; + for (let i = 0; i < len; i++) { + if (buf[off + i] !== id[i]) return false; + } + return true; +} + +/** + * Streaming WebM/Ogg positioner. + * @extends {Transform} + */ +export class StreamPositioner extends Transform { + /** + * @param {object} [options] + * @param {"webm"|"ogg"} [options.kind="webm"] - Container kind (magic-byte sniffed upstream). + * @param {number} [options.seekMs=0] - Target position in milliseconds. <= 0 → pure pass-through. + */ + constructor(options = {}) { + super(); + this._kind = options.kind === "ogg" ? "ogg" : "webm"; + this._targetMs = Math.max(0, Math.floor(options.seekMs ?? 0)); + + this._buf = Buffer.alloc(0); + this._done = this._targetMs <= 0; // nothing to drop → pass everything through + + // WebM state + this._state = "scan"; // scan | pass | cluster | clusterUnknown | passthrough + this._passRemaining = 0; + this._returnState = null; // state to resume after a "drop" finishes + this._clusterSize = 0; + this._clusterTc = 0; + + // Ogg state + this._oggPagesKept = 0; + this._oggReplay = []; // last dropped pages, replayed before the first kept page + } + + /** @param {Buffer} chunk @param {string} _enc @param {Function} cb @protected */ + _transform(chunk, _enc, cb) { + try { + if (this._done) { + this.push(chunk); + return cb(); + } + if (this._kind === "ogg") this._feedOgg(chunk); + else this._feedWebm(chunk); + cb(); + } catch (err) { + cb(err); + } + } + + /** @param {Function} cb @protected */ + _flush(cb) { + // A truncated header-only stream (target past EOF) is still valid output. + cb(); + } + + /** Enter permanent pass-through mode and flush any pending bytes. @private */ + _startPassthrough(pending) { + this._done = true; + this._state = "passthrough"; + if (pending && pending.length) this.push(pending); + if (this._buf.length) { + this.push(this._buf); + this._buf = Buffer.alloc(0); + } + } + + // ─── WebM ───────────────────────────────────────────────────────────────── + + /** Feed one chunk into the WebM state machine. @private */ + _feedWebm(chunk) { + this._buf = this._buf.length ? Buffer.concat([this._buf, chunk]) : chunk; + + for (;;) { + if (this._state === "scan") { + const id = readVint(this._buf, 0, true); + if (!id) return; + const size = readVint(this._buf, id.length, false); + if (!size) return; + const headerLen = id.length + size.length; + + if (idEquals(this._buf, 0, id.length, ID_CLUSTER)) { + if (size.unknown) { + this._state = "clusterUnknown"; + this._clusterTc = null; + this._unknownPrefix = Buffer.from(this._buf.subarray(0, headerLen)); + this._consume(headerLen); + continue; + } + if (size.value > MAX_KNOWN_CLUSTER_BYTES) { + // Abnormally large cluster — do not buffer; keep from here on. + this._startPassthrough(); + return; + } + if (this._buf.length < headerLen + size.value) return; // wait for full cluster + this._clusterSize = size.value; + this._handleKnownCluster(headerLen); + continue; + } + + // Non-cluster element: pass ID + size through, then its payload. + this.push(Buffer.from(this._buf.subarray(0, headerLen))); + this._consume(headerLen); + if (!size.unknown) { + this._passRemaining = size.value; + this._state = "pass"; + continue; // pass loop drains below / on next chunks + } + // Unknown-size container (e.g. Segment): keep scanning its children. + continue; + } + + if (this._state === "pass") { + if (this._buf.length === 0) return; + const n = Math.min(this._passRemaining, this._buf.length); + this.push(Buffer.from(this._buf.subarray(0, n))); + this._consume(n); + this._passRemaining -= n; + if (this._passRemaining === 0) this._state = "scan"; + if (this._buf.length === 0) return; + continue; + } + + if (this._state === "clusterUnknown") { + if (!this._scanUnknownClusterChildren()) return; + continue; + } + + if (this._state === "drop") { + if (this._buf.length === 0) return; + const n = Math.min(this._passRemaining, this._buf.length); + this._consume(n); + this._passRemaining -= n; + if (this._passRemaining === 0) this._state = this._returnState ?? "scan"; + continue; + } + + return; // passthrough / cluster handled elsewhere + } + } + + /** + * Process one fully buffered known-size cluster: drop it when every packet + * ends before the target; otherwise emit its header + surviving blocks and + * switch to permanent pass-through. + * @param {number} headerLen - Bytes of the Cluster ID + size vint at buffer start. + * @private + */ + _handleKnownCluster(headerLen) { + const cluster = this._buf.subarray(0, headerLen + this._clusterSize); + + // Parse children: Timecode (E7) then SimpleBlocks (A3). Anything else → keep whole cluster. + let pos = headerLen; + let tc = null; + let firstKeptOffset = -1; // offset of first block child whose abs time >= target + let firstBlockRegionStart = -1; // offset where block children begin (end of Timecode element) + let conservative = false; + + while (pos < cluster.length) { + const id = readVint(cluster, pos, true); + if (!id) { conservative = true; break; } + const size = readVint(cluster, pos + id.length, false); + if (!size || size.unknown) { conservative = true; break; } + const childStart = pos; + const payloadOff = pos + id.length + size.length; + const nextPos = payloadOff + size.value; + if (nextPos > cluster.length) { conservative = true; break; } + + if (idEquals(cluster, pos, id.length, ID_TIMECODE)) { + tc = 0; + for (let i = 0; i < size.value && i < 6; i++) tc = tc * 256 + cluster[payloadOff + i]; + if (firstBlockRegionStart === -1) firstBlockRegionStart = nextPos; + } else if (idEquals(cluster, pos, id.length, ID_SIMPLEBLOCK)) { + const rel = this._simpleBlockRelTime(cluster, payloadOff, size.value); + if (rel === null) { conservative = true; break; } + const abs = (tc ?? 0) + rel; + if (abs >= this._targetMs && firstKeptOffset === -1) { + firstKeptOffset = childStart; + break; // every later block is >= target too (blocks are time-ordered) + } + } else { + conservative = true; + break; + } + pos = nextPos; + } + + if (conservative || firstBlockRegionStart === -1) { + // Unparsed structure — keep the whole cluster to stay safe. + this._consume(cluster.length); + this._startPassthrough(Buffer.from(cluster)); + return; + } + + if (firstKeptOffset === -1) { + // Whole cluster ends before the target → drop it. + this._consume(cluster.length); + return; + } + + // Emit: cluster header (+ Timecode) then from the first surviving block on. + const skipped = firstKeptOffset - firstBlockRegionStart; + this._consume(firstKeptOffset); // buffer now starts at the surviving block + if (skipped > 0) { + // Blocks were trimmed — the original size vint would now overstate the + // payload and desync the demuxer. Rebuild the header with the real size. + const keptPayload = + (firstBlockRegionStart - headerLen) + (cluster.length - firstKeptOffset); + this.push(Buffer.concat([ + ID_CLUSTER, + encodeSizeVint(keptPayload), + Buffer.from(cluster.subarray(headerLen, firstBlockRegionStart)), + Buffer.from(cluster.subarray(firstKeptOffset)), + ])); + this._consume(cluster.length - firstKeptOffset); + } else { + this.push(Buffer.from(cluster)); + this._consume(cluster.length); + } + this._startPassthrough(); + } + + /** + * Stream children of an unknown-size cluster, dropping SimpleBlocks before + * the target and emitting the saved header + first surviving block. + * @returns {boolean} true when the state machine can make progress with the + * current buffer; false when more bytes are needed. + * @private + */ + _scanUnknownClusterChildren() { + const id = readVint(this._buf, 0, true); + if (!id) return false; + const size = readVint(this._buf, id.length, false); + if (!size) return false; + const headerLen = id.length + size.length; + + if (idEquals(this._buf, 0, id.length, ID_TIMECODE)) { + if (size.unknown) { this._startPassthrough(this._unknownPrefix); return false; } + if (this._buf.length < headerLen + size.value) return false; + let tc = 0; + for (let i = 0; i < size.value && i < 6; i++) tc = tc * 256 + this._buf[headerLen + i]; + this._clusterTc = tc; + this._unknownPrefix = Buffer.concat([this._unknownPrefix, Buffer.from(this._buf.subarray(0, headerLen + size.value))]); + this._consume(headerLen + size.value); + return true; + } + + if (idEquals(this._buf, 0, id.length, ID_SIMPLEBLOCK) && !size.unknown) { + // Wait until enough of the payload is buffered to read the rel timestamp. + if (this._buf.length < headerLen + Math.min(size.value, 6)) return false; + const rel = this._simpleBlockRelTime(this._buf, headerLen, size.value); + if (rel !== null) { + const abs = (this._clusterTc ?? 0) + rel; + if (abs >= this._targetMs) { + // First surviving block: emit saved header + Timecode + this block's + // header, then pass everything (payload included) through. + const childHeader = Buffer.from(this._buf.subarray(0, headerLen)); + this._consume(headerLen); // buffer now starts at the block payload + this._startPassthrough(Buffer.concat([this._unknownPrefix, childHeader])); + return true; + } + if (this._unknownPrefix.length > MAX_UNKNOWN_CLUSTER_BYTES) { + this._startPassthrough(); + return false; + } + if (this._buf.length < headerLen + size.value) { + // Block payload spans chunks — drop what is here, discard the rest + // of the payload in "drop" state as it arrives. + const avail = this._buf.length; + this._passRemaining = size.value - (avail - headerLen); + this._consume(avail); + this._state = "drop"; + this._returnState = "clusterUnknown"; // still inside the cluster + return true; + } + this._consume(headerLen + size.value); + return true; + } + } + + // Any other child (BlockGroup, ...) → keep from here on. + const childHeader = Buffer.from(this._buf.subarray(0, headerLen)); + this._consume(headerLen); + this._startPassthrough(Buffer.concat([this._unknownPrefix, childHeader])); + return true; + } + + /** + * Extract the signed 16-bit cluster-relative timestamp from a SimpleBlock payload. + * @param {Buffer} buf - Buffer holding the payload at `off`. + * @param {number} off - Payload start offset. + * @param {number} size - Payload size. + * @returns {number|null} Relative ms, or null when it cannot be read safely. + * @private + */ + _simpleBlockRelTime(buf, off, size) { + if (size < 4) return null; + const tb = readVint(buf, off, true); + if (!tb || tb.length > 2) return null; + if (off + tb.length + 2 > buf.length) return null; + return buf.readInt16BE(off + tb.length); + } + + // ─── Ogg ────────────────────────────────────────────────────────────────── + + /** Feed one chunk into the Ogg state machine. @private */ + _feedOgg(chunk) { + this._buf = this._buf.length ? Buffer.concat([this._buf, chunk]) : chunk; + + for (;;) { + if (this._buf.length < OGG_MAGIC.length) return; // need more bytes + if (!this._startsWith(OGG_MAGIC)) { + // Not a page boundary at buffer start — corrupt/resync: pass through. + this._startPassthrough(); + return; + } + if (this._buf.length < 27) return; + const segCount = this._buf[26]; + const headerLen = 27 + segCount; + if (this._buf.length < headerLen) return; + let payload = 0; + for (let i = 0; i < segCount; i++) payload += this._buf[27 + i]; + const pageLen = headerLen + payload; + if (pageLen > MAX_OGG_PAGE_BYTES) { this._startPassthrough(); return; } + if (this._buf.length < pageLen) return; + + const granule = Number(this._buf.readBigUInt64LE(6)); + const page = Buffer.from(this._buf.subarray(0, pageLen)); + this._consume(pageLen); + + if (this._oggPagesKept < 2) { + // OpusHead (BOS) + OpusTags pages must survive for the demuxer. + this._oggPagesKept++; + this.push(page); + continue; + } + + const isFiller = granule === -1n || granule === 0xffffffffffffffffn; + if (!isFiller && granule >= this._targetMs * OPUS_SAMPLE_RATE) { + for (const p of this._oggReplay) this.push(p); + this._oggReplay = []; + this._startPassthrough(page); + return; + } + + // Page ends before the target → drop, but remember recent ones so + // packets spanning into the kept page stay complete. + this._oggReplay.push(page); + while (this._oggReplay.length > OGG_REPLAY_PAGES) this._oggReplay.shift(); + } + } + + /** + * @param {Buffer} magic + * @returns {boolean} + * @private + */ + _startsWith(magic) { + if (this._buf.length < magic.length) return false; + return this._buf.subarray(0, magic.length).equals(magic); + } + + /** + * Drop `n` consumed bytes from the internal buffer. + * @param {number} n + * @private + */ + _consume(n) { + if (n <= 0) return; + if (n >= this._buf.length) { + this._buf = Buffer.alloc(0); + return; + } + this._buf = Buffer.from(this._buf.subarray(n)); + } + + /** Validate magic bytes once on the first chunk. @internal */ + static sniffKind(head) { + if (head.length >= 4 && head.subarray(0, 4).equals(WEBM_MAGIC)) return "webm"; + if (head.length >= 4 && head.subarray(0, 4).equals(OGG_MAGIC)) return "ogg"; + return null; + } +} + +export default StreamPositioner; diff --git a/src/music/player/PlaybackMixin.mjs b/src/music/player/PlaybackMixin.mjs index a7ca116..72dadec 100644 --- a/src/music/player/PlaybackMixin.mjs +++ b/src/music/player/PlaybackMixin.mjs @@ -14,6 +14,7 @@ import { Utils, cleanId } from "../../utils/Utils.mjs"; import { logger } from "../../core/Logger.mjs"; import meta from "../probe.mjs"; import { getBilibiliStreamUrl } from "../bilibili/index.mjs"; +import { isLoadstreamEnabled } from "../audio/AudioSettings.mjs"; /** * @type {object} @@ -477,7 +478,9 @@ const PlaybackMixin = { /** * @async Apply an audio filter to playback. Stores filter metadata for * dashboard tracking; filters are applied server-side by NodeLink on the - * next track. + * next track. Requires the loadstream route (config.json -> + * audio.allowLoadstream) — NodeLink server-side effects cannot run when the + * bot is in trackstream-only mode, so activation is rejected with a reason. * @this {import('./Player.mjs').Player} * @param {object} filterPayload * @param {object|null} [filterMeta=null] @@ -488,6 +491,14 @@ const PlaybackMixin = { return { ok: false, reason: "Player not bound to a guild." }; } + if (filterMeta && !isLoadstreamEnabled()) { + logger.warn("[Player] applyFilter rejected — loadstream route disabled (audio.allowLoadstream), filters are NodeLink server-side effects"); + return { + ok: false, + reason: "filters need the NodeLink loadstream route — set audio.allowLoadstream to true in config.json; playback is unfiltered in trackstream mode", + }; + } + const current = this.queue.getCurrent(); this.activeFilter = filterMeta ?? null;