nixamp 0.56.0 → 0.57.1

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 (51) hide show
  1. package/dist/channels.d.ts +20 -0
  2. package/dist/channels.js +24 -0
  3. package/dist/label-profiles.js +2 -2
  4. package/dist/library.d.ts +6 -0
  5. package/dist/library.js +11 -0
  6. package/dist/oauth.d.ts +36 -3
  7. package/dist/oauth.js +107 -7
  8. package/dist/playlist-input.d.ts +32 -7
  9. package/dist/playlist-input.js +20 -2
  10. package/dist/server.js +16 -6
  11. package/dist/station-routes.d.ts +1 -0
  12. package/dist/station-routes.js +23 -5
  13. package/dist/station-runner.d.ts +48 -0
  14. package/dist/station-runner.js +208 -4
  15. package/dist/stations.d.ts +14 -0
  16. package/dist/stations.js +11 -0
  17. package/package.json +1 -1
  18. package/src/channels.ts +30 -0
  19. package/src/label-profiles.ts +2 -2
  20. package/src/library.ts +14 -0
  21. package/src/oauth.ts +119 -6
  22. package/src/playlist-input.ts +46 -5
  23. package/src/server.ts +18 -5
  24. package/src/station-routes.ts +23 -6
  25. package/src/station-runner.ts +205 -4
  26. package/src/stations.ts +15 -0
  27. package/web/dist/assets/{ar-CwZJb_gN.js → ar-HteUbQ_m.js} +1 -1
  28. package/web/dist/assets/{cs-BQeUHU5U.js → cs-CjN_4DAJ.js} +1 -1
  29. package/web/dist/assets/{da-B9gLGX-j.js → da-CzsSXVfk.js} +1 -1
  30. package/web/dist/assets/{de-BtKJqMyc.js → de-D7zVt1UT.js} +1 -1
  31. package/web/dist/assets/{es-xCZPNIQ8.js → es-D8duNQiq.js} +1 -1
  32. package/web/dist/assets/{fi-Bs6hJxj9.js → fi-CSKCYE5E.js} +1 -1
  33. package/web/dist/assets/{fr-Db3viYEV.js → fr-DnjuIwaN.js} +1 -1
  34. package/web/dist/assets/{hi-BEO0uXMK.js → hi-ByZe82O5.js} +1 -1
  35. package/web/dist/assets/{hu-DddOFPOR.js → hu-B3iwlAuW.js} +1 -1
  36. package/web/dist/assets/{id-Ca4dDDtC.js → id-B58CS7rH.js} +1 -1
  37. package/web/dist/assets/{it-B9cFkgz7.js → it-CaVLbop_.js} +1 -1
  38. package/web/dist/assets/{main-CHubaPAu.js → main-yTRNIxIl.js} +2 -2
  39. package/web/dist/assets/{nl-kUxjpAwG.js → nl-Dk0ss8Tf.js} +1 -1
  40. package/web/dist/assets/{radio-CtAne8M1.css → radio-Cmg6GPN2.css} +1 -1
  41. package/web/dist/assets/{radio-yD_-qpS7.js → radio-DV3h4YZS.js} +1 -1
  42. package/web/dist/assets/{ru-BE9Sxy3t.js → ru-CGuA41ji.js} +1 -1
  43. package/web/dist/assets/{station-DxBlD6Yl.js → station-D6sd4DqP.js} +1 -1
  44. package/web/dist/assets/{sv-Cp6BIRXI.js → sv-B309Td6Z.js} +1 -1
  45. package/web/dist/assets/{uk-DavLH9cs.js → uk-CCCKvR-U.js} +1 -1
  46. package/web/dist/assets/{vi-eAlsSX6P.js → vi-DfVTbK_t.js} +1 -1
  47. package/web/dist/assets/{zh-D2Y8KIQG.js → zh-BU9_CD0f.js} +1 -1
  48. package/web/dist/index.html +1 -1
  49. package/web/dist/radio.html +2 -2
  50. package/web/dist/station.html +1 -1
  51. package/web/dist/sw.js +22 -22
@@ -37,14 +37,16 @@ function nowPlayingFile(ctx, station) {
37
37
  }
38
38
  export function publicView(ctx, station) {
39
39
  const state = ctx.runner.observed(station.id);
40
- const file = state === "live" || state === "recovering" ? nowPlayingFile(ctx, station) : "";
40
+ // Asleep, what it will wake on: the first listener hears that next.
41
+ const asleep = ctx.runner.isSleeping?.(station.id) ?? false;
42
+ const file = asleep ? ctx.runner.nextUp(station.id) : state === "live" || state === "recovering" ? nowPlayingFile(ctx, station) : "";
41
43
  // The tags the player read when it put this file on, else the library's.
42
44
  const track = file ? (ctx.channels.tagsOf(channelOf(station.id), file) ?? ctx.trackFor(file)) : null;
43
45
  // What the channel is carrying wins over the flag: a station made by hand
44
46
  // from films streams video whether or not anyone said so.
45
47
  const video = station.video || ctx.channels.kindOf(channelOf(station.id)) === "video";
46
48
  // How far into the song (or film) on the air, by the encoder's clock, and how long it is.
47
- const position = file ? ctx.channels.info(channelOf(station.id))?.position : undefined;
49
+ const position = file && !asleep ? ctx.channels.info(channelOf(station.id))?.position : undefined;
48
50
  const duration = file && ctx.durationOf ? ctx.durationOf(file) : 0;
49
51
  const progress = typeof position === "number" && duration > 0 ? { position: Math.round(Math.min(position, duration) * 10) / 10, duration: Math.round(duration * 10) / 10 } : null;
50
52
  return {
@@ -86,6 +88,8 @@ export function ownerView(ctx, station) {
86
88
  return {
87
89
  ...rest,
88
90
  state: ctx.runner.observed(station.id),
91
+ // On the air with nobody listening: no encoder until somebody does.
92
+ sleeping: ctx.runner.isSleeping?.(station.id) ?? false,
89
93
  excluded: Object.entries(failures).filter(([, count]) => count >= 3).map(([file]) => file),
90
94
  listeners: ctx.runner.listeners(station.id),
91
95
  error: ctx.runner.error(station.id),
@@ -264,18 +268,32 @@ export async function handleStations(request, response, path, url, ctx) {
264
268
  return true;
265
269
  }
266
270
  const channelId = channelOf(station.id);
267
- if (!ctx.channels.has(channelId)) {
268
- ctx.json(response, 503, { error: "the station is not on the air", code: "not_live", state: ctx.runner.observed(station.id) });
271
+ // Asleep, a HEAD is told what it would get without waking it.
272
+ if (method === "HEAD" && ctx.runner.isSleeping?.(station.id)) {
273
+ response.writeHead(200, { ...ctx.headers, "content-type": station.video ? "video/mp4" : "audio/mpeg", "cache-control": "no-store" });
274
+ response.end();
269
275
  return true;
270
276
  }
271
277
  // Admitted only within the station's and the server's limits, and the
272
- // month's allowance; refused with what to do about it.
278
+ // month's allowance; refused with what to do about it. Before waking it:
279
+ // a listener turned away is no reason to start the encoder.
273
280
  const refused = method === "GET" && ctx.usage && ctx.limits ? ctx.usage.admit(station.id, ctx.limits) : null;
274
281
  if (refused) {
275
282
  response.writeHead(refused.status, { ...ctx.headers, "content-type": "application/json; charset=utf-8", "retry-after": String(refused.retryAfter) });
276
283
  response.end(JSON.stringify({ error: refused.error, code: refused.code, retryAfter: refused.retryAfter }));
277
284
  return true;
278
285
  }
286
+ // The first listener wakes a sleeping station, and is held until it
287
+ // starts sending, so they hear it begin rather than a stream that ends.
288
+ let closed = false;
289
+ response.once("close", () => { closed = true; });
290
+ await ctx.runner.awake?.(station.id, undefined, () => closed);
291
+ if (closed)
292
+ return true;
293
+ if (!ctx.channels.has(channelId)) {
294
+ ctx.json(response, 503, { error: "the station is not on the air", code: "not_live", state: ctx.runner.observed(station.id) });
295
+ return true;
296
+ }
279
297
  // Signed in at nixamp.com: no breaks, starting a little behind live so
280
298
  // they can be left out without a gap. Radio only (Channel.listenWithoutBreaks).
281
299
  const pass = url.searchParams.get(PASS_PARAM) ?? "";
@@ -8,6 +8,13 @@
8
8
  * long as it is still wanted, so a disk that comes back or a file put back in
9
9
  * place brings it back under the same id and link. A station its owner
10
10
  * stopped is never restarted by anything here.
11
+ *
12
+ * A station nobody is listening to sleeps: after `idleSeconds` with nobody
13
+ * attached to its channel, the channel (and its ffmpeg) is stopped, but the
14
+ * station stays wanted on and is still on the air to the guide. The first
15
+ * listener wakes it, and it carries on from the track after the one it slept
16
+ * on, with its break clock where it was. A sleep is not a failure: no
17
+ * recovery, no restart counted.
11
18
  */
12
19
  import type { Channels, ChannelInfo, PullResume } from "./channels.ts";
13
20
  import { type Observed, type Station, type StationStore } from "./stations.ts";
@@ -30,7 +37,11 @@ export interface RunnerDeps {
30
37
  breaks?: (video: boolean) => Promise<string | null>;
31
38
  /** Who a file is by, from the library's tags, for a shuffle that spreads artists out; "" when unknown. */
32
39
  artistOf?: (file: string) => string;
40
+ /** Seconds with nobody listening before a station sleeps; 0 (or unset) never. Asked at every sweep. */
41
+ idleSeconds?: () => number;
33
42
  }
43
+ /** How long a listener waking a station is held for its first bytes. */
44
+ export declare const WAKE_WAIT_MS = 10000;
34
45
  /**
35
46
  * Who a file is by when the tags do not say: "Artist - Album/track" names
36
47
  * them in the folder, and "Artist/Album/track" one folder up.
@@ -53,6 +64,14 @@ export declare class StationRunner {
53
64
  private down;
54
65
  /** The server is going down: its channels end because it is, not because a station failed. */
55
66
  private closing;
67
+ /** Wanted on, with nobody listening: no channel until somebody does. */
68
+ private asleep;
69
+ /** For a station asleep: the rest of the pass it was playing, in order. */
70
+ private parked;
71
+ /** Since when a station's channel has had nobody on it. */
72
+ private quietSince;
73
+ private waking;
74
+ private idleTimer;
56
75
  constructor(deps: RunnerDeps);
57
76
  /**
58
77
  * Called before the server stops every channel on its way out. Without it,
@@ -74,6 +93,35 @@ export declare class StationRunner {
74
93
  remove(id: string): void;
75
94
  /** Put back every station that was running when this server last stopped. */
76
95
  restore(): void;
96
+ /** Whether a station is asleep: wanted on, on the air to the guide, with no channel until somebody listens. */
97
+ isSleeping(id: string): boolean;
98
+ /** The file a sleeping station would wake on, "" when it cannot say. */
99
+ nextUp(id: string): string;
100
+ /** Look every so often for stations nobody is listening to. */
101
+ watchIdle(everyMs?: number): void;
102
+ /**
103
+ * Put to sleep every station whose channel has had nobody on it for the
104
+ * idle time. Anybody attached counts: a listener on the link or /radio, a
105
+ * class or room relaying it, an HLS packager, a peer pulling it. The
106
+ * now-playing events alone do not.
107
+ */
108
+ sweep(): void;
109
+ /** Off the air for now, still wanted on: remembers where it was, and is not a failure. */
110
+ sleep(id: string): void;
111
+ /** On again for a listener, if it was asleep. True when its channel is up (or coming up). */
112
+ wake(id: string): Promise<boolean>;
113
+ /**
114
+ * Wake it if it is asleep, and wait (up to `timeoutMs`) for its first
115
+ * bytes, so a listener hears it start rather than a stream that ends.
116
+ * True when the channel is up.
117
+ */
118
+ awake(id: string, timeoutMs?: number, gone?: () => boolean): Promise<boolean>;
119
+ /**
120
+ * Where a launch picks up: the rest of the pass it slept in, or (after the
121
+ * server restarted) the files after the one it was on; and the break
122
+ * clock. Taken once, by the next launch.
123
+ */
124
+ private takeResume;
77
125
  private launch;
78
126
  /** Told by the server when any channel ends. */
79
127
  onChannelEnd(info: ChannelInfo): void;
@@ -1,4 +1,6 @@
1
1
  import { EXCLUDE_AFTER, OFFLINE_RETRY_MS, RECOVERY_DELAYS_MS, StationError, channelOf, insideRoots, spreadByArtist, stationOfChannel, } from "./stations.js";
2
+ /** How long a listener waking a station is held for its first bytes. */
3
+ export const WAKE_WAIT_MS = 10_000;
2
4
  /**
3
5
  * Who a file is by when the tags do not say: "Artist - Album/track" names
4
6
  * them in the folder, and "Artist/Album/track" one folder up.
@@ -26,6 +28,14 @@ export class StationRunner {
26
28
  down = new Map();
27
29
  /** The server is going down: its channels end because it is, not because a station failed. */
28
30
  closing = false;
31
+ /** Wanted on, with nobody listening: no channel until somebody does. */
32
+ asleep = new Set();
33
+ /** For a station asleep: the rest of the pass it was playing, in order. */
34
+ parked = new Map();
35
+ /** Since when a station's channel has had nobody on it. */
36
+ quietSince = new Map();
37
+ waking = new Map();
38
+ idleTimer = null;
29
39
  constructor(deps) {
30
40
  this.deps = deps;
31
41
  }
@@ -35,7 +45,21 @@ export class StationRunner {
35
45
  * busy day every station said "something keeps stopping it".
36
46
  */
37
47
  close() {
48
+ if (!this.closing) {
49
+ // Where each station on the air was, so after an update it wakes on
50
+ // the next track with its break clock, as it would from a sleep.
51
+ for (const station of this.deps.store.list()) {
52
+ if (station.desired !== "running" || this.asleep.has(station.id))
53
+ continue;
54
+ const point = this.deps.channels.resumePoint(channelOf(station.id));
55
+ if (point)
56
+ this.deps.store.setResume(station.id, { after: point.file || station.resume?.after || "", sinceBreak: point.sinceBreak });
57
+ }
58
+ }
38
59
  this.closing = true;
60
+ if (this.idleTimer)
61
+ clearInterval(this.idleTimer);
62
+ this.idleTimer = null;
39
63
  for (const timer of this.timers.values())
40
64
  clearTimeout(timer);
41
65
  this.timers.clear();
@@ -60,6 +84,7 @@ export class StationRunner {
60
84
  throw new StationError("nothing_playable", "none of this station's files can be found in the library", 409);
61
85
  }
62
86
  this.deps.store.setDesired(id, "running", this.now());
87
+ this.asleep.delete(id);
63
88
  this.cancelRecovery(id);
64
89
  this.attempts.delete(id);
65
90
  await this.launch(id);
@@ -68,6 +93,9 @@ export class StationRunner {
68
93
  /** Wanted off, and taken off. Stays off across restarts. */
69
94
  stop(id) {
70
95
  const station = this.deps.store.setDesired(id, "stopped", this.now());
96
+ this.asleep.delete(id);
97
+ this.parked.delete(id);
98
+ this.quietSince.delete(id);
71
99
  this.down.delete(id);
72
100
  this.cancelRecovery(id);
73
101
  this.attempts.delete(id);
@@ -83,6 +111,11 @@ export class StationRunner {
83
111
  skip(id) {
84
112
  if (!this.deps.store.get(id))
85
113
  throw new StationError("not_found", "no such station", 404);
114
+ // Asleep, the next track is the one after the one it will wake on.
115
+ if (this.asleep.has(id)) {
116
+ this.parked.get(id)?.shift();
117
+ return;
118
+ }
86
119
  if (!this.deps.channels.skip(channelOf(id)))
87
120
  throw new StationError("not_live", "the station is not playing", 409);
88
121
  }
@@ -96,13 +129,162 @@ export class StationRunner {
96
129
  }
97
130
  /** Put back every station that was running when this server last stopped. */
98
131
  restore() {
132
+ // Asleep until somebody listens, when stations sleep at all: putting
133
+ // every one on at once, to have each go back to sleep a minute later,
134
+ // is a storm of ffmpeg for nobody.
135
+ const sleepy = (this.deps.idleSeconds?.() ?? 0) > 0;
99
136
  for (const station of this.deps.store.list()) {
100
137
  if (station.desired !== "running")
101
138
  continue;
139
+ if (sleepy) {
140
+ this.asleep.add(station.id);
141
+ continue;
142
+ }
102
143
  this.log(` Putting station "${station.name}" back on the air.`);
103
144
  void this.launch(station.id);
104
145
  }
105
146
  }
147
+ /** Whether a station is asleep: wanted on, on the air to the guide, with no channel until somebody listens. */
148
+ isSleeping(id) {
149
+ return this.asleep.has(id);
150
+ }
151
+ /** The file a sleeping station would wake on, "" when it cannot say. */
152
+ nextUp(id) {
153
+ if (!this.asleep.has(id))
154
+ return "";
155
+ const parked = this.parked.get(id)?.[0];
156
+ if (parked)
157
+ return parked;
158
+ const station = this.deps.store.get(id);
159
+ if (!station || station.shuffle || !station.resume?.after)
160
+ return "";
161
+ const files = station.items;
162
+ const at = files.indexOf(station.resume.after);
163
+ return at >= 0 ? files[at + 1] ?? "" : "";
164
+ }
165
+ /** Look every so often for stations nobody is listening to. */
166
+ watchIdle(everyMs = 5_000) {
167
+ if (this.idleTimer)
168
+ return;
169
+ this.idleTimer = setInterval(() => this.sweep(), everyMs);
170
+ this.idleTimer.unref?.();
171
+ }
172
+ /**
173
+ * Put to sleep every station whose channel has had nobody on it for the
174
+ * idle time. Anybody attached counts: a listener on the link or /radio, a
175
+ * class or room relaying it, an HLS packager, a peer pulling it. The
176
+ * now-playing events alone do not.
177
+ */
178
+ sweep() {
179
+ const idle = this.deps.idleSeconds?.() ?? 0;
180
+ if (idle <= 0 || this.closing)
181
+ return;
182
+ const now = this.now();
183
+ for (const station of this.deps.store.list()) {
184
+ const id = station.id;
185
+ const channelId = channelOf(id);
186
+ if (station.desired !== "running" || this.asleep.has(id) || this.starting.has(id) || !this.deps.channels.has(channelId)) {
187
+ this.quietSince.delete(id);
188
+ continue;
189
+ }
190
+ if (this.deps.channels.listenersOf(channelId) > 0) {
191
+ this.quietSince.delete(id);
192
+ continue;
193
+ }
194
+ const since = this.quietSince.get(id);
195
+ if (since === undefined)
196
+ this.quietSince.set(id, now);
197
+ else if (now - since >= idle * 1000)
198
+ this.sleep(id);
199
+ }
200
+ }
201
+ /** Off the air for now, still wanted on: remembers where it was, and is not a failure. */
202
+ sleep(id) {
203
+ const station = this.deps.store.get(id);
204
+ const channelId = channelOf(id);
205
+ if (!station || station.desired !== "running" || this.asleep.has(id))
206
+ return;
207
+ const point = this.deps.channels.resumePoint(channelId);
208
+ this.deps.store.setResume(id, {
209
+ after: point?.file || station.resume?.after || "",
210
+ sinceBreak: point ? point.sinceBreak : station.resume?.sinceBreak ?? 0,
211
+ });
212
+ this.parked.set(id, point?.upcoming ?? []);
213
+ this.asleep.add(id);
214
+ this.quietSince.delete(id);
215
+ this.cancelRecovery(id);
216
+ this.attempts.delete(id);
217
+ this.errors.delete(id);
218
+ this.down.delete(id);
219
+ if (this.deps.channels.has(channelId)) {
220
+ this.stopping.add(channelId);
221
+ this.deps.channels.stop(channelId);
222
+ }
223
+ this.log(` Station "${station.name}" is asleep until somebody listens.`);
224
+ }
225
+ /** On again for a listener, if it was asleep. True when its channel is up (or coming up). */
226
+ wake(id) {
227
+ const pending = this.waking.get(id);
228
+ if (pending)
229
+ return pending;
230
+ if (!this.asleep.has(id))
231
+ return Promise.resolve(this.deps.channels.has(channelOf(id)) || this.starting.has(id));
232
+ this.asleep.delete(id);
233
+ this.quietSince.delete(id);
234
+ const station = this.deps.store.get(id);
235
+ if (station)
236
+ this.log(` Station "${station.name}" woke for a listener.`);
237
+ const woken = this.launch(id).finally(() => this.waking.delete(id));
238
+ this.waking.set(id, woken);
239
+ return woken;
240
+ }
241
+ /**
242
+ * Wake it if it is asleep, and wait (up to `timeoutMs`) for its first
243
+ * bytes, so a listener hears it start rather than a stream that ends.
244
+ * True when the channel is up.
245
+ */
246
+ async awake(id, timeoutMs = WAKE_WAIT_MS, gone = () => false) {
247
+ const channelId = channelOf(id);
248
+ const deadline = Date.now() + timeoutMs;
249
+ const woke = this.asleep.has(id) || this.waking.has(id);
250
+ if (!woke)
251
+ return this.deps.channels.has(channelId);
252
+ let timer;
253
+ const up = await Promise.race([
254
+ this.wake(id),
255
+ new Promise((done) => { timer = setTimeout(() => done(false), timeoutMs); }),
256
+ ]);
257
+ clearTimeout(timer);
258
+ if (!up && !this.deps.channels.has(channelId))
259
+ return false;
260
+ while (!this.deps.channels.flowing(channelId) && Date.now() < deadline && !gone()) {
261
+ if (!this.deps.channels.has(channelId) && !this.starting.has(id))
262
+ return false;
263
+ await new Promise((done) => setTimeout(done, 50));
264
+ }
265
+ return this.deps.channels.has(channelId);
266
+ }
267
+ /**
268
+ * Where a launch picks up: the rest of the pass it slept in, or (after the
269
+ * server restarted) the files after the one it was on; and the break
270
+ * clock. Taken once, by the next launch.
271
+ */
272
+ takeResume(id, station, files) {
273
+ const parked = this.parked.get(id);
274
+ this.parked.delete(id);
275
+ let upcoming = parked && parked.length > 0 ? parked : null;
276
+ const after = station.resume?.after ?? "";
277
+ if (!parked && after && !station.shuffle) {
278
+ const at = files.indexOf(after);
279
+ if (at >= 0 && at + 1 < files.length)
280
+ upcoming = files.slice(at + 1);
281
+ }
282
+ const sinceBreak = station.resume?.sinceBreak ?? 0;
283
+ // Used once: a recovery later is a start like any other.
284
+ if (station.resume)
285
+ this.deps.store.setResume(id, null);
286
+ return { upcoming, sinceBreak };
287
+ }
106
288
  async launch(id) {
107
289
  const station = this.deps.store.get(id);
108
290
  if (!station || station.desired !== "running")
@@ -118,6 +300,10 @@ export class StationRunner {
118
300
  }
119
301
  this.starting.add(id);
120
302
  const store = this.deps.store;
303
+ const resume = this.takeResume(id, station, files);
304
+ // The first pass after a sleep is the rest of the one it slept in.
305
+ let carryOn = resume.upcoming;
306
+ let clock = resume.sinceBreak;
121
307
  try {
122
308
  const ok = await this.deps.pull(channelId, station.name, files, {
123
309
  audioBitrate: station.bitrate,
@@ -125,9 +311,19 @@ export class StationRunner {
125
311
  repeat: station.repeat,
126
312
  passOver: true,
127
313
  // Read at every pass, so turning shuffle on or off lands then.
128
- order: (length, files) => (store.get(id)?.shuffle
129
- ? spreadByArtist(files, (file) => this.deps.artistOf?.(file) || artistFromPath(file))
130
- : [...Array(length).keys()]),
314
+ order: (length, files) => {
315
+ if (carryOn) {
316
+ const wanted = carryOn;
317
+ carryOn = null;
318
+ const index = new Map(files.map((file, at) => [file, at]));
319
+ const picked = wanted.map((file) => index.get(file)).filter((at) => at !== undefined && !store.isExcluded(id, files[at]));
320
+ if (picked.length > 0)
321
+ return picked;
322
+ }
323
+ return store.get(id)?.shuffle
324
+ ? spreadByArtist(files, (file) => this.deps.artistOf?.(file) || artistFromPath(file))
325
+ : [...Array(length).keys()];
326
+ },
131
327
  // Read at every track, so an edit lands on the next one.
132
328
  current: () => {
133
329
  const now = store.get(id);
@@ -137,7 +333,12 @@ export class StationRunner {
137
333
  // Read at every boundary, so setting breaks on a running station
138
334
  // lands without a restart; 0 is none.
139
335
  ...(this.deps.breaks
140
- ? { breaks: { everySeconds: () => store.get(id)?.breaksEvery ?? 0, next: () => this.deps.breaks(station.video) } }
336
+ ? { breaks: {
337
+ everySeconds: () => store.get(id)?.breaksEvery ?? 0,
338
+ next: () => this.deps.breaks(station.video),
339
+ // Once: a redial later in the day starts its own clock, as it always has.
340
+ sinceBreak: () => { const was = clock; clock = 0; return was; },
341
+ } }
141
342
  : {}),
142
343
  onFailure: ({ file, reason }) => {
143
344
  this.errors.set(id, reason);
@@ -218,6 +419,9 @@ export class StationRunner {
218
419
  return "stopped";
219
420
  if (station.desired === "stopped")
220
421
  return "stopped";
422
+ // On the air to anyone asking: the first listener wakes it.
423
+ if (this.asleep.has(id))
424
+ return "live";
221
425
  if (this.starting.has(id))
222
426
  return "starting";
223
427
  const info = this.deps.channels.info(channelOf(id));
@@ -41,6 +41,15 @@ export interface Station {
41
41
  idempotencyKey: string;
42
42
  createdAt: number;
43
43
  updatedAt: number;
44
+ /**
45
+ * Where it was when it last went to sleep with nobody listening: the file
46
+ * that was on, so it carries on after it, and the seconds of airtime since
47
+ * its last break, so breaks keep their spacing across sleeps.
48
+ */
49
+ resume?: {
50
+ after: string;
51
+ sinceBreak: number;
52
+ };
44
53
  }
45
54
  /** Times an item may fail in a row before rotation leaves it out. */
46
55
  export declare const EXCLUDE_AFTER = 3;
@@ -97,6 +106,11 @@ export declare class StationStore {
97
106
  /** Name, words, files and rotation. Who may listen is changed by publish/unpublish. */
98
107
  update(id: string, input: StationInput, items: string[] | null, now?: number): Station;
99
108
  remove(id: string): boolean;
109
+ /** Where it was when it went to sleep (Station.resume); null forgets it. */
110
+ setResume(id: string, resume: {
111
+ after: string;
112
+ sinceBreak: number;
113
+ } | null): void;
100
114
  setDesired(id: string, desired: Desired, now?: number): Station;
101
115
  /**
102
116
  * Who may hear it, and whether the directory lists it. Public needs a
package/dist/stations.js CHANGED
@@ -262,6 +262,17 @@ export class StationStore {
262
262
  this.save();
263
263
  return had;
264
264
  }
265
+ /** Where it was when it went to sleep (Station.resume); null forgets it. */
266
+ setResume(id, resume) {
267
+ const station = this.stations.get(id);
268
+ if (!station)
269
+ return;
270
+ if (resume)
271
+ station.resume = { after: resume.after, sinceBreak: Math.max(0, Math.round(resume.sinceBreak)) };
272
+ else
273
+ delete station.resume;
274
+ this.save();
275
+ }
265
276
  setDesired(id, desired, now = Date.now()) {
266
277
  const station = this.require(id);
267
278
  station.desired = desired;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nixamp",
3
- "version": "0.56.0",
3
+ "version": "0.57.1",
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/channels.ts CHANGED
@@ -325,6 +325,19 @@ export class Channel {
325
325
  return done;
326
326
  }
327
327
 
328
+ /** How far listeners have got into this dial of a list, by the encoder's progress. */
329
+ private heard = 0;
330
+
331
+ /** Where a list would pick up after what listeners hear now (PlaylistInputStream.resumePoint). */
332
+ resumePoint(): { file: string; upcoming: string[]; sinceBreak: number } | null {
333
+ return this.playlistInput?.resumePoint(this.heard) ?? null;
334
+ }
335
+
336
+ /** Whether listeners would get sound (and, for a picture, its opening) if they joined now. */
337
+ get flowing(): boolean {
338
+ return this.info.bytes > 0 && (!this.fragments || this.fragments.ready);
339
+ }
340
+
328
341
  /** An entry's tags, as read when it was put on. */
329
342
  tagsOf(file: string): { title: string; artist: string; album: string } | undefined {
330
343
  return this.playlistInput?.tags.get(file);
@@ -503,6 +516,7 @@ export class Channel {
503
516
  ...resume.rotation,
504
517
  }) : null;
505
518
  this.playlistInput = playlistInput;
519
+ this.heard = 0;
506
520
  const through = this.outroOn ? null : playlistInput
507
521
  ? { format: "mpegts", open: async (signal: AbortSignal) => playlistInput.open(signal) }
508
522
  : this.options.through?.(this.info, from, input, audio) ?? null;
@@ -585,6 +599,7 @@ export class Channel {
585
599
  if (match) {
586
600
  const seconds = Number(match[1]) / 1e6;
587
601
  if (playlistInput) {
602
+ this.heard = seconds;
588
603
  const place = playlistInput.place(seconds);
589
604
  // A break (-1) belongs to no list; a track's index belongs to its own.
590
605
  if (place.at >= 0 && this.info.playlist !== place.list) this.info.playlist = place.list as string[];
@@ -1450,6 +1465,21 @@ export class Channels {
1450
1465
  return this.open.get(id)?.tagsOf(file);
1451
1466
  }
1452
1467
 
1468
+ /** Where a channel playing a list would pick up after what is on now; null when it is not one. */
1469
+ resumePoint(id: string): { file: string; upcoming: string[]; sinceBreak: number } | null {
1470
+ return this.open.get(id)?.resumePoint() ?? null;
1471
+ }
1472
+
1473
+ /** Whether a channel is up and has started sending. */
1474
+ flowing(id: string): boolean {
1475
+ return this.open.get(id)?.flowing ?? false;
1476
+ }
1477
+
1478
+ /** Who is attached to one channel: listeners, relays, packagers. */
1479
+ listenersOf(id: string): number {
1480
+ return this.open.get(id)?.listeners.size ?? 0;
1481
+ }
1482
+
1453
1483
  /** The next entry, now, on a channel playing a list of files. */
1454
1484
  skip(id: string): boolean {
1455
1485
  return this.open.get(id)?.skip() ?? false;
@@ -121,7 +121,7 @@ export function bandMarkdown(band: {
121
121
  const MEMBERS_SYSTEM = [
122
122
  "You cast the members of a fictional band (or the one person behind a solo act) for an AI record label.",
123
123
  "Everyone is invented: never a real person, never a lookalike of one. Give each a full name, their role, and a look described",
124
- "precisely enough that an illustrator could draw the same person every time: age range, face, skin tone, hair, build, signature outfit and accessories.",
124
+ "precisely enough that an illustrator could draw the same person every time. Start every look with their gender and age (\"woman, 24, ...\"), then face, skin tone, hair, build, signature outfit and accessories.",
125
125
  "Answer as JSON: {\"members\": [{\"name\": \"\", \"role\": \"\", \"look\": \"at most 300 characters\", \"voice\": \"how they sing or play, at most 150 characters\",",
126
126
  "\"personality\": \"at most 150 characters\", \"influences\": \"styles and eras, never named artists, at most 120 characters\", \"bio\": \"one or two sentences\"}]}.",
127
127
  ].join(" ");
@@ -171,7 +171,7 @@ export function castLine(members: Member[]): string {
171
171
 
172
172
  /** The portrait prompt for a member: the same person every time it is used as a reference. */
173
173
  export function portraitPrompt(member: Member, band: { name: string; genre: string }): string {
174
- return `Photographic portrait of ${member.look}. ${member.role} in the ${band.genre} band ${band.name}. Head and shoulders, three-quarter view, natural expression, soft studio light, plain dark background, sharp focus, 85mm lens. No text, no logos.`;
174
+ return `Photographic portrait of ${member.name}: ${member.look}. ${member.role} in the ${band.genre} band ${band.name}. Head and shoulders, three-quarter view, natural expression, soft studio light, plain dark background, sharp focus, 85mm lens. No text, no logos.`;
175
175
  }
176
176
 
177
177
  /** Writes the member pages and portraits that are missing; returns the members as the pages now say. */
package/src/library.ts CHANGED
@@ -39,6 +39,19 @@ export interface Config {
39
39
  limits?: Record<string, unknown>;
40
40
  /** Proxies whose X-Forwarded-For is believed for listener shares (`nixamp station shares trust ADDRESS`). */
41
41
  trustedProxies?: string[];
42
+ /** Seconds with nobody listening before a station sleeps; 0 never. 60 when unset. */
43
+ stationIdleSeconds?: number;
44
+ }
45
+
46
+ /** A station with nobody listening sleeps after this many seconds, unless config or NIXAMP_STATION_IDLE says otherwise. */
47
+ export const DEFAULT_STATION_IDLE_SECONDS = 60;
48
+
49
+ /** How long a station waits with nobody listening before it sleeps: env, then config, then 60; 0 is never. */
50
+ export function stationIdleSeconds(env: Record<string, string | undefined>, config: Config): number {
51
+ const raw = env["NIXAMP_STATION_IDLE"];
52
+ if (raw !== undefined && raw.trim() !== "" && Number.isFinite(Number(raw)) && Number(raw) >= 0) return Number(raw);
53
+ const set = config.stationIdleSeconds;
54
+ return typeof set === "number" && Number.isFinite(set) && set >= 0 ? set : DEFAULT_STATION_IDLE_SECONDS;
42
55
  }
43
56
 
44
57
  export function configPath(): string {
@@ -55,6 +68,7 @@ export function readConfig(): Config {
55
68
  ...(typeof record["publish"] === "boolean" ? { publish: record["publish"] } : {}),
56
69
  ...(typeof record["autoStations"] === "object" && record["autoStations"] !== null ? { autoStations: record["autoStations"] as Record<string, unknown> } : {}),
57
70
  ...(typeof record["limits"] === "object" && record["limits"] !== null ? { limits: record["limits"] as Record<string, unknown> } : {}),
71
+ ...(typeof record["stationIdleSeconds"] === "number" ? { stationIdleSeconds: record["stationIdleSeconds"] } : {}),
58
72
  ...(Array.isArray(record["trustedProxies"]) ? { trustedProxies: (record["trustedProxies"] as unknown[]).filter((one): one is string => typeof one === "string") } : {}),
59
73
  ...(Array.isArray(record["guideHosts"]) ? { guideHosts: (record["guideHosts"] as unknown[]).filter((one): one is string => typeof one === "string") } : {}),
60
74
  ...(typeof record["guideAds"] === "object" && record["guideAds"] !== null ? { guideAds: record["guideAds"] as Config["guideAds"] } : {}),