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:
Shinuwa 2026-11-29 12:10:49 +01:00
parent d200040691
commit 98f4d29ac7
9 changed files with 309 additions and 22 deletions

68
test/audio.test.js Normal file
View file

@ -0,0 +1,68 @@
import test from "node:test";
import assert from "node:assert/strict";
import { spawn, spawnSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { StreamType, createAudioResource } from "@discordjs/voice";
import { createOpusStream, probeAudioFile } from "../src/media/validateAudioFile.js";
const hasFfmpeg =
spawnSync("ffmpeg", ["-version"]).status === 0 &&
spawnSync("ffprobe", ["-version"]).status === 0;
const skip = hasFfmpeg ? false : "ffmpeg et ffprobe sont nécessaires";
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-audio-"));
test.after(() => fs.rmSync(directory, { recursive: true, force: true }));
// Un MP3 de `seconds` secondes (un la à 440 Hz) avec des tags ID3.
function makeTone(name, seconds, { title = "Chanson", artist = "Palico" } = {}) {
const file = path.join(directory, name);
const result = spawnSync("ffmpeg", [
"-v", "error", "-y",
"-f", "lavfi", "-i", `sine=frequency=440:duration=${seconds}`,
"-metadata", `title=${title}`, "-metadata", `artist=${artist}`,
"-c:a", "libmp3lame", "-b:a", "64k", file,
]);
assert.equal(result.status, 0, result.stderr?.toString());
return file;
}
test("probeAudioFile reads the duration and the tags", { skip }, async () => {
const metadata = await probeAudioFile(makeTone("tagged.mp3", 2));
assert.equal(metadata.duration, 2);
assert.equal(metadata.title, "Chanson");
assert.equal(metadata.artist, "Palico");
});
test("probeAudioFile rejects a file without audio", { skip }, async () => {
const file = path.join(directory, "not-audio.mp3");
fs.writeFileSync(file, "pas du son");
await assert.rejects(probeAudioFile(file), { status: 400 });
});
test("createOpusStream yields Opus packets that Discord can play as is", { skip }, async () => {
const resource = createAudioResource(createOpusStream(makeTone("short.mp3", 1)), {
inputType: StreamType.OggOpus,
});
let packets = 0;
for await (const packet of resource.playStream) {
assert.ok(Buffer.isBuffer(packet) && packet.length > 0);
packets += 1;
}
// 1 s d'audio en trames Opus de 20 ms : une cinquantaine de paquets.
assert.ok(packets >= 45, `${packets} paquets`);
});
test("closing the Opus stream stops ffmpeg", { skip }, async () => {
let child;
const output = createOpusStream(makeTone("long.mp3", 120), {
spawnProcess: (...args) => (child = spawn(...args)),
});
await new Promise((resolve) => output.once("data", resolve));
const exited = new Promise((resolve) => child.once("exit", (_code, signal) => resolve(signal)));
output.destroy();
assert.equal(await exited, "SIGKILL");
});

View file

@ -49,6 +49,7 @@ test("queue snapshots do not expose filesystem paths", () => {
current: { id: "current" },
upcoming: [{ id: "next" }],
status: "playing",
position: 0,
});
});

View file

@ -81,3 +81,36 @@ test("legacy library entries migrate without their absolute paths", async () =>
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
}
});
test("library metadata backfill fills the missing durations", async () => {
const originalDirectory = process.cwd();
const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-storage-"));
try {
process.chdir(temporaryDirectory);
const storage = await import(`../src/web/storage/storageManager.js?backfill=${Date.now()}`);
storage.ensureStorageLayout();
const uploadedPath = path.join(storage.TEMP_DIR, "upload");
fs.writeFileSync(uploadedPath, "fake audio content");
storage.registerUploadedFile(
{ path: uploadedPath, originalname: "old.mp3", size: 18, mimetype: "audio/mpeg" },
{ permanent: true, uploader: "test", title: "Old" }
);
// libraryMetadata.js importe storageManager.js sans paramètre : on passe par la même
// instance de module que lui, avec le répertoire de travail temporaire.
const { backfillLibraryMetadata } = await import("../src/web/storage/libraryMetadata.js");
const shared = await import("../src/web/storage/storageManager.js");
shared.ensureStorageLayout();
const updated = await backfillLibraryMetadata({
probe: async () => ({ duration: 42, artist: "Palico", title: null }),
});
assert.equal(updated.length, 1);
assert.equal(shared.getPermanentLibrary()[0].duration, 42);
assert.equal(shared.getPermanentLibrary()[0].artist, "Palico");
} finally {
process.chdir(originalDirectory);
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
}
});