nixamp 0.1.0 → 0.3.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.
Files changed (65) hide show
  1. package/README.md +225 -0
  2. package/bin/nixamp.mjs +4 -1
  3. package/dist/accounts.d.ts +54 -0
  4. package/dist/accounts.js +160 -0
  5. package/dist/admin.d.ts +47 -0
  6. package/dist/admin.js +209 -0
  7. package/dist/broadcast.d.ts +96 -0
  8. package/dist/broadcast.js +193 -0
  9. package/dist/channels.d.ts +94 -0
  10. package/dist/channels.js +235 -0
  11. package/dist/connections.d.ts +72 -0
  12. package/dist/connections.js +128 -0
  13. package/dist/daemon.d.ts +39 -0
  14. package/dist/daemon.js +170 -0
  15. package/dist/directory.d.ts +63 -0
  16. package/dist/directory.js +111 -0
  17. package/dist/ingest.d.ts +80 -0
  18. package/dist/ingest.js +252 -0
  19. package/dist/main.js +103 -6
  20. package/dist/manage.js +30 -7
  21. package/dist/owner.d.ts +53 -0
  22. package/dist/owner.js +96 -0
  23. package/dist/paywall.d.ts +60 -0
  24. package/dist/paywall.js +162 -0
  25. package/dist/playlist.d.ts +16 -0
  26. package/dist/playlist.js +57 -2
  27. package/dist/publish.d.ts +36 -0
  28. package/dist/publish.js +90 -0
  29. package/dist/rtmp-in.d.ts +22 -0
  30. package/dist/rtmp-in.js +79 -0
  31. package/dist/server.d.ts +117 -4
  32. package/dist/server.js +923 -24
  33. package/dist/session.d.ts +29 -0
  34. package/dist/session.js +184 -0
  35. package/dist/share.d.ts +74 -0
  36. package/dist/share.js +172 -0
  37. package/dist/sources.d.ts +37 -0
  38. package/dist/sources.js +125 -0
  39. package/package.json +5 -2
  40. package/src/accounts.ts +193 -0
  41. package/src/admin.ts +243 -0
  42. package/src/broadcast.ts +264 -0
  43. package/src/channels.ts +281 -0
  44. package/src/connections.ts +158 -0
  45. package/src/daemon.ts +193 -0
  46. package/src/directory.ts +135 -0
  47. package/src/ingest.ts +297 -0
  48. package/src/main.ts +107 -6
  49. package/src/manage.ts +35 -7
  50. package/src/owner.ts +113 -0
  51. package/src/paywall.ts +198 -0
  52. package/src/playlist.ts +68 -2
  53. package/src/publish.ts +101 -0
  54. package/src/rtmp-in.ts +90 -0
  55. package/src/server.ts +1087 -23
  56. package/src/session.ts +209 -0
  57. package/src/share.ts +193 -0
  58. package/src/sources.ts +136 -0
  59. package/src/types/auth-system.d.ts +77 -0
  60. package/web/dist/assets/{index-BGKWWaIx.css → index-0wAv50Ay.css} +1 -1
  61. package/web/dist/assets/index-WYJ6R4uF.js +1 -0
  62. package/web/dist/index.html +37 -6
  63. package/web/dist/install.ps1 +214 -0
  64. package/web/dist/sw.js +3 -3
  65. package/web/dist/assets/index-Dhja5wxB.js +0 -1
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The public directory.
3
+ *
4
+ * A nixamp that agrees to be listed announces itself to nixamp.com every so
5
+ * often and is forgotten when it stops. There is no database behind it: an
6
+ * entry lives for a few minutes and a heartbeat renews it, so a restart of the
7
+ * directory costs one heartbeat rather than a migration, and a stream that
8
+ * dies falls out of the list without anyone having to notice.
9
+ *
10
+ * What is published is the *listen* link. The control key never leaves the
11
+ * machine it was minted on.
12
+ */
13
+ /** How long an entry survives without a heartbeat. */
14
+ export declare const TTL_MS: number;
15
+ /** How often a publisher renews. Comfortably inside the TTL. */
16
+ export declare const HEARTBEAT_MS: number;
17
+ export declare const DEFAULT_DIRECTORY = "https://nixamp.com";
18
+ export interface Listing {
19
+ /** Assigned by the directory, so a publisher cannot claim someone else's. */
20
+ id: string;
21
+ name: string;
22
+ /** The listen link, which is what a browser opens. */
23
+ url: string;
24
+ tracks: number;
25
+ nowPlaying: string;
26
+ /** Set by the directory from the request, never by the publisher. */
27
+ updatedAt: number;
28
+ }
29
+ /** What a publisher sends. Everything else about a listing is ours to decide. */
30
+ export interface Announcement {
31
+ id?: string;
32
+ name: string;
33
+ url: string;
34
+ tracks: number;
35
+ nowPlaying: string;
36
+ }
37
+ /** Trim and flatten, so one publisher cannot draw a box in someone's terminal. */
38
+ export declare function clean(value: unknown, max: number): string;
39
+ /**
40
+ * A URL we are willing to list. It has to be somewhere a browser can go, and
41
+ * it must not be a loopback or link-local address: those are only reachable
42
+ * from the machine that published them, so listing one is an entry nobody but
43
+ * the publisher can ever open.
44
+ */
45
+ export declare function publishable(raw: string): URL | null;
46
+ export declare function parseAnnouncement(input: unknown): Announcement | null;
47
+ /**
48
+ * The registry. In memory on purpose: see the note at the top of the file.
49
+ * One entry per URL, so a publisher restarting does not leave a ghost of
50
+ * itself behind next to the entry that replaced it.
51
+ */
52
+ export declare class Directory {
53
+ private readonly ttl;
54
+ private readonly now;
55
+ private readonly items;
56
+ private sequence;
57
+ constructor(ttl?: number, now?: () => number);
58
+ announce(announcement: Announcement): Listing;
59
+ withdraw(id: string): void;
60
+ list(): Listing[];
61
+ /** Forget anything that stopped renewing. */
62
+ private sweep;
63
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The public directory.
3
+ *
4
+ * A nixamp that agrees to be listed announces itself to nixamp.com every so
5
+ * often and is forgotten when it stops. There is no database behind it: an
6
+ * entry lives for a few minutes and a heartbeat renews it, so a restart of the
7
+ * directory costs one heartbeat rather than a migration, and a stream that
8
+ * dies falls out of the list without anyone having to notice.
9
+ *
10
+ * What is published is the *listen* link. The control key never leaves the
11
+ * machine it was minted on.
12
+ */
13
+ /** How long an entry survives without a heartbeat. */
14
+ export const TTL_MS = 4 * 60 * 1000;
15
+ /** How often a publisher renews. Comfortably inside the TTL. */
16
+ export const HEARTBEAT_MS = 90 * 1000;
17
+ export const DEFAULT_DIRECTORY = "https://nixamp.com";
18
+ const MAX_NAME = 60;
19
+ const MAX_TRACK = 120;
20
+ /** Trim and flatten, so one publisher cannot draw a box in someone's terminal. */
21
+ export function clean(value, max) {
22
+ if (typeof value !== "string")
23
+ return "";
24
+ // Control characters include the escape that starts an ANSI sequence, and
25
+ // this text is rendered in a terminal as well as a browser.
26
+ return value.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max);
27
+ }
28
+ /**
29
+ * A URL we are willing to list. It has to be somewhere a browser can go, and
30
+ * it must not be a loopback or link-local address: those are only reachable
31
+ * from the machine that published them, so listing one is an entry nobody but
32
+ * the publisher can ever open.
33
+ */
34
+ export function publishable(raw) {
35
+ let url;
36
+ try {
37
+ url = new URL(raw);
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ if (url.protocol !== "http:" && url.protocol !== "https:")
43
+ return null;
44
+ const host = url.hostname.replace(/^\[|\]$/g, "");
45
+ if (host === "localhost" || host === "::1" || host.endsWith(".localhost"))
46
+ return null;
47
+ if (/^127\./.test(host) || /^169\.254\./.test(host))
48
+ return null;
49
+ return url;
50
+ }
51
+ export function parseAnnouncement(input) {
52
+ if (typeof input !== "object" || input === null)
53
+ return null;
54
+ const record = input;
55
+ const url = typeof record["url"] === "string" ? record["url"] : "";
56
+ if (publishable(url) === null)
57
+ return null;
58
+ const name = clean(record["name"], MAX_NAME);
59
+ const tracks = Number(record["tracks"]);
60
+ return {
61
+ ...(typeof record["id"] === "string" ? { id: clean(record["id"], 40) } : {}),
62
+ name: name || "a nixamp",
63
+ url,
64
+ tracks: Number.isFinite(tracks) && tracks >= 0 ? Math.min(1_000_000, Math.floor(tracks)) : 0,
65
+ nowPlaying: clean(record["nowPlaying"], MAX_TRACK),
66
+ };
67
+ }
68
+ /**
69
+ * The registry. In memory on purpose: see the note at the top of the file.
70
+ * One entry per URL, so a publisher restarting does not leave a ghost of
71
+ * itself behind next to the entry that replaced it.
72
+ */
73
+ export class Directory {
74
+ ttl;
75
+ now;
76
+ items = new Map();
77
+ sequence = 0;
78
+ constructor(ttl = TTL_MS, now = Date.now) {
79
+ this.ttl = ttl;
80
+ this.now = now;
81
+ }
82
+ announce(announcement) {
83
+ this.sweep();
84
+ const existing = [...this.items.values()].find((item) => item.url === announcement.url);
85
+ const id = existing?.id ?? `s${++this.sequence}${this.now().toString(36)}`;
86
+ const listing = {
87
+ id,
88
+ name: announcement.name,
89
+ url: announcement.url,
90
+ tracks: announcement.tracks,
91
+ nowPlaying: announcement.nowPlaying,
92
+ updatedAt: this.now(),
93
+ };
94
+ this.items.set(id, listing);
95
+ return listing;
96
+ }
97
+ withdraw(id) {
98
+ this.items.delete(id);
99
+ }
100
+ list() {
101
+ this.sweep();
102
+ return [...this.items.values()].sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id));
103
+ }
104
+ /** Forget anything that stopped renewing. */
105
+ sweep() {
106
+ const cutoff = this.now() - this.ttl;
107
+ for (const [id, item] of this.items)
108
+ if (item.updatedAt < cutoff)
109
+ this.items.delete(id);
110
+ }
111
+ }
@@ -0,0 +1,80 @@
1
+ import type { Readable } from "node:stream";
2
+ /** A live source is one session at a time: two would be two songs at once. */
3
+ export interface IngestSession {
4
+ id: string;
5
+ /** What the sender called itself. */
6
+ name: string;
7
+ /** The container the sender is producing, e.g. webm from MediaRecorder. */
8
+ format: string;
9
+ startedAt: number;
10
+ bytes: number;
11
+ }
12
+ export interface IngestStatus {
13
+ live: boolean;
14
+ session: IngestSession | null;
15
+ /** Where a native broadcaster should publish, when one is being listened for. */
16
+ rtmp: {
17
+ port: number;
18
+ path: string;
19
+ } | null;
20
+ }
21
+ /**
22
+ * ffmpeg's `-f` is a demuxer name, and passing an unknown one is how a stream
23
+ * dies four seconds in with a message nobody sees. An unrecognised container is
24
+ * refused up front instead.
25
+ */
26
+ export declare function normaliseFormat(value: unknown): string | null;
27
+ export interface IngestOptions {
28
+ ffmpeg: string[];
29
+ /** Where the decoded audio should go: a file ffmpeg writes, or a pipe. */
30
+ sink: string;
31
+ /** Called when a session starts, so the player can switch to it. */
32
+ onStart: (session: IngestSession) => void;
33
+ /** Called when it ends, cleanly or otherwise. */
34
+ onEnd: (session: IngestSession, error: string) => void;
35
+ /** Encoded audio, as it arrives from a live publisher. */
36
+ onAudio?: (chunk: Buffer) => void;
37
+ }
38
+ /**
39
+ * The live input.
40
+ *
41
+ * One session at a time: a second sender is refused rather than mixed, because
42
+ * mixing two uninvited streams is never what anybody meant.
43
+ */
44
+ export declare class Ingest {
45
+ private readonly options;
46
+ private child;
47
+ private session;
48
+ private closing;
49
+ /** The RTMP listener, which outlives any one publisher. */
50
+ private rtmpChild;
51
+ private rtmpPort;
52
+ private rtmpKey;
53
+ constructor(options: IngestOptions);
54
+ status(): IngestStatus;
55
+ get live(): boolean;
56
+ /**
57
+ * Open a session. Returns the session, or null when one is already running:
58
+ * the caller answers 409, because "somebody else is already broadcasting" is
59
+ * a different problem from "your request was wrong".
60
+ */
61
+ open(name: string, format: string): IngestSession | null;
62
+ /** Feed it. Returns false once the session is over. */
63
+ write(chunk: Buffer): boolean;
64
+ /** Pipe a whole request body in, for a sender that can stream one. */
65
+ pump(body: Readable): Promise<void>;
66
+ /**
67
+ * Wait for an RTMP publisher, and keep waiting after each one leaves.
68
+ *
69
+ * ffmpeg is the RTMP server here: `-rtmp_listen 1` binds the port and blocks
70
+ * until somebody publishes. It serves one publisher and exits, so the
71
+ * listener is started again afterwards -- otherwise a broadcaster who
72
+ * reconnects finds nothing listening.
73
+ */
74
+ listenRtmp(port: number, key: string): void;
75
+ /** Stop waiting for publishers. */
76
+ stopRtmp(): void;
77
+ private armRtmp;
78
+ /** End the session, whoever ended it. */
79
+ close(error?: string): void;
80
+ }
package/dist/ingest.js ADDED
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Streaming into a nixamp, rather than out of one.
3
+ *
4
+ * A phone or a laptop sends live audio to the server, and the server plays it,
5
+ * serves it to listeners, and broadcasts it onward. Two ways in, because one is
6
+ * not enough:
7
+ *
8
+ * - A single long POST whose body is the stream. ffmpeg, OBS, curl and the
9
+ * desktop app can all do this, and it is the efficient one.
10
+ * - A sequence of small POSTs, for browsers. Chrome only allows a streaming
11
+ * request body over HTTP/2, and a nixamp on your own network is plain
12
+ * HTTP/1.1, so a phone that wants to broadcast has to send chunks.
13
+ *
14
+ * Both end up writing into the same ffmpeg stdin, which is what makes the two
15
+ * paths interchangeable to everything downstream.
16
+ *
17
+ * And a third, which is the one anything native should use: RTMP. Point OBS,
18
+ * Larix or another ffmpeg at rtmp://this-machine/live/<key> and it publishes,
19
+ * with no nixamp-shaped client in the middle. ffmpeg listens for it (-rtmp_listen),
20
+ * so this costs no dependency and no protocol implementation. The HTTP paths
21
+ * above are not a workaround for that: they are what a *browser* has, since a
22
+ * web page cannot speak RTMP at all.
23
+ */
24
+ import { spawn } from "node:child_process";
25
+ import { randomBytes } from "node:crypto";
26
+ /** Containers a browser or a desktop encoder actually produces. */
27
+ const FORMATS = new Set(["webm", "ogg", "mp4", "matroska", "mp3", "wav", "flv"]);
28
+ /**
29
+ * ffmpeg's `-f` is a demuxer name, and passing an unknown one is how a stream
30
+ * dies four seconds in with a message nobody sees. An unrecognised container is
31
+ * refused up front instead.
32
+ */
33
+ export function normaliseFormat(value) {
34
+ if (typeof value !== "string")
35
+ return null;
36
+ const format = value.trim().toLowerCase();
37
+ if (format === "")
38
+ return null;
39
+ // A MediaRecorder mime type: audio/webm;codecs=opus.
40
+ // The subtype may carry a hyphen: audio/x-matroska is what some browsers
41
+ // hand out, and stopping at the hyphen turned it into "x".
42
+ const fromMime = /^(?:audio|video)\/([a-z0-9-]+)/.exec(format)?.[1];
43
+ const candidate = fromMime ?? format;
44
+ const mapped = candidate === "x-matroska" ? "matroska" : candidate;
45
+ return FORMATS.has(mapped) ? mapped : null;
46
+ }
47
+ /**
48
+ * The live input.
49
+ *
50
+ * One session at a time: a second sender is refused rather than mixed, because
51
+ * mixing two uninvited streams is never what anybody meant.
52
+ */
53
+ export class Ingest {
54
+ options;
55
+ child = null;
56
+ session = null;
57
+ closing = false;
58
+ /** The RTMP listener, which outlives any one publisher. */
59
+ rtmpChild = null;
60
+ rtmpPort = null;
61
+ rtmpKey = "";
62
+ constructor(options) {
63
+ this.options = options;
64
+ }
65
+ status() {
66
+ return {
67
+ live: this.session !== null,
68
+ session: this.session,
69
+ rtmp: this.rtmpPort === null ? null : { port: this.rtmpPort, path: `/live/${this.rtmpKey}` },
70
+ };
71
+ }
72
+ get live() {
73
+ return this.session !== null;
74
+ }
75
+ /**
76
+ * Open a session. Returns the session, or null when one is already running:
77
+ * the caller answers 409, because "somebody else is already broadcasting" is
78
+ * a different problem from "your request was wrong".
79
+ */
80
+ open(name, format) {
81
+ if (this.session !== null)
82
+ return null;
83
+ const session = {
84
+ id: randomBytes(8).toString("hex"),
85
+ name: name || "a device",
86
+ format,
87
+ startedAt: Date.now(),
88
+ bytes: 0,
89
+ };
90
+ const [command, ...prefix] = this.options.ffmpeg;
91
+ const child = spawn(command, [
92
+ ...prefix,
93
+ "-hide_banner",
94
+ "-loglevel", "error",
95
+ // The demuxer is stated because ffmpeg mis-probes a live, unseekable
96
+ // pipe: it reads a few kilobytes, guesses, and guesses wrong.
97
+ "-f", format,
98
+ "-i", "pipe:0",
99
+ "-vn",
100
+ "-c:a", "libmp3lame",
101
+ "-b:a", "192k",
102
+ "-y",
103
+ "-f", "mp3",
104
+ this.options.sink,
105
+ ], { stdio: ["pipe", "ignore", "pipe"] });
106
+ let tail = "";
107
+ child.stderr?.on("data", (chunk) => {
108
+ tail = (tail + chunk.toString()).slice(-2000);
109
+ });
110
+ // A sender that hangs up mid-write breaks the pipe, and an unhandled EPIPE
111
+ // takes the whole server down with it.
112
+ child.stdin?.on("error", () => this.close(""));
113
+ child.on("error", (error) => this.close(error.message));
114
+ child.on("close", (code) => this.close(code === 0 ? "" : tail.trim().split("\n").pop() ?? ""));
115
+ this.child = child;
116
+ this.session = session;
117
+ this.closing = false;
118
+ this.options.onStart(session);
119
+ return session;
120
+ }
121
+ /** Feed it. Returns false once the session is over. */
122
+ write(chunk) {
123
+ const child = this.child;
124
+ const session = this.session;
125
+ if (child === null || session === null || child.stdin === null)
126
+ return false;
127
+ session.bytes += chunk.byteLength;
128
+ return child.stdin.write(chunk);
129
+ }
130
+ /** Pipe a whole request body in, for a sender that can stream one. */
131
+ async pump(body) {
132
+ for await (const chunk of body) {
133
+ if (!this.write(chunk)) {
134
+ // Backpressure: wait for the drain rather than growing a buffer that
135
+ // is really the network's problem.
136
+ await new Promise((done) => this.child?.stdin?.once("drain", done) ?? done(null));
137
+ }
138
+ if (this.session === null)
139
+ return;
140
+ }
141
+ }
142
+ /**
143
+ * Wait for an RTMP publisher, and keep waiting after each one leaves.
144
+ *
145
+ * ffmpeg is the RTMP server here: `-rtmp_listen 1` binds the port and blocks
146
+ * until somebody publishes. It serves one publisher and exits, so the
147
+ * listener is started again afterwards -- otherwise a broadcaster who
148
+ * reconnects finds nothing listening.
149
+ */
150
+ listenRtmp(port, key) {
151
+ this.rtmpPort = port;
152
+ this.rtmpKey = key;
153
+ this.armRtmp();
154
+ }
155
+ /** Stop waiting for publishers. */
156
+ stopRtmp() {
157
+ this.rtmpPort = null;
158
+ const listener = this.rtmpChild;
159
+ this.rtmpChild = null;
160
+ listener?.kill("SIGKILL");
161
+ }
162
+ armRtmp() {
163
+ const port = this.rtmpPort;
164
+ if (port === null || this.rtmpChild !== null)
165
+ return;
166
+ const [command, ...prefix] = this.options.ffmpeg;
167
+ const child = spawn(command, [
168
+ ...prefix,
169
+ "-hide_banner",
170
+ "-loglevel", "error",
171
+ "-rtmp_listen", "1",
172
+ // Wait indefinitely: a stream that starts tomorrow is still the stream.
173
+ "-timeout", "-1",
174
+ "-f", "flv",
175
+ "-i", `rtmp://0.0.0.0:${port}/live/${this.rtmpKey}`,
176
+ "-vn",
177
+ "-c:a", "libmp3lame",
178
+ "-b:a", "192k",
179
+ "-y",
180
+ "-f", "mp3",
181
+ this.options.sink,
182
+ ],
183
+ // stdout is watched rather than ignored: the encoded bytes are the only
184
+ // honest signal that a publisher turned up. ffmpeg does not announce a
185
+ // connect, a healthy stream says nothing at -loglevel error, and
186
+ // -progress only reports at the end in this build. Audio existing means
187
+ // audio arrived.
188
+ { stdio: ["ignore", "pipe", "pipe"] });
189
+ const session = {
190
+ id: randomBytes(8).toString("hex"),
191
+ name: "an RTMP publisher",
192
+ format: "flv",
193
+ startedAt: Date.now(),
194
+ bytes: 0,
195
+ };
196
+ let tail = "";
197
+ child.stderr?.on("data", (chunk) => {
198
+ tail = (tail + chunk.toString()).slice(-2000);
199
+ });
200
+ child.stdout?.on("data", (chunk) => {
201
+ if (this.rtmpChild !== child)
202
+ return;
203
+ if (this.session === null) {
204
+ this.session = session;
205
+ this.options.onStart(session);
206
+ }
207
+ if (this.session === session)
208
+ session.bytes += chunk.byteLength;
209
+ // Consumed and dropped for now. The pipe has to be read either way --
210
+ // an unread one fills and stalls the encoder -- and handing these bytes
211
+ // to the listeners is the next piece of work, not a missing one here.
212
+ this.options.onAudio?.(chunk);
213
+ });
214
+ child.on("error", () => {
215
+ if (this.rtmpChild === child)
216
+ this.rtmpChild = null;
217
+ });
218
+ child.on("close", () => {
219
+ if (this.rtmpChild !== child)
220
+ return;
221
+ this.rtmpChild = null;
222
+ if (this.session === session) {
223
+ this.session = null;
224
+ // A publisher disconnecting is how a broadcast ends, not an error.
225
+ this.options.onEnd(session, "");
226
+ }
227
+ // Listen again for the next one.
228
+ if (this.rtmpPort !== null)
229
+ this.armRtmp();
230
+ });
231
+ this.rtmpChild = child;
232
+ }
233
+ /** End the session, whoever ended it. */
234
+ close(error = "") {
235
+ if (this.closing)
236
+ return;
237
+ this.closing = true;
238
+ const session = this.session;
239
+ const child = this.child;
240
+ this.session = null;
241
+ this.child = null;
242
+ try {
243
+ child?.stdin?.end();
244
+ }
245
+ catch {
246
+ // Already broken, which is usually why we are here.
247
+ }
248
+ child?.kill("SIGKILL");
249
+ if (session)
250
+ this.options.onEnd(session, error);
251
+ }
252
+ }
package/dist/main.js CHANGED
@@ -7,11 +7,13 @@
7
7
  * ffmpeg decodes; we read every sample on its way to the speakers and draw it.
8
8
  */
9
9
  import { createApp, themes } from "@profullstack/hqtui";
10
+ import { fileURLToPath } from "node:url";
10
11
  import { resolve } from "node:path";
11
12
  import { detectTools, formatTime, peaks, RATE, Stream, toMono, } from "./audio.js";
12
13
  import { Analyser, bandEdges, bands, decay } from "./fft.js";
13
14
  import { version } from "./meta.js";
14
- import { displayName, loadPlaylist } from "./playlist.js";
15
+ import { displayName, loadSource } from "./playlist.js";
16
+ import { isRemote } from "./sources.js";
15
17
  import { DEFAULT_PORT } from "./server.js";
16
18
  const FFT_SIZE = 2048;
17
19
  export const BAND_COUNT = 24;
@@ -41,20 +43,93 @@ export function barGlyph(value) {
41
43
  }
42
44
  const HELP = `nixamp — it really whips the terminal's ass.
43
45
 
44
- nixamp [path] play a directory or a file in the terminal
45
- nixamp serve [path] [options] play here, and hand out a browser remote
46
+ nixamp [source] play it in the terminal
47
+ nixamp serve [source] [options] play here, and hand out a browser remote
48
+ nixamp daemon start|stop|status serve in the background, and let go of it
49
+ nixamp admin [--url U] [--key K] who is connected, and re-stream to them
50
+ nixamp login [--signup] sign in to nixamp.com
51
+ nixamp logout / whoami forget it, or check it
46
52
  nixamp update [version] re-run the installer, keeping your choices
47
53
  nixamp uninstall [--yes] remove everything the installer created
48
54
 
55
+ A source is a directory, a file, an .m3u, an .m3u8, a .pls, or a URL to any
56
+ of those.
57
+
49
58
  Options for serve:
50
59
  -p, --port N port to listen on (default ${DEFAULT_PORT})
51
- -h, --host HOST address to bind (default 127.0.0.1; 0.0.0.0 for the LAN)
60
+ -h, --host HOST address to bind (default 0.0.0.0, every interface)
52
61
  --web DIR directory of built PWA files to serve at /
53
62
  --no-media do not stream the library's bytes to remotes
63
+ --no-key serve to anyone who can reach the port, with no share link
64
+ --open-port let the port through the local firewall, and close it on exit
65
+ --publish list it at nixamp.com/directory without asking first
66
+ --no-publish never list it, and do not ask
67
+ --name NAME what to call it in the directory (default: this hostname)
68
+ --ingest accept a live stream in at POST /api/ingest
69
+ --rtmp-in N also listen for RTMP publishers (OBS, Larix) from port N
70
+ --rtmp-streams N how many may publish at once (default 3, a port each)
71
+ --rtmp D broadcast out, e.g. --rtmp youtube=<key>. Repeatable
72
+ --x402 charge for listening once more than 5 people are listening
73
+ --no-x402 never charge
54
74
 
55
75
  -v, --version print the version
56
76
  --help print this
57
77
  `;
78
+ /**
79
+ * `nixamp daemon <start|stop|status>`.
80
+ *
81
+ * The daemon is `nixamp serve` with nobody holding its terminal, so this is
82
+ * mostly bookkeeping: start it detached, remember where it went, and be able
83
+ * to answer whether it is still there.
84
+ */
85
+ async function runDaemon(argv) {
86
+ const d = await import("./daemon.js");
87
+ const [action = "status", ...rest] = argv;
88
+ const entry = fileURLToPath(new URL("./main.js", import.meta.url));
89
+ if (action === "start") {
90
+ try {
91
+ const state = await d.start(rest, entry);
92
+ console.log(`nixamp daemon running (pid ${state.pid})`);
93
+ const url = d.daemonUrl(state);
94
+ console.log(` ${state.key ? `${url}/s/${state.key}` : url}`);
95
+ console.log(` ${state.source}`);
96
+ console.log("");
97
+ console.log(" nixamp admin who is connected");
98
+ console.log(" nixamp daemon stop when you are done");
99
+ return 0;
100
+ }
101
+ catch (error) {
102
+ console.error(error.message);
103
+ return 1;
104
+ }
105
+ }
106
+ if (action === "stop") {
107
+ const stopped = await d.stop();
108
+ console.log(stopped ? "nixamp daemon stopped" : "nixamp: no daemon was running");
109
+ return 0;
110
+ }
111
+ if (action === "status") {
112
+ const { running, state } = d.status();
113
+ if (!state) {
114
+ console.log("nixamp: no daemon. Start one with `nixamp daemon start`.");
115
+ return 1;
116
+ }
117
+ // A pid file outlives its process often enough that saying "running"
118
+ // without checking is how you report a daemon that died on Tuesday.
119
+ if (!running) {
120
+ console.log(`nixamp: the daemon (pid ${state.pid}) is gone. See ${state.log}`);
121
+ return 1;
122
+ }
123
+ const url = d.daemonUrl(state);
124
+ console.log(`nixamp daemon running (pid ${state.pid})`);
125
+ console.log(` ${state.key ? `${url}/s/${state.key}` : url}`);
126
+ console.log(` ${state.source}`);
127
+ console.log(` up ${Math.round((Date.now() - state.startedAt) / 1000)}s`);
128
+ return 0;
129
+ }
130
+ console.error(`nixamp daemon: unknown action ${action}. Try start, stop or status.`);
131
+ return 64;
132
+ }
58
133
  /**
59
134
  * The whole CLI, as a function. `bin/nixamp.mjs` imports and calls it: relying
60
135
  * on `import.meta.main` there would leave the installed binary doing nothing,
@@ -67,6 +142,25 @@ export async function main() {
67
142
  await serve(rest, version());
68
143
  return;
69
144
  }
145
+ if (first === "daemon") {
146
+ process.exitCode = await runDaemon(rest);
147
+ return;
148
+ }
149
+ if (first === "admin") {
150
+ const { admin } = await import("./admin.js");
151
+ await admin(rest);
152
+ return;
153
+ }
154
+ if (first === "login" || first === "signup") {
155
+ const { login } = await import("./session.js");
156
+ process.exitCode = await login(first === "signup" ? [...rest, "--signup"] : rest);
157
+ return;
158
+ }
159
+ if (first === "logout" || first === "whoami") {
160
+ const session = await import("./session.js");
161
+ process.exitCode = first === "logout" ? session.logout() : await session.whoami();
162
+ return;
163
+ }
70
164
  if (first === "update" || first === "uninstall") {
71
165
  const manage = await import("./manage.js");
72
166
  process.exitCode = first === "update" ? manage.update(rest) : manage.uninstall(rest);
@@ -80,9 +174,12 @@ export async function main() {
80
174
  console.log(HELP);
81
175
  return;
82
176
  }
83
- const target = resolve(first ?? ".");
177
+ // resolve() would turn https://host/x into /cwd/https:/host/x, so a URL is
178
+ // left exactly as it was typed.
179
+ const asked = first ?? ".";
180
+ const target = isRemote(asked) ? asked : resolve(asked);
84
181
  const tools = detectTools();
85
- const tracks = loadPlaylist(tools, target);
182
+ const tracks = await loadSource(tools, target);
86
183
  if (tracks.length === 0) {
87
184
  console.error(`nixamp: no audio files under ${target}`);
88
185
  process.exit(1);