diff --git a/commands/play.mjs b/commands/play.mjs index 62a3ba2..f5a6b47 100644 --- a/commands/play.mjs +++ b/commands/play.mjs @@ -95,6 +95,60 @@ function parseLastFmTrackQuery(raw) { return null; } +/** @type {RegExp} Known music-service URL patterns that should go through Lavalink search. */ +const KNOWN_SERVICE_HOSTS = /(?:youtu(?:be\.com|\.be)|youtube\.com|music\.youtube\.com|open\.spotify\.com|soundcloud\.com|deezer\.com|music\.apple\.com|tidal\.com|bandcamp\.com|last\.fm|mixcloud\.com|tunein\.com)/i; + +/** Audio file extensions for formats the bridge handles natively (no Lavalink needed). */ +const NATIVE_AUDIO_EXTENSIONS = /\.(?:opus|webm|ogg)(?:\?|$)/i; + +/** Audio file extensions that indicate any direct audio URL (broader set). */ +const AUDIO_EXTENSIONS = /\.(?:mp3|m4a|aac|ogg|opus|flac|wav|wma|webm|stream|m3u8|pls)(?:\?|$)/i; + +/** Common stream/radio content-type paths or patterns. */ +const STREAM_PATH_HINTS = /\/(?:stream|live|radio|audio|playlist|play|listen|mp3|aac|ogg)/i; + +/** + * Check if a URL points to an audio format the FluxerAudioBridge handles natively + * (Opus, WebM, OGG) — no Lavalink resolution needed, goes straight to playExternal. + * @param {string} str + * @returns {boolean} + */ +function isNativeAudioUrl(str) { + if (!str || typeof str !== "string") return false; + const trimmed = str.trim(); + if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) return false; + try { + const url = new URL(trimmed); + if (KNOWN_SERVICE_HOSTS.test(url.hostname)) return false; + return NATIVE_AUDIO_EXTENSIONS.test(url.pathname); + } catch (_) {} + return false; +} + +/** + * Check if a URL looks like a direct audio stream/file rather than a music-service page. + * Excludes known service URLs (YouTube, Spotify, etc.) which should use Lavalink search. + * + * @param {string} str - The raw query string. + * @returns {boolean} True if this looks like a direct audio URL. + */ +function isDirectAudioUrl(str) { + if (!str || typeof str !== "string") return false; + const trimmed = str.trim(); + if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) return false; + try { + const url = new URL(trimmed); + if (KNOWN_SERVICE_HOSTS.test(url.hostname)) return false; + if (AUDIO_EXTENSIONS.test(url.pathname)) return true; + if (STREAM_PATH_HINTS.test(url.pathname) && !url.pathname.includes(".html") && !url.pathname.includes(".php")) { + return true; + } + if (/:80\d{0,2}\//.test(trimmed) || /:8\d{3}\//.test(trimmed)) return true; + } catch (_) {} + return false; +} + + /** * @type {CommandBuilder} * @description Command definition for the play command. @@ -106,6 +160,7 @@ export const command = new CommandBuilder() .setDescription( "Play a song or playlist from a URL or search query.\n" + "Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, and more.\n" + + "Also accepts direct audio URLs (MP3, OGG, AAC, radio streams).\n" + "Default search: YouTube Music. Use `-p ` or inline prefix e.g. `sp: blinding lights`.", "commands.play" ) @@ -115,6 +170,8 @@ export const command = new CommandBuilder() "$prefixplay dz: get lucky", "$prefixplay -p yt take over league of legends", "$prefixplay https://open.spotify.com/track/...", + "$prefixplay https://example.com/stream.mp3", + "$prefixplay https://radio.example.com:8000/live", "$prefixplay https://www.last.fm/music/Drake/_/Make+Them+Cry", "$prefixplay lastfm:loved", "$prefixplay lastfm:soda pop", @@ -151,6 +208,44 @@ export async function run(message, data) { const { provider: inlineProvider, query } = parseInlineProvider(rawQuery); const provider = inlineProvider ?? flagProvider ?? "ytm"; + if (isNativeAudioUrl(rawQuery)) { + const p = await this.getPlayer(message, true, true, true); + if (!p) return; + + const statusEmbed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setDescription(":mag_right: Loading direct stream..."); + let statusMsg = null; + try { statusMsg = await message.reply({ embeds: [statusEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); } + + const messages = p.playExternal(rawQuery); + messages.on("message", d => { + const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d); + if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); } + else { message.reply({ embeds: [embed] }).catch(() => {}); } + }); + return; + } + + if (isDirectAudioUrl(rawQuery)) { + const p = await this.getPlayer(message, true, true, true); + if (!p) return; + + const statusEmbed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setDescription(":mag_right: Resolving stream via Lavalink..."); + let statusMsg = null; + try { statusMsg = await message.reply({ embeds: [statusEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); } + + const messages = p.playExternal(rawQuery, null, null, false, "stream"); + messages.on("message", d => { + const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d); + if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); } + else { message.reply({ embeds: [embed] }).catch(() => {}); } + }); + return; + } + if (isLastFmUrl(rawQuery) || isLastFmUrl(query)) { const lfUrl = isLastFmUrl(rawQuery) ? rawQuery : query; const parsed = parseLastFmUrl(lfUrl); diff --git a/src/FluxerAudioBridge.mjs b/src/FluxerAudioBridge.mjs index e4cc0ff..c3fb09e 100644 --- a/src/FluxerAudioBridge.mjs +++ b/src/FluxerAudioBridge.mjs @@ -1,7 +1,7 @@ -/** @module src/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. */ +/** @module src/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. */ import { logger } from "./constants/Logger.mjs"; -import { WebMOpusMuxer } from "./constants/audio/WebMOpusMuxer.mjs"; +import { WebMOpusMuxer, OPUS_FRAME_MS } from "./constants/audio/WebMOpusMuxer.mjs"; import { EventEmitter } from "node:events"; import { Readable } from "node:stream"; import http from "node:http"; @@ -13,6 +13,15 @@ const { Encoder: PrismOpusEncoder, OggDemuxer: PrismOggDemuxer } = prismMedia.op /** @type {number} @description Maximum number of HTTP redirect hops to follow. */ const MAX_REDIRECTS = 5; +/** @type {number} @description Timeout (ms) for HTTP requests to Lavalink REST endpoints (trackstream, loadtracks JSON). */ +const REST_REQUEST_TIMEOUT_MS = 15_000; + +/** @type {number} @description Timeout (ms) to wait for the first byte from loadstream (Lavalink may need time to resolve HLS/external streams). */ +const LOADSTREAM_CONNECT_TIMEOUT_MS = 60_000; + +/** @type {number} @description Idle timeout (ms) once loadstream data is flowing — if no data arrives for this long, abort. */ +const LOADSTREAM_IDLE_TIMEOUT_MS = 30_000; + /** @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. */ @@ -91,10 +100,9 @@ export class FluxerAudioBridge extends EventEmitter { this._usedTrackstream = false; const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000); - const durationMs = options.durationMs || 0; + let durationMs = options.durationMs || 0; try { - // --- Route 1: trackstream passthrough (no re-encode at all) --- if (seekMs === 0 && !options.filterPayload && trackInfo.encoded && this._lavalink) { try { const direct = await this._getTrackstreamUrl(trackInfo); @@ -115,7 +123,38 @@ export class FluxerAudioBridge extends EventEmitter { } return "stopped"; } - logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct?.format || "?") + "), using loadstream"); + 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; @@ -124,7 +163,6 @@ export class FluxerAudioBridge extends EventEmitter { } } - // --- Route 2: loadstream (PCM -> in-process Opus encode -> WebM) --- if (trackInfo.encoded && this._lavalink) { const loaded = await this._streamFromLoadstream(trackInfo, seekMs, options.filterPayload); if (generation !== this._playGeneration) { @@ -137,17 +175,19 @@ export class FluxerAudioBridge extends EventEmitter { if (routed.kind === "webm") { logger.player("[AudioBridge] Playing loadstream webm/opus passthrough: " + (trackInfo.title || "unknown") + - (seekMs > 0 ? " [seek: " + seekMs + "ms]" : "")); + (seekMs > 0 ? " [seek: " + seekMs + "ms]" : "")); this._stream = routed.stream; await conn.play(routed.stream); } else if (routed.kind === "ogg") { logger.player("[AudioBridge] Playing loadstream ogg/opus (remux to webm): " + (trackInfo.title || "unknown")); - this._stream = await this._remuxOggToWebM(routed.stream); + const oggResult = await this._remuxOggToWebM(routed.stream); + this._stream = oggResult; + if (durationMs <= 0) durationMs = oggResult.getDurationMs(); await conn.play(this._stream); } else { logger.player("[AudioBridge] Playing via loadstream PCM -> in-process Opus: " + (trackInfo.title || "unknown") + - (seekMs > 0 ? " [seek: " + seekMs + "ms]" : "") + - (options.filterPayload ? " [filters]" : "")); + (seekMs > 0 ? " [seek: " + seekMs + "ms]" : "") + + (options.filterPayload ? " [filters]" : "")); this._stream = this._buildPcmPipeline(routed.stream); await conn.play(this._stream); } @@ -164,9 +204,8 @@ export class FluxerAudioBridge extends EventEmitter { return "stopped"; } - // --- Route 3: direct URL fallback (magic sniff: webm passthrough / ogg remux) --- if (trackInfo.url && trackInfo.url.startsWith("http")) { - logger.player("[AudioBridge] Fetching directly: " + trackInfo.url.substring(0, 80) + "..."); + 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)" }, redirect: "follow", @@ -179,15 +218,90 @@ export class FluxerAudioBridge extends EventEmitter { const routed = await this._routeByMagic(stream); if (routed.kind === "webm") { + logger.player("[AudioBridge] Route 3a: webm/opus passthrough: " + (trackInfo.title || "unknown")); this._stream = routed.stream; await conn.play(routed.stream); } else if (routed.kind === "ogg") { - this._stream = await this._remuxOggToWebM(routed.stream); + logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown")); + const oggResult = await this._remuxOggToWebM(routed.stream); + this._stream = oggResult; await conn.play(this._stream); + if (generation !== this._playGeneration) return "stopped"; + + await new Promise(r => { + if (this._stream.readableEnded) return r(); + const done = () => { this._stream.off("end", done); this._stream.off("close", done); r(); }; + this._stream.once("end", done); + this._stream.once("close", done); + }); + if (generation !== this._playGeneration) return "stopped"; + + const fullDurationMs = oggResult.getDurationMs(); + const elapsedMs = Date.now() - this._startedAt; + const remainingMs = Math.max(0, fullDurationMs - elapsedMs); + logger.player("[AudioBridge] Route 3b: OGG " + fullDurationMs + "ms total, " + elapsedMs + "ms elapsed, waiting " + remainingMs + "ms more"); + + if (remainingMs > 0) await this._awaitEnd(remainingMs); + if (generation !== this._playGeneration) return "stopped"; + + if (this._playing && !this._stopped) { + this._playing = false; + logger.player("[AudioBridge] Track finished naturally (direct URL, OGG remux)"); + return "finished"; + } + return "stopped"; } else { + stream.destroy(); + 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); + if (generation !== this._playGeneration) { + loaded.stream.destroy(); + return "stopped"; + } + + const routed2 = await this._routeByMagic(loaded.stream); + this._sourceStream = loaded.stream; + + 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); + 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); + await conn.play(this._stream); + } + 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 (Route 3c Lavalink resolve)"); + return "finished"; + } + return "stopped"; + } + } + throw new Error( - "[AudioBridge] Direct URL is not WebM/Opus or Ogg/Opus (" + routed.kind + "). " + - "Resolve the track through the Lavalink node instead — in-process playback has no FFmpeg decoder." + "[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." ); } if (generation !== this._playGeneration) return "stopped"; @@ -225,36 +339,35 @@ export class FluxerAudioBridge extends EventEmitter { * @private */ _awaitEnd(durationMs) { return new Promise((resolve, reject) => { - this._endResolve = resolve; - this._endReject = reject; - const failFast = (err) => { - if (this._playing && !this._stopped) { - this._playing = false; - reject(err); - } else { - resolve(); - } - }; - - if (durationMs > 0) { - this._durationTimer = setTimeout(resolve, durationMs); + this._endResolve = resolve; + this._endReject = reject; + const failFast = (err) => { + if (this._playing && !this._stopped) { + this._playing = false; + reject(err); } else { - // No duration info (radio/live): wait until the WebM stream is fully consumed. - const stream = this._stream; - if (!stream) return resolve(); - const onEnd = () => resolve(); - stream.once("end", onEnd); - stream.once("close", onEnd); - stream.once("error", failFast); + resolve(); } + }; - if (this._sourceStream) { - this._sourceStream.once("error", failFast); - } - if (this._encoder) { - this._encoder.once("error", failFast); - } - }); + if (durationMs > 0) { + this._durationTimer = setTimeout(resolve, durationMs); + } else { + const stream = this._stream; + if (!stream) return resolve(); + const onEnd = () => resolve(); + stream.once("end", onEnd); + stream.once("close", onEnd); + stream.once("error", failFast); + } + + if (this._sourceStream) { + this._sourceStream.once("error", failFast); + } + if (this._encoder) { + this._encoder.once("error", failFast); + } + }); } /** @@ -312,7 +425,6 @@ export class FluxerAudioBridge extends EventEmitter { resolve(buf.subarray(0, n)); return; } - waitForMore(); }; const onReadable = () => { cleanup(); tryRead(); }; const onEnd = () => { cleanup(); tryRead(); }; @@ -346,7 +458,7 @@ export class FluxerAudioBridge extends EventEmitter { } catch (e) { pcmStream.destroy(); throw new Error( - "No Opus encoder available (" + e.message + "). Install one: npm install @discordjs/opus (or opusscript)" + "No Opus encoder available (" + e.message + "). Install one: npm install @discordjs/opus (or opusscript)" ); } try { encoder.setBitrate(OPUS_BITRATE); } catch (_) {} @@ -369,7 +481,7 @@ export class FluxerAudioBridge extends EventEmitter { /** * Remux an Ogg/Opus stream into WebM/Opus (packet-level, no re-encode). * @param {Readable} oggStream - * @returns {Promise} + * @returns {Promise<{stream: WebMOpusMuxer, getDurationMs: function}>} * @private */ async _remuxOggToWebM(oggStream) { @@ -377,7 +489,8 @@ export class FluxerAudioBridge extends EventEmitter { const muxer = new WebMOpusMuxer(); oggStream.on("error", (err) => demuxer.destroy(err)); demuxer.on("error", (err) => muxer.destroy(err)); - // Wait for the OpusHead so we reject non-Opus OGG early with a clear error. + let frameCount = 0; + demuxer.on("data", () => { frameCount++; }); const headPromise = new Promise((resolve, reject) => { demuxer.once("head", () => resolve()); demuxer.once("error", (err) => reject(new Error("OGG demux: " + err.message))); @@ -385,7 +498,9 @@ export class FluxerAudioBridge extends EventEmitter { }); oggStream.pipe(demuxer).pipe(muxer); await headPromise; - return muxer; + const wrapper = Object.create(muxer); + wrapper.getDurationMs = () => frameCount * OPUS_FRAME_MS; + return wrapper; } /** @@ -453,13 +568,61 @@ export class FluxerAudioBridge extends EventEmitter { return this._httpRequestStream(url, headers); } + /** + * Resolve a direct audio URL through Lavalink's /v4/loadtracks to get an encoded track. + * This allows MP3/AAC radio streams and direct audio URLs to be played through + * the loadstream pipeline without any FFmpeg dependency. + * @param {string} url - The HTTP(S) audio stream URL to resolve. + * @param {string} [guildId] - Optional guild ID for the request. + * @returns {Promise} The encoded track string, or null if resolution failed. + * @private + */ + async _resolveUrlViaLavalink(url, guildId) { + try { + const nlInfo = this._lavalink.getNodeLinkInfo?.(); + if (!nlInfo) { + logger.warn("[AudioBridge] _resolveUrlViaLavalink: no NodeLink info"); + return null; + } + + 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 (guildId) headers["Guild-Id"] = guildId; + + const params = "identifier=" + encodeURIComponent(url); + const loadtracksUrl = baseUrl + "/v4/loadtracks?" + params; + + logger.player("[AudioBridge] Resolving URL via Lavalink /v4/loadtracks: " + url.substring(0, 80) + "..."); + + const body = await this._httpGetJson(loadtracksUrl, headers, 0, 30_000); + + const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data; + const encoded = track?.encoded ?? track?.data; + + if (encoded && typeof encoded === "string") { + logger.player("[AudioBridge] Lavalink resolved URL to encoded track successfully"); + return encoded; + } + + const loadType = body?.loadType ?? body?.data?.loadType; + logger.warn("[AudioBridge] Lavalink loadtracks returned no playable track (loadType=" + loadType + ")"); + return null; + } catch (e) { + logger.warn("[AudioBridge] _resolveUrlViaLavalink failed: " + e.message); + return null; + } + } + /** * @param {string} url * @param {object} [headers] * @returns {Promise} * @private */ - _httpGetJson(url, headers = {}, _redirectCount = 0) { + _httpGetJson(url, headers = {}, _redirectCount = 0, timeoutMs = REST_REQUEST_TIMEOUT_MS) { return new Promise((resolve, reject) => { if (_redirectCount >= MAX_REDIRECTS) { return reject(new Error("Too many redirects (" + _redirectCount + ")")); @@ -479,7 +642,7 @@ export class FluxerAudioBridge extends EventEmitter { res.resume(); let loc = res.headers.location; if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc; - return this._httpGetJson(loc, headers, _redirectCount + 1).then(resolve, reject); + return this._httpGetJson(loc, headers, _redirectCount + 1, timeoutMs).then(resolve, reject); } if (res.statusCode !== 200) { let body = ""; @@ -502,9 +665,9 @@ export class FluxerAudioBridge extends EventEmitter { }); req.on("error", reject); - req.setTimeout(15_000, () => { + req.setTimeout(timeoutMs, () => { req.destroy(); - reject(new Error("trackstream timeout (15s)")); + reject(new Error("REST request timeout (" + timeoutMs / 1000 + "s)")); }); req.end(); }); @@ -525,6 +688,18 @@ export class FluxerAudioBridge extends EventEmitter { const urlObj = new URL(url); const client = urlObj.protocol === "https:" ? https : http; + let firstByte = true; + let connectTimer = null; + let idleTimer = null; + + const resetIdleTimeout = () => { + if (idleTimer) clearTimeout(idleTimer); + idleTimer = setTimeout(() => { + req.destroy(); + reject(new Error("loadstream idle timeout (" + LOADSTREAM_IDLE_TIMEOUT_MS / 1000 + "s no data)")); + }, LOADSTREAM_IDLE_TIMEOUT_MS); + idleTimer.unref?.(); + }; const req = client.request({ protocol: urlObj.protocol, @@ -535,6 +710,7 @@ export class FluxerAudioBridge extends EventEmitter { headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers }, }, (res) => { if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; } res.resume(); let nextHeaders = headers; let loc = res.headers.location; @@ -549,6 +725,7 @@ export class FluxerAudioBridge extends EventEmitter { return this._httpRequestStream(loc, nextHeaders, _redirectCount + 1).then(resolve, reject); } if (res.statusCode !== 200) { + if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; } let body = ""; res.on("data", (chunk) => { body += chunk; }); res.on("end", () => { @@ -557,15 +734,26 @@ export class FluxerAudioBridge extends EventEmitter { return; } + if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; } + resetIdleTimeout(); + res.once("data", () => resetIdleTimeout()); + logger.player("[AudioBridge] loadstream response: " + res.statusCode + " content-type=" + (res.headers["content-type"] || "?")); resolve({ stream: res, inputFormat: res.headers["content-type"] || null }); }); - req.on("error", reject); - req.setTimeout(30_000, () => { - req.destroy(); - reject(new Error("loadstream timeout (30s)")); + req.on("error", (err) => { + if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; } + if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } + reject(err); }); + + connectTimer = setTimeout(() => { + req.destroy(); + reject(new Error("loadstream connect timeout (" + LOADSTREAM_CONNECT_TIMEOUT_MS / 1000 + "s — Lavalink took too long to start stream)")); + }, LOADSTREAM_CONNECT_TIMEOUT_MS); + connectTimer.unref?.(); + req.end(); }); } @@ -614,7 +802,6 @@ export class FluxerAudioBridge extends EventEmitter { } catch (_) {} } } catch (_) { - // Never let cleanup break playback. } } diff --git a/src/Player.mjs b/src/Player.mjs index 8141a86..33aa861 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -1134,7 +1134,7 @@ export default class Player extends EventEmitter { ? `[Radio]: ${vid.title} - ${vid.author?.url || ""}` : `[Radio] [${vid.title} by ${vid.author?.name || "Unknown"}](${vid.author?.url || ""})`; } - if (vid.type === "external") { + if (vid.type === "external" || vid.type === "stream") { return code ? `${vid.title} - ${vid.url}` : `[${vid.title}](${vid.url})`; @@ -1232,7 +1232,7 @@ export default class Player extends EventEmitter { } } - if (current.type === "external") { + if (current.type === "external" || current.type === "stream") { const totalMs = this._getTrackDurationMs(current); let progressLine = ""; @@ -1304,11 +1304,18 @@ export default class Player extends EventEmitter { ? s.artists.map(a => a.url ? `[${a.name}](${a.url})` : a.name).join(" & ") : s.author?.url ? `[${s.author.name}](${s.author.url})` - : s.author?.name || "Unknown"; + : s.author?.name || null; + + if (!author && (s.type === "external" || s.type === "stream")) { + const desc = "🎵 Now playing [" + Utils.escapeMarkdown(s.title) + "](" + (s.url || "") + ") in <#" + (this._channelId || "") + ">"; + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }); + return; + } + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.play.nowPlaying", { title: Utils.escapeMarkdown(s.title), url: s.spotifyUrl || s.url, - author: author, + author: author || "Unknown", channel: this._channelId || "", }))] }); } @@ -1555,6 +1562,64 @@ export default class Player extends EventEmitter { if (!this.leaving) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); } + /** @private Build a direct-URL track object. @param {string} url @param {string} [title] @param {string} [artist] @param {string} [trackType="external"] @returns {object} */ + _buildExternalTrack(url, title = null, artist = null, trackType = "external") { + const displayTitle = title || this._extractFilenameFromUrl(url); + return { + type: trackType, + title: displayTitle, + url: url, + artist: artist || null, + thumbnail: null, + }; + } + + /** @private Extract a display filename from a URL. @param {string} url @returns {string} */ + _extractFilenameFromUrl(url) { + try { + const pathname = new URL(url).pathname; + const filename = pathname.split("/").pop(); + if (filename && filename.includes(".")) { + return decodeURIComponent(filename.replace(/\.[^.]+$/, "")) || "Stream"; + } + } catch (_) {} + return "External Stream"; + } + + /** + * Play a direct audio URL (MP3, OGG, AAC, stream, etc.) without Lavalink search. + * The bridge handles decoding via Lavalink if needed. No FFmpeg required. + * @param {string} url - Direct HTTP(S) audio URL. + * @param {string} [title] - Optional display title. + * @param {string} [artist] - Optional artist name. + * @param {boolean} [top=false] - Insert at top of queue. + * @param {string} [trackType="external"] - Track type: "external" (no pre-resolve) or "stream" (Lavalink pre-resolve). + * @returns {EventEmitter} Emitter that emits "message" events with status strings. + */ + playExternal(url, title = null, artist = null, top = false, trackType = "external") { + const events = new EventEmitter(); + + (async () => { + try { + const track = this._buildExternalTrack(url, title, artist, trackType); + this.addToQueue(track, top); + events.emit("message", "Added **[" + track.title + "](" + url + ")** to the queue."); + + if (!this.queue.getCurrent()) { + this.playNext().catch(e => { + logger.error("[Player] playExternal playNext error:", e.message); + events.emit("message", "Error playing stream: " + e.message); + }); + } + } catch (err) { + logger.error("[Player] playExternal error:", err?.message); + events.emit("message", "Error: " + (err?.message || "Failed to add external stream.")); + } + })(); + + return events; + } + /** @private @async Advance to the next track. */ async playNext() { if (this._playingNext) return; @@ -1691,7 +1756,10 @@ export default class Player extends EventEmitter { } } - /** @private @async Play a track through the FluxerAudioBridge. @param {object} songData @param {object} [options={}] @returns {Promise} */ + /** @private @async Play a track through the FluxerAudioBridge. For radio/external tracks + * without an encoded payload, attempts Lavalink URL resolution first so MP3/AAC + * streams can use the loadstream pipeline instead of the limited direct-URL path. + * @param {object} songData @param {object} [options={}] @returns {Promise} */ async _playTrackViaBridge(songData, options = {}) { if (!this._voiceConn || !this._audioBridge) { throw new Error("No voice connection or audio bridge available"); @@ -1700,6 +1768,35 @@ export default class Player extends EventEmitter { throw new Error("No encoded track or URL for: " + (songData?.title ?? "unknown")); } + if (!songData.encoded && songData.url && songData.url.startsWith("http") && this._lavalink && songData.type !== "external") { + try { + 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(songData.url); + logger.player(`[Player] Pre-resolving ${songData.type || "external"} URL via Lavalink...`); + + const body = await this._request(loadtracksUrl, { headers }); + const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data; + const encoded = track?.encoded ?? track?.data; + + if (encoded && typeof encoded === "string") { + songData.encoded = encoded; + logger.player("[Player] Lavalink pre-resolve succeeded — track now has encoded payload"); + } else { + logger.player("[Player] Lavalink pre-resolve: no encoded track returned, bridge will try direct URL"); + } + } + } catch (e) { + logger.warn("[Player] Lavalink pre-resolve failed (bridge will try direct URL): " + e.message); + } + } + this._audioBridge._conn = this._voiceConn; const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000);