nixamp 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -12,6 +12,7 @@
12
12
  import { createReadStream, statSync } from "node:fs";
13
13
  import { createServer as createHttpServer } from "node:http";
14
14
  import { createServer as createHttpsServer } from "node:https";
15
+ import { randomBytes } from "node:crypto";
15
16
  import { hostname } from "node:os";
16
17
  import { spawn, spawnSync } from "node:child_process";
17
18
  import { readFileSync } from "node:fs";
@@ -21,6 +22,7 @@ import { Ingest, normaliseFormat } from "./ingest.js";
21
22
  import { Channels, cleanId } from "./channels.js";
22
23
  import { RtmpListeners } from "./rtmp-in.js";
23
24
  import { Accounts, clearedCookie, sessionCookie, tokenFrom } from "./accounts.js";
25
+ import { anonymousHandle, Handles } from "./handles.js";
24
26
  import { Servers } from "./servers.js";
25
27
  import { DeviceGrants } from "./device.js";
26
28
  import { BAD_KEY_LIMIT, callerOf, Guard, SIGN_IN_LIMIT } from "./guard.js";
@@ -555,6 +557,7 @@ export function isSignInPath(path) {
555
557
  // rather than by a share key it has nothing to do with.
556
558
  path === "/api/v1/servers" ||
557
559
  path.startsWith("/api/v1/servers/") ||
560
+ path === "/api/v1/me/handle" ||
558
561
  OAUTH_ROUTE.test(path));
559
562
  }
560
563
  function html(response, code, body) {
@@ -994,6 +997,42 @@ export function createHandler(engine, options) {
994
997
  json(response, 404, { error: "no such endpoint" });
995
998
  return;
996
999
  }
1000
+ // --- the name other people see ---------------------------------------
1001
+ //
1002
+ // Separate from the address on purpose. The address is a credential and
1003
+ // a way to reach somebody; publishing it in a directory listing or an
1004
+ // invite would be publishing what they log in with.
1005
+ if (path === "/api/v1/me/handle" && options.handles) {
1006
+ const handles = options.handles;
1007
+ const who = await accounts.whoIs(tokenFrom(request.headers));
1008
+ if (who === null) {
1009
+ json(response, 401, { error: "not signed in" });
1010
+ return;
1011
+ }
1012
+ if (request.method === "GET") {
1013
+ json(response, 200, { handle: await handles.of(who.id) });
1014
+ return;
1015
+ }
1016
+ if (request.method === "PUT" || request.method === "POST") {
1017
+ let body;
1018
+ try {
1019
+ body = JSON.parse(await readBody(request));
1020
+ }
1021
+ catch {
1022
+ json(response, 400, { error: "bad JSON" });
1023
+ return;
1024
+ }
1025
+ const claimed = await handles.claim(who.id, body.handle);
1026
+ if (claimed.error) {
1027
+ json(response, 409, { error: claimed.error });
1028
+ return;
1029
+ }
1030
+ json(response, 200, { handle: claimed.handle });
1031
+ return;
1032
+ }
1033
+ json(response, 405, { error: "GET or PUT" });
1034
+ return;
1035
+ }
997
1036
  // --- the servers this account runs ----------------------------------
998
1037
  //
999
1038
  // Kept against the account rather than the machine, so the list reads the
@@ -1140,6 +1179,17 @@ export function createHandler(engine, options) {
1140
1179
  const result = signingUp
1141
1180
  ? await accounts.signUp(body.email, body.password)
1142
1181
  : await accounts.signIn(body.email, body.password);
1182
+ // A handle asked for at sign-up, or one nobody has to think about. Never
1183
+ // derived from the address: turning anthony@… into "anthony" is the leak
1184
+ // this whole idea exists to avoid, and it is one nobody would notice
1185
+ // until it was already in a directory listing.
1186
+ if (signingUp && result.ok && result.account && options.handles) {
1187
+ const asked = body.handle;
1188
+ const claimed = await options.handles.claim(result.account.id, asked);
1189
+ if (claimed.error) {
1190
+ await options.handles.claim(result.account.id, anonymousHandle((size) => randomBytes(size)));
1191
+ }
1192
+ }
1143
1193
  // Getting it right costs nothing: the counters only exist to stop people
1144
1194
  // who keep getting it wrong.
1145
1195
  if (result.ok)
@@ -1655,7 +1705,12 @@ export function createHandler(engine, options) {
1655
1705
  // to it raw is bytes it cannot play. Seeking is what this route is for
1656
1706
  // and transcoding gives it up, but an unseekable film beats a silent
1657
1707
  // one -- and the seekable formats are untouched.
1658
- if (playsInBrowser(file)) {
1708
+ // A ceiling the caller asked for, because only the caller knows what its
1709
+ // link can carry. Capped at both ends: nothing below 200k is watchable,
1710
+ // and above 20 megabits the original was always the better answer.
1711
+ const asked = Number(url.searchParams.get("kbps") ?? "");
1712
+ const capKbps = Number.isFinite(asked) && asked > 0 ? Math.min(20_000, Math.max(200, asked)) : 0;
1713
+ if (playsInBrowser(file) && capKbps === 0) {
1659
1714
  sendFile(request, response, file);
1660
1715
  }
1661
1716
  else if (hasPicture(file)) {
@@ -1663,7 +1718,7 @@ export function createHandler(engine, options) {
1663
1718
  // soundtrack over a blank panel; what ffprobe finds inside decides how
1664
1719
  // little work it takes to keep the picture.
1665
1720
  const codecs = await codecsOf({ ffmpeg: [], ffprobe: options.ffprobe ?? ["ffprobe"], play: null }, file);
1666
- pipeFfmpeg(request, response, file, options.ffmpeg ?? ["ffmpeg"], videoArgs(codecs), "video/mp4");
1721
+ pipeFfmpeg(request, response, file, options.ffmpeg ?? ["ffmpeg"], videoArgs(codecs, capKbps), "video/mp4");
1667
1722
  }
1668
1723
  else {
1669
1724
  transcode(request, response, file, options.ffmpeg ?? ["ffmpeg"]);
@@ -2269,7 +2324,7 @@ export async function serve(argv, version = "0.1.0") {
2269
2324
  // all: a browser already signed in can approve a terminal.
2270
2325
  // The same pool the follows and reminders use: three small tables in
2271
2326
  // one database do not want three sets of connections.
2272
- ...(pool ? { servers: new Servers(pool) } : {}),
2327
+ ...(pool ? { servers: new Servers(pool), handles: new Handles(pool) } : {}),
2273
2328
  signIn: new SignIn(providersFrom(process.env), new DeviceGrants(), process.env["NIXAMP_SITE"] ?? DEFAULT_DIRECTORY),
2274
2329
  }
2275
2330
  : {}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nixamp",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "It really whips the terminal's ass. A Winamp-shaped audio player for your terminal.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/audio.ts CHANGED
@@ -232,6 +232,82 @@ export function formatTime(seconds: number): string {
232
232
  return `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
233
233
  }
234
234
 
235
+ /**
236
+ * The same tags, read without blocking anything.
237
+ *
238
+ * `probe` is spawnSync, and 0.5.5 tried to fix the tagging pass by yielding
239
+ * between files. That is not enough: each individual call still stops the
240
+ * process for as long as one ffprobe takes, and on a large file over a slow
241
+ * disk that is hundreds of milliseconds. Yield, block, yield, block, and a
242
+ * server delivers a stream in slivers -- measured at 357 KB/s on a machine
243
+ * whose disk reads at 6.5 MB/s and whose link runs at 1.4 Gbps.
244
+ *
245
+ * ffprobe still costs what it costs. It just costs it in a child process now,
246
+ * which is where that work belongs.
247
+ */
248
+ export async function probeAsync(tools: Tools, path: string): Promise<Track> {
249
+ const [cmd, ...rest] = tools.ffprobe;
250
+ const fallback: Track = {
251
+ path,
252
+ title: path.split("/").pop() ?? path,
253
+ artist: "",
254
+ album: "",
255
+ duration: 0,
256
+ };
257
+ if (!cmd) return fallback;
258
+
259
+ return new Promise<Track>((done) => {
260
+ const child = spawn(
261
+ cmd,
262
+ [
263
+ ...rest,
264
+ "-v", "quiet", "-print_format", "json",
265
+ "-show_format", "-show_entries", "format_tags=title,artist,album",
266
+ path,
267
+ ],
268
+ { stdio: ["ignore", "pipe", "ignore"] },
269
+ );
270
+ let out = "";
271
+ // A file that will not answer must not hold a place in the queue for ever.
272
+ const giveUp = setTimeout(() => child.kill("SIGKILL"), 20_000);
273
+ giveUp.unref?.();
274
+
275
+ child.stdout.on("data", (chunk: Buffer) => {
276
+ if (out.length < 4 * 1024 * 1024) out += chunk.toString("utf8");
277
+ });
278
+ child.on("error", () => {
279
+ clearTimeout(giveUp);
280
+ done(fallback);
281
+ });
282
+ child.on("close", (code) => {
283
+ clearTimeout(giveUp);
284
+ if (code !== 0) return done(fallback);
285
+ done(readTags(out, fallback));
286
+ });
287
+ });
288
+ }
289
+
290
+ /** The tags out of ffprobe's JSON, or the filename when it said nothing useful. */
291
+ function readTags(stdout: string, fallback: Track): Track {
292
+ try {
293
+ const parsed = JSON.parse(stdout) as {
294
+ format?: { duration?: string; tags?: Record<string, string> };
295
+ };
296
+ const tags = parsed.format?.tags ?? {};
297
+ const lower: Record<string, string> = {};
298
+ for (const [k, v] of Object.entries(tags)) lower[k.toLowerCase()] = v;
299
+ return {
300
+ path: fallback.path,
301
+ title: lower.title || fallback.title,
302
+ artist: lower.artist ?? "",
303
+ album: lower.album ?? "",
304
+ duration: Number(parsed.format?.duration ?? 0) || 0,
305
+ };
306
+ } catch {
307
+ return fallback;
308
+ }
309
+ }
310
+
235
311
  /** What is actually inside a container, as opposed to what the name suggests. */
236
312
  export interface Codecs {
237
313
  /** e.g. "h264", "hevc", "vp9". Empty when there is no video stream. */
@@ -293,7 +369,11 @@ export async function codecsOf(tools: Tools, path: string): Promise<Codecs> {
293
369
  * would cost a core per viewer and look worse. So the streams decide, one part
294
370
  * at a time -- a film can have its video copied and only its DTS re-encoded.
295
371
  */
296
- export function videoArgs(codecs: Codecs): string[] {
372
+ export function videoArgs(codecs: Codecs, capKbps = 0): string[] {
373
+ // A ceiling means re-encoding whatever is there, because you cannot cap the
374
+ // bitrate of a stream you are copying: copying is what "unchanged" means.
375
+ if (capKbps > 0) return cappedArgs(capKbps);
376
+
297
377
  // What a browser can play inside MP4 without help.
298
378
  const keepVideo = codecs.video === "h264";
299
379
  const keepAudio = codecs.audio === "aac" || codecs.audio === "mp3";
@@ -309,3 +389,42 @@ export function videoArgs(codecs: Codecs): string[] {
309
389
  "-movflags", "frag_keyframe+empty_moov+default_base_moof",
310
390
  ];
311
391
  }
392
+
393
+ /**
394
+ * The width that suits a bitrate.
395
+ *
396
+ * 1080p squeezed into a megabit is worse than 360p at the same megabit: the
397
+ * encoder spends everything it has on detail it cannot afford and the result
398
+ * smears on every motion. Dropping the resolution with the bitrate is what
399
+ * makes a small stream watchable rather than merely small.
400
+ */
401
+ export function widthFor(kbps: number): number {
402
+ if (kbps <= 800) return 640;
403
+ if (kbps <= 1800) return 854;
404
+ if (kbps <= 4000) return 1280;
405
+ return 1920;
406
+ }
407
+
408
+ /** Arguments for a stream that has to fit through a link of a known size. */
409
+ function cappedArgs(kbps: number): string[] {
410
+ const audioKbps = kbps <= 800 ? 96 : 128;
411
+ const videoKbps = Math.max(200, kbps - audioKbps);
412
+ return [
413
+ "-c:v", "libx264",
414
+ "-preset", "veryfast",
415
+ "-pix_fmt", "yuv420p",
416
+ // -2 keeps the aspect ratio and an even height, which H.264 requires.
417
+ // The min() never enlarges: a 480p source asked for 720p stays 480p.
418
+ "-vf", `scale='min(${widthFor(kbps)},iw)':-2`,
419
+ "-b:v", `${videoKbps}k`,
420
+ // A ceiling rather than an average, because an average that spikes is a
421
+ // stall on a link this size. The buffer is one second of it.
422
+ "-maxrate", `${videoKbps}k`,
423
+ "-bufsize", `${videoKbps}k`,
424
+ "-c:a", "aac",
425
+ "-b:a", `${audioKbps}k`,
426
+ "-ac", "2",
427
+ "-f", "mp4",
428
+ "-movflags", "frag_keyframe+empty_moov+default_base_moof",
429
+ ];
430
+ }
package/src/handles.ts ADDED
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The name other people see.
3
+ *
4
+ * An account is keyed on an email address, because that is what the auth module
5
+ * authenticates. An address is a credential and a way to reach somebody, and it
6
+ * is not a name: putting it in a directory listing, an invite or a subdomain
7
+ * publishes something the account holder gave us to log in with.
8
+ *
9
+ * So there are two names. The address stays private and does the linking, and a
10
+ * handle is the one that appears in front of strangers. They are never the same
11
+ * field and never travel in the same response.
12
+ */
13
+ import type { Queryable } from "./follows.ts";
14
+
15
+ const TABLE = "nixamp_handles";
16
+
17
+ const SCHEMA = `
18
+ CREATE TABLE IF NOT EXISTS ${TABLE} (
19
+ user_id TEXT PRIMARY KEY,
20
+ handle TEXT NOT NULL,
21
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
22
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
23
+ );
24
+ CREATE UNIQUE INDEX IF NOT EXISTS ${TABLE}_lower ON ${TABLE} (lower(handle));
25
+ `;
26
+
27
+ /**
28
+ * What a handle may be.
29
+ *
30
+ * It ends up in a URL, a subdomain and a text message, so it is the intersection
31
+ * of what all three tolerate: lowercase letters, digits and hyphens, not
32
+ * starting or ending with one. Two to thirty characters, because a subdomain
33
+ * label cannot exceed sixty-three and nobody types thirty.
34
+ */
35
+ export function cleanHandle(value: unknown): string {
36
+ if (typeof value !== "string") return "";
37
+ const wanted = value.trim().toLowerCase();
38
+ if (!/^[a-z0-9](?:[a-z0-9-]{0,28}[a-z0-9])?$/.test(wanted)) return "";
39
+ // Doubled hyphens are how punycode marks an encoded label, so a handle with
40
+ // one in it can collide with an internationalised domain.
41
+ return wanted.includes("--") ? "" : wanted;
42
+ }
43
+
44
+ /**
45
+ * Names nobody may take, because a subdomain carrying one would impersonate the
46
+ * service or reach a machine we run.
47
+ */
48
+ const RESERVED = new Set([
49
+ "www", "api", "admin", "root", "nixamp", "mail", "smtp", "imap", "ns1", "ns2",
50
+ "static", "cdn", "assets", "app", "dev", "staging", "test", "support", "help",
51
+ "status", "blog", "directory", "login", "signup", "account", "settings", "me",
52
+ ]);
53
+
54
+ export function isReserved(handle: string): boolean {
55
+ return RESERVED.has(handle);
56
+ }
57
+
58
+ /**
59
+ * A handle for somebody who has not chosen one.
60
+ *
61
+ * Deliberately not derived from the address. "anthony@profullstack.com" turning
62
+ * into "anthony" is exactly the leak this whole file exists to avoid, and it
63
+ * would be a leak nobody noticed until it was already in a directory listing.
64
+ */
65
+ export function anonymousHandle(random: (size: number) => Uint8Array): string {
66
+ const bytes = random(4);
67
+ let out = "";
68
+ for (const byte of bytes) out += byte.toString(16).padStart(2, "0");
69
+ return `nixamp-${out}`;
70
+ }
71
+
72
+ export class Handles {
73
+ private ready: Promise<void> | null = null;
74
+
75
+ constructor(private readonly db: Queryable) {}
76
+
77
+ private async ensure(): Promise<void> {
78
+ this.ready ??= this.db.query(SCHEMA).then(() => undefined);
79
+ await this.ready;
80
+ }
81
+
82
+ async of(userId: string): Promise<string> {
83
+ await this.ensure();
84
+ const { rows } = await this.db.query(`SELECT handle FROM ${TABLE} WHERE user_id = $1`, [userId]);
85
+ return rows[0] ? String(rows[0]["handle"] ?? "") : "";
86
+ }
87
+
88
+ /** Who holds this handle, so a listing can name somebody without their address. */
89
+ async holder(handle: string): Promise<string> {
90
+ const wanted = cleanHandle(handle);
91
+ if (!wanted) return "";
92
+ await this.ensure();
93
+ const { rows } = await this.db.query(`SELECT user_id FROM ${TABLE} WHERE lower(handle) = $1`, [wanted]);
94
+ return rows[0] ? String(rows[0]["user_id"] ?? "") : "";
95
+ }
96
+
97
+ /**
98
+ * Claim one. Answers the reason it could not be taken rather than a boolean,
99
+ * because "that is already somebody's" and "that is not a name" are different
100
+ * things to tell a person.
101
+ */
102
+ async claim(userId: string, wanted: unknown): Promise<{ handle: string; error: string }> {
103
+ const handle = cleanHandle(wanted);
104
+ if (!handle) {
105
+ return { handle: "", error: "letters, digits and hyphens, 2 to 30 characters" };
106
+ }
107
+ if (isReserved(handle)) return { handle: "", error: "that one is reserved" };
108
+
109
+ await this.ensure();
110
+ const taken = await this.holder(handle);
111
+ if (taken && taken !== userId) return { handle: "", error: "somebody already has that one" };
112
+
113
+ await this.db.query(
114
+ `INSERT INTO ${TABLE} (user_id, handle) VALUES ($1, $2)
115
+ ON CONFLICT (user_id) DO UPDATE SET handle = EXCLUDED.handle, updated_at = NOW()`,
116
+ [userId, handle],
117
+ );
118
+ return { handle, error: "" };
119
+ }
120
+ }
package/src/invite.ts ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Asking somebody to watch, when that somebody is not technical.
3
+ *
4
+ * A share link is a URL with a key in it, which is fine for the person who
5
+ * runs the server and useless as a thing to text your mother. An invite is the
6
+ * three ways in, written as a sentence: a link that opens a player, a phone
7
+ * number, and the code to key once it answers.
8
+ *
9
+ * The sender is signed in, because sending is an action with a cost: a text
10
+ * message is money and somebody's phone. The recipient signs in too, but only
11
+ * once and only at the far end of a single click, because a stream can ask to
12
+ * be paid for -- x402 starts charging past five listeners -- and there is
13
+ * nobody to charge without an account. The dial-in path is the exception and
14
+ * stays open to anybody, since a phone call cannot sign in to anything.
15
+ */
16
+
17
+ /** Where the phone line answers, and what to key when it does. */
18
+ export interface Invite {
19
+ /** What the stream is called, as the recipient will see it. */
20
+ name: string;
21
+ /** A link that opens a player on this stream, listen only. */
22
+ link: string;
23
+ /** The phone number, when this stream is one the line knows about. */
24
+ phone: string;
25
+ /** The six digits that reach this stream, when it has been published. */
26
+ code: string;
27
+ }
28
+
29
+ /** Looks like a phone number rather than an address. */
30
+ export function isPhone(value: string): boolean {
31
+ return /^\+?[\d\s().-]{7,20}$/.test(value.trim()) && /\d{7}/.test(value.replace(/\D/g, ""));
32
+ }
33
+
34
+ /** Looks like somewhere an email could arrive. */
35
+ export function isEmail(value: string): boolean {
36
+ return /^[^@\s]+@[^@\s.]+\.[^@\s]+$/.test(value.trim());
37
+ }
38
+
39
+ /**
40
+ * The message itself.
41
+ *
42
+ * Short, because it is going into a text message, and ordered by how likely
43
+ * each way in is to work for the person reading it. The link first: most
44
+ * people have a browser in their hand. The phone last, because it is the one
45
+ * that needs no browser at all and is therefore the fallback that never fails.
46
+ */
47
+ export function inviteText(invite: Invite): string {
48
+ const lines = [`${invite.name} is streaming.`, "", `Watch: ${invite.link}`];
49
+ if (invite.phone && invite.code) {
50
+ lines.push("", `Or call ${invite.phone} and key ${invite.code} to listen.`);
51
+ }
52
+ return lines.join("\n");
53
+ }
54
+
55
+ /** The same thing as a subject line, for the surface that wants one. */
56
+ export function inviteSubject(invite: Invite): string {
57
+ return `${invite.name} is streaming`;
58
+ }
59
+
60
+ /**
61
+ * A link that opens a player on this stream.
62
+ *
63
+ * Sent through nixamp.com when the stream is https, because that page is a
64
+ * player anybody can already open and reaches this stream with `?url=`. An
65
+ * http stream is sent as its own address instead: a browser refuses every
66
+ * request from an https page to an http one, so routing it through nixamp.com
67
+ * would produce a link that cannot work, which is worse than a plainer one
68
+ * that does.
69
+ */
70
+ export function watchLink(streamUrl: string, site: string): string {
71
+ const bare = streamUrl.replace(/\/+$/, "");
72
+ if (!bare.startsWith("https://")) return bare;
73
+ return `${site.replace(/\/+$/, "")}/?url=${encodeURIComponent(bare)}`;
74
+ }
package/src/playlist.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** The playlist: audio found on disk or named by a playlist, in a stable order. */
2
2
  import { readFileSync, readdirSync, statSync } from "node:fs";
3
3
  import { join } from "node:path";
4
- import { probe, type Tools, type Track } from "./audio.ts";
4
+ import { probe, probeAsync, type Tools, type Track } from "./audio.ts";
5
5
  import {
6
6
  type Entry,
7
7
  isHls,
@@ -87,6 +87,64 @@ export async function readPlaylist(source: string): Promise<Entry[]> {
87
87
  return entries;
88
88
  }
89
89
 
90
+ /**
91
+ * The audio linked from a directory listing a web server generated.
92
+ *
93
+ * A seedbox or a plain Apache with autoindex on serves a folder as an HTML page
94
+ * of relative links. Handed one of those, nixamp used to make a single track of
95
+ * the page itself and give it to ffmpeg, which is asked to decode HTML and says
96
+ * so in a way nobody reads. It is a folder; it should behave like one.
97
+ *
98
+ * Not recursive, deliberately: one page is one album, the subdirectory links are
99
+ * on it, and walking a stranger's whole tree from a text box is a different and
100
+ * much larger thing to ask for.
101
+ */
102
+ export async function readRemoteIndex(source: string, send: typeof fetch = fetch): Promise<Entry[]> {
103
+ let answer: Response;
104
+ try {
105
+ answer = await send(source, {
106
+ redirect: "follow",
107
+ headers: { accept: "text/html,*/*" },
108
+ signal: AbortSignal.timeout(15_000),
109
+ });
110
+ } catch {
111
+ return [];
112
+ }
113
+ if (!answer.ok) return [];
114
+ // Anything that is not a page is the thing itself, and the caller plays it.
115
+ if (!/^text\/html/i.test(answer.headers.get("content-type") ?? "")) return [];
116
+
117
+ const html = await answer.text().catch(() => "");
118
+ const found: Entry[] = [];
119
+ const seen = new Set<string>();
120
+ for (const match of html.matchAll(/href\s*=\s*["']([^"']+)["']/gi)) {
121
+ const href = match[1];
122
+ // The sort links an index puts at the top of every column, and anchors.
123
+ if (!href || href.startsWith("?") || href.startsWith("#")) continue;
124
+ let url: URL;
125
+ try {
126
+ // Relative to the page, which is how an index writes them.
127
+ url = new URL(href.replace(/&amp;/g, "&"), source);
128
+ } catch {
129
+ continue;
130
+ }
131
+ if (!isAudio(url.pathname)) continue;
132
+ const link = url.toString();
133
+ if (seen.has(link)) continue;
134
+ seen.add(link);
135
+ found.push({
136
+ source: link,
137
+ // The name as a person wrote it, not as a URL spells it.
138
+ title: decodeURIComponent(url.pathname.split("/").pop() ?? link),
139
+ duration: 0,
140
+ });
141
+ }
142
+ // Server order is by whatever column the index sorted on; by name is what
143
+ // somebody handing over an album meant.
144
+ found.sort((a, b) => a.title.localeCompare(b.title, undefined, { numeric: true }));
145
+ return found;
146
+ }
147
+
90
148
  /**
91
149
  * Everything `nixamp <thing>` can be handed: a directory, a file, a playlist,
92
150
  * or a URL to any of those.
@@ -112,9 +170,18 @@ export async function loadSource(tools: Tools, source: string, probeTags = true)
112
170
  );
113
171
  }
114
172
 
115
- // A bare URL is one remote thing to play. Whether it is a song or a live
116
- // stream is ffmpeg's problem, and it is good at it.
117
- if (isRemote(source)) return [bare({ source, title: nameOf(source), duration: 0 })];
173
+ if (isRemote(source)) {
174
+ // A URL that names no file is probably a folder, and a folder served over
175
+ // http is a page of links. Asked only when it could be one: a stream URL
176
+ // must not pay for a fetch that will tell us nothing.
177
+ if (!isAudio(new URL(source).pathname)) {
178
+ const listed = await readRemoteIndex(source);
179
+ if (listed.length > 0) return listed.map(bare);
180
+ }
181
+ // A bare URL is one remote thing to play. Whether it is a song or a live
182
+ // stream is ffmpeg's problem, and it is good at it.
183
+ return [bare({ source, title: nameOf(source), duration: 0 })];
184
+ }
118
185
 
119
186
  return loadPlaylist(tools, source, probeTags);
120
187
  }
@@ -146,15 +213,23 @@ export function loadPlaylist(tools: Tools, root: string, probeTags = true): Trac
146
213
  * ffprobe rather than for the whole library, and the tagging still finishes in
147
214
  * about the time it did.
148
215
  */
149
- export async function loadTagged(tools: Tools, source: string): Promise<Track[]> {
216
+ export async function loadTagged(
217
+ tools: Tools,
218
+ source: string,
219
+ /** Injected by the test, which must not depend on ffprobe being installed. */
220
+ probeOne: (tools: Tools, path: string) => Promise<Track> = probeAsync,
221
+ ): Promise<Track[]> {
150
222
  // A URL is one thing and is never probed; a playlist carries its own titles.
151
223
  if (isRemote(source) || isPlaylistFile(source)) return loadSource(tools, source, true);
152
224
 
153
225
  const paths = findAudio(source);
154
226
  const tracks: Track[] = [];
155
227
  for (const path of paths) {
156
- tracks.push(probe(tools, path));
157
- await new Promise<void>((done) => setImmediate(done));
228
+ // Awaiting a child process, not blocking on one. Yielding between files
229
+ // was not enough: each spawnSync still stopped everything for as long as
230
+ // one ffprobe took, which on a large file is long enough to strangle a
231
+ // stream being served at the same time.
232
+ tracks.push(await probeOne(tools, path));
158
233
  }
159
234
  return tracks;
160
235
  }