mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
feat: add WebM codec validation and demuxer error handling in audio streaming
This commit is contained in:
1 parent
952924cdd5
commit
4bc2a98bab
2 files changed
+96
-33
No files matched your search
@@ -140,8 +140,10 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
if (routed.kind === "webm") {
|
if (routed.kind === "webm") {
|
||||||
logger.player("[AudioBridge] Playing loadstream webm/opus passthrough: " + (trackInfo.title || "unknown") +
|
logger.player("[AudioBridge] Playing loadstream webm/opus passthrough: " + (trackInfo.title || "unknown") +
|
||||||
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : ""));
|
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : ""));
|
||||||
|
await this._assertWebmOpus(routed.stream);
|
||||||
this._stream = routed.stream;
|
this._stream = routed.stream;
|
||||||
await conn.play(routed.stream);
|
await conn.play(routed.stream);
|
||||||
|
this._guardDemuxer(conn);
|
||||||
} else if (routed.kind === "ogg") {
|
} else if (routed.kind === "ogg") {
|
||||||
logger.player("[AudioBridge] Playing loadstream ogg/opus (remux to webm): " + (trackInfo.title || "unknown"));
|
logger.player("[AudioBridge] Playing loadstream ogg/opus (remux to webm): " + (trackInfo.title || "unknown"));
|
||||||
const oggResult = await this._remuxOggToWebM(routed.stream);
|
const oggResult = await this._remuxOggToWebM(routed.stream);
|
||||||
@@ -202,8 +204,10 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
const routed = await this._routeByMagic(stream);
|
const routed = await this._routeByMagic(stream);
|
||||||
if (routed.kind === "webm") {
|
if (routed.kind === "webm") {
|
||||||
logger.player("[AudioBridge] Route 3a: webm/opus passthrough: " + (trackInfo.title || "unknown"));
|
logger.player("[AudioBridge] Route 3a: webm/opus passthrough: " + (trackInfo.title || "unknown"));
|
||||||
|
await this._assertWebmOpus(routed.stream);
|
||||||
this._stream = routed.stream;
|
this._stream = routed.stream;
|
||||||
await conn.play(routed.stream);
|
await conn.play(routed.stream);
|
||||||
|
this._guardDemuxer(conn);
|
||||||
} else if (routed.kind === "ogg") {
|
} else if (routed.kind === "ogg") {
|
||||||
logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown"));
|
logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown"));
|
||||||
const oggResult = await this._remuxOggToWebM(routed.stream);
|
const oggResult = await this._remuxOggToWebM(routed.stream);
|
||||||
@@ -259,8 +263,10 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
this._sourceReq = loaded3c.req || null;
|
this._sourceReq = loaded3c.req || null;
|
||||||
if (routed3c.kind === "webm") {
|
if (routed3c.kind === "webm") {
|
||||||
logger.player("[AudioBridge] Route 3c (loadstream): webm/opus passthrough");
|
logger.player("[AudioBridge] Route 3c (loadstream): webm/opus passthrough");
|
||||||
|
await this._assertWebmOpus(routed3c.stream);
|
||||||
this._stream = routed3c.stream;
|
this._stream = routed3c.stream;
|
||||||
await conn.play(routed3c.stream);
|
await conn.play(routed3c.stream);
|
||||||
|
this._guardDemuxer(conn);
|
||||||
} else if (routed3c.kind === "ogg") {
|
} else if (routed3c.kind === "ogg") {
|
||||||
logger.player("[AudioBridge] Route 3c (loadstream): ogg/opus remux to webm");
|
logger.player("[AudioBridge] Route 3c (loadstream): ogg/opus remux to webm");
|
||||||
const oggResult3c = await this._remuxOggToWebM(routed3c.stream);
|
const oggResult3c = await this._remuxOggToWebM(routed3c.stream);
|
||||||
@@ -375,6 +381,7 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
}
|
}
|
||||||
this._stream = opened.stream;
|
this._stream = opened.stream;
|
||||||
await conn.play(opened.stream);
|
await conn.play(opened.stream);
|
||||||
|
this._guardDemuxer(conn);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
if (this._stopped || !this._playing) return "stopped";
|
if (this._stopped || !this._playing) return "stopped";
|
||||||
@@ -549,6 +556,9 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
} catch (e3) {
|
} catch (e3) {
|
||||||
if (stale()) return "stopped";
|
if (stale()) return "stopped";
|
||||||
logger.player("[AudioBridge] trackstream direct URL not playable in-process (" + e3.message + ")");
|
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;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -561,36 +571,22 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
(trackInfo.title || "unknown"));
|
(trackInfo.title || "unknown"));
|
||||||
|
|
||||||
try {
|
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);
|
const opened = await this._openPositionedStream(direct.url, seekMs);
|
||||||
if (stale()) {
|
if (stale()) {
|
||||||
opened.stream.destroy();
|
opened.stream.destroy();
|
||||||
return "stopped";
|
return "stopped";
|
||||||
}
|
}
|
||||||
return await this._playOpened(conn, opened, durationMs, generation);
|
return await this._playOpened(conn, opened, durationMs, generation);
|
||||||
}
|
|
||||||
// Zero-copy: the voice connection fetches the URL itself.
|
|
||||||
await conn.play(direct.url);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (stale()) return "stopped";
|
if (stale()) return "stopped";
|
||||||
if (this._stopped || !this._playing) 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);
|
logger.warn("[AudioBridge] Trackstream playback failed, falling back: " + e.message);
|
||||||
return null;
|
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 current playback and clean up resources. */
|
||||||
|
|||||||
@@ -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. */
|
/** @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");
|
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). */
|
/** @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)";
|
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 positioner = new StreamPositioner({ kind: routed.kind, seekMs });
|
||||||
const out = routed.stream.pipe(positioner);
|
const out = routed.stream.pipe(positioner);
|
||||||
logger.player("[AudioBridge] Positioned stream open (kind=" + routed.kind + ", seek=" + seekMs + "ms)");
|
logger.player("[AudioBridge] Positioned stream open (kind=" + routed.kind + ", seek=" + seekMs + "ms)");
|
||||||
return { stream: out, kind: routed.kind };
|
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<void>}
|
||||||
|
* @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
|
* 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
|
* bytes back so nothing is lost. MP4/M4A/MOV (ISOBMFF) is detected via the
|
||||||
@@ -245,34 +304,42 @@ const StreamPipeline = {
|
|||||||
*/
|
*/
|
||||||
_peek(stream, n) {
|
_peek(stream, n) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const tryRead = () => {
|
|
||||||
const chunks = [];
|
const chunks = [];
|
||||||
let total = 0;
|
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;
|
let chunk;
|
||||||
while (total < n && (chunk = stream.read()) !== null) {
|
while (total < n && (chunk = stream.read()) !== null) {
|
||||||
chunks.push(chunk);
|
chunks.push(chunk);
|
||||||
total += chunk.length;
|
total += chunk.length;
|
||||||
}
|
}
|
||||||
if (total >= n || stream.readableEnded) {
|
const ended = stream.readableEnded || stream._readableState?.ended === true;
|
||||||
const buf = Buffer.concat(chunks);
|
if (total >= n || ended) finish();
|
||||||
|
};
|
||||||
|
const onError = (err) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
cleanup();
|
cleanup();
|
||||||
if (buf.length > 0) stream.unshift(buf);
|
reject(err);
|
||||||
resolve(buf.subarray(0, n));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
const onReadable = () => { cleanup(); tryRead(); };
|
|
||||||
const onEnd = () => { cleanup(); tryRead(); };
|
|
||||||
const onError = (err) => { cleanup(); reject(err); };
|
|
||||||
const cleanup = () => {
|
const cleanup = () => {
|
||||||
stream.off("readable", onReadable);
|
stream.off("readable", drain);
|
||||||
stream.off("end", onEnd);
|
stream.off("end", finish);
|
||||||
stream.off("error", onError);
|
stream.off("error", onError);
|
||||||
};
|
};
|
||||||
stream.once("readable", onReadable);
|
stream.on("readable", drain);
|
||||||
stream.once("end", onEnd);
|
stream.once("end", finish);
|
||||||
stream.once("error", onError);
|
stream.once("error", onError);
|
||||||
tryRead();
|
drain();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user