Encode jukebox audio with native ffmpeg, normalise loudness, read metadata
- Play every track through an ffmpeg process that normalises loudness (EBU R128) and outputs Ogg Opus, handed to Discord as is: no more Opus encoding in JavaScript with opusscript. Measured at over 40x real time, about 2% of a core while playing. Closing the stream kills ffmpeg. - Encoding at upload instead was ruled out: over two minutes for an 85-minute mix, during which the upload would hang. - Read duration, title and artist with ffprobe at upload; default the title to "Artist - Title" or the file name without extension. - Fill the duration of existing library entries at startup. - Expose the position of the current track in queue snapshots. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
d200040691
commit
98f4d29ac7
9 changed files with 309 additions and 22 deletions
|
|
@ -1,35 +1,134 @@
|
|||
import { execFile } from "node:child_process";
|
||||
import { execFile, spawn } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
async function validateAudioFile(filePath) {
|
||||
// Normalisation du volume (EBU R128, mode dynamique en une passe) : tous les morceaux sortent
|
||||
// au même niveau, quel que soit le fichier d'origine.
|
||||
const LOUDNORM_FILTER = "loudnorm=I=-16:TP=-1.5:LRA=11";
|
||||
const MAX_STDERR_LENGTH = 4_000;
|
||||
|
||||
function cleanTag(value) {
|
||||
if (typeof value !== "string") return null;
|
||||
const cleaned = value.replace(/[\u0000-\u001f]/g, "").trim().slice(0, 200);
|
||||
return cleaned || null;
|
||||
}
|
||||
|
||||
// Les noms des tags varient selon le format (« title » en ID3, « TITLE » en Vorbis) : on les
|
||||
// met en minuscules. Les tags Ogg sont portés par le flux, les autres par le conteneur.
|
||||
function lowerCaseTags(...tagSets) {
|
||||
const tags = {};
|
||||
for (const set of tagSets) {
|
||||
for (const [key, value] of Object.entries(set || {})) {
|
||||
tags[key.toLowerCase()] ??= value;
|
||||
}
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
// Vérifie qu'un fichier contient une piste audio et lit sa durée (secondes) et ses tags.
|
||||
async function probeAudioFile(filePath) {
|
||||
let parsed;
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
"ffprobe",
|
||||
[
|
||||
"-v",
|
||||
"error",
|
||||
"-select_streams",
|
||||
"a:0",
|
||||
"-show_entries",
|
||||
"stream=codec_type",
|
||||
"format=duration:format_tags:stream=codec_type:stream_tags",
|
||||
"-of",
|
||||
"default=noprint_wrappers=1:nokey=1",
|
||||
"json",
|
||||
filePath,
|
||||
],
|
||||
{ timeout: 15_000, maxBuffer: 1024 * 1024 }
|
||||
);
|
||||
|
||||
if (stdout.trim() !== "audio") {
|
||||
throw new Error("Aucune piste audio détectée");
|
||||
}
|
||||
parsed = JSON.parse(stdout);
|
||||
} catch (error) {
|
||||
const validationError = new Error("Le fichier fourni n'est pas un audio valide");
|
||||
validationError.status = 400;
|
||||
validationError.cause = error;
|
||||
throw validationError;
|
||||
throw invalidAudioError(error);
|
||||
}
|
||||
|
||||
const audioStream = parsed.streams?.find((stream) => stream.codec_type === "audio");
|
||||
if (!audioStream) {
|
||||
throw invalidAudioError(new Error("Aucune piste audio détectée"));
|
||||
}
|
||||
|
||||
const duration = Number(parsed.format?.duration);
|
||||
const tags = lowerCaseTags(parsed.format?.tags, audioStream.tags);
|
||||
return {
|
||||
duration: Number.isFinite(duration) && duration > 0 ? Math.round(duration) : null,
|
||||
title: cleanTag(tags.title),
|
||||
artist: cleanTag(tags.artist),
|
||||
};
|
||||
}
|
||||
|
||||
export { validateAudioFile };
|
||||
function invalidAudioError(cause) {
|
||||
const error = new Error("Le fichier fourni n'est pas un audio valide");
|
||||
error.status = 400;
|
||||
error.cause = cause;
|
||||
return error;
|
||||
}
|
||||
|
||||
async function validateAudioFile(filePath) {
|
||||
await probeAudioFile(filePath);
|
||||
}
|
||||
|
||||
// Décode le fichier, normalise le volume et encode en Ogg Opus avec le ffmpeg natif : Discord
|
||||
// reçoit l'Opus tel quel, sans réencodage en JavaScript. Fermer le flux arrête ffmpeg.
|
||||
function createOpusStream(filePath, { spawnProcess = spawn } = {}) {
|
||||
const ffmpeg = spawnProcess(
|
||||
"ffmpeg",
|
||||
[
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-i",
|
||||
filePath,
|
||||
"-map",
|
||||
"0:a:0",
|
||||
"-vn",
|
||||
"-af",
|
||||
LOUDNORM_FILTER,
|
||||
"-c:a",
|
||||
"libopus",
|
||||
"-b:a",
|
||||
"128k",
|
||||
"-ar",
|
||||
"48000",
|
||||
"-ac",
|
||||
"2",
|
||||
"-f",
|
||||
"ogg",
|
||||
"pipe:1",
|
||||
],
|
||||
{ stdio: ["ignore", "pipe", "pipe"] }
|
||||
);
|
||||
|
||||
const output = ffmpeg.stdout;
|
||||
let stderr = "";
|
||||
ffmpeg.stderr.on("data", (chunk) => {
|
||||
if (stderr.length < MAX_STDERR_LENGTH) {
|
||||
stderr += chunk.toString();
|
||||
}
|
||||
});
|
||||
|
||||
ffmpeg.on("error", (error) => {
|
||||
output.destroy(error);
|
||||
});
|
||||
ffmpeg.on("close", (code, signal) => {
|
||||
if (code !== 0 && signal === null && !output.destroyed) {
|
||||
output.destroy(
|
||||
new Error(`ffmpeg exited with code ${code}: ${stderr.trim().slice(0, 500)}`)
|
||||
);
|
||||
}
|
||||
});
|
||||
output.on("close", () => {
|
||||
if (ffmpeg.exitCode === null && ffmpeg.signalCode === null) {
|
||||
ffmpeg.kill("SIGKILL");
|
||||
}
|
||||
});
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
export { LOUDNORM_FILTER, createOpusStream, probeAudioFile, validateAudioFile };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue