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";
|
import { promisify } from "node:util";
|
||||||
|
|
||||||
const execFileAsync = promisify(execFile);
|
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 {
|
try {
|
||||||
const { stdout } = await execFileAsync(
|
const { stdout } = await execFileAsync(
|
||||||
"ffprobe",
|
"ffprobe",
|
||||||
[
|
[
|
||||||
"-v",
|
"-v",
|
||||||
"error",
|
"error",
|
||||||
"-select_streams",
|
|
||||||
"a:0",
|
|
||||||
"-show_entries",
|
"-show_entries",
|
||||||
"stream=codec_type",
|
"format=duration:format_tags:stream=codec_type:stream_tags",
|
||||||
"-of",
|
"-of",
|
||||||
"default=noprint_wrappers=1:nokey=1",
|
"json",
|
||||||
filePath,
|
filePath,
|
||||||
],
|
],
|
||||||
{ timeout: 15_000, maxBuffer: 1024 * 1024 }
|
{ timeout: 15_000, maxBuffer: 1024 * 1024 }
|
||||||
);
|
);
|
||||||
|
parsed = JSON.parse(stdout);
|
||||||
if (stdout.trim() !== "audio") {
|
|
||||||
throw new Error("Aucune piste audio détectée");
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const validationError = new Error("Le fichier fourni n'est pas un audio valide");
|
throw invalidAudioError(error);
|
||||||
validationError.status = 400;
|
|
||||||
validationError.cause = error;
|
|
||||||
throw validationError;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 };
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
import fs from "fs";
|
|
||||||
import { EventEmitter } from "events";
|
import { EventEmitter } from "events";
|
||||||
import {
|
import {
|
||||||
AudioPlayerStatus,
|
AudioPlayerStatus,
|
||||||
NoSubscriberBehavior,
|
NoSubscriberBehavior,
|
||||||
|
StreamType,
|
||||||
VoiceConnectionStatus,
|
VoiceConnectionStatus,
|
||||||
createAudioPlayer,
|
createAudioPlayer,
|
||||||
createAudioResource,
|
createAudioResource,
|
||||||
|
|
@ -11,6 +11,7 @@ import {
|
||||||
} from "@discordjs/voice";
|
} from "@discordjs/voice";
|
||||||
import { Events } from "discord.js";
|
import { Events } from "discord.js";
|
||||||
import { config } from "../config.js";
|
import { config } from "../config.js";
|
||||||
|
import { createOpusStream } from "../media/validateAudioFile.js";
|
||||||
import { serializeTrack, serializeTracks } from "../web/serializers.js";
|
import { serializeTrack, serializeTracks } from "../web/serializers.js";
|
||||||
import {
|
import {
|
||||||
deleteTrackFile,
|
deleteTrackFile,
|
||||||
|
|
@ -80,6 +81,8 @@ class MusicQueue extends EventEmitter {
|
||||||
current: serializeTrack(this.currentTrack),
|
current: serializeTrack(this.currentTrack),
|
||||||
upcoming: serializeTracks(this.queue),
|
upcoming: serializeTracks(this.queue),
|
||||||
status: this.playbackStatus,
|
status: this.playbackStatus,
|
||||||
|
// Millisecondes déjà jouées du morceau en cours (pauses exclues).
|
||||||
|
position: this.audioPlayer?.state?.resource?.playbackDuration ?? 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -245,7 +248,9 @@ class MusicQueue extends EventEmitter {
|
||||||
}
|
}
|
||||||
|
|
||||||
createResource(track) {
|
createResource(track) {
|
||||||
return createAudioResource(fs.createReadStream(track.path));
|
return createAudioResource(createOpusStream(track.path), {
|
||||||
|
inputType: StreamType.OggOpus,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
scheduleConnectRetry() {
|
scheduleConnectRetry() {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import multer from "multer";
|
import multer from "multer";
|
||||||
import { validateAudioFile } from "../../media/validateAudioFile.js";
|
import { probeAudioFile } from "../../media/validateAudioFile.js";
|
||||||
import { serializeTrack } from "../serializers.js";
|
import { serializeTrack } from "../serializers.js";
|
||||||
import {
|
import {
|
||||||
TEMP_DIR,
|
TEMP_DIR,
|
||||||
|
|
@ -29,6 +29,15 @@ const upload = multer({
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Titre par défaut : « Artiste - Titre » d'après les tags, sinon le nom du fichier sans
|
||||||
|
// son extension.
|
||||||
|
function defaultTitle({ title, artist }, originalName) {
|
||||||
|
if (title) {
|
||||||
|
return (artist ? `${artist} - ${title}` : title).slice(0, 200);
|
||||||
|
}
|
||||||
|
return originalName.replace(/\.[a-z0-9]{1,10}$/i, "").slice(0, 200) || originalName;
|
||||||
|
}
|
||||||
|
|
||||||
function uploadsRouter({ queue }) {
|
function uploadsRouter({ queue }) {
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
||||||
|
|
@ -43,7 +52,7 @@ function uploadsRouter({ queue }) {
|
||||||
.replace(/[\u0000-\u001f]/g, "")
|
.replace(/[\u0000-\u001f]/g, "")
|
||||||
.trim()
|
.trim()
|
||||||
.slice(0, 80);
|
.slice(0, 80);
|
||||||
const title = String(req.body?.notes || req.file.originalname)
|
const customTitle = String(req.body?.notes || "")
|
||||||
.replace(/[\u0000-\u001f]/g, "")
|
.replace(/[\u0000-\u001f]/g, "")
|
||||||
.trim()
|
.trim()
|
||||||
.slice(0, 200);
|
.slice(0, 200);
|
||||||
|
|
@ -57,12 +66,17 @@ function uploadsRouter({ queue }) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
await validateAudioFile(req.file.path);
|
const metadata = await probeAudioFile(req.file.path);
|
||||||
const track = registerUploadedFile(req.file, {
|
const track = registerUploadedFile(req.file, {
|
||||||
permanent,
|
permanent,
|
||||||
uploader,
|
uploader,
|
||||||
title: title || req.file.originalname,
|
title: customTitle || defaultTitle(metadata, req.file.originalname),
|
||||||
|
duration: metadata.duration,
|
||||||
|
artist: metadata.artist,
|
||||||
});
|
});
|
||||||
|
if (permanent) {
|
||||||
|
queue.emit("libraryUpdate");
|
||||||
|
}
|
||||||
|
|
||||||
if (enqueue) {
|
if (enqueue) {
|
||||||
queue.enqueue(track);
|
queue.enqueue(track);
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ import { notificationsRouter } from "./routes/notifications.js";
|
||||||
import { playerRouter } from "./routes/player.js";
|
import { playerRouter } from "./routes/player.js";
|
||||||
import { queueRouter } from "./routes/queue.js";
|
import { queueRouter } from "./routes/queue.js";
|
||||||
import { uploadsRouter } from "./routes/uploads.js";
|
import { uploadsRouter } from "./routes/uploads.js";
|
||||||
|
import { backfillLibraryMetadata } from "./storage/libraryMetadata.js";
|
||||||
import {
|
import {
|
||||||
cleanupTemporaryFiles,
|
cleanupTemporaryFiles,
|
||||||
ensureStorageLayout,
|
ensureStorageLayout,
|
||||||
|
|
@ -120,6 +121,17 @@ function startWebServer(dependencies) {
|
||||||
const cleanupInterval = setInterval(cleanup, TEMP_CLEANUP_INTERVAL);
|
const cleanupInterval = setInterval(cleanup, TEMP_CLEANUP_INTERVAL);
|
||||||
cleanupInterval.unref();
|
cleanupInterval.unref();
|
||||||
|
|
||||||
|
backfillLibraryMetadata()
|
||||||
|
.then((updated) => {
|
||||||
|
if (updated.length > 0) {
|
||||||
|
console.log(
|
||||||
|
`[${new Date().toLocaleString()}] Library metadata completed for ${updated.length} track(s)`
|
||||||
|
);
|
||||||
|
dependencies.queue.emit("libraryUpdate");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => console.error("Unable to complete library metadata", error));
|
||||||
|
|
||||||
const app = createApp(dependencies);
|
const app = createApp(dependencies);
|
||||||
const port = Number(process.env.PORT || config.webServerPort || 3000);
|
const port = Number(process.env.PORT || config.webServerPort || 3000);
|
||||||
|
|
||||||
|
|
|
||||||
24
src/web/storage/libraryMetadata.js
Normal file
24
src/web/storage/libraryMetadata.js
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
import { probeAudioFile } from "../../media/validateAudioFile.js";
|
||||||
|
import { getPermanentLibrary, updatePermanentTracks } from "./storageManager.js";
|
||||||
|
|
||||||
|
// Complète la durée et l'artiste des morceaux ajoutés avant que l'upload ne les relève.
|
||||||
|
// Un fichier illisible est ignoré : il sera retenté au prochain démarrage.
|
||||||
|
async function backfillLibraryMetadata({ probe = probeAudioFile } = {}) {
|
||||||
|
const missing = getPermanentLibrary().filter((entry) => entry.duration == null);
|
||||||
|
const updates = new Map();
|
||||||
|
|
||||||
|
for (const entry of missing) {
|
||||||
|
try {
|
||||||
|
const { duration, artist } = await probe(entry.path);
|
||||||
|
if (duration != null) {
|
||||||
|
updates.set(entry.id, { duration, artist: entry.artist ?? artist });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Unable to read metadata of library entry ${entry.id}`, error.cause ?? error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return updatePermanentTracks(updates);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { backfillLibraryMetadata };
|
||||||
|
|
@ -87,7 +87,13 @@ function writeLibrary(entries) {
|
||||||
|
|
||||||
function registerUploadedFile(
|
function registerUploadedFile(
|
||||||
file,
|
file,
|
||||||
{ permanent, uploader = "unknown", title = file.originalname }
|
{
|
||||||
|
permanent,
|
||||||
|
uploader = "unknown",
|
||||||
|
title = file.originalname,
|
||||||
|
duration = null,
|
||||||
|
artist = null,
|
||||||
|
}
|
||||||
) {
|
) {
|
||||||
ensureStorageLayout();
|
ensureStorageLayout();
|
||||||
const createdAt = new Date().toISOString();
|
const createdAt = new Date().toISOString();
|
||||||
|
|
@ -120,6 +126,8 @@ function registerUploadedFile(
|
||||||
path: finalPath,
|
path: finalPath,
|
||||||
size: file.size,
|
size: file.size,
|
||||||
mimetype: file.mimetype,
|
mimetype: file.mimetype,
|
||||||
|
duration,
|
||||||
|
artist,
|
||||||
uploader,
|
uploader,
|
||||||
createdAt,
|
createdAt,
|
||||||
};
|
};
|
||||||
|
|
@ -135,6 +143,8 @@ function registerUploadedFile(
|
||||||
storedName,
|
storedName,
|
||||||
size: file.size,
|
size: file.size,
|
||||||
mimetype: file.mimetype,
|
mimetype: file.mimetype,
|
||||||
|
duration,
|
||||||
|
artist,
|
||||||
permanent,
|
permanent,
|
||||||
uploader,
|
uploader,
|
||||||
libraryTrackId: permanentEntry ? permanentEntry.id : null,
|
libraryTrackId: permanentEntry ? permanentEntry.id : null,
|
||||||
|
|
@ -164,6 +174,8 @@ function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") {
|
||||||
storedName: libraryTrack.storedName,
|
storedName: libraryTrack.storedName,
|
||||||
size: libraryTrack.size,
|
size: libraryTrack.size,
|
||||||
mimetype: libraryTrack.mimetype,
|
mimetype: libraryTrack.mimetype,
|
||||||
|
duration: libraryTrack.duration ?? null,
|
||||||
|
artist: libraryTrack.artist ?? null,
|
||||||
permanent: true,
|
permanent: true,
|
||||||
uploader: requestedBy,
|
uploader: requestedBy,
|
||||||
libraryTrackId: libraryTrack.id,
|
libraryTrackId: libraryTrack.id,
|
||||||
|
|
@ -211,6 +223,24 @@ function discardUploadedFile(file) {
|
||||||
deleteFileSafe(file?.path);
|
deleteFileSafe(file?.path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Modifie des champs d'entrées de la bibliothèque : updates est une Map id → champs.
|
||||||
|
// Relit le fichier juste avant d'écrire, pour ne pas écraser un ajout fait entre-temps.
|
||||||
|
function updatePermanentTracks(updates) {
|
||||||
|
const library = getPermanentLibrary();
|
||||||
|
const updated = [];
|
||||||
|
for (const entry of library) {
|
||||||
|
const fields = updates.get(entry.id);
|
||||||
|
if (fields) {
|
||||||
|
Object.assign(entry, fields);
|
||||||
|
updated.push(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (updated.length > 0) {
|
||||||
|
writeLibrary(library);
|
||||||
|
}
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
function deletePermanentTrack(id) {
|
function deletePermanentTrack(id) {
|
||||||
const library = getPermanentLibrary();
|
const library = getPermanentLibrary();
|
||||||
const index = library.findIndex((entry) => entry.id === id);
|
const index = library.findIndex((entry) => entry.id === id);
|
||||||
|
|
@ -252,6 +282,7 @@ export {
|
||||||
cleanupTemporaryFiles,
|
cleanupTemporaryFiles,
|
||||||
discardUploadedFile,
|
discardUploadedFile,
|
||||||
deletePermanentTrack,
|
deletePermanentTrack,
|
||||||
|
updatePermanentTracks,
|
||||||
handleTrackCompletion,
|
handleTrackCompletion,
|
||||||
deleteTrackFile,
|
deleteTrackFile,
|
||||||
};
|
};
|
||||||
|
|
|
||||||
68
test/audio.test.js
Normal file
68
test/audio.test.js
Normal 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");
|
||||||
|
});
|
||||||
|
|
@ -49,6 +49,7 @@ test("queue snapshots do not expose filesystem paths", () => {
|
||||||
current: { id: "current" },
|
current: { id: "current" },
|
||||||
upcoming: [{ id: "next" }],
|
upcoming: [{ id: "next" }],
|
||||||
status: "playing",
|
status: "playing",
|
||||||
|
position: 0,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -81,3 +81,36 @@ test("legacy library entries migrate without their absolute paths", async () =>
|
||||||
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
|
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 });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue