diff --git a/src/music/audio/FluxerAudioBridge.mjs b/src/music/audio/FluxerAudioBridge.mjs index 8581a1d..f2e7980 100644 --- a/src/music/audio/FluxerAudioBridge.mjs +++ b/src/music/audio/FluxerAudioBridge.mjs @@ -140,8 +140,10 @@ 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]" : "")); + await this._assertWebmOpus(routed.stream); this._stream = routed.stream; await conn.play(routed.stream); + this._guardDemuxer(conn); } else if (routed.kind === "ogg") { logger.player("[AudioBridge] Playing loadstream ogg/opus (remux to webm): " + (trackInfo.title || "unknown")); const oggResult = await this._remuxOggToWebM(routed.stream); @@ -202,8 +204,10 @@ 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")); + await this._assertWebmOpus(routed.stream); this._stream = routed.stream; await conn.play(routed.stream); + this._guardDemuxer(conn); } else if (routed.kind === "ogg") { logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown")); const oggResult = await this._remuxOggToWebM(routed.stream); @@ -259,8 +263,10 @@ export class FluxerAudioBridge extends EventEmitter { this._sourceReq = loaded3c.req || null; if (routed3c.kind === "webm") { logger.player("[AudioBridge] Route 3c (loadstream): webm/opus passthrough"); + await this._assertWebmOpus(routed3c.stream); this._stream = routed3c.stream; await conn.play(routed3c.stream); + this._guardDemuxer(conn); } else if (routed3c.kind === "ogg") { logger.player("[AudioBridge] Route 3c (loadstream): ogg/opus remux to webm"); const oggResult3c = await this._remuxOggToWebM(routed3c.stream); @@ -375,6 +381,7 @@ export class FluxerAudioBridge extends EventEmitter { } this._stream = opened.stream; await conn.play(opened.stream); + this._guardDemuxer(conn); } catch (e) { if (generation !== this._playGeneration) return "stopped"; if (this._stopped || !this._playing) return "stopped"; @@ -549,6 +556,9 @@ export class FluxerAudioBridge extends EventEmitter { } catch (e3) { if (stale()) return "stopped"; logger.player("[AudioBridge] trackstream direct URL not playable in-process (" + e3.message + ")"); + if (e3?.code === "WEBM_NOT_OPUS" && !this._stopped) { + return await this._playViaFfmpeg(conn, { ...trackInfo, url: direct.url }, { seekMs, durationMs, generation }); + } return null; } } @@ -561,36 +571,22 @@ export class FluxerAudioBridge extends EventEmitter { (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); + const opened = await this._openPositionedStream(direct.url, seekMs); + if (stale()) { + opened.stream.destroy(); + return "stopped"; } - // Zero-copy: the voice connection fetches the URL itself. - await conn.play(direct.url); + return await this._playOpened(conn, opened, durationMs, generation); } catch (e) { if (stale()) return "stopped"; if (this._stopped || !this._playing) return "stopped"; + if (e?.code === "WEBM_NOT_OPUS") { + logger.warn("[AudioBridge] " + e.message + " — trying local ffmpeg decode"); + return await this._playViaFfmpeg(conn, { ...trackInfo, url: direct.url }, { seekMs, durationMs, generation }); + } 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. */ diff --git a/src/music/audio/StreamPipeline.mjs b/src/music/audio/StreamPipeline.mjs index ab41364..da919ea 100644 --- a/src/music/audio/StreamPipeline.mjs +++ b/src/music/audio/StreamPipeline.mjs @@ -36,6 +36,16 @@ const OGG_MAGIC = Buffer.from("OggS", "ascii"); /** @type {Buffer} @description ISOBMFF box header (MP4/M4A/MOV/3GP family) — sits at byte offset 4, after the 4-byte big-endian box size. */ const FTYP_MAGIC = Buffer.from("ftyp", "ascii"); +/** @type {number} @description Bytes of a WebM stream inspected to find its track codecs (EBML header + Info + Tracks sit at the very start). */ +const WEBM_CODEC_PEEK_BYTES = 16384; +/** @type {Buffer} @description Matroska CodecID of Opus audio. */ +const WEBM_CODEC_OPUS = Buffer.from("A_OPUS", "ascii"); +/** @type {string[]} @description Matroska CodecIDs that @fluxerjs/voice's WebmDemuxer (prism-media) cannot play: any non-Opus audio and any video track (prism throws "Audio codec is not Opus!" on their CodecPrivate). */ +const WEBM_UNSUPPORTED_CODECS = [ + "A_VORBIS", "A_AAC", "A_FLAC", "A_MPEG", "A_AC3", "A_EAC3", "A_DTS", "A_PCM", "A_TTA1", "A_WAVPACK4", + "V_VP8", "V_VP9", "V_AV1", "V_MPEG", "V_MS/", "V_THEORA", "V_REAL", "V_UNCOMPRESSED", "V_PRORES", +]; + /** @type {string} @description User-Agent sent for direct media fetches (kept identical across the bridge and ffmpeg's own HTTP client). */ const HTTP_UA = "Mozilla/5.0 (compatible; Bot/1.0)"; @@ -212,12 +222,61 @@ const StreamPipeline = { ); } + if (routed.kind === "webm") { + try { + await this._assertWebmOpus(routed.stream); + } catch (err) { + loaded.stream.destroy(); + this._sourceStream = null; + this._sourceReq = null; + throw err; + } + } + 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 }; }, + /** + * Verify a WebM stream carries only Opus audio before it is handed to + * conn.play(). @fluxerjs/voice pipes the stream into prism-media's + * WebmDemuxer WITHOUT an error listener, so a Vorbis/AAC/video track makes + * the demuxer throw "Audio codec is not Opus!" as an uncaught exception. + * Detecting it up front lets the caller fall back (ffmpeg) instead. + * The peeked bytes are pushed back, so the stream stays intact. + * @param {Readable} stream - WebM stream (paused mode, magic already sniffed) + * @returns {Promise} + * @throws {Error} err.code === "WEBM_NOT_OPUS" when a non-Opus codec is found + * @private + */ + async _assertWebmOpus(stream) { + const head = await this._peek(stream, WEBM_CODEC_PEEK_BYTES); + const bad = WEBM_UNSUPPORTED_CODECS.find((c) => head.includes(c)); + if (bad) { + const err = new Error("WebM stream is not Opus-only (found " + bad + ") — cannot play without decoding"); + err.code = "WEBM_NOT_OPUS"; + throw err; + } + }, + + /** + * Best-effort safety net: @fluxerjs/voice's internal demuxer has no error + * listener, so any late demux failure (corrupt data, truncated header) + * would crash the process. Attach a logger to it right after play(). + * @param {object} conn - Fluxer voice connection + * @private + */ + _guardDemuxer(conn) { + const demuxer = conn?.currentStream; + if (!demuxer || typeof demuxer.on !== "function" || demuxer.__fluxerGuarded) return; + demuxer.__fluxerGuarded = true; + demuxer.on("error", (err) => { + logger.warn("[AudioBridge] Demuxer error (ignored, track will end): " + (err?.message || err)); + }); + }, + /** * Peek at the first bytes of a stream and classify it, pushing the peeked * bytes back so nothing is lost. MP4/M4A/MOV (ISOBMFF) is detected via the @@ -245,34 +304,42 @@ const StreamPipeline = { */ _peek(stream, n) { return new Promise((resolve, reject) => { - const tryRead = () => { - const chunks = []; - let total = 0; + const chunks = []; + let total = 0; + let settled = false; + + const finish = () => { + if (settled) return; + settled = true; + cleanup(); + const buf = Buffer.concat(chunks); + if (buf.length > 0) stream.unshift(buf); + resolve(buf.subarray(0, n)); + }; + const drain = () => { let chunk; while (total < n && (chunk = stream.read()) !== null) { chunks.push(chunk); total += chunk.length; } - if (total >= n || stream.readableEnded) { - const buf = Buffer.concat(chunks); - cleanup(); - if (buf.length > 0) stream.unshift(buf); - resolve(buf.subarray(0, n)); - return; - } + const ended = stream.readableEnded || stream._readableState?.ended === true; + if (total >= n || ended) finish(); + }; + const onError = (err) => { + if (settled) return; + settled = true; + cleanup(); + reject(err); }; - const onReadable = () => { cleanup(); tryRead(); }; - const onEnd = () => { cleanup(); tryRead(); }; - const onError = (err) => { cleanup(); reject(err); }; const cleanup = () => { - stream.off("readable", onReadable); - stream.off("end", onEnd); + stream.off("readable", drain); + stream.off("end", finish); stream.off("error", onError); }; - stream.once("readable", onReadable); - stream.once("end", onEnd); + stream.on("readable", drain); + stream.once("end", finish); stream.once("error", onError); - tryRead(); + drain(); }); },