// One file's analysis -- the bench's waveform, the mix bench's envelope and // brightness -- and the disk cache it lives in. // // Plain ESM, so a plain node process makes the very file the app reads: the // bench's prep (lib/report/benchPrep.mjs, `umtool prep`) analyses a clip's // window ahead of the walk, and /api/report/peaks (through lib/media.ts // analyseMedia, which keeps the type and an in-memory memo) then finds it. // The key is spelled once, here. // // One decode per file gives everything the bench draws: // // peak a plain envelope, for the shape of the track // ratio high-band over low-band energy -- WHERE A CUE STARTS // firstSound the first sustained sound, matched to ffmpeg's own // silencedetect so the number on screen equals the number the // command line would print import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync } from "node:fs"; import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { MIX_CACHE, labelFor } from "./paths.mjs"; import { brightnessCurve, brightnessSteps } from "../song/flatness.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Analysis sample rate. 16 kHz resolves the whole band the ratio looks at. */ const ANALYSIS_SR = 16000; /** Envelope frames per second. */ export const ENV_RATE = 100; /** Brightness frames per second. */ export const RATIO_RATE = 50; /** -45 dBFS, held for 150ms: the same test `silencedetect=n=-45dB:d=0.15` makes. */ const SILENCE_FLOOR = 10 ** (-45 / 20); const SILENCE_HOLD = 0.15; /** Refuse to decode something absurd rather than sitting on it. */ const MAX_ANALYSIS_SECONDS = 3600; /** The key: the file's absolute path, its mtime and its size. */ export const analysisCacheKey = (abs, mtimeMs, size) => createHash("sha1").update(`${abs}|${Math.round(mtimeMs)}|${size}|v3`).digest("hex").slice(0, 16); /** * The cache file for `abs` as it is now (`st` is its stat). * @param {string} abs * @param {{ mtimeMs: number, size: number }} st * @param {string} [dir] */ export const analysisCacheFile = (abs, st, dir = MIX_CACHE) => path.join(/* turbopackIgnore: true */ dir, `${analysisCacheKey(abs, st.mtimeMs, st.size)}.json`); /** @param {string} abs */ async function decodeMono(abs) { /** @type {Buffer[]} */ const chunks = []; await new Promise((resolve, reject) => { const ff = spawn("ffmpeg", [ "-nostdin", "-v", "error", "-i", abs, "-map", "a:0?", "-ac", "1", "-ar", String(ANALYSIS_SR), "-f", "f32le", "-", ]); let err = ""; ff.stdout.on("data", (b) => chunks.push(b)); ff.stderr.on("data", (b) => { err += b.toString(); }); ff.on("error", reject); ff.on("close", (code) => (code === 0 ? resolve(undefined) : reject(new Error(err.trim() || `ffmpeg exited ${code}`)))); }); const buf = Buffer.concat(chunks); // Buffer.concat may hand back a view into a larger pool, so honour the offset // -- reading from byteOffset 0 would silently analyse the wrong bytes. const usable = buf.length - (buf.length % 4); return new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + usable)); } /** * Envelope + brightness for a whole track, from the disk cache when it is * there, else decoded and written to it. * * @param {string} abs * @param {{ st?: { mtimeMs: number, size: number }, cacheDir?: string }} [opts] */ export async function analyseFile(abs, { st = undefined, cacheDir = MIX_CACHE } = {}) { const s = st ?? (await stat(abs)); const file = analysisCacheFile(abs, s, cacheDir); if (existsSync(/* turbopackIgnore: true */ file)) { try { return JSON.parse(await readFile(file, "utf8")); } catch { /* rewrite it below */ } } const x = await decodeMono(abs); const duration = x.length / ANALYSIS_SR; if (duration > MAX_ANALYSIS_SECONDS) { throw new Error(`${labelFor(abs)} is ${Math.round(duration)}s; the bench analyses up to ${MAX_ANALYSIS_SECONDS}s`); } const envHop = Math.round(ANALYSIS_SR / ENV_RATE); const peak = []; for (let i = 0; i + envHop <= x.length; i += envHop) { let p = 0; for (let k = 0; k < envHop; k += 1) { const v = x[i + k] < 0 ? -x[i + k] : x[i + k]; if (v > p) p = v; } peak.push(+p.toFixed(5)); } const holdFrames = Math.max(1, Math.round(SILENCE_HOLD * ENV_RATE)); let firstSound = null; for (let i = 0; i + holdFrames <= peak.length; i += 1) { if (peak[i] < SILENCE_FLOOR) continue; let ok = true; for (let k = 0; k < holdFrames; k += 1) { if (peak[i + k] < SILENCE_FLOOR) { ok = false; break; } } if (ok) { firstSound = +(i / ENV_RATE).toFixed(3); break; } } const curve = brightnessCurve(x, ANALYSIS_SR, { N: 512, hop: Math.round(ANALYSIS_SR / RATIO_RATE) }); // Keep a GENEROUS list, in time order, and let the caller choose by locality. // // Ranking these globally by strength and keeping the top handful is wrong for // the job: over a 150s background the Pokemon encounter alarm at 3.96s is a // perfectly clear 3.6x step, and it still ranked below eight louder cues // elsewhere in the file -- so the one onset the whole exercise was about // never reached the screen. The strongest cue in a file is rarely the one you // are working next to. const steps = brightnessSteps(curve, { hold: 0.4, rise: 1.8 }) .map((/** @type {{ at: number, gain: number }} */ s) => ({ at: s.at, gain: s.gain })) .sort((/** @type {{ at: number }} */ a, /** @type {{ at: number }} */ b) => a.at - b.at) .slice(0, 60); const out = { label: labelFor(abs), duration: +duration.toFixed(3), envRate: ENV_RATE, peak, ratioRate: RATIO_RATE, ratio: /** @type {number[]} */ (curve.ratio).map((v) => +v.toFixed(3)), flux: /** @type {number[]} */ (curve.flux).map((v) => +v.toFixed(2)), firstSound, steps, }; await mkdir(cacheDir, { recursive: true }); const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(out)); await rename(tmp, file).catch(() => {}); return out; }