diff --git a/package.json b/package.json index ff7df6a..b71accc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nixamp", - "version": "0.80.3", + "version": "0.80.4", "description": "It really whips the terminal's ass. A Winamp-shaped audio player for your terminal.", "license": "MIT", "type": "module", diff --git a/src/server.ts b/src/server.ts index 5640715..8cf7f29 100644 --- a/src/server.ts +++ b/src/server.ts @@ -95,7 +95,7 @@ import { MusicLicenses } from "./music-license.ts"; import { handleLicenseRoutes, isLicensePath } from "./license-routes.ts"; import { AiRadio } from "./ai-radio.ts"; import { ListenerShares } from "./listener-shares.ts"; -import { HolderStore, TagReader, factsFor } from "./track-facts.ts"; +import { DurationProbe, HolderStore, TagReader, factsFor } from "./track-facts.ts"; import { SUPPORT_CSP, SUPPORT_PAGE, Support, SupportError, SupportSubscriptions, supportHoldersFrom } from "./support.ts"; import { LyricsFinder } from "./lyrics.ts"; import { LyricsPublisher } from "./lyrics-publish.ts"; @@ -2060,6 +2060,9 @@ export function createHandler(engine: Engine, options: HandlerOptions) { const release = latestRelease(); const tracker = options.connections ?? new Connections(); + // A station file the library has not indexed (an AI label's ai-radio links) still has a length for the clock. + const durations = new DurationProbe(options.ffprobe ?? []); + const durationOf = (file: string): number => options.library?.index.itemAt(file)?.duration || durations.of(file); const started = Date.now(); /** Count a request in, count its bytes, and close it out exactly once. */ @@ -3625,7 +3628,7 @@ export function createHandler(engine: Engine, options: HandlerOptions) { }, trackFor: (file) => trackFor(engine, file), ...(options.library ? { isVideo: (file: string) => options.library!.index.itemAt(file)?.video === true } : {}), - ...(options.library ? { durationOf: (file: string) => options.library!.index.itemAt(file)?.duration ?? 0 } : {}), + durationOf, base: `${scheme}://${request.headers.host ?? "localhost"}`, publicBase: options.stations.publicBase?.() ?? "", json, diff --git a/src/track-facts.ts b/src/track-facts.ts index 2517957..0c95a31 100644 --- a/src/track-facts.ts +++ b/src/track-facts.ts @@ -50,6 +50,73 @@ export interface Holder { license: string; } +/** + * How long a file plays, for one the library has not indexed: a station's + * files can live outside every library folder (an AI label's ai-radio links), + * and without a length the player's clock, progress bar and karaoke stop. + * Answers at once from the cache, else 0 while ffprobe runs in the background; + * the player asks the clock again every few seconds and gets the length then. + */ +export class DurationProbe { + private cache = new Map(); + private running = new Set(); + + constructor(private readonly ffprobe: string[]) {} + + of(path: string): number { + let key = ""; + try { + const info = statSync(path); + key = `${info.size}:${info.mtimeMs}`; + } catch { + return 0; + } + const hit = this.cache.get(path); + if (hit && hit.key === key) return hit.seconds; + this.probe(path, key); + return 0; + } + + /** The length, waiting for ffprobe when it is not known yet. */ + async wait(path: string): Promise { + const now = this.of(path); + if (now > 0) return now; + for (let i = 0; i < 200 && this.running.has(path); i++) await new Promise((done) => setTimeout(done, 50)); + return this.cache.get(path)?.seconds ?? 0; + } + + private probe(path: string, key: string): void { + const [command, ...prefix] = this.ffprobe; + if (!command || this.running.has(path)) return; + this.running.add(path); + const child = spawn(command, [...prefix, "-v", "error", "-print_format", "json", "-show_entries", "format=duration", path], { stdio: ["ignore", "pipe", "ignore"] }); + let out = ""; + const timer = setTimeout(() => child.kill("SIGKILL"), 10_000); + timer.unref?.(); + child.stdout.on("data", (chunk: Buffer) => { if (out.length < 64 * 1024) out += chunk.toString("utf8"); }); + let done = false; + const finish = (seconds: number): void => { + if (done) return; + done = true; + clearTimeout(timer); + this.running.delete(path); + if (this.cache.size > 5000) this.cache.clear(); + // A failed probe is remembered too (as 0), so it is not rerun on every clock. + this.cache.set(path, { key, seconds }); + }; + child.on("error", () => finish(0)); + child.on("close", () => { + let seconds = 0; + try { + seconds = Number((JSON.parse(out) as { format?: { duration?: string } }).format?.duration ?? 0); + } catch { + // Not JSON: no length. + } + finish(Number.isFinite(seconds) && seconds > 0 ? seconds : 0); + }); + } +} + /** The tags ffprobe reads from a file, lower-cased, cached by size and time. */ export class TagReader { private cache = new Map }>(); diff --git a/test/track-facts.test.ts b/test/track-facts.test.ts index 4f6bf02..5e7b9ea 100644 --- a/test/track-facts.test.ts +++ b/test/track-facts.test.ts @@ -1,9 +1,9 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { mkdtempSync, rmSync } from "node:fs"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { HolderStore, aiFromTags, factsFor, type Holder } from "../src/track-facts.ts"; +import { DurationProbe, HolderStore, aiFromTags, factsFor, type Holder } from "../src/track-facts.ts"; import { Support, supportHoldersFrom } from "../src/support.ts"; import type { Station } from "../src/stations.ts"; @@ -146,3 +146,24 @@ test("monthly support: month one at once, a link a month while paid, lapsed when assert.equal(row["status"], "canceled"); await assert.rejects(monthly.cancel(again.id, "wrong"), /not one of ours/); }); + +test("a file outside the library still gets a length for the clock (ai-radio links)", async () => { + const dir = mkdtempSync(join(tmpdir(), "nixamp-duration-")); + try { + const song = join(dir, "001. Whispers in Dark.mp3"); + writeFileSync(song, "not really audio"); + // A stand-in ffprobe: the length a real one reads from the file's header. + const stub = join(dir, "ffprobe.sh"); + writeFileSync(stub, "printf '{\"format\":{\"duration\":\"120.032653\"}}'\n"); + const probe = new DurationProbe(["sh", stub]); + assert.equal(probe.of(song), 0, "unknown at first: answers at once, probes in the background"); + assert.equal(await probe.wait(song), 120.032653); + assert.equal(probe.of(song), 120.032653, "then from the cache"); + assert.equal(new DurationProbe(["sh", stub]).of(join(dir, "gone.mp3")), 0, "a missing file is 0, never a crash"); + const broken = join(dir, "broken.sh"); + writeFileSync(broken, "echo nope\n"); + assert.equal(await new DurationProbe(["sh", broken]).wait(song), 0, "ffprobe that says nothing useful is 0"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +});