mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
rollback
This commit is contained in:
1 parent
4bc2a98bab
commit
500b0de4c8
15 files changed
+134
-714
No files matched your search
+3
-56
@@ -2,8 +2,6 @@
|
||||
* @module commands/play
|
||||
* @description Play a song or playlist from a URL or search query.
|
||||
* Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bilibili, and Last.fm integration.
|
||||
* Audio files attached to the command message (Opus, OGG, WebM, MP3, M4A, AAC, FLAC, WAV)
|
||||
* are played directly when no text query is given.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
@@ -11,7 +9,6 @@ import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mjs";
|
||||
import { getAudioAttachments, attachmentTitle, attachmentTrackMeta, attachmentUrl } from "../src/music/attachments.mjs";
|
||||
import { playLastFmCategory } from "./lastfm.mjs";
|
||||
import { parseLastFmUrl, isLastFmUrl } from "../src/services/lastfm/LastFmManager.mjs";
|
||||
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||
@@ -164,7 +161,6 @@ export const command = new CommandBuilder()
|
||||
"Play a song or playlist from a URL or search query.\n" +
|
||||
"Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bilibili, and more.\n" +
|
||||
"Also accepts direct audio URLs (MP3, OGG, AAC, radio streams) and Bilibili video links (incl. b23.tv and ?p= parts).\n" +
|
||||
"Attach an audio file (Opus, OGG, WebM, MP3, M4A, AAC, FLAC, WAV) to this command with no text to play it directly.\n" +
|
||||
"Default search: YouTube Music. Use `-p <provider>` or inline prefix e.g. `sp: blinding lights`.",
|
||||
"commands.play"
|
||||
)
|
||||
@@ -178,7 +174,6 @@ export const command = new CommandBuilder()
|
||||
"$prefixplay https://www.bilibili.com/video/BV1y7bg6kEhY",
|
||||
"$prefixplay https://example.com/stream.mp3",
|
||||
"$prefixplay https://radio.example.com:8000/live",
|
||||
"$prefixplay (attach an Opus/MP3 audio file, no text needed)",
|
||||
"$prefixplay https://www.last.fm/music/Drake/_/Make+Them+Cry",
|
||||
"$prefixplay lastfm:loved",
|
||||
"$prefixplay lastfm:soda pop",
|
||||
@@ -189,8 +184,8 @@ export const command = new CommandBuilder()
|
||||
)
|
||||
.addTextOption(option =>
|
||||
option.setName("query")
|
||||
.setDescription("A search query, music genre (for example `pop`), URL, or provider-prefixed query like `sp: song name`. Leave empty when attaching an audio file.", "options.play.query")
|
||||
.setRequired(false)
|
||||
.setDescription("A search query, music genre (for example `pop`), URL, or provider-prefixed query like `sp: song name`.", "options.play.query")
|
||||
.setRequired(true)
|
||||
)
|
||||
.addChoiceOption(o =>
|
||||
o.setName("provider")
|
||||
@@ -210,59 +205,11 @@ export const command = new CommandBuilder()
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function run(message, data) {
|
||||
const rawQuery = data.get("query")?.value ?? "";
|
||||
const rawQuery = data.get("query").value;
|
||||
const flagProvider = data.get("provider")?.value;
|
||||
const { provider: inlineProvider, query } = parseInlineProvider(rawQuery);
|
||||
const provider = inlineProvider ?? flagProvider ?? "ytm";
|
||||
|
||||
/* Audio file attachments — `%p` with an attached Opus/OGG/WebM/MP3/etc.
|
||||
file and no text query queues the file(s) directly through the audio
|
||||
bridge (Ogg/Opus and WebM play natively, others resolve via Lavalink). */
|
||||
if (!rawQuery.trim()) {
|
||||
const attachments = getAudioAttachments(message);
|
||||
|
||||
if (attachments.length === 0) {
|
||||
const hasAnyAttachment = (message.message?.attachments?.size ?? 0) > 0;
|
||||
return message.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||
this.t(message, hasAnyAttachment ? "responses.play.attachmentNotAudio" : "responses.play.noQuery")
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
const p = await this.getPlayer(message, true, true, true);
|
||||
if (!p) return;
|
||||
|
||||
const statusEmbed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setDescription(attachments.length === 1
|
||||
? this.t(message, "responses.play.loadingAttachment", { filename: attachmentTitle(attachments[0]) })
|
||||
: this.t(message, "responses.play.loadingAttachments", { count: attachments.length }));
|
||||
let statusMsg = null;
|
||||
try { statusMsg = await message.reply({ embeds: [statusEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
|
||||
|
||||
const post = (desc) => {
|
||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc);
|
||||
if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); }
|
||||
else { message.reply({ embeds: [embed] }).catch(() => {}); }
|
||||
};
|
||||
|
||||
if (attachments.length === 1) {
|
||||
const att = attachments[0];
|
||||
const url = attachmentUrl(att);
|
||||
const messages = p.playExternal(url, attachmentTitle(att), null, false, "external", attachmentTrackMeta(att));
|
||||
messages.on("message", post);
|
||||
return;
|
||||
}
|
||||
|
||||
attachments.forEach(att => {
|
||||
p.playExternal(attachmentUrl(att), attachmentTitle(att), null, false, "external", attachmentTrackMeta(att))
|
||||
.on("message", () => {});
|
||||
});
|
||||
post(this.t(message, "responses.play.addedPlaylist", { count: attachments.length }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (isNativeAudioUrl(rawQuery)) {
|
||||
const p = await this.getPlayer(message, true, true, true);
|
||||
if (!p) return;
|
||||
|
||||
+5
-52
@@ -2,17 +2,12 @@
|
||||
* @module commands/playnext
|
||||
* @description Play a song and insert it at the top of the queue instead of the end.
|
||||
* Supports inline provider prefixes and flag-based provider selection.
|
||||
* Audio files attached to the command message (Opus, OGG, WebM, MP3, ...) are
|
||||
* queued at the top directly when no text query is given.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mjs";
|
||||
import { getAudioAttachments, attachmentTitle, attachmentTrackMeta, attachmentUrl } from "../src/music/attachments.mjs";
|
||||
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||
|
||||
|
||||
/**
|
||||
@@ -22,18 +17,17 @@ import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||
export const command = new CommandBuilder()
|
||||
.setName("playnext")
|
||||
.setId("playnext")
|
||||
.setDescription("Same as $prefixplay but adds the result to the top of the queue. Attach an audio file to play it next.", "commands.playnext")
|
||||
.setDescription("Same as $prefixplay but adds the result to the top of the queue.", "commands.playnext")
|
||||
.setCategory("music")
|
||||
.addExamples(
|
||||
"$prefixplaynext blinding lights",
|
||||
"$prefixplaynext sp: blinding lights",
|
||||
"$prefixplaynext -p dz get lucky",
|
||||
"$prefixplaynext (attach an Opus/MP3 audio file, no text needed)"
|
||||
"$prefixplaynext -p dz get lucky"
|
||||
)
|
||||
.addTextOption(option =>
|
||||
option.setName("query")
|
||||
.setDescription("A search query, URL, or provider-prefixed query like `sp: song name`. Leave empty when attaching an audio file.", "options.playnext.query")
|
||||
.setRequired(false)
|
||||
.setDescription("A search query, URL, or provider-prefixed query like `sp: song name`.", "options.playnext.query")
|
||||
.setRequired(true)
|
||||
)
|
||||
.addChoiceOption(o =>
|
||||
o.setName("provider")
|
||||
@@ -53,51 +47,10 @@ export const command = new CommandBuilder()
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function run(message, data) {
|
||||
const rawQuery = data.get("query")?.value ?? "";
|
||||
|
||||
/* Audio file attachments — `%playnext` with an attached audio file and no
|
||||
text queues it at the top of the queue through the audio bridge. */
|
||||
if (!rawQuery.trim()) {
|
||||
const attachments = getAudioAttachments(message);
|
||||
|
||||
if (attachments.length === 0) {
|
||||
const hasAnyAttachment = (message.message?.attachments?.size ?? 0) > 0;
|
||||
return message.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||
this.t(message, hasAnyAttachment ? "responses.play.attachmentNotAudio" : "responses.play.noQuery")
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
const p = await this.getPlayer(message, true, true, true);
|
||||
if (!p) return;
|
||||
|
||||
const statusEmbed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setDescription(attachments.length === 1
|
||||
? this.t(message, "responses.play.loadingAttachment", { filename: attachmentTitle(attachments[0]) })
|
||||
: this.t(message, "responses.play.loadingAttachments", { count: attachments.length }));
|
||||
let statusMsg = null;
|
||||
try { statusMsg = await message.reply({ embeds: [statusEmbed] }); } catch(e) { logger.warn("[PlayNext] Error:", e?.message); }
|
||||
|
||||
const post = (desc) => {
|
||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc);
|
||||
if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); }
|
||||
else { message.reply({ embeds: [embed] }).catch(() => {}); }
|
||||
};
|
||||
|
||||
attachments.forEach((att, i) => {
|
||||
/* First file jumps to the top; the rest queue behind it in order. */
|
||||
const top = i === 0;
|
||||
p.playExternal(attachmentUrl(att), attachmentTitle(att), null, top, "external", attachmentTrackMeta(att))
|
||||
.on("message", post);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const p = await this.getPlayer(message, true, true, true);
|
||||
if (!p) return;
|
||||
|
||||
const rawQuery = data.get("query").value;
|
||||
const flagProvider = data.get("provider")?.value;
|
||||
const { provider: inlineProvider, query } = parseInlineProvider(rawQuery);
|
||||
const provider = inlineProvider ?? flagProvider ?? "ytm";
|
||||
|
||||
@@ -16,9 +16,6 @@
|
||||
"prism-media": "^1.3.5",
|
||||
"redis": "^6.3.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"ffmpeg-static": "^5.2.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "node --inspect index.mjs --trace-warnings",
|
||||
"start": "node index.mjs",
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
/** @module src/music/attachments
|
||||
* @description Helpers for playing audio files attached directly to command
|
||||
* messages (Opus voice files, OGG, WebM, MP3, MP4/M4A/MOV video+audio, AAC,
|
||||
* FLAC, WAV).
|
||||
*
|
||||
* Attachment URLs are queued through {@link module:src/music/player/SearchMixin~playExternal}
|
||||
* as "external" tracks. The FluxerAudioBridge's direct-URL route sniffs magic
|
||||
* bytes on fetch: Ogg/Opus (incl. `.opus` voice recordings) is remuxed to
|
||||
* WebM/Opus in-process without re-encoding, WebM passes through untouched,
|
||||
* MP4/M4A/MOV ("ftyp" box header) is decoded locally by ffmpeg (audio track
|
||||
* only), and other formats are resolved through Lavalink.
|
||||
*/
|
||||
|
||||
/** @type {RegExp} Audio file extensions recognized on attachment filenames. mp4/m4v/mov are accepted for their audio track (decoded locally by ffmpeg). */
|
||||
const AUDIO_ATTACHMENT_EXTENSIONS = /\.(?:opus|ogg|oga|webm|mp3|mp4|m4v|m4a|m4b|mov|aac|flac|wav|wma)$/i;
|
||||
|
||||
/** @type {string[]} Content-type prefixes that always count as playable audio. */
|
||||
const AUDIO_CONTENT_TYPE_PREFIXES = ["audio/", "application/ogg", "video/ogg", "video/mp4", "video/quicktime"];
|
||||
|
||||
/**
|
||||
* Decide whether an attachment is a playable audio file.
|
||||
* @param {object} att - Raw Fluxer MessageAttachment.
|
||||
* @returns {boolean} True when the attachment can be queued for playback.
|
||||
*/
|
||||
export function isAudioAttachment(att) {
|
||||
if (!att || att.expired) return false;
|
||||
if (!att.url && !att.proxyUrl) return false;
|
||||
|
||||
const contentType = String(att.contentType ?? "").toLowerCase();
|
||||
if (AUDIO_CONTENT_TYPE_PREFIXES.some(prefix => contentType.startsWith(prefix))) return true;
|
||||
|
||||
const name = String(att.filename ?? "");
|
||||
return AUDIO_ATTACHMENT_EXTENSIONS.test(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect every playable audio attachment from a command message, in the
|
||||
* order they appear on the message.
|
||||
* @param {object} message - Command message wrapper (src/ui/Wrappers.Message).
|
||||
* The raw Fluxer message with its attachments Collection is read from
|
||||
* `message.message`, falling back to the wrapper itself.
|
||||
* @returns {object[]} Array of raw attachment objects.
|
||||
*/
|
||||
export function getAudioAttachments(message) {
|
||||
const raw = message?.message ?? message;
|
||||
const attachments = raw?.attachments;
|
||||
if (!attachments || typeof attachments.values !== "function") return [];
|
||||
return [...attachments.values()].filter(isAudioAttachment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a display title from an attachment: the platform-provided title when
|
||||
* present, otherwise the filename without its extension.
|
||||
* @param {object} att - Raw Fluxer MessageAttachment.
|
||||
* @returns {string} Human-readable track title.
|
||||
*/
|
||||
export function attachmentTitle(att) {
|
||||
const name = String(att?.title ?? att?.filename ?? "attachment").trim();
|
||||
return name.replace(/\.[^.]+$/, "").trim() || "attachment";
|
||||
}
|
||||
|
||||
/**
|
||||
* Build playback metadata for an attachment. Voice-note style attachments
|
||||
* carry their duration in seconds (Discord-compatible schema); it is exposed
|
||||
* in milliseconds via `_durationMs`, the field the player's duration
|
||||
* resolution (`_getTrackDurationMs`) reads first, so queue/now-playing
|
||||
* displays get a progress bar without an extra ffprobe round-trip.
|
||||
* @param {object} att - Raw Fluxer MessageAttachment.
|
||||
* @returns {{durationMs: number, artist: null, thumbnail: null}} Metadata for playExternal().
|
||||
*/
|
||||
export function attachmentTrackMeta(att) {
|
||||
let durationMs = 0;
|
||||
const dur = att?.duration;
|
||||
if (typeof dur === "number" && dur > 0) {
|
||||
durationMs = dur < 100_000 ? Math.round(dur * 1000) : Math.round(dur);
|
||||
}
|
||||
return { durationMs, artist: null, thumbnail: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the download URL for an attachment, preferring the canonical CDN URL.
|
||||
* @param {object} att - Raw Fluxer MessageAttachment.
|
||||
* @returns {string|null} Absolute URL or null when the attachment has none.
|
||||
*/
|
||||
export function attachmentUrl(att) {
|
||||
return att?.url ?? att?.proxyUrl ?? null;
|
||||
}
|
||||
@@ -24,7 +24,6 @@ export class FluxerAudioBridge extends EventEmitter {
|
||||
_encoder = null;
|
||||
_sourceStream = null;
|
||||
_sourceReq = null;
|
||||
_ffmpegProc = null;
|
||||
_playing = false;
|
||||
_stopped = false;
|
||||
_startedAt = 0;
|
||||
@@ -68,11 +67,6 @@ export class FluxerAudioBridge extends EventEmitter {
|
||||
* (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.
|
||||
* 4. local ffmpeg decode (Route 3d) — last resort for direct files the
|
||||
* in-process pipeline and NodeLink cannot serve (FLAC, MP4/M4A/MOV,
|
||||
* odd MP3/AAC): ffmpeg decodes to PCM which is Opus-encoded in-process.
|
||||
* Requires an ffmpeg binary (ffmpeg-static or system PATH); skipped
|
||||
* otherwise.
|
||||
* 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
|
||||
@@ -140,41 +134,24 @@ 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);
|
||||
this._stream = oggResult;
|
||||
await conn.play(this._stream);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
await this._awaitSourceEnd();
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (durationMs <= 0) durationMs = oggResult.getDurationMs();
|
||||
await conn.play(this._stream);
|
||||
} else {
|
||||
if (routed.kind === "mp4") {
|
||||
loaded.stream.destroy();
|
||||
throw new Error("loadstream returned undecoded MP4/MOV audio (no PCM) — the audio node could not decode this file");
|
||||
}
|
||||
logger.player("[AudioBridge] Playing via loadstream PCM -> in-process Opus: " + (trackInfo.title || "unknown") +
|
||||
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : "") +
|
||||
(filterPayload ? " [filters]" : ""));
|
||||
this._stream = this._buildPcmPipeline(routed.stream);
|
||||
await conn.play(this._stream);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
await this._awaitSourceEnd();
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (durationMs <= 0 && this._stream?.getDurationMs) durationMs = this._stream.getDurationMs();
|
||||
}
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
const measuredMs = this._stream?.getDurationMs?.() ?? 0;
|
||||
const finite = durationMs > 0 || measuredMs > 0;
|
||||
await this._awaitEnd(finite ? this._remainingPlayMs(durationMs, measuredMs) : 0);
|
||||
await this._awaitEnd(durationMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
@@ -204,10 +181,8 @@ 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);
|
||||
@@ -215,10 +190,12 @@ export class FluxerAudioBridge extends EventEmitter {
|
||||
await conn.play(this._stream);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
// Wait for the SOURCE OGG to finish downloading so the demuxed frame
|
||||
// count (duration) is final; the remuxed muxer stream itself ends
|
||||
// when conn.play drains it, not when playback ends.
|
||||
await this._awaitSourceEnd();
|
||||
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();
|
||||
@@ -238,7 +215,7 @@ export class FluxerAudioBridge extends EventEmitter {
|
||||
} else {
|
||||
stream.destroy();
|
||||
this._sourceStream = null;
|
||||
logger.player("[AudioBridge] Route 3c: Direct stream is " + routed.kind + " (needs decode) — resolving through Lavalink...");
|
||||
logger.player("[AudioBridge] Route 3c: Direct stream is " + routed.kind + " (MP3/AAC?) — resolving through Lavalink...");
|
||||
|
||||
const encoded = this._lavalink
|
||||
? await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId)
|
||||
@@ -250,87 +227,54 @@ export class FluxerAudioBridge extends EventEmitter {
|
||||
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 ffmpeg fallback.
|
||||
// through to loadstream when allowed, else the explicit error.
|
||||
if (loadstreamEnabled) {
|
||||
try {
|
||||
const loaded3c = await this._streamFromLoadstream(trackInfo, seekMs, null);
|
||||
if (generation !== this._playGeneration) {
|
||||
loaded3c.stream.destroy();
|
||||
return "stopped";
|
||||
}
|
||||
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");
|
||||
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);
|
||||
this._stream = oggResult3c;
|
||||
await conn.play(this._stream);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
await this._awaitSourceEnd();
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (durationMs <= 0) durationMs = oggResult3c.getDurationMs();
|
||||
} else {
|
||||
if (routed3c.kind === "mp4") {
|
||||
loaded3c.stream.destroy();
|
||||
throw new Error("loadstream returned undecoded MP4/MOV audio (no PCM)");
|
||||
}
|
||||
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";
|
||||
|
||||
await this._awaitSourceEnd();
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (durationMs <= 0 && this._stream?.getDurationMs) durationMs = this._stream.getDurationMs();
|
||||
}
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
const measured3c = this._stream?.getDurationMs?.() ?? 0;
|
||||
const finite3c = durationMs > 0 || measured3c > 0;
|
||||
await this._awaitEnd(finite3c ? this._remainingPlayMs(durationMs, measured3c) : 0);
|
||||
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";
|
||||
}
|
||||
const loaded3c = await this._streamFromLoadstream(trackInfo, seekMs, null);
|
||||
if (generation !== this._playGeneration) {
|
||||
loaded3c.stream.destroy();
|
||||
return "stopped";
|
||||
} catch (e) {
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (this._stopped || !this._playing) return "stopped";
|
||||
logger.warn("[AudioBridge] loadstream failed (" + String(e.message).substring(0, 140) + ") — trying local ffmpeg fallback");
|
||||
}
|
||||
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 (loadstream): PCM -> Opus -> WebM");
|
||||
this._stream = this._buildPcmPipeline(routed3c.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";
|
||||
}
|
||||
}
|
||||
|
||||
const ffResult = await this._playViaFfmpeg(conn, trackInfo, {
|
||||
seekMs,
|
||||
durationMs,
|
||||
generation,
|
||||
directInput: routed.kind === "mp4", // MP4/MOV: ffmpeg must fetch + range-seek the URL itself
|
||||
});
|
||||
if (ffResult !== null) return ffResult;
|
||||
|
||||
throw new Error(
|
||||
"[AudioBridge] Direct stream is " + routed.kind + " — no decoder available for this format. " +
|
||||
"Install ffmpeg (or npm i ffmpeg-static) so the bot can decode it locally, " +
|
||||
"or update your NodeLink so /v4/loadstream handles it."
|
||||
"[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";
|
||||
|
||||
const measured3a = this._stream?.getDurationMs?.() ?? 0;
|
||||
const finite3a = durationMs > 0 || measured3a > 0;
|
||||
await this._awaitEnd(finite3a ? this._remainingPlayMs(durationMs, measured3a) : 0);
|
||||
await this._awaitEnd(durationMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
@@ -381,7 +325,6 @@ 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";
|
||||
@@ -402,76 +345,6 @@ export class FluxerAudioBridge extends EventEmitter {
|
||||
return "stopped";
|
||||
}
|
||||
|
||||
/**
|
||||
* Route 3d: play a direct URL through a local ffmpeg decode (PCM -> Opus ->
|
||||
* WebM in-process). Last resort when trackstream/loadstream cannot serve a
|
||||
* format (FLAC, MP4/M4A/MOV, odd MP3/AAC files). MP4-family files play via
|
||||
* directInput (ffmpeg fetches the URL itself — their moov atom can trail
|
||||
* mdat, which a piped non-seekable stream cannot decode). Returns null when
|
||||
* no ffmpeg binary is available so the caller can raise the actionable error.
|
||||
* @param {object} conn - Fluxer voice connection
|
||||
* @param {object} trackInfo - Track metadata (url, title, guildId)
|
||||
* @param {object} ctx - { seekMs, durationMs, generation, directInput }
|
||||
* @returns {Promise<"finished"|"stopped"|null>} null when ffmpeg is unavailable
|
||||
* @private
|
||||
*/
|
||||
async _playViaFfmpeg(conn, trackInfo, ctx) {
|
||||
const { seekMs, durationMs, generation, directInput = false } = ctx;
|
||||
let ff;
|
||||
try {
|
||||
ff = await this._spawnFfmpegPcm(trackInfo.url, seekMs / 1000, { directInput });
|
||||
} catch (e) {
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (this._stopped || !this._playing) return "stopped";
|
||||
logger.warn("[AudioBridge] ffmpeg fallback fetch failed: " + e.message);
|
||||
return null;
|
||||
}
|
||||
if (!ff) return null;
|
||||
|
||||
logger.player("[AudioBridge] Route 3d: local ffmpeg decode" + (directInput ? " (direct URL fetch)" : " (piped)") + ": " +
|
||||
(trackInfo.title || trackInfo.url || "unknown") +
|
||||
(seekMs > 0 ? " [seek " + seekMs + "ms]" : ""));
|
||||
this._sourceStream = ff.source;
|
||||
this._ffmpegProc = ff.proc;
|
||||
this._stream = ff.stream;
|
||||
try {
|
||||
await conn.play(ff.stream);
|
||||
} catch (e) {
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (this._stopped || !this._playing) return "stopped";
|
||||
logger.warn("[AudioBridge] ffmpeg playback failed: " + e.message);
|
||||
return null;
|
||||
}
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
// Wait for the ffmpeg PROCESS (not just the HTTP body) — the decode keeps
|
||||
// running after the download ends, and PCM frames trail the source.
|
||||
await ff.exited;
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (!ff.hasAudio()) {
|
||||
const detail = ff.stderrText();
|
||||
throw new Error(
|
||||
"ffmpeg decode produced no audio (exit=" + ff.proc.exitCode + " signal=" + ff.proc.signalCode + ")" +
|
||||
(detail ? ": " + detail : "")
|
||||
);
|
||||
}
|
||||
|
||||
const decodedMs = ff.getDurationMs();
|
||||
const remainingMs = this._remainingPlayMs(durationMs, decodedMs);
|
||||
logger.player("[AudioBridge] Route 3d: " + decodedMs + "ms decoded, " + (Date.now() - this._startedAt) + "ms elapsed, waiting " + remainingMs + "ms more");
|
||||
|
||||
await this._awaitEnd(remainingMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (Route 3d ffmpeg)");
|
||||
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 —
|
||||
@@ -556,9 +429,6 @@ 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;
|
||||
}
|
||||
}
|
||||
@@ -571,22 +441,36 @@ export class FluxerAudioBridge extends EventEmitter {
|
||||
(trackInfo.title || "unknown"));
|
||||
|
||||
try {
|
||||
const opened = await this._openPositionedStream(direct.url, seekMs);
|
||||
if (stale()) {
|
||||
opened.stream.destroy();
|
||||
return "stopped";
|
||||
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);
|
||||
}
|
||||
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";
|
||||
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. */
|
||||
@@ -728,11 +612,6 @@ export class FluxerAudioBridge extends EventEmitter {
|
||||
this._endReject = null;
|
||||
resolve();
|
||||
}
|
||||
if (this._ffmpegProc) {
|
||||
const proc = this._ffmpegProc;
|
||||
this._ffmpegProc = null;
|
||||
try { proc.kill("SIGKILL"); } catch (_) {}
|
||||
}
|
||||
for (const s of [this._stream, this._encoder, this._sourceStream]) {
|
||||
if (s) {
|
||||
try { s.destroy(); } catch (_) {}
|
||||
|
||||
@@ -11,9 +11,6 @@
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { Readable } from "node:stream";
|
||||
import { spawn as spawnProcess } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { WebMOpusMuxer, OPUS_FRAME_MS } from "./WebMOpusMuxer.mjs";
|
||||
import { StreamPositioner } from "./StreamPositioner.mjs";
|
||||
import prismMedia from "prism-media";
|
||||
@@ -33,60 +30,6 @@ const OPUS_BITRATE = 128000;
|
||||
const WEBM_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]);
|
||||
/** @type {Buffer} @description OGG container magic bytes ("OggS"). */
|
||||
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)";
|
||||
|
||||
/** @type {string|null} @description Resolved ffmpeg binary (null = not installed). Checked once per process. */
|
||||
let _ffmpegCmd = null;
|
||||
/** @type {boolean} @description Whether the ffmpeg binary lookup already ran. */
|
||||
let _ffmpegChecked = false;
|
||||
|
||||
/**
|
||||
* Locate a usable ffmpeg binary: ffmpeg-static (when installed) first, then
|
||||
* the system PATH. Result is memoized for the process lifetime.
|
||||
* @returns {Promise<string|null>}
|
||||
* @private
|
||||
*/
|
||||
async function _resolveFfmpegCmd() {
|
||||
if (_ffmpegChecked) return _ffmpegCmd;
|
||||
_ffmpegChecked = true;
|
||||
const candidates = [];
|
||||
try {
|
||||
candidates.push(createRequire(import.meta.url)("ffmpeg-static"));
|
||||
} catch (_) {}
|
||||
candidates.push("ffmpeg");
|
||||
for (const cmd of candidates) {
|
||||
if (!cmd) continue;
|
||||
const ok = await new Promise((resolve) => {
|
||||
let probe;
|
||||
try {
|
||||
probe = spawnProcess(cmd, ["-version"], { stdio: "ignore" });
|
||||
} catch (_) {
|
||||
return resolve(false);
|
||||
}
|
||||
probe.on("error", () => resolve(false));
|
||||
probe.on("close", (code) => resolve(code === 0));
|
||||
});
|
||||
if (ok) {
|
||||
_ffmpegCmd = cmd;
|
||||
return cmd;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
@@ -116,14 +59,13 @@ const StreamPipeline = {
|
||||
|
||||
const stream = this._stream;
|
||||
if (stream) {
|
||||
if (durationMs <= 0 && (stream.readableEnded || stream.destroyed)) {
|
||||
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();
|
||||
}
|
||||
// Finite tracks: never short-circuit on stream state — conn.play can
|
||||
// drain the whole stream into its playback buffer far faster than
|
||||
// realtime, so only the duration timer reflects actual playback end.
|
||||
const onEnd = () => {
|
||||
if (durationMs > 0 && this._playing && !this._stopped) return;
|
||||
resolve();
|
||||
@@ -148,29 +90,6 @@ const StreamPipeline = {
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Wait until the bridge's source stream is fully consumed (end/close) so
|
||||
* downstream frame counts (durations) are final. Stop-safe: cleanup()
|
||||
* destroys the source, which fires "close". Resolves on source errors.
|
||||
* @returns {Promise<void>}
|
||||
* @private
|
||||
*/
|
||||
_awaitSourceEnd() {
|
||||
return new Promise((resolve) => {
|
||||
const src = this._sourceStream;
|
||||
if (!src || src.readableEnded || src.destroyed) return resolve();
|
||||
const done = () => {
|
||||
src.off("end", done);
|
||||
src.off("close", done);
|
||||
src.off("error", done);
|
||||
resolve();
|
||||
};
|
||||
src.once("end", done);
|
||||
src.once("close", done);
|
||||
src.once("error", done);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Simple timed wait used by the trackstream passthrough route (no local
|
||||
* pipeline to watch). Resolves early when stop()/cleanup clears the timer —
|
||||
@@ -222,76 +141,23 @@ 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<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
|
||||
* bytes back so nothing is lost. MP4/M4A/MOV (ISOBMFF) is detected via the
|
||||
* "ftyp" box header at offset 4 — those files must be decoded by ffmpeg
|
||||
* fetching the URL itself (their moov atom often trails mdat, which a
|
||||
* non-seekable pipe cannot reach back into).
|
||||
* bytes back so nothing is lost.
|
||||
* @param {Readable} stream
|
||||
* @returns {Promise<{stream: Readable, kind: "webm"|"ogg"|"mp4"|"pcm"}>}
|
||||
* @returns {Promise<{stream: Readable, kind: "webm"|"ogg"|"pcm"}>}
|
||||
* @private
|
||||
*/
|
||||
async _routeByMagic(stream) {
|
||||
const head = await this._peek(stream, 8);
|
||||
const head = await this._peek(stream, 4);
|
||||
if (head.length >= 4 && head.subarray(0, 4).equals(WEBM_MAGIC)) return { stream, kind: "webm" };
|
||||
if (head.length >= 4 && head.subarray(0, 4).equals(OGG_MAGIC)) return { stream, kind: "ogg" };
|
||||
if (head.length >= 8 && head.subarray(4, 8).equals(FTYP_MAGIC)) return { stream, kind: "mp4" };
|
||||
return { stream, kind: "pcm" };
|
||||
},
|
||||
|
||||
@@ -304,63 +170,39 @@ const StreamPipeline = {
|
||||
*/
|
||||
_peek(stream, n) {
|
||||
return new Promise((resolve, reject) => {
|
||||
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 = () => {
|
||||
const tryRead = () => {
|
||||
const chunks = [];
|
||||
let total = 0;
|
||||
let chunk;
|
||||
while (total < n && (chunk = stream.read()) !== null) {
|
||||
chunks.push(chunk);
|
||||
total += chunk.length;
|
||||
}
|
||||
const ended = stream.readableEnded || stream._readableState?.ended === true;
|
||||
if (total >= n || ended) finish();
|
||||
};
|
||||
const onError = (err) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
cleanup();
|
||||
reject(err);
|
||||
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 onReadable = () => { cleanup(); tryRead(); };
|
||||
const onEnd = () => { cleanup(); tryRead(); };
|
||||
const onError = (err) => { cleanup(); reject(err); };
|
||||
const cleanup = () => {
|
||||
stream.off("readable", drain);
|
||||
stream.off("end", finish);
|
||||
stream.off("readable", onReadable);
|
||||
stream.off("end", onEnd);
|
||||
stream.off("error", onError);
|
||||
};
|
||||
stream.on("readable", drain);
|
||||
stream.once("end", finish);
|
||||
stream.once("readable", onReadable);
|
||||
stream.once("end", onEnd);
|
||||
stream.once("error", onError);
|
||||
drain();
|
||||
tryRead();
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Wall-clock ms still left to play: durationMs (already remaining-after-seek
|
||||
* when the player knows the track length) or, when unknown, the pipeline's
|
||||
* measured frame/byte count — minus playback time elapsed since start.
|
||||
* @param {number} durationMs
|
||||
* @param {number} [measuredMs=0]
|
||||
* @returns {number}
|
||||
* @private
|
||||
*/
|
||||
_remainingPlayMs(durationMs, measuredMs = 0) {
|
||||
const total = durationMs > 0 ? durationMs : measuredMs;
|
||||
return Math.max(0, total - (Date.now() - this._startedAt));
|
||||
},
|
||||
|
||||
/**
|
||||
* Build the in-process PCM -> Opus -> WebM pipeline. The returned wrapper
|
||||
* exposes getDurationMs() derived from counted PCM bytes (final once the
|
||||
* PCM source ends) so unknown-duration tracks can still be timed.
|
||||
* Build the in-process PCM -> Opus -> WebM pipeline.
|
||||
* @param {Readable} pcmStream - s16le 48kHz stereo byte stream
|
||||
* @returns {WebMOpusMuxer} - byte stream consumable by conn.play()
|
||||
* @private
|
||||
@@ -384,103 +226,20 @@ const StreamPipeline = {
|
||||
const muxer = new WebMOpusMuxer({ sampleRate: PCM_RATE, channels: PCM_CHANNELS });
|
||||
this._encoder = encoder;
|
||||
|
||||
let pcmBytes = 0;
|
||||
pcmStream.on("data", (chunk) => { pcmBytes += chunk.length; });
|
||||
|
||||
pcmStream.pipe(encoder).pipe(muxer);
|
||||
muxer.getDurationMs = () => Math.round((pcmBytes / (PCM_RATE * PCM_CHANNELS * 2)) * 1000);
|
||||
return muxer;
|
||||
},
|
||||
|
||||
/**
|
||||
* Spawn a local ffmpeg process decoding an audio URL to s16le 48kHz stereo
|
||||
* PCM on stdout (fed through _buildPcmPipeline). Last-resort route for
|
||||
* formats the in-process pipeline cannot handle (FLAC, MP4/M4A/MOV, MP3/AAC
|
||||
* files the NodeLink worker refuses, ...).
|
||||
*
|
||||
* Input modes:
|
||||
* - piped (default): the bot fetches the URL itself and pipes the body into
|
||||
* ffmpeg's stdin, so request headers match the other direct-URL routes.
|
||||
* Works for streamable containers (FLAC, OGG, MP3, WAV, faststart MP4).
|
||||
* - directInput: ffmpeg fetches the URL itself via its HTTP protocol (range
|
||||
* requests, proper seeking). Required for MP4/MOV files whose moov atom
|
||||
* trails mdat — a non-seekable pipe can never reach back to demux it.
|
||||
* @param {string} url - Audio URL (signed attachment URL, radio, ...)
|
||||
* @param {number} [seekSeconds=0]
|
||||
* @param {object} [options]
|
||||
* @param {boolean} [options.directInput=false] - Let ffmpeg fetch the URL itself.
|
||||
* @returns {Promise<{stream: WebMOpusMuxer, source: Readable|null, proc: ChildProcess, getDurationMs: function, hasAudio: function, stderrText: function}|null>} null when no usable ffmpeg binary is installed
|
||||
* @private
|
||||
*/
|
||||
async _spawnFfmpegPcm(url, seekSeconds = 0, { directInput = false } = {}) {
|
||||
const cmd = await _resolveFfmpegCmd();
|
||||
if (!cmd) return null;
|
||||
|
||||
const args = ["-hide_banner", "-loglevel", "error"];
|
||||
if (seekSeconds > 0) args.push("-ss", String(Math.floor(seekSeconds)));
|
||||
if (directInput) {
|
||||
args.push("-user_agent", HTTP_UA, "-i", url);
|
||||
} else {
|
||||
args.push("-i", "pipe:0");
|
||||
}
|
||||
args.push("-vn", "-f", "s16le", "-ar", String(PCM_RATE), "-ac", String(PCM_CHANNELS), "pipe:1");
|
||||
|
||||
let proc;
|
||||
try {
|
||||
proc = spawnProcess(cmd, args, { stdio: ["pipe", "pipe", "pipe"] });
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let source = null;
|
||||
if (!directInput) {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: { "User-Agent": HTTP_UA },
|
||||
redirect: "follow",
|
||||
});
|
||||
if (!response.ok) throw new Error("HTTP " + response.status + " for " + url);
|
||||
source = Readable.fromWeb(response.body);
|
||||
} catch (e) {
|
||||
try { proc.kill("SIGKILL"); } catch (_) {}
|
||||
throw e;
|
||||
pcmStream.on("error", (err) => {
|
||||
if (this._stopped || !this._playing) {
|
||||
logger.player("[AudioBridge] PCM source torn down after stop: " + err.message);
|
||||
} else {
|
||||
logger.warn("[AudioBridge] PCM source error: " + err.message);
|
||||
encoder.destroy(err);
|
||||
}
|
||||
}
|
||||
|
||||
const stderrChunks = [];
|
||||
proc.stderr.on("data", (chunk) => { if (stderrChunks.length < 16) stderrChunks.push(chunk); });
|
||||
let gotPcm = false;
|
||||
proc.stdout.once("data", () => { gotPcm = true; });
|
||||
let closeResolve;
|
||||
const exited = new Promise((resolve) => { closeResolve = resolve; });
|
||||
proc.stdin.on("error", () => {}); // EPIPE when ffmpeg exits early — not fatal
|
||||
if (source) {
|
||||
source.on("error", (err) => {
|
||||
try { proc.stdin.destroy(); } catch (_) {}
|
||||
try { proc.kill("SIGKILL"); } catch (_) {}
|
||||
logger.warn("[AudioBridge] ffmpeg source error: " + err.message);
|
||||
});
|
||||
}
|
||||
proc.on("close", (code, signal) => {
|
||||
if (!gotPcm) logger.warn("[AudioBridge] ffmpeg exited early (code=" + code + " signal=" + signal + ")");
|
||||
closeResolve();
|
||||
if (source) { try { source.destroy(); } catch (_) {} }
|
||||
});
|
||||
encoder.on("error", (err) => {
|
||||
muxer.destroy(err);
|
||||
});
|
||||
|
||||
if (source) source.pipe(proc.stdin);
|
||||
const pipeline = this._buildPcmPipeline(proc.stdout);
|
||||
return {
|
||||
stream: pipeline,
|
||||
source,
|
||||
proc,
|
||||
exited,
|
||||
getDurationMs: () => pipeline.getDurationMs(),
|
||||
hasAudio: () => gotPcm,
|
||||
stderrText: () => {
|
||||
const text = Buffer.concat(stderrChunks).toString("utf8").trim();
|
||||
return text.length > 400 ? text.substring(text.length - 400) : text;
|
||||
},
|
||||
};
|
||||
pcmStream.pipe(encoder).pipe(muxer);
|
||||
return muxer;
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -503,8 +262,9 @@ const StreamPipeline = {
|
||||
});
|
||||
oggStream.pipe(demuxer).pipe(muxer);
|
||||
await headPromise;
|
||||
muxer.getDurationMs = () => frameCount * OPUS_FRAME_MS;
|
||||
return muxer;
|
||||
const wrapper = Object.create(muxer);
|
||||
wrapper.getDurationMs = () => frameCount * OPUS_FRAME_MS;
|
||||
return wrapper;
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -162,15 +162,17 @@ export class StreamPositioner extends Transform {
|
||||
|
||||
/** @param {Buffer} chunk @param {string} _enc @param {Function} cb @protected */
|
||||
_transform(chunk, _enc, cb) {
|
||||
let error = null;
|
||||
try {
|
||||
if (this._done) this.push(chunk);
|
||||
else if (this._kind === "ogg") this._feedOgg(chunk);
|
||||
if (this._done) {
|
||||
this.push(chunk);
|
||||
return cb();
|
||||
}
|
||||
if (this._kind === "ogg") this._feedOgg(chunk);
|
||||
else this._feedWebm(chunk);
|
||||
cb();
|
||||
} catch (err) {
|
||||
error = err;
|
||||
cb(err);
|
||||
}
|
||||
cb(error);
|
||||
}
|
||||
|
||||
/** @param {Function} cb @protected */
|
||||
|
||||
@@ -252,28 +252,26 @@ export class WebMOpusMuxer extends Transform {
|
||||
* @protected
|
||||
*/
|
||||
_transform(packet, _encoding, callback) {
|
||||
let error = null;
|
||||
try {
|
||||
if (Buffer.isBuffer(packet) && packet.length > 0) {
|
||||
this._addBlock(packet);
|
||||
}
|
||||
callback();
|
||||
} catch (err) {
|
||||
error = err;
|
||||
callback(err);
|
||||
}
|
||||
callback(error);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Function} callback
|
||||
* @protected
|
||||
*/
|
||||
_flush(callback) {
|
||||
let error = null;
|
||||
_final(callback) {
|
||||
try {
|
||||
this._flushCluster();
|
||||
callback();
|
||||
} catch (err) {
|
||||
error = err;
|
||||
callback(err);
|
||||
}
|
||||
callback(error);
|
||||
}
|
||||
}
|
||||
@@ -669,20 +669,17 @@ const SearchMixin = {
|
||||
* @param {string} [title]
|
||||
* @param {string} [artist]
|
||||
* @param {string} [trackType="external"]
|
||||
* @param {object} [meta=null] - Optional metadata ({durationMs, artist, thumbnail}).
|
||||
* @returns {object}
|
||||
*/
|
||||
_buildExternalTrack(url, title = null, artist = null, trackType = "external", meta = null) {
|
||||
_buildExternalTrack(url, title = null, artist = null, trackType = "external") {
|
||||
const displayTitle = title || this._extractFilenameFromUrl(url);
|
||||
const track = {
|
||||
return {
|
||||
type: trackType,
|
||||
title: displayTitle,
|
||||
url: url,
|
||||
artist: artist || meta?.artist || null,
|
||||
thumbnail: meta?.thumbnail ?? null,
|
||||
artist: artist || null,
|
||||
thumbnail: null,
|
||||
};
|
||||
if (meta?.durationMs > 0) track._durationMs = Math.round(meta.durationMs);
|
||||
return track;
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -770,16 +767,14 @@ const SearchMixin = {
|
||||
* @param {string} [artist] - Optional artist name.
|
||||
* @param {boolean} [top=false] - Insert at top of queue.
|
||||
* @param {string} [trackType="external"] - "external" or "stream".
|
||||
* @param {object} [meta=null] - Optional metadata ({durationMs, artist, thumbnail})
|
||||
* e.g. from an audio file attachment (see module:src/music/attachments).
|
||||
* @returns {EventEmitter} Emits "message" events with status strings.
|
||||
*/
|
||||
playExternal(url, title = null, artist = null, top = false, trackType = "external", meta = null) {
|
||||
playExternal(url, title = null, artist = null, top = false, trackType = "external") {
|
||||
const events = new EventEmitter();
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const track = this._buildExternalTrack(url, title, artist, trackType, meta);
|
||||
const track = this._buildExternalTrack(url, title, artist, trackType);
|
||||
this.addToQueue(track, top);
|
||||
events.emit("message", "Added **[" + track.title + "](" + url + ")** to the queue.");
|
||||
|
||||
|
||||
@@ -380,10 +380,6 @@
|
||||
"bilibiliResolving": "📺 جارٍ تحليل فيديو Bilibili...",
|
||||
"bilibiliNoAudio": "❌ لا يوجد صوت قابل للتشغيل لـ **{{title}}** — قد يكون الفيديو مقفلًا جغرافيًا أو مدفوعًا أو محذوفًا.",
|
||||
"bilibiliError": "❌ Bilibili: {{message}}",
|
||||
"noQuery": "❌ اكتب اسم أغنية أو رابطًا — أو أرفق ملفًا صوتيًا (Opus، MP3، OGG، FLAC، WAV…) لتشغيله.\nمثال: `$prefixplay blinding lights`",
|
||||
"attachmentNotAudio": "❌ الملف المرفق ليس بتنسيق صوتي مدعوم (Opus، OGG، WebM، MP3، MP4، MOV، M4A، AAC، FLAC، WAV).",
|
||||
"loadingAttachment": "📄 جارٍ تحميل **{{filename}}**...",
|
||||
"loadingAttachments": "📄 جارٍ تحميل **{{count}}** من الملفات المرفقة...",
|
||||
"bilibiliDisabled": "❌ تشغيل Bilibili معطل (config.json → bilibili.enabled)."
|
||||
},
|
||||
"playnext": {
|
||||
|
||||
@@ -380,10 +380,6 @@
|
||||
"bilibiliResolving": "📺 ڤیدیۆی Bilibili چارەسەر دەکرێت...",
|
||||
"bilibiliNoAudio": "❌ هیچ دەنگێکی لێدراو نییە بۆ **{{title}}** — لەوانەیە ڤیدیۆکە بە ناوچە دەبەسترێت، پارەدار بێت یان سڕدرابێتەوە.",
|
||||
"bilibiliError": "❌ Bilibili: {{message}}",
|
||||
"noQuery": "❌ ناوی گۆرانی یان بەستەرێک بنووسە — یان پەڕگەیەکی دەنگی هاوپێچ بکە (Opus، MP3، OGG، FLAC، WAV…) بۆ لێدانی.\nنموونە: `$prefixplay blinding lights`",
|
||||
"attachmentNotAudio": "❌ پەڕگە هاوپێچکراوەکە جۆرێکی دەنگی پشتگیریکراو نییە (Opus، OGG، WebM، MP3، MP4، MOV، M4A، AAC، FLAC، WAV).",
|
||||
"loadingAttachment": "📄 بارکردنی **{{filename}}**...",
|
||||
"loadingAttachments": "📄 بارکردنی **{{count}}** پەڕگەی هاوپێچ...",
|
||||
"bilibiliDisabled": "❌ لێدانی Bilibili ناچالاک کراوە (config.json → bilibili.enabled)."
|
||||
},
|
||||
"playnext": {
|
||||
|
||||
@@ -380,10 +380,6 @@
|
||||
"bilibiliResolving": "📺 Bilibili-Video wird aufgelöst...",
|
||||
"bilibiliNoAudio": "❌ Kein abspielbares Audio für **{{title}}** — das Video ist möglicherweise regional gesperrt, kostenpflichtig oder gelöscht.",
|
||||
"bilibiliError": "❌ Bilibili: {{message}}",
|
||||
"noQuery": "❌ Gib einen Songnamen oder eine URL ein — oder hänge eine Audiodatei an (Opus, MP3, OGG, FLAC, WAV …), um sie abzuspielen.\nBeispiel: `$prefixplay blinding lights`",
|
||||
"attachmentNotAudio": "❌ Die angehängte Datei ist kein unterstütztes Audioformat (Opus, OGG, WebM, MP3, MP4, MOV, M4A, AAC, FLAC, WAV).",
|
||||
"loadingAttachment": "📄 Lade **{{filename}}**...",
|
||||
"loadingAttachments": "📄 Lade **{{count}}** angehängte Dateien...",
|
||||
"bilibiliDisabled": "❌ Bilibili-Wiedergabe ist deaktiviert (config.json → bilibili.enabled)."
|
||||
},
|
||||
"playnext": {
|
||||
|
||||
@@ -497,10 +497,6 @@
|
||||
"bilibiliResolving": "📺 Resolving Bilibili video...",
|
||||
"bilibiliNoAudio": "❌ No playable audio for **{{title}}** — the video may be region-locked, premium-only, or deleted.",
|
||||
"bilibiliError": "❌ Bilibili: {{message}}",
|
||||
"noQuery": "❌ Type a song name or URL — or attach an audio file (Opus, MP3, OGG, FLAC, WAV…) to play it.\nExample: `$prefixplay blinding lights`",
|
||||
"attachmentNotAudio": "❌ The attached file isn't a supported audio format (Opus, OGG, WebM, MP3, MP4, MOV, M4A, AAC, FLAC, WAV).",
|
||||
"loadingAttachment": "📄 Loading **{{filename}}**...",
|
||||
"loadingAttachments": "📄 Loading **{{count}}** attached files...",
|
||||
"bilibiliDisabled": "❌ Bilibili playback is disabled (config.json → bilibili.enabled)."
|
||||
},
|
||||
"playnext": {
|
||||
|
||||
@@ -380,10 +380,6 @@
|
||||
"bilibiliResolving": "📺 Resolvendo vídeo do Bilibili...",
|
||||
"bilibiliNoAudio": "❌ Nenhum áudio reproduzível para **{{title}}** — o vídeo pode estar bloqueado por região, ser pago ou ter sido excluído.",
|
||||
"bilibiliError": "❌ Bilibili: {{message}}",
|
||||
"noQuery": "❌ Digite o nome de uma música ou URL — ou anexe um arquivo de áudio (Opus, MP3, OGG, FLAC, WAV…) para tocá-lo.\nExemplo: `$prefixplay blinding lights`",
|
||||
"attachmentNotAudio": "❌ O arquivo anexado não é um formato de áudio suportado (Opus, OGG, WebM, MP3, MP4, MOV, M4A, AAC, FLAC, WAV).",
|
||||
"loadingAttachment": "📄 Carregando **{{filename}}**...",
|
||||
"loadingAttachments": "📄 Carregando **{{count}}** arquivos anexados...",
|
||||
"bilibiliDisabled": "❌ A reprodução do Bilibili está desativada (config.json → bilibili.enabled)."
|
||||
},
|
||||
"playnext": {
|
||||
|
||||
@@ -486,10 +486,6 @@
|
||||
"bilibiliResolving": "📺 Bilibili videosu çözümleniyor...",
|
||||
"bilibiliNoAudio": "❌ **{{title}}** için çalınabilir ses yok — video bölge kilitli, ücretli olabilir veya silinmiş olabilir.",
|
||||
"bilibiliError": "❌ Bilibili: {{message}}",
|
||||
"noQuery": "❌ Bir şarkı adı veya URL yaz — ya da çalmak için bir ses dosyası ekle (Opus, MP3, OGG, FLAC, WAV…).\nÖrnek: `$prefixplay blinding lights`",
|
||||
"attachmentNotAudio": "❌ Eklenen dosya desteklenen bir ses biçimi değil (Opus, OGG, WebM, MP3, MP4, MOV, M4A, AAC, FLAC, WAV).",
|
||||
"loadingAttachment": "📄 **{{filename}}** yükleniyor...",
|
||||
"loadingAttachments": "📄 **{{count}}** ekli dosya yükleniyor...",
|
||||
"bilibiliDisabled": "❌ Bilibili oynatma devre dışı (config.json → bilibili.enabled)."
|
||||
},
|
||||
"playnext": {
|
||||
|
||||
Reference in new issue
Block a user