Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
7 changes: 5 additions & 2 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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,
Expand Down
67 changes: 67 additions & 0 deletions src/track-facts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, { key: string; seconds: number }>();
private running = new Set<string>();

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<number> {
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<string, { key: string; tags: Record<string, string> }>();
Expand Down
25 changes: 23 additions & 2 deletions test/track-facts.test.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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 });
}
});
Loading