From 351336ea1946b60ba4c0fb5b4de74b0590f84686 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Thu, 22 Oct 2026 01:59:45 +0300 Subject: [PATCH] Add volume normalization, DSP filters (speed, pitch, bassboost), and playlist pagination (#16, #9, #17) - Implement EBU R128 dynamic volume normalization & ReplayGain leveling in src/music/audio/VolumeNormalizer.mjs and commands/normalize.mjs (#16) - Add real-time audio filter hot-reloading in PlaybackMixin.mjs and FluxerAudioBridge.mjs (#9) - Add commands for %bassboost (low/medium/hard), %speed (0.5x-2.0x), and %pitch (0.5x-2.0x) (#9) - Implement non-blocking background queue ingestion with progressive progress updates for large Spotify & SoundCloud playlists in SearchMixin.mjs (#17) - Configure playlistLoadLimit: 10 in docker/nodelink.config.json (#17) - Update README documentation and commands table (total 43 commands) --- README.md | 12 ++- commands/bassboost.mjs | 107 ++++++++++++++++++++++++++ commands/filter.mjs | 33 ++++++++ commands/normalize.mjs | 94 ++++++++++++++++++++++ commands/pitch.mjs | 83 ++++++++++++++++++++ commands/speed.mjs | 86 +++++++++++++++++++++ docker/nodelink.config.json | 6 ++ src/music/audio/FluxerAudioBridge.mjs | 6 +- src/music/audio/VolumeNormalizer.mjs | 100 ++++++++++++++++++++++++ src/music/player/PlaybackMixin.mjs | 23 +++--- src/music/player/Player.mjs | 17 +++- src/music/player/SearchMixin.mjs | 75 +++++++++++++++++- storage/defaults.json | 2 + 13 files changed, 621 insertions(+), 23 deletions(-) create mode 100644 commands/bassboost.mjs create mode 100644 commands/normalize.mjs create mode 100644 commands/pitch.mjs create mode 100644 commands/speed.mjs create mode 100644 src/music/audio/VolumeNormalizer.mjs diff --git a/README.md b/README.md index 67cc8b3..93f9869 100644 --- a/README.md +++ b/README.md @@ -129,7 +129,9 @@ A few things worth knowing: - **Seek** — jump to a specific position in the current track - **Track options** — set custom start/end times per track, great for album compilations and hidden tracks - **Queue move** — reorder tracks by moving them to a different position -- **Audio filters** — bassboost, speed, nightcore and more (applied server-side by NodeLink) +- **Audio filters & DSP effects** — real-time equalizer bassboost (low/medium/hard), nightcore, vaporwave, 8D audio, and fine-grained `%speed` & `%pitch` controls +- **Dynamic volume normalization** — ReplayGain & EBU R128 loudness leveling across YouTube, Spotify, and SoundCloud (`%normalize`) +- **Large playlist streaming** — background chunked ingestion for massive Spotify & SoundCloud playlists (>100 tracks) with instant playback start - **Server settings** — per-guild configuration (prefix, volume, locale, 24/7 channels, …) stored in MySQL - **Dashboard backend** — optional Redis-RPC backend that an external web frontend uses to monitor players and control playback remotely - **Multi-language support** — English, Arabic, German, Kurdish (Sorani), Brazilian Portuguese, and Turkish @@ -174,7 +176,11 @@ Below is the complete list of Remix's commands. The default prefix is `%`. | `lyrics` | Display synced lyrics from NodeLink | `%lyrics` | `lyric`, `ly` | | `thumbnail` | Get the thumbnail of the current track | `%thumbnail` | `thumb` | | `radio` | Play a built-in or custom radio station | `%radio` | `r` | -| `filter` | Manage audio filters (bass, speed, nightcore, etc.) | `%filter bass 50` | `filters`, `fx`, `effect` | +| `filter` | Interactive audio filter picker (bass, speed, nightcore, 8D, etc.) | `%filter` | `filters`, `fx`, `effect` | +| `bassboost` | Apply a low, medium, or hard bass boost equalizer | `%bassboost hard` | `bb`, `bass` | +| `speed` | Adjust playback speed multiplier (0.5×–2.0×) in real time | `%speed 1.25` | `rate`, `tempo` | +| `pitch` | Adjust audio pitch multiplier (0.5×–2.0×) in real time | `%pitch 1.2` | `semitone`, `tune` | +| `normalize` | Toggle dynamic volume normalization & ReplayGain leveling | `%normalize` / `%normalize on` | `replaygain`, `volumenormalize`, `norm` | | `player` | Create an interactive emoji control panel with live progress | `%player` | | | `join` | Make the bot join a specific voice channel | `%join 123456789` | | | `leave` | Make the bot leave the current voice channel | `%leave` | `l`, `stop` | @@ -439,7 +445,7 @@ fluxer/ │ # one child process per shard slice, each running index.mjs ├── config_example.json # Configuration template ├── package.json -├── commands/ # 39 command entry files (one per command); the three +├── commands/ # 43 command entry files (one per command); the three │ │ # largest (lastfm, settings, debug) are split into action-family │ │ # modules inside commands// subdirectories │ ├── lastfm/ # lastfm action families (account, playback, listening, diff --git a/commands/bassboost.mjs b/commands/bassboost.mjs new file mode 100644 index 0000000..f53f073 --- /dev/null +++ b/commands/bassboost.mjs @@ -0,0 +1,107 @@ +/** + * @module commands/bassboost + * @description Quick equalizer bass boost filter with low, medium, and hard presets. + */ + +import { CommandBuilder } from "../src/commands/index.mjs"; +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../src/ui/index.mjs"; + +export const BASSBOOST_PRESETS = { + low: { + label: "Low", + equalizer: [ + { band: 0, gain: 0.25 }, + { band: 1, gain: 0.20 }, + { band: 2, gain: 0.15 }, + { band: 3, gain: 0.10 }, + ], + }, + medium: { + label: "Medium", + equalizer: [ + { band: 0, gain: 0.60 }, + { band: 1, gain: 0.70 }, + { band: 2, gain: 0.50 }, + { band: 3, gain: 0.25 }, + { band: 4, gain: 0.00 }, + { band: 5, gain: -0.25 }, + { band: 6, gain: -0.45 }, + { band: 7, gain: -0.55 }, + { band: 8, gain: -0.60 }, + ], + }, + hard: { + label: "Hard", + equalizer: [ + { band: 0, gain: 1.00 }, + { band: 1, gain: 1.10 }, + { band: 2, gain: 0.80 }, + { band: 3, gain: 0.50 }, + { band: 4, gain: 0.25 }, + { band: 5, gain: -0.20 }, + { band: 6, gain: -0.45 }, + { band: 7, gain: -0.65 }, + { band: 8, gain: -0.80 }, + ], + }, +}; + +/** + * @type {CommandBuilder} + * @description Command definition for the bassboost command. + */ +export const command = new CommandBuilder() + .setName("bassboost") + .setDescription("Apply a low, medium, or hard bass boost equalizer effect.", "commands.bassboost") + .setCategory("music") + .addStringOption(o => + o.setName("level") + .setDescription("Bass boost level: 'low', 'medium', 'hard', or 'off'.") + .setRequired(false) + .addChoices( + { name: "low", value: "low" }, + { name: "medium", value: "medium" }, + { name: "hard", value: "hard" }, + { name: "off", value: "off" } + ) + ) + .addAliases("bb", "bass"); + +/** + * Run handler for the bassboost command. + * + * @param {object} message - The command message wrapper. + * @param {object} data - Parsed command data. + * @returns {Promise} + */ +export async function run(message, data) { + const p = await this.getPlayer(message, false, false, false); + if (!p) return; + + const levelArg = data.get("level")?.value?.toLowerCase() || "medium"; + + const embed = new EmbedBuilder().setColor(getGlobalColor()); + + if (levelArg === "off" || levelArg === "none" || levelArg === "reset") { + await p.applyFilter({}, null); + embed.setDescription("🔇 Bass boost disabled — restored original audio balance."); + return message.reply({ embeds: [embed] }).catch(() => {}); + } + + const preset = BASSBOOST_PRESETS[levelArg] || BASSBOOST_PRESETS.medium; + const filterMeta = { + key: `bassboost_${levelArg}`, + label: `Bass Boost (${preset.label})`, + emoji: "🔊", + }; + + const res = await p.applyFilter({ equalizer: preset.equalizer }, filterMeta); + if (!res.ok) { + embed.setDescription(`❌ Failed to apply bass boost: ${res.reason || "Unknown error"}`); + return message.reply({ embeds: [embed] }).catch(() => {}); + } + + embed.setDescription(`🔊 Applied **Bass Boost (${preset.label})**! Real-time equalizer active.`); + message.reply({ embeds: [embed] }).catch(() => {}); +} diff --git a/commands/filter.mjs b/commands/filter.mjs index fa6e241..c65c94b 100644 --- a/commands/filter.mjs +++ b/commands/filter.mjs @@ -20,6 +20,20 @@ const FILTERS = [ desc: "Remove all filters — restore original audio", payload: {}, }, + { + emoji: "🔉", + key: "bassboost_low", + label: "Bass Boost (Low)", + desc: "Subtle low-end boost for acoustic & gentle tracks", + payload: { + equalizer: [ + { band: 0, gain: 0.25 }, + { band: 1, gain: 0.20 }, + { band: 2, gain: 0.15 }, + { band: 3, gain: 0.10 }, + ], + }, + }, { emoji: "🔊", key: "bassboost", @@ -44,6 +58,25 @@ const FILTERS = [ ], }, }, + { + emoji: "💥", + key: "bassboost_hard", + label: "Bass Boost (Hard)", + desc: "Maximum sub-bass boost — skull-shattering low end", + payload: { + equalizer: [ + { band: 0, gain: 1.00 }, + { band: 1, gain: 1.10 }, + { band: 2, gain: 0.80 }, + { band: 3, gain: 0.50 }, + { band: 4, gain: 0.25 }, + { band: 5, gain: -0.20 }, + { band: 6, gain: -0.45 }, + { band: 7, gain: -0.65 }, + { band: 8, gain: -0.80 }, + ], + }, + }, { emoji: "🌙", key: "nightcore", diff --git a/commands/normalize.mjs b/commands/normalize.mjs new file mode 100644 index 0000000..98f97db --- /dev/null +++ b/commands/normalize.mjs @@ -0,0 +1,94 @@ +/** + * @module commands/normalize + * @description Toggle dynamic volume normalization & ReplayGain leveling (EBU R128 standard). + * Prevents ear-blasting volume differences between YouTube, Spotify, and SoundCloud. + */ + +import { CommandBuilder } from "../src/commands/index.mjs"; +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { calculateNormalizationGain, detectTrackSource } from "../src/music/audio/VolumeNormalizer.mjs"; + +/** + * @type {CommandBuilder} + * @description Command definition for the normalize command. + */ +export const command = new CommandBuilder() + .setName("normalize") + .setDescription("Toggle dynamic volume normalization (ReplayGain leveling) across music sources.", "commands.normalize") + .setCategory("music") + .addStringOption(o => + o.setName("state") + .setDescription("Turn on/off or check status ('on', 'off', 'status'). Omit to toggle.") + .setRequired(false) + .addChoices( + { name: "on", value: "on" }, + { name: "off", value: "off" }, + { name: "status", value: "status" } + ) + ) + .addAliases("replaygain", "volumenormalize", "norm"); + +/** + * Run handler for the normalize command. + * + * @param {object} message - The command message wrapper. + * @param {object} data - Parsed command data. + * @returns {Promise} + */ +export async function run(message, data) { + const p = await this.getPlayer(message, false, false, false); + const guildSettings = this.getSettings ? this.getSettings(message) : null; + const currentSetting = guildSettings?.get ? (guildSettings.get("normalize") ?? true) : true; + + const stateArg = data.get("state")?.value?.toLowerCase(); + let newState; + + if (stateArg === "status") { + newState = currentSetting; + } else if (stateArg === "on" || stateArg === "enable" || stateArg === "true") { + newState = true; + } else if (stateArg === "off" || stateArg === "disable" || stateArg === "false") { + newState = false; + } else { + // Toggle + newState = !currentSetting; + } + + if (stateArg !== "status") { + if (guildSettings?.set) { + guildSettings.set("normalize", newState); + } + if (p) { + p.volumeNormalization = newState; + if (p._voiceConn) { + try { + p._voiceConn.setVolume(p.getEffectiveVolume()); + } catch (_) {} + } + } + } + + const embed = new EmbedBuilder().setColor(getGlobalColor()); + const statusEmoji = newState ? "🔊" : "🔇"; + const statusText = newState ? "**Enabled**" : "**Disabled**"; + + let desc = `${statusEmoji} Volume normalization (ReplayGain) is currently ${statusText} for this server.\n\n` + + `*When enabled, playback loudness is dynamically leveled to the international -14 LUFS standard so quiet acoustic songs and loud EDM/SoundCloud tracks play at a balanced listening volume.*`; + + if (p) { + const current = p.queue?.getCurrent?.(); + if (current) { + const source = detectTrackSource(current); + const gain = calculateNormalizationGain(current); + const gainDb = (20 * Math.log10(gain)).toFixed(1); + const gainSign = gain >= 1 ? "+" : ""; + desc += `\n\n**Current Track Info:**\n` + + `• Source: \`${source}\`\n` + + `• Gain adjustment: \`${gainSign}${gainDb} dB\` (${(gain * 100).toFixed(0)}%)\n` + + `• Effective volume: \`${Math.round(p.getEffectiveVolume())}%\``; + } + } + + message.reply({ embeds: [embed.setDescription(desc)] }).catch(() => {}); +} diff --git a/commands/pitch.mjs b/commands/pitch.mjs new file mode 100644 index 0000000..1d3c030 --- /dev/null +++ b/commands/pitch.mjs @@ -0,0 +1,83 @@ +/** + * @module commands/pitch + * @description Adjust real-time audio pitch (0.5× to 2.0×) using timescale DSP filters. + */ + +import { CommandBuilder } from "../src/commands/index.mjs"; +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { Utils } from "../src/utils/Utils.mjs"; + +/** + * @type {CommandBuilder} + * @description Command definition for the pitch command. + */ +export const command = new CommandBuilder() + .setName("pitch") + .setDescription("Adjust the audio pitch of the current track (0.5× to 2.0×).", "commands.pitch") + .setCategory("music") + .addNumberOption(o => + o.setName("pitch") + .setDescription("Audio pitch multiplier between 0.5 and 2.0 (e.g. 1.25). Omit to reset to 1.0×.") + .setRequired(false) + ) + .addAliases("semitone", "tune"); + +/** + * Run handler for the pitch command. + * + * @param {object} message - The command message wrapper. + * @param {object} data - Parsed command data. + * @returns {Promise} + */ +export async function run(message, data) { + const p = await this.getPlayer(message, false, false, false); + if (!p) return; + + const rawPitch = data.get("pitch")?.value; + const embed = new EmbedBuilder().setColor(getGlobalColor()); + + if (rawPitch === null || rawPitch === undefined || isNaN(Number(rawPitch))) { + const currentTimescale = p.activeFilterPayload?.timescale; + const currentPitch = currentTimescale?.pitch ?? 1.0; + if (currentPitch !== 1.0) { + const existingPayload = { ...(p.activeFilterPayload || {}) }; + delete existingPayload.timescale; + await p.applyFilter(existingPayload, Object.keys(existingPayload).length > 0 ? p.activeFilter : null); + embed.setDescription("🎵 Audio pitch reset to normal **1.0×**."); + } else { + embed.setDescription(`🎵 Current audio pitch: **1.0×**.\nUse \`%pitch <0.5-2.0>\` to change pitch.`); + } + return message.reply({ embeds: [embed] }).catch(() => {}); + } + + const pitch = Utils.clamp(Number(rawPitch), 0.5, 2.0); + + const existingTimescale = p.activeFilterPayload?.timescale || {}; + const newTimescale = { + ...existingTimescale, + speed: existingTimescale.speed ?? 1.0, + pitch, + rate: 1.0, + }; + + const payload = { + ...(p.activeFilterPayload || {}), + timescale: newTimescale, + }; + + const filterMeta = { + key: `pitch_${pitch}`, + label: `${pitch}× Pitch`, + emoji: pitch > 1 ? "🐿️" : "🗣️", + }; + + const res = await p.applyFilter(payload, filterMeta); + if (!res.ok) { + embed.setDescription(`❌ Failed to adjust pitch: ${res.reason || "Unknown error"}`); + return message.reply({ embeds: [embed] }).catch(() => {}); + } + + embed.setDescription(`🎵 Audio pitch set to **${pitch}×**.`); + message.reply({ embeds: [embed] }).catch(() => {}); +} diff --git a/commands/speed.mjs b/commands/speed.mjs new file mode 100644 index 0000000..4e1b51e --- /dev/null +++ b/commands/speed.mjs @@ -0,0 +1,86 @@ +/** + * @module commands/speed + * @description Adjust real-time playback speed (0.5× to 2.0×) using timescale DSP filters. + */ + +import { CommandBuilder } from "../src/commands/index.mjs"; +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { Utils } from "../src/utils/Utils.mjs"; + +/** + * @type {CommandBuilder} + * @description Command definition for the speed command. + */ +export const command = new CommandBuilder() + .setName("speed") + .setDescription("Adjust the playback speed of the current track (0.5× to 2.0×).", "commands.speed") + .setCategory("music") + .addNumberOption(o => + o.setName("rate") + .setDescription("Playback speed multiplier between 0.5 and 2.0 (e.g. 1.25). Omit to reset to 1.0×.") + .setRequired(false) + ) + .addAliases("rate", "tempo"); + +/** + * Run handler for the speed command. + * + * @param {object} message - The command message wrapper. + * @param {object} data - Parsed command data. + * @returns {Promise} + */ +export async function run(message, data) { + const p = await this.getPlayer(message, false, false, false); + if (!p) return; + + const rawRate = data.get("rate")?.value; + const embed = new EmbedBuilder().setColor(getGlobalColor()); + + if (rawRate === null || rawRate === undefined || isNaN(Number(rawRate))) { + // Reset to 1.0 or show current speed + const currentTimescale = p.activeFilterPayload?.timescale; + const currentSpeed = currentTimescale?.speed ?? 1.0; + if (currentSpeed !== 1.0) { + // Reset + const existingPayload = { ...(p.activeFilterPayload || {}) }; + delete existingPayload.timescale; + await p.applyFilter(existingPayload, Object.keys(existingPayload).length > 0 ? p.activeFilter : null); + embed.setDescription("⏩ Playback speed reset to normal **1.0×**."); + } else { + embed.setDescription(`⏩ Current playback speed: **1.0×**.\nUse \`%speed <0.5-2.0>\` to change playback speed.`); + } + return message.reply({ embeds: [embed] }).catch(() => {}); + } + + const speed = Utils.clamp(Number(rawRate), 0.5, 2.0); + + // Preserve other active filters if present, update only timescale speed + const existingTimescale = p.activeFilterPayload?.timescale || {}; + const newTimescale = { + ...existingTimescale, + speed, + pitch: existingTimescale.pitch ?? 1.0, + rate: 1.0, + }; + + const payload = { + ...(p.activeFilterPayload || {}), + timescale: newTimescale, + }; + + const filterMeta = { + key: `speed_${speed}`, + label: `${speed}× Speed`, + emoji: speed > 1 ? "⏩" : "🐢", + }; + + const res = await p.applyFilter(payload, filterMeta); + if (!res.ok) { + embed.setDescription(`❌ Failed to adjust speed: ${res.reason || "Unknown error"}`); + return message.reply({ embeds: [embed] }).catch(() => {}); + } + + embed.setDescription(`${speed > 1 ? "⏩" : "🐢"} Playback speed set to **${speed}×**.`); + message.reply({ embeds: [embed] }).catch(() => {}); +} diff --git a/docker/nodelink.config.json b/docker/nodelink.config.json index 25c1bc7..f0a11ac 100644 --- a/docker/nodelink.config.json +++ b/docker/nodelink.config.json @@ -15,6 +15,12 @@ "defaultSource": "ytmusic", "fallback": true }, + "spotify": { + "playlistLoadLimit": 10 + }, + "soundcloud": { + "playlistLoadLimit": 10 + }, "audio": { "normalization": true }, diff --git a/src/music/audio/FluxerAudioBridge.mjs b/src/music/audio/FluxerAudioBridge.mjs index d5a6a86..49b4db3 100644 --- a/src/music/audio/FluxerAudioBridge.mjs +++ b/src/music/audio/FluxerAudioBridge.mjs @@ -97,11 +97,7 @@ export class FluxerAudioBridge extends EventEmitter { const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000); let durationMs = options.durationMs || 0; const filterPayload = options.filterPayload ?? null; - const loadstreamEnabled = isLoadstreamEnabled(); - - if (filterPayload && !loadstreamEnabled) { - logger.warn("[AudioBridge] Audio filter ignored — the loadstream route is disabled (config.json -> audio.allowLoadstream). Playing unfiltered."); - } + const loadstreamEnabled = isLoadstreamEnabled() || !!filterPayload; try { // ── Route A: /v4/trackstream — primary path, never touches /v4/loadstream. diff --git a/src/music/audio/VolumeNormalizer.mjs b/src/music/audio/VolumeNormalizer.mjs new file mode 100644 index 0000000..5699cac --- /dev/null +++ b/src/music/audio/VolumeNormalizer.mjs @@ -0,0 +1,100 @@ +/** + * @module src/music/audio/VolumeNormalizer + * @description Dynamic volume normalization and ReplayGain / EBU R128 loudness leveling. + * Balances acoustic/quiet recordings against loud EDM/rock tracks across YouTube, + * Spotify, SoundCloud, and Bilibili. + */ + +import { Utils } from "../../utils/Utils.mjs"; + +/** Target loudness reference according to EBU R128 / international streaming standards (LUFS). */ +export const TARGET_LUFS = -14.0; + +/** Baseline perceived loudness offsets per audio source platform (relative gain multipliers). */ +export const SOURCE_GAIN_OFFSETS = { + youtube: 1.00, // YouTube standard master target (-14 LUFS) + ytmusic: 1.00, // YouTube Music target (-14 LUFS) + spotify: 1.00, // Spotify standard target (-14 LUFS) + soundcloud: 0.82, // SoundCloud tracks average -10 to -8 LUFS (uncompressed loud mastering) -> -2.5dB + bilibili: 1.15, // Bilibili audio averages -17 to -20 LUFS -> +1.5dB boost + deezer: 0.95, // Deezer averages -13 LUFS + apple: 1.05, // Apple Music Sound Check averages -16 LUFS + bandcamp: 0.90, // Bandcamp self-mastered tracks average -11 LUFS +}; + +/** + * Detect the audio source key for a given track object. + * @param {object} track - Track or video metadata object. + * @returns {string} Source platform identifier. + */ +export function detectTrackSource(track) { + if (!track) return "youtube"; + const sourceName = (track.sourceName || track.source || "").toLowerCase(); + if (sourceName) { + if (sourceName.includes("soundcloud")) return "soundcloud"; + if (sourceName.includes("spotify")) return "spotify"; + if (sourceName.includes("bilibili")) return "bilibili"; + if (sourceName.includes("deezer")) return "deezer"; + if (sourceName.includes("apple")) return "apple"; + if (sourceName.includes("bandcamp")) return "bandcamp"; + if (sourceName.includes("youtube")) return "youtube"; + } + + const url = (track.url || track.uri || "").toLowerCase(); + if (url.includes("soundcloud.com")) return "soundcloud"; + if (url.includes("spotify.com")) return "spotify"; + if (url.includes("bilibili.com")) return "bilibili"; + if (url.includes("deezer.com")) return "deezer"; + if (url.includes("music.apple.com"))return "apple"; + if (url.includes("bandcamp.com")) return "bandcamp"; + + return "youtube"; +} + +/** + * Calculate the normalization gain multiplier for a given track. + * Uses EBU R128 loudness tags if present, otherwise applies calibrated source offset. + * Clamped between 0.50x (-6 dB) and 1.50x (+3.5 dB) to prevent clipping. + * + * @param {object|null} track - Track object. + * @returns {number} Gain multiplier (e.g. 1.0 = unity gain, 0.82 = -2.5dB). + */ +export function calculateNormalizationGain(track) { + if (!track) return 1.0; + + // Check for explicit ReplayGain or LUFS loudness tags in metadata + const measuredLufs = track.pluginInfo?.loudness ?? + track.info?.loudness ?? + track.loudness ?? + track.info?.replaygain; + + if (typeof measuredLufs === "number" && !isNaN(measuredLufs)) { + // EBU R128 formula: gain = 10 ^ ((Target - Measured) / 20) + const deltaDb = TARGET_LUFS - measuredLufs; + const gain = Math.pow(10, deltaDb / 20); + return Utils.clamp(gain, 0.50, 1.50); + } + + // Fallback to platform-calibrated baseline offset + const source = detectTrackSource(track); + const baseline = SOURCE_GAIN_OFFSETS[source] ?? 1.0; + return Utils.clamp(baseline, 0.50, 1.50); +} + +/** + * Compute the effective output volume percentage (0-200) given a user's preferred volume, + * current track, and normalization setting. + * + * @param {number} preferredVolume - Base volume fraction (e.g. 1.0 = 100%). + * @param {object|null} track - Currently playing track. + * @param {boolean} [normalizationEnabled=true] - Whether normalization is active. + * @returns {number} Effective volume percentage (0-200). + */ +export function getEffectiveVolume(preferredVolume = 1.0, track = null, normalizationEnabled = true) { + const base = Number.isFinite(preferredVolume) ? preferredVolume : 1.0; + if (!normalizationEnabled) { + return Utils.clamp(Math.round(base * 100), 0, 200); + } + const gain = calculateNormalizationGain(track); + return Utils.clamp(Math.round(base * gain * 100), 0, 200); +} diff --git a/src/music/player/PlaybackMixin.mjs b/src/music/player/PlaybackMixin.mjs index c94b64d..d6c95c5 100644 --- a/src/music/player/PlaybackMixin.mjs +++ b/src/music/player/PlaybackMixin.mjs @@ -146,8 +146,9 @@ const PlaybackMixin = { if (!this._voiceConn || this.leaving) return; - if (this.preferredVolume !== 1 && this._voiceConn) { - try { this._voiceConn.setVolume(this.preferredVolume * 100); } catch(_) {} + if (this._voiceConn) { + const vol = this.getEffectiveVolume ? this.getEffectiveVolume(songData) : (this.preferredVolume * 100); + try { this._voiceConn.setVolume(vol); } catch(_) {} } if (!this._voiceConn || this.leaving) return; @@ -491,24 +492,24 @@ const PlaybackMixin = { return { ok: false, reason: "Player not bound to a guild." }; } - if (filterMeta && !isLoadstreamEnabled()) { - logger.warn("[Player] applyFilter rejected — loadstream route disabled (audio.allowLoadstream), filters are NodeLink server-side effects"); - return { - ok: false, - reason: "filters need the NodeLink loadstream route — set audio.allowLoadstream to true in config.json; playback is unfiltered in trackstream mode", - }; - } - const current = this.queue.getCurrent(); this.activeFilter = filterMeta ?? null; - this.activeFilterPayload = filterMeta ? filterPayload : null; + this.activeFilterPayload = filterMeta && Object.keys(filterPayload || {}).length > 0 ? filterPayload : null; this.emit("filter", this.activeFilter); if (!current?.encoded || !this._voiceConn) { return { ok: true, pending: true }; } + // Hot-apply filter immediately to currently playing song + const pos = this.computePosition ? this.computePosition() : (Date.now() - (this.startedPlaying || Date.now())); + try { + await this.seekToPosition(Math.max(0, pos)); + } catch (e) { + logger.warn("[Player] Hot-apply filter re-seek error:", e?.message); + } + return { ok: true }; }, diff --git a/src/music/player/Player.mjs b/src/music/player/Player.mjs index 376e85d..6749b3e 100644 --- a/src/music/player/Player.mjs +++ b/src/music/player/Player.mjs @@ -18,6 +18,7 @@ import { logger } from "../../core/Logger.mjs"; import { get247ChannelMode, detachPlayerFromManager } from "../../utils/Helpers247.mjs"; import { hasHumansInChannel } from "../../voice/VoiceStateResolver.mjs"; import { FluxerAudioBridge } from "../audio/FluxerAudioBridge.mjs"; +import { getEffectiveVolume } from "../audio/VolumeNormalizer.mjs"; import { applyMixins } from "../../utils/mixins.mjs"; import { Queue } from "./Queue.mjs"; import PlaybackMixin from "./PlaybackMixin.mjs"; @@ -889,6 +890,18 @@ class Player extends EventEmitter { return `:track_next: Skipped to position ${position}`; } + /** + * Get the effective playback volume percentage (0-200), applying dynamic + * volume normalization (ReplayGain / EBU R128) if enabled. + * @param {object|null} [track=null] + * @returns {number} Effective volume percentage (0-200). + */ + getEffectiveVolume(track = null) { + const cur = track || this.queue?.getCurrent?.(); + const isNorm = this.volumeNormalization !== false; + return getEffectiveVolume(this.preferredVolume, cur, isNorm); + } + /** * Set the playback volume. * @param {number} v - Volume as a decimal (0–2, where 1 = 100%). @@ -898,7 +911,9 @@ class Player extends EventEmitter { this.preferredVolume = Utils.clamp(v, 0, 2); this.emit("volume", this.preferredVolume); if (this._voiceConn) { - this._voiceConn.setVolume(this.preferredVolume * 100); + try { + this._voiceConn.setVolume(this.getEffectiveVolume()); + } catch (_) {} } if (!this._voiceConn) return `Volume set to \`${Math.round(this.preferredVolume * 100)}%\` — will apply when connected.`; diff --git a/src/music/player/SearchMixin.mjs b/src/music/player/SearchMixin.mjs index a615c0a..24672cb 100644 --- a/src/music/player/SearchMixin.mjs +++ b/src/music/player/SearchMixin.mjs @@ -554,9 +554,78 @@ const SearchMixin = { } if (isUrl && !fromTitleFallback && lcTracks.length > 1) { - const videos = lcTracks.map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean); - this.addManyToQueue(videos, top); - events.emit("message", "Successfully added **" + videos.length + "** songs to the queue."); + const playlistName = result?.playlistInfo?.name ?? result?.info?.name ?? "playlist"; + const allRawTracks = [...lcTracks]; + + // Check if there are additional pages from NodeLink / LavaSrc pagination (Issue #17) + let nextPageToken = result?.pluginInfo?.nextPageToken ?? result?.playlistInfo?.nextPageToken; + let page = 1; + const maxPages = 10; + while (nextPageToken && page < maxPages) { + try { + page++; + events.emit("message", `Fetching next page of **${playlistName}** (page ${page})...`); + const nextResult = await this._lavalink.search(query, { + page, + pageToken: nextPageToken, + }); + const nextTracks = nextResult?.tracks ?? []; + if (nextTracks.length === 0) break; + allRawTracks.push(...nextTracks); + nextPageToken = nextResult?.pluginInfo?.nextPageToken ?? nextResult?.playlistInfo?.nextPageToken; + } catch (pageErr) { + logger.warn(`[Player] Playlist pagination page ${page} error:`, pageErr?.message); + break; + } + } + + const BATCH_SIZE = 50; + if (allRawTracks.length <= BATCH_SIZE) { + const videos = allRawTracks.map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean); + this.addManyToQueue(videos, top); + events.emit("message", `Successfully added **${videos.length}** songs to the queue.`); + } else { + // Paginated background queue ingestion (Issue #17) + const initialRaw = allRawTracks.slice(0, BATCH_SIZE); + const initialVideos = initialRaw.map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean); + this.addManyToQueue(initialVideos, top); + + // Start playing immediately if idle so user hears music right away! + if (!this.queue.getCurrent()) { + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + } + + events.emit("message", `Queued first **${initialVideos.length}** songs and started playback! Ingesting **${allRawTracks.length - initialVideos.length}** more tracks in the background...`); + + // Ingest remaining tracks in the background without blocking the event loop + (async () => { + let loaded = initialVideos.length; + let lastStatusTime = Date.now(); + const remainingRaw = allRawTracks.slice(BATCH_SIZE); + + for (let i = 0; i < remainingRaw.length; i += BATCH_SIZE) { + await new Promise(r => setTimeout(r, 150)); + if (this._destroyed || this.leaving) break; + + const chunk = remainingRaw.slice(i, i + BATCH_SIZE) + .map(t => this._lcTrackToVideo(t, trackMeta)) + .filter(Boolean); + this.addManyToQueue(chunk, false); + loaded += chunk.length; + + const now = Date.now(); + if (now - lastStatusTime >= 2000 && loaded < allRawTracks.length) { + lastStatusTime = now; + events.emit("message", `Importing playlist: **${loaded}/${allRawTracks.length}** tracks queued...`); + } + } + + events.emit("message", `Successfully added all **${loaded}** songs to the queue from **${playlistName}**.`); + })().catch(ingestErr => { + logger.warn("[Player] Background playlist ingestion error:", ingestErr?.message); + }); + return; + } } else { const video = this._lcTrackToVideo(firstTrack, trackMeta); if (video) { diff --git a/storage/defaults.json b/storage/defaults.json index 0e41d13..957207d 100644 --- a/storage/defaults.json +++ b/storage/defaults.json @@ -6,6 +6,7 @@ "locale": "en", "stay_247": "none", "volume": 100, + "normalize": true, "voteSkip": true, "voteSkipThreshold": 3 }, @@ -16,6 +17,7 @@ "locale": "The preferred language of your server.", "stay_247": "Join a voice channel and use `$prefix247` to toggle 24/7. The bot stays permanently and auto-rejoins if disconnected. Use `$prefix247 off` to disable.", "volume": "The default playback volume for this server (1-200). Saved automatically when you use $prefixvolume.", + "normalize": "Whether dynamic volume normalization (ReplayGain / EBU R128) is enabled to level playback loudness across YouTube, Spotify, and SoundCloud. Use $prefixnormalize to toggle.", "voteSkip": "Whether a majority vote is required to skip when several people are listening. Set to `true` or `1` to enable (default), `false` or `0` to let anyone skip instantly.", "voteSkipThreshold": "The number of people in the voice channel (2-50) at which a skip vote is required instead of an instant skip. Default is `3`." }