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)
This commit is contained in:
NoLogicAlan committed 2026-10-22 01:59:45 +03:00
1 parent 90a53f047f
commit 351336ea19
13 files changed
+621 -23

No files matched your search

+1 -5
View File
@@ -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.
+100
View File
@@ -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);
}
+12 -11
View File
@@ -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 };
},
+16 -1
View File
@@ -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.`;
+72 -3
View File
@@ -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) {