nixamp 0.2.0 → 0.4.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 (69) hide show
  1. package/README.md +171 -0
  2. package/dist/accounts.d.ts +54 -0
  3. package/dist/accounts.js +160 -0
  4. package/dist/broadcast.d.ts +96 -0
  5. package/dist/broadcast.js +193 -0
  6. package/dist/channels.d.ts +94 -0
  7. package/dist/channels.js +235 -0
  8. package/dist/connections.d.ts +6 -0
  9. package/dist/connections.js +13 -0
  10. package/dist/directory.d.ts +186 -0
  11. package/dist/directory.js +275 -0
  12. package/dist/durable.d.ts +70 -0
  13. package/dist/durable.js +156 -0
  14. package/dist/follows.d.ts +92 -0
  15. package/dist/follows.js +248 -0
  16. package/dist/ingest.d.ts +80 -0
  17. package/dist/ingest.js +252 -0
  18. package/dist/main.js +21 -0
  19. package/dist/manage.js +2 -1
  20. package/dist/notify.d.ts +83 -0
  21. package/dist/notify.js +126 -0
  22. package/dist/optin.d.ts +37 -0
  23. package/dist/optin.js +122 -0
  24. package/dist/owner.d.ts +53 -0
  25. package/dist/owner.js +96 -0
  26. package/dist/partyline.d.ts +259 -0
  27. package/dist/partyline.js +616 -0
  28. package/dist/paywall.d.ts +60 -0
  29. package/dist/paywall.js +162 -0
  30. package/dist/playlist.js +5 -0
  31. package/dist/publish.d.ts +57 -0
  32. package/dist/publish.js +106 -0
  33. package/dist/rtmp-in.d.ts +22 -0
  34. package/dist/rtmp-in.js +79 -0
  35. package/dist/server.d.ts +94 -0
  36. package/dist/server.js +1158 -12
  37. package/dist/session.d.ts +29 -0
  38. package/dist/session.js +184 -0
  39. package/dist/share.d.ts +26 -0
  40. package/dist/share.js +31 -0
  41. package/package.json +8 -2
  42. package/src/accounts.ts +193 -0
  43. package/src/broadcast.ts +264 -0
  44. package/src/channels.ts +281 -0
  45. package/src/connections.ts +13 -0
  46. package/src/directory.ts +362 -0
  47. package/src/durable.ts +215 -0
  48. package/src/follows.ts +307 -0
  49. package/src/ingest.ts +297 -0
  50. package/src/main.ts +21 -0
  51. package/src/manage.ts +2 -1
  52. package/src/notify.ts +217 -0
  53. package/src/optin.ts +128 -0
  54. package/src/owner.ts +113 -0
  55. package/src/partyline.ts +742 -0
  56. package/src/paywall.ts +198 -0
  57. package/src/playlist.ts +5 -0
  58. package/src/publish.ts +137 -0
  59. package/src/rtmp-in.ts +90 -0
  60. package/src/server.ts +1304 -12
  61. package/src/session.ts +209 -0
  62. package/src/share.ts +40 -0
  63. package/src/types/auth-system.d.ts +77 -0
  64. package/web/dist/assets/{index-BGKWWaIx.css → index-DSIDSSPF.css} +1 -1
  65. package/web/dist/assets/index-qRguFskX.js +1 -0
  66. package/web/dist/index.html +62 -6
  67. package/web/dist/install.sh +82 -0
  68. package/web/dist/sw.js +45 -3
  69. package/web/dist/assets/index-Dhja5wxB.js +0 -1
package/src/follows.ts ADDED
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Following a broadcaster, and where to reach the people who do.
3
+ *
4
+ * The phone line got here first, and its reminder is a different thing: you
5
+ * key a code, press 1, and are told once when that particular stream comes
6
+ * back. It is per-stream, one-shot, and tied to the handset you called from.
7
+ * That is right for somebody who dialled a number, and useless for somebody
8
+ * who wants to know whenever a person they like goes live, on whatever device
9
+ * they happen to be holding.
10
+ *
11
+ * So a follow is account to account, and delivery is a set of addresses rather
12
+ * than a phone number: an email, a phone if they gave one, and any number of
13
+ * browsers that have granted permission. One person with a laptop, a phone and
14
+ * a desktop app is three push subscriptions and one account.
15
+ *
16
+ * Unlike the rest of nixamp this is durable. The directory can afford to be a
17
+ * four-minute TTL because a stream that stops is a stream nobody is listening
18
+ * to; a follow has to outlive the stream by definition -- the whole point is
19
+ * to be told about a broadcast that is not happening yet.
20
+ *
21
+ * The query function is injected rather than a Pool being constructed here, so
22
+ * a test can describe a database instead of running one.
23
+ */
24
+
25
+ /** The slice of `pg` this needs. Postgres in production, a fake in tests. */
26
+ export interface Queryable {
27
+ query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
28
+ }
29
+
30
+ /** A browser, desktop app or phone that has granted notification permission. */
31
+ export interface PushTarget {
32
+ endpoint: string;
33
+ p256dh: string;
34
+ auth: string;
35
+ }
36
+
37
+ /** Everywhere one follower can be reached. */
38
+ export interface Reachable {
39
+ accountId: string;
40
+ email: string;
41
+ /** E.164, if they gave one. Empty when they never did. */
42
+ phone: string;
43
+ /** Whether each channel is on. A follower who wants none is still a follower. */
44
+ wantsEmail: boolean;
45
+ wantsSms: boolean;
46
+ wantsWeb: boolean;
47
+ push: PushTarget[];
48
+ }
49
+
50
+ /**
51
+ * The tables.
52
+ *
53
+ * Created on demand rather than in a migration because the auth module owns
54
+ * the schema this sits beside and there is no migration runner to hook into.
55
+ * `IF NOT EXISTS` throughout, so starting a second instance is not a race that
56
+ * takes the first one down.
57
+ *
58
+ * `follows` is keyed on the pair, which makes following twice a no-op rather
59
+ * than a duplicate to deduplicate later. `push_subscriptions` is keyed on the
60
+ * endpoint alone: an endpoint is issued by the browser vendor and is already
61
+ * unique, and the same browser re-subscribing should replace its row rather
62
+ * than accumulate one per sign-in.
63
+ */
64
+ const SCHEMA = `
65
+ CREATE TABLE IF NOT EXISTS follows (
66
+ follower_id TEXT NOT NULL,
67
+ streamer_id TEXT NOT NULL,
68
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
69
+ PRIMARY KEY (follower_id, streamer_id)
70
+ );
71
+ CREATE INDEX IF NOT EXISTS follows_streamer ON follows (streamer_id);
72
+
73
+ CREATE TABLE IF NOT EXISTS push_subscriptions (
74
+ endpoint TEXT PRIMARY KEY,
75
+ account_id TEXT NOT NULL,
76
+ p256dh TEXT NOT NULL,
77
+ auth TEXT NOT NULL,
78
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
79
+ );
80
+ CREATE INDEX IF NOT EXISTS push_account ON push_subscriptions (account_id);
81
+
82
+ CREATE TABLE IF NOT EXISTS notify_prefs (
83
+ account_id TEXT PRIMARY KEY,
84
+ phone TEXT NOT NULL DEFAULT '',
85
+ want_email BOOLEAN NOT NULL DEFAULT TRUE,
86
+ want_sms BOOLEAN NOT NULL DEFAULT FALSE,
87
+ want_web BOOLEAN NOT NULL DEFAULT TRUE
88
+ );
89
+ `;
90
+
91
+ /** E.164, or nothing. A number we cannot dial is not a number worth storing. */
92
+ export function phoneFrom(value: unknown): string {
93
+ if (typeof value !== "string") return "";
94
+ const digits = value.replace(/[^\d+]/g, "");
95
+ if (/^\+[1-9]\d{7,14}$/.test(digits)) return digits;
96
+ // A bare US ten-digit number is the common case and is unambiguous.
97
+ if (/^\d{10}$/.test(digits)) return `+1${digits}`;
98
+ if (/^1\d{10}$/.test(digits)) return `+${digits}`;
99
+ return "";
100
+ }
101
+
102
+ export class Follows {
103
+ private ready: Promise<void> | null = null;
104
+
105
+ constructor(private readonly db: Queryable) {}
106
+
107
+ /** Make the tables, once per process, on first use. */
108
+ private async ensure(): Promise<void> {
109
+ this.ready ??= this.db.query(SCHEMA).then(() => undefined);
110
+ await this.ready;
111
+ }
112
+
113
+ async follow(followerId: string, streamerId: string): Promise<boolean> {
114
+ // Following yourself is not an error worth an error, but it is not a
115
+ // follow either: you do not need telling that you went live.
116
+ if (!followerId || !streamerId || followerId === streamerId) return false;
117
+ await this.ensure();
118
+ await this.db.query(
119
+ `INSERT INTO follows (follower_id, streamer_id) VALUES ($1, $2)
120
+ ON CONFLICT DO NOTHING`,
121
+ [followerId, streamerId],
122
+ );
123
+ return true;
124
+ }
125
+
126
+ async unfollow(followerId: string, streamerId: string): Promise<void> {
127
+ await this.ensure();
128
+ await this.db.query(
129
+ "DELETE FROM follows WHERE follower_id = $1 AND streamer_id = $2",
130
+ [followerId, streamerId],
131
+ );
132
+ }
133
+
134
+ /** Who this account follows. */
135
+ async following(followerId: string): Promise<string[]> {
136
+ await this.ensure();
137
+ const { rows } = await this.db.query(
138
+ "SELECT streamer_id FROM follows WHERE follower_id = $1 ORDER BY created_at",
139
+ [followerId],
140
+ );
141
+ return rows.map((r) => String(r["streamer_id"]));
142
+ }
143
+
144
+ async isFollowing(followerId: string, streamerId: string): Promise<boolean> {
145
+ await this.ensure();
146
+ const { rows } = await this.db.query(
147
+ "SELECT 1 FROM follows WHERE follower_id = $1 AND streamer_id = $2",
148
+ [followerId, streamerId],
149
+ );
150
+ return rows.length > 0;
151
+ }
152
+
153
+ async followerCount(streamerId: string): Promise<number> {
154
+ await this.ensure();
155
+ const { rows } = await this.db.query(
156
+ "SELECT COUNT(*)::int AS n FROM follows WHERE streamer_id = $1",
157
+ [streamerId],
158
+ );
159
+ return Number(rows[0]?.["n"] ?? 0);
160
+ }
161
+
162
+ /** Remember a browser that has granted permission. */
163
+ async addPush(accountId: string, target: PushTarget): Promise<void> {
164
+ if (!accountId || !target.endpoint) return;
165
+ await this.ensure();
166
+ await this.db.query(
167
+ `INSERT INTO push_subscriptions (endpoint, account_id, p256dh, auth)
168
+ VALUES ($1, $2, $3, $4)
169
+ ON CONFLICT (endpoint) DO UPDATE
170
+ SET account_id = EXCLUDED.account_id,
171
+ p256dh = EXCLUDED.p256dh,
172
+ auth = EXCLUDED.auth`,
173
+ [target.endpoint, accountId, target.p256dh, target.auth],
174
+ );
175
+ }
176
+
177
+ /**
178
+ * Forget a browser.
179
+ *
180
+ * Called when somebody turns notifications off, and again when a push is
181
+ * rejected as gone: a subscription outlives the browser that made it, and
182
+ * pushing to a dead endpoint forever is how a table becomes mostly rubbish.
183
+ */
184
+ async removePush(endpoint: string): Promise<void> {
185
+ if (!endpoint) return;
186
+ await this.ensure();
187
+ await this.db.query("DELETE FROM push_subscriptions WHERE endpoint = $1", [endpoint]);
188
+ }
189
+
190
+ async setPrefs(
191
+ accountId: string,
192
+ prefs: { phone?: string; wantsEmail?: boolean; wantsSms?: boolean; wantsWeb?: boolean },
193
+ ): Promise<void> {
194
+ if (!accountId) return;
195
+ await this.ensure();
196
+ // Every column is COALESCEd on the way IN as well as on conflict. A caller
197
+ // setting only the switches sends no phone, and an unset field arrives as
198
+ // null -- which the ON CONFLICT branch handles fine and the INSERT branch
199
+ // does not, because these columns are NOT NULL. Saving preferences for the
200
+ // first time was a 500 until this said so.
201
+ //
202
+ // The casts are not decoration either: Postgres cannot infer the type of a
203
+ // parameter that is only ever seen inside COALESCE against a null.
204
+ await this.db.query(
205
+ `INSERT INTO notify_prefs (account_id, phone, want_email, want_sms, want_web)
206
+ VALUES ($1,
207
+ COALESCE($2::text, ''),
208
+ COALESCE($3::boolean, TRUE),
209
+ COALESCE($4::boolean, FALSE),
210
+ COALESCE($5::boolean, TRUE))
211
+ ON CONFLICT (account_id) DO UPDATE
212
+ SET phone = COALESCE($2::text, notify_prefs.phone),
213
+ want_email = COALESCE($3::boolean, notify_prefs.want_email),
214
+ want_sms = COALESCE($4::boolean, notify_prefs.want_sms),
215
+ want_web = COALESCE($5::boolean, notify_prefs.want_web)`,
216
+ [
217
+ accountId,
218
+ prefs.phone === undefined ? null : phoneFrom(prefs.phone),
219
+ prefs.wantsEmail ?? null,
220
+ prefs.wantsSms ?? null,
221
+ prefs.wantsWeb ?? null,
222
+ ],
223
+ );
224
+ }
225
+
226
+ async prefs(accountId: string): Promise<{ phone: string; wantsEmail: boolean; wantsSms: boolean; wantsWeb: boolean }> {
227
+ await this.ensure();
228
+ const { rows } = await this.db.query(
229
+ "SELECT phone, want_email, want_sms, want_web FROM notify_prefs WHERE account_id = $1",
230
+ [accountId],
231
+ );
232
+ const row = rows[0];
233
+ // Defaults for somebody who has never opened the settings: mail yes, web
234
+ // yes, texts no. A text costs them nothing but is the most intrusive of
235
+ // the three, so it is the one you have to ask for.
236
+ return {
237
+ phone: String(row?.["phone"] ?? ""),
238
+ wantsEmail: row === undefined ? true : row["want_email"] !== false,
239
+ wantsSms: row === undefined ? false : row["want_sms"] === true,
240
+ wantsWeb: row === undefined ? true : row["want_web"] !== false,
241
+ };
242
+ }
243
+
244
+ /**
245
+ * Everyone following this broadcaster, and every way to reach them.
246
+ *
247
+ * One query rather than one per follower. A broadcaster with a thousand
248
+ * followers going live should not be a thousand round trips while the
249
+ * publisher's heartbeat waits on the response.
250
+ */
251
+ async audience(streamerId: string): Promise<Reachable[]> {
252
+ if (!streamerId) return [];
253
+ await this.ensure();
254
+ const { rows } = await this.db.query(
255
+ `SELECT f.follower_id AS account_id,
256
+ COALESCE(u.email, '') AS email,
257
+ COALESCE(p.phone, '') AS phone,
258
+ COALESCE(p.want_email, TRUE) AS want_email,
259
+ COALESCE(p.want_sms, FALSE) AS want_sms,
260
+ COALESCE(p.want_web, TRUE) AS want_web,
261
+ COALESCE(
262
+ json_agg(json_build_object('endpoint', s.endpoint, 'p256dh', s.p256dh, 'auth', s.auth))
263
+ FILTER (WHERE s.endpoint IS NOT NULL),
264
+ '[]'
265
+ ) AS push
266
+ FROM follows f
267
+ LEFT JOIN users u ON u.id = f.follower_id
268
+ LEFT JOIN notify_prefs p ON p.account_id = f.follower_id
269
+ LEFT JOIN push_subscriptions s ON s.account_id = f.follower_id
270
+ WHERE f.streamer_id = $1
271
+ GROUP BY f.follower_id, u.email, p.phone, p.want_email, p.want_sms, p.want_web`,
272
+ [streamerId],
273
+ );
274
+
275
+ return rows.map((r) => ({
276
+ accountId: String(r["account_id"] ?? ""),
277
+ email: String(r["email"] ?? ""),
278
+ phone: String(r["phone"] ?? ""),
279
+ wantsEmail: r["want_email"] !== false,
280
+ wantsSms: r["want_sms"] === true,
281
+ wantsWeb: r["want_web"] !== false,
282
+ push: readPush(r["push"]),
283
+ }));
284
+ }
285
+ }
286
+
287
+ /** json_agg comes back as an array or as a string, depending on the driver. */
288
+ function readPush(value: unknown): PushTarget[] {
289
+ const list = typeof value === "string" ? safeParse(value) : value;
290
+ if (!Array.isArray(list)) return [];
291
+ return list
292
+ .map((item) => (item ?? {}) as Record<string, unknown>)
293
+ .filter((item) => typeof item["endpoint"] === "string" && item["endpoint"] !== "")
294
+ .map((item) => ({
295
+ endpoint: String(item["endpoint"]),
296
+ p256dh: String(item["p256dh"] ?? ""),
297
+ auth: String(item["auth"] ?? ""),
298
+ }));
299
+ }
300
+
301
+ function safeParse(text: string): unknown {
302
+ try {
303
+ return JSON.parse(text);
304
+ } catch {
305
+ return [];
306
+ }
307
+ }
package/src/ingest.ts ADDED
@@ -0,0 +1,297 @@
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, type ChildProcess } from "node:child_process";
25
+ import { randomBytes } from "node:crypto";
26
+ import type { Readable } from "node:stream";
27
+
28
+ /** A live source is one session at a time: two would be two songs at once. */
29
+ export interface IngestSession {
30
+ id: string;
31
+ /** What the sender called itself. */
32
+ name: string;
33
+ /** The container the sender is producing, e.g. webm from MediaRecorder. */
34
+ format: string;
35
+ startedAt: number;
36
+ bytes: number;
37
+ }
38
+
39
+ export interface IngestStatus {
40
+ live: boolean;
41
+ session: IngestSession | null;
42
+ /** Where a native broadcaster should publish, when one is being listened for. */
43
+ rtmp: { port: number; path: string } | null;
44
+ }
45
+
46
+ /** Containers a browser or a desktop encoder actually produces. */
47
+ const FORMATS = new Set(["webm", "ogg", "mp4", "matroska", "mp3", "wav", "flv"]);
48
+
49
+ /**
50
+ * ffmpeg's `-f` is a demuxer name, and passing an unknown one is how a stream
51
+ * dies four seconds in with a message nobody sees. An unrecognised container is
52
+ * refused up front instead.
53
+ */
54
+ export function normaliseFormat(value: unknown): string | null {
55
+ if (typeof value !== "string") return null;
56
+ const format = value.trim().toLowerCase();
57
+ if (format === "") return null;
58
+ // A MediaRecorder mime type: audio/webm;codecs=opus.
59
+ // The subtype may carry a hyphen: audio/x-matroska is what some browsers
60
+ // hand out, and stopping at the hyphen turned it into "x".
61
+ const fromMime = /^(?:audio|video)\/([a-z0-9-]+)/.exec(format)?.[1];
62
+ const candidate = fromMime ?? format;
63
+ const mapped = candidate === "x-matroska" ? "matroska" : candidate;
64
+ return FORMATS.has(mapped) ? mapped : null;
65
+ }
66
+
67
+ export interface IngestOptions {
68
+ ffmpeg: string[];
69
+ /** Where the decoded audio should go: a file ffmpeg writes, or a pipe. */
70
+ sink: string;
71
+ /** Called when a session starts, so the player can switch to it. */
72
+ onStart: (session: IngestSession) => void;
73
+ /** Called when it ends, cleanly or otherwise. */
74
+ onEnd: (session: IngestSession, error: string) => void;
75
+ /** Encoded audio, as it arrives from a live publisher. */
76
+ onAudio?: (chunk: Buffer) => void;
77
+ }
78
+
79
+ /**
80
+ * The live input.
81
+ *
82
+ * One session at a time: a second sender is refused rather than mixed, because
83
+ * mixing two uninvited streams is never what anybody meant.
84
+ */
85
+ export class Ingest {
86
+ private child: ChildProcess | null = null;
87
+ private session: IngestSession | null = null;
88
+ private closing = false;
89
+ /** The RTMP listener, which outlives any one publisher. */
90
+ private rtmpChild: ChildProcess | null = null;
91
+ private rtmpPort: number | null = null;
92
+ private rtmpKey = "";
93
+
94
+ constructor(private readonly options: IngestOptions) {}
95
+
96
+ status(): IngestStatus {
97
+ return {
98
+ live: this.session !== null,
99
+ session: this.session,
100
+ rtmp: this.rtmpPort === null ? null : { port: this.rtmpPort, path: `/live/${this.rtmpKey}` },
101
+ };
102
+ }
103
+
104
+ get live(): boolean {
105
+ return this.session !== null;
106
+ }
107
+
108
+ /**
109
+ * Open a session. Returns the session, or null when one is already running:
110
+ * the caller answers 409, because "somebody else is already broadcasting" is
111
+ * a different problem from "your request was wrong".
112
+ */
113
+ open(name: string, format: string): IngestSession | null {
114
+ if (this.session !== null) return null;
115
+
116
+ const session: IngestSession = {
117
+ id: randomBytes(8).toString("hex"),
118
+ name: name || "a device",
119
+ format,
120
+ startedAt: Date.now(),
121
+ bytes: 0,
122
+ };
123
+
124
+ const [command, ...prefix] = this.options.ffmpeg as [string, ...string[]];
125
+ const child = spawn(
126
+ command,
127
+ [
128
+ ...prefix,
129
+ "-hide_banner",
130
+ "-loglevel", "error",
131
+ // The demuxer is stated because ffmpeg mis-probes a live, unseekable
132
+ // pipe: it reads a few kilobytes, guesses, and guesses wrong.
133
+ "-f", format,
134
+ "-i", "pipe:0",
135
+ "-vn",
136
+ "-c:a", "libmp3lame",
137
+ "-b:a", "192k",
138
+ "-y",
139
+ "-f", "mp3",
140
+ this.options.sink,
141
+ ],
142
+ { stdio: ["pipe", "ignore", "pipe"] },
143
+ );
144
+
145
+ let tail = "";
146
+ child.stderr?.on("data", (chunk: Buffer) => {
147
+ tail = (tail + chunk.toString()).slice(-2000);
148
+ });
149
+ // A sender that hangs up mid-write breaks the pipe, and an unhandled EPIPE
150
+ // takes the whole server down with it.
151
+ child.stdin?.on("error", () => this.close(""));
152
+ child.on("error", (error) => this.close(error.message));
153
+ child.on("close", (code) => this.close(code === 0 ? "" : tail.trim().split("\n").pop() ?? ""));
154
+
155
+ this.child = child;
156
+ this.session = session;
157
+ this.closing = false;
158
+ this.options.onStart(session);
159
+ return session;
160
+ }
161
+
162
+ /** Feed it. Returns false once the session is over. */
163
+ write(chunk: Buffer): boolean {
164
+ const child = this.child;
165
+ const session = this.session;
166
+ if (child === null || session === null || child.stdin === null) return false;
167
+ session.bytes += chunk.byteLength;
168
+ return child.stdin.write(chunk);
169
+ }
170
+
171
+ /** Pipe a whole request body in, for a sender that can stream one. */
172
+ async pump(body: Readable): Promise<void> {
173
+ for await (const chunk of body) {
174
+ if (!this.write(chunk as Buffer)) {
175
+ // Backpressure: wait for the drain rather than growing a buffer that
176
+ // is really the network's problem.
177
+ await new Promise((done) => this.child?.stdin?.once("drain", done) ?? done(null));
178
+ }
179
+ if (this.session === null) return;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Wait for an RTMP publisher, and keep waiting after each one leaves.
185
+ *
186
+ * ffmpeg is the RTMP server here: `-rtmp_listen 1` binds the port and blocks
187
+ * until somebody publishes. It serves one publisher and exits, so the
188
+ * listener is started again afterwards -- otherwise a broadcaster who
189
+ * reconnects finds nothing listening.
190
+ */
191
+ listenRtmp(port: number, key: string): void {
192
+ this.rtmpPort = port;
193
+ this.rtmpKey = key;
194
+ this.armRtmp();
195
+ }
196
+
197
+ /** Stop waiting for publishers. */
198
+ stopRtmp(): void {
199
+ this.rtmpPort = null;
200
+ const listener = this.rtmpChild;
201
+ this.rtmpChild = null;
202
+ listener?.kill("SIGKILL");
203
+ }
204
+
205
+ private armRtmp(): void {
206
+ const port = this.rtmpPort;
207
+ if (port === null || this.rtmpChild !== null) return;
208
+
209
+ const [command, ...prefix] = this.options.ffmpeg as [string, ...string[]];
210
+ const child = spawn(
211
+ command,
212
+ [
213
+ ...prefix,
214
+ "-hide_banner",
215
+ "-loglevel", "error",
216
+ "-rtmp_listen", "1",
217
+ // Wait indefinitely: a stream that starts tomorrow is still the stream.
218
+ "-timeout", "-1",
219
+ "-f", "flv",
220
+ "-i", `rtmp://0.0.0.0:${port}/live/${this.rtmpKey}`,
221
+ "-vn",
222
+ "-c:a", "libmp3lame",
223
+ "-b:a", "192k",
224
+ "-y",
225
+ "-f", "mp3",
226
+ this.options.sink,
227
+ ],
228
+ // stdout is watched rather than ignored: the encoded bytes are the only
229
+ // honest signal that a publisher turned up. ffmpeg does not announce a
230
+ // connect, a healthy stream says nothing at -loglevel error, and
231
+ // -progress only reports at the end in this build. Audio existing means
232
+ // audio arrived.
233
+ { stdio: ["ignore", "pipe", "pipe"] },
234
+ );
235
+
236
+ const session: IngestSession = {
237
+ id: randomBytes(8).toString("hex"),
238
+ name: "an RTMP publisher",
239
+ format: "flv",
240
+ startedAt: Date.now(),
241
+ bytes: 0,
242
+ };
243
+
244
+ let tail = "";
245
+ child.stderr?.on("data", (chunk: Buffer) => {
246
+ tail = (tail + chunk.toString()).slice(-2000);
247
+ });
248
+
249
+ child.stdout?.on("data", (chunk: Buffer) => {
250
+ if (this.rtmpChild !== child) return;
251
+ if (this.session === null) {
252
+ this.session = session;
253
+ this.options.onStart(session);
254
+ }
255
+ if (this.session === session) session.bytes += chunk.byteLength;
256
+ // Consumed and dropped for now. The pipe has to be read either way --
257
+ // an unread one fills and stalls the encoder -- and handing these bytes
258
+ // to the listeners is the next piece of work, not a missing one here.
259
+ this.options.onAudio?.(chunk);
260
+ });
261
+
262
+ child.on("error", () => {
263
+ if (this.rtmpChild === child) this.rtmpChild = null;
264
+ });
265
+
266
+ child.on("close", () => {
267
+ if (this.rtmpChild !== child) return;
268
+ this.rtmpChild = null;
269
+ if (this.session === session) {
270
+ this.session = null;
271
+ // A publisher disconnecting is how a broadcast ends, not an error.
272
+ this.options.onEnd(session, "");
273
+ }
274
+ // Listen again for the next one.
275
+ if (this.rtmpPort !== null) this.armRtmp();
276
+ });
277
+
278
+ this.rtmpChild = child;
279
+ }
280
+
281
+ /** End the session, whoever ended it. */
282
+ close(error = ""): void {
283
+ if (this.closing) return;
284
+ this.closing = true;
285
+ const session = this.session;
286
+ const child = this.child;
287
+ this.session = null;
288
+ this.child = null;
289
+ try {
290
+ child?.stdin?.end();
291
+ } catch {
292
+ // Already broken, which is usually why we are here.
293
+ }
294
+ child?.kill("SIGKILL");
295
+ if (session) this.options.onEnd(session, error);
296
+ }
297
+ }
package/src/main.ts CHANGED
@@ -70,6 +70,8 @@ const HELP = `nixamp — it really whips the terminal's ass.
70
70
  nixamp serve [source] [options] play here, and hand out a browser remote
71
71
  nixamp daemon start|stop|status serve in the background, and let go of it
72
72
  nixamp admin [--url U] [--key K] who is connected, and re-stream to them
73
+ nixamp login [--signup] sign in to nixamp.com
74
+ nixamp logout / whoami forget it, or check it
73
75
  nixamp update [version] re-run the installer, keeping your choices
74
76
  nixamp uninstall [--yes] remove everything the installer created
75
77
 
@@ -83,6 +85,15 @@ Options for serve:
83
85
  --no-media do not stream the library's bytes to remotes
84
86
  --no-key serve to anyone who can reach the port, with no share link
85
87
  --open-port let the port through the local firewall, and close it on exit
88
+ --publish list it at nixamp.com/directory without asking first
89
+ --no-publish never list it, and do not ask
90
+ --name NAME what to call it in the directory (default: this hostname)
91
+ --ingest accept a live stream in at POST /api/ingest
92
+ --rtmp-in N also listen for RTMP publishers (OBS, Larix) from port N
93
+ --rtmp-streams N how many may publish at once (default 3, a port each)
94
+ --rtmp D broadcast out, e.g. --rtmp youtube=<key>. Repeatable
95
+ --x402 charge for listening once more than 5 people are listening
96
+ --no-x402 never charge
86
97
 
87
98
  -v, --version print the version
88
99
  --help print this
@@ -169,6 +180,16 @@ export async function main(): Promise<void> {
169
180
  await admin(rest);
170
181
  return;
171
182
  }
183
+ if (first === "login" || first === "signup") {
184
+ const { login } = await import("./session.ts");
185
+ process.exitCode = await login(first === "signup" ? [...rest, "--signup"] : rest);
186
+ return;
187
+ }
188
+ if (first === "logout" || first === "whoami") {
189
+ const session = await import("./session.ts");
190
+ process.exitCode = first === "logout" ? session.logout() : await session.whoami();
191
+ return;
192
+ }
172
193
  if (first === "update" || first === "uninstall") {
173
194
  const manage = await import("./manage.ts");
174
195
  process.exitCode = first === "update" ? manage.update(rest) : manage.uninstall(rest);
package/src/manage.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  import { spawnSync } from "node:child_process";
10
10
  import { existsSync, readFileSync } from "node:fs";
11
11
  import { dirname, join, resolve } from "node:path";
12
+ import { fileURLToPath } from "node:url";
12
13
 
13
14
  /** What the installer recorded about this install. */
14
15
  export interface Manifest {
@@ -31,7 +32,7 @@ const windows = process.platform === "win32";
31
32
  * wrote, which is the only thing that knows for certain; the walk up from this
32
33
  * file covers a shim from an older install that did not set it.
33
34
  */
34
- export function installRoot(from = new URL(".", import.meta.url).pathname): string | null {
35
+ export function installRoot(from = fileURLToPath(new URL(".", import.meta.url))): string | null {
35
36
  const declared = process.env["NIXAMP_HOME"];
36
37
  if (declared && existsSync(join(declared, "manifest.json"))) return declared;
37
38