nixamp 0.55.2 → 0.57.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 (51) hide show
  1. package/dist/ai-label.d.ts +38 -3
  2. package/dist/ai-label.js +96 -5
  3. package/dist/channels.d.ts +20 -0
  4. package/dist/channels.js +24 -0
  5. package/dist/label-profiles.d.ts +60 -0
  6. package/dist/label-profiles.js +190 -0
  7. package/dist/label-routes.js +29 -2
  8. package/dist/library.d.ts +6 -0
  9. package/dist/library.js +11 -0
  10. package/dist/playlist-input.d.ts +32 -7
  11. package/dist/playlist-input.js +20 -2
  12. package/dist/server.js +9 -1
  13. package/dist/station-routes.d.ts +1 -0
  14. package/dist/station-routes.js +23 -5
  15. package/dist/station-runner.d.ts +48 -0
  16. package/dist/station-runner.js +208 -4
  17. package/dist/stations.d.ts +14 -0
  18. package/dist/stations.js +11 -0
  19. package/package.json +1 -1
  20. package/src/ai-label.ts +95 -8
  21. package/src/channels.ts +30 -0
  22. package/src/label-profiles.ts +212 -0
  23. package/src/label-routes.ts +30 -2
  24. package/src/library.ts +14 -0
  25. package/src/playlist-input.ts +46 -5
  26. package/src/server.ts +10 -1
  27. package/src/station-routes.ts +23 -6
  28. package/src/station-runner.ts +205 -4
  29. package/src/stations.ts +15 -0
  30. package/web/dist/assets/{ar-DDphLo2L.js → ar-d05d_7Df.js} +1 -1
  31. package/web/dist/assets/{cs-CMKLJTnw.js → cs-CclrNwa7.js} +1 -1
  32. package/web/dist/assets/{da-CibDEkHw.js → da-C30KTGl1.js} +1 -1
  33. package/web/dist/assets/{de-D1BL2QsJ.js → de-D2A2RQwi.js} +1 -1
  34. package/web/dist/assets/{es-Cj9qr9jo.js → es-BXFx0WZ5.js} +1 -1
  35. package/web/dist/assets/{fi-DqCO5i_7.js → fi-DPA3S8og.js} +1 -1
  36. package/web/dist/assets/{fr-DUk14AWf.js → fr-D_0wnr4h.js} +1 -1
  37. package/web/dist/assets/{hi-U_jzSO9-.js → hi-EfiCQnb9.js} +1 -1
  38. package/web/dist/assets/{hu-B28enhWa.js → hu-CK5rnxKO.js} +1 -1
  39. package/web/dist/assets/{id-DlGfGd_6.js → id-BgTV_4UK.js} +1 -1
  40. package/web/dist/assets/{it-D3HMQpf5.js → it-DGefapXn.js} +1 -1
  41. package/web/dist/assets/{main-D0eqtyhi.js → main-C-tWhTWo.js} +2 -2
  42. package/web/dist/assets/{nl-i1Y9R3xr.js → nl-Cyst29Bp.js} +1 -1
  43. package/web/dist/assets/{ru-DjRg1y2P.js → ru-D8G6Wynm.js} +1 -1
  44. package/web/dist/assets/{station-DxBlD6Yl.js → station-D6sd4DqP.js} +1 -1
  45. package/web/dist/assets/{sv-Dsj-93a2.js → sv-aYnDAFwz.js} +1 -1
  46. package/web/dist/assets/{uk-COWBdTZb.js → uk-BDtew7z3.js} +1 -1
  47. package/web/dist/assets/{vi-CgEMtDCA.js → vi-CRlDn2Xh.js} +1 -1
  48. package/web/dist/assets/{zh-CBa5mJ__.js → zh-BCAIjeQq.js} +1 -1
  49. package/web/dist/index.html +1 -1
  50. package/web/dist/station.html +1 -1
  51. package/web/dist/sw.js +20 -20
@@ -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.55.2",
3
+ "version": "0.57.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/ai-label.ts CHANGED
@@ -34,6 +34,7 @@ import { aiKey } from "./ai-keys.ts";
34
34
  import { composerFromEnv, OutOfCredit, type Composer } from "./ai-radio.ts";
35
35
  import { askJson, hasModel } from "./ai-text.ts";
36
36
  import { formatLrc, type SyncedLine } from "./lyrics.ts";
37
+ import { bandMarkdown, castLine, inventMembers, readMembers, writeMembers, type Member } from "./label-profiles.ts";
37
38
  import type { LibraryIndex, Probed } from "./library-index.ts";
38
39
  import type { StationRunner } from "./station-runner.ts";
39
40
  import { StationError, type StationStore } from "./stations.ts";
@@ -94,6 +95,8 @@ export interface LabelArtist {
94
95
  themes: string;
95
96
  enabled: boolean;
96
97
  albums: LabelAlbum[];
98
+ /** Its people, by slug: each has members/<slug>.md and .jpg in the artist's folder (label-profiles.ts). */
99
+ members?: string[];
97
100
  createdAt: number;
98
101
  lastAttemptAt: number;
99
102
  lastError: string;
@@ -426,7 +429,7 @@ const LYRICS_SYSTEM = [
426
429
  ].join(" ");
427
430
 
428
431
  export async function planAlbum(
429
- artist: Pick<LabelArtist, "name" | "genre" | "sound" | "voice" | "bio" | "themes" | "albums">,
432
+ artist: Pick<LabelArtist, "name" | "genre" | "sound" | "voice" | "bio" | "themes" | "albums"> & { cast?: string },
430
433
  songs: number,
431
434
  ask: typeof askJson = askJson,
432
435
  ): Promise<{ title: string; concept: string; songs: Array<{ title: string; style: string }>; model: string }> {
@@ -440,6 +443,7 @@ export async function planAlbum(
440
443
  `Voice: ${artist.voice}`,
441
444
  artist.bio ? `Who they are: ${artist.bio}` : "",
442
445
  artist.themes ? `What they sing about: ${artist.themes}` : "",
446
+ artist.cast ? `The band, as they are (write for these people): ${artist.cast}` : "",
443
447
  before.length ? `Albums already out (do not reuse their titles or song titles; take the story somewhere new): ${before.join(" | ")}` : "This is the artist's debut album.",
444
448
  `The album has exactly ${songs} songs.`,
445
449
  ].filter(Boolean).join("\n"),
@@ -481,7 +485,7 @@ export async function inventArtist(genre: string, taken: string[], ask: typeof a
481
485
  }
482
486
 
483
487
  export async function writeLyrics(
484
- artist: Pick<LabelArtist, "name" | "genre" | "voice" | "themes">,
488
+ artist: Pick<LabelArtist, "name" | "genre" | "voice" | "themes"> & { cast?: string },
485
489
  album: Pick<LabelAlbum, "title" | "concept">,
486
490
  song: Pick<LabelSong, "title" | "style" | "seconds">,
487
491
  ask: typeof askJson = askJson,
@@ -491,6 +495,7 @@ export async function writeLyrics(
491
495
  prompt: [
492
496
  `Artist: ${artist.name} (${artist.genre}); voice: ${artist.voice}`,
493
497
  artist.themes ? `What they sing about: ${artist.themes}` : "",
498
+ artist.cast ? `Who sings and plays it (their voice and personality shape the words): ${artist.cast}` : "",
494
499
  `Album: "${album.title}"${album.concept ? `: ${album.concept}` : ""}`,
495
500
  `Song: "${song.title}": ${song.style}`,
496
501
  `The song lasts about ${song.seconds} seconds: keep the words under ${Math.max(600, Math.round(song.seconds * 10))} characters.`,
@@ -583,7 +588,7 @@ const STORYBOARD_SYSTEM = [
583
588
 
584
589
  /** Image prompts for a song's video, one a scene, from its words and mood. */
585
590
  export async function writeStoryboard(
586
- artist: Pick<LabelArtist, "name" | "genre" | "sound">,
591
+ artist: Pick<LabelArtist, "name" | "genre" | "sound"> & { cast?: string },
587
592
  album: Pick<LabelAlbum, "title" | "concept">,
588
593
  song: Pick<LabelSong, "title" | "style" | "lyrics">,
589
594
  scenes: number,
@@ -593,6 +598,7 @@ export async function writeStoryboard(
593
598
  system: STORYBOARD_SYSTEM,
594
599
  prompt: [
595
600
  `Song: "${song.title}" by ${artist.name} (${artist.genre}; ${artist.sound}), from "${album.title}"${album.concept ? `: ${album.concept}` : ""}`,
601
+ artist.cast ? `The band (these are the only performers; whenever one appears, name them and repeat their full look in that prompt, the image model remembers nothing): ${artist.cast}` : "",
596
602
  `Mood and arrangement: ${song.style}`,
597
603
  song.lyrics ? `Lyrics:\n${song.lyrics.slice(0, 1800)}` : "",
598
604
  `Exactly ${scenes} scenes.`,
@@ -746,6 +752,7 @@ export class AiLabel {
746
752
  private settings: LabelSettings = { ...DEFAULTS, pausedReason: "" };
747
753
  private usage: Record<string, number> = {};
748
754
  private running = false;
755
+ private profiling = false;
749
756
  /** Songs being made now, by `<album>:<n>`. */
750
757
  private claims = new Map<string, { label: string; seconds: number }>();
751
758
  /** Artists whose next album is being planned now. */
@@ -976,7 +983,8 @@ export class AiLabel {
976
983
  if (!this.canAsk()) throw new StationError("no_writer", "no language model to write the album: set GEMINI_API_KEY, OPENAI_API_KEY (or NIXAMP_OPENAI_URL) or ANTHROPIC_API_KEY", 409);
977
984
  const pending = artist.albums.find((one) => !one.doneAt);
978
985
  if (pending) throw new StationError("album_in_progress", `"${pending.title}" is still being made`, 409);
979
- const plan = await planAlbum(artist, this.settings.songsPerAlbum, this.deps.ask ?? askJson);
986
+ await this.ensureProfile(artist).catch(() => undefined);
987
+ const plan = await planAlbum({ ...artist, cast: this.castOf(artist) }, this.settings.songsPerAlbum, this.deps.ask ?? askJson);
980
988
  const year = new Date(this.now()).getUTCFullYear();
981
989
  let title = plan.title;
982
990
  if (artist.albums.some((one) => one.title.toLowerCase() === title.toLowerCase())) title = `${title} II`;
@@ -1005,7 +1013,8 @@ export class AiLabel {
1005
1013
  this.timer = setInterval(() => { void this.tick(); void this.videos(); }, everyMs);
1006
1014
  this.timer.unref?.();
1007
1015
  void this.tick();
1008
- void this.videos();
1016
+ // Profiles first (quick), so videos made after cast the right people.
1017
+ void this.profiles().finally(() => void this.videos());
1009
1018
  }
1010
1019
 
1011
1020
  /**
@@ -1132,7 +1141,7 @@ export class AiLabel {
1132
1141
  if (this.canAsk()) {
1133
1142
  try {
1134
1143
  const count = Math.max(4, Math.min(16, Math.round(seconds / 9)));
1135
- const prompts = await writeStoryboard(artist, album, song, count, this.deps.ask ?? askJson);
1144
+ const prompts = await writeStoryboard({ ...artist, cast: this.castOf(artist) }, album, song, count, this.deps.ask ?? askJson);
1136
1145
  mkdirSync(scenes, { recursive: true });
1137
1146
  const draw = this.deps.image ?? ((prompt: string) => workersAiCover(prompt));
1138
1147
  // A few at a time: the image model is quick, the machine is shared.
@@ -1334,7 +1343,7 @@ export class AiLabel {
1334
1343
  try {
1335
1344
  let writer = song.made || album.writer;
1336
1345
  if (!song.lyrics) {
1337
- const written = await writeLyrics(artist, album, song, this.deps.ask ?? askJson);
1346
+ const written = await writeLyrics({ ...artist, cast: this.castOf(artist) }, album, song, this.deps.ask ?? askJson);
1338
1347
  song.lyrics = written.lyrics;
1339
1348
  writer = written.model;
1340
1349
  song.made = writer;
@@ -1374,6 +1383,7 @@ export class AiLabel {
1374
1383
  if (album.songs.every((one) => one.file)) {
1375
1384
  album.doneAt = this.now();
1376
1385
  this.log(`${artist.name} released "${album.title}"`);
1386
+ void this.ensureProfile(artist).catch(() => undefined);
1377
1387
  }
1378
1388
  this.save();
1379
1389
  this.writeAlbumJson(artist, album);
@@ -1399,7 +1409,8 @@ export class AiLabel {
1399
1409
  }
1400
1410
 
1401
1411
  private async drawCover(artist: LabelArtist, album: LabelAlbum): Promise<void> {
1402
- const prompt = `Album cover art for "${album.title}", a ${artist.genre} album by ${artist.name}. ${album.concept} Style: ${artist.sound}. Striking, original, square composition. No text, no letters, no logos, no watermark.`;
1412
+ const cast = this.castOf(artist);
1413
+ const prompt = `Album cover art for "${album.title}", a ${artist.genre} album by ${artist.name}. ${album.concept} Style: ${artist.sound}.${cast ? ` If the band appears, they look exactly like this: ${cast}.` : ""} Striking, original, square composition. No text, no letters, no logos, no watermark.`;
1403
1414
  try {
1404
1415
  const picture = await (this.deps.cover ?? ((text) => workersAiCover(text)))(prompt);
1405
1416
  if (picture) {
@@ -1485,6 +1496,7 @@ export class AiLabel {
1485
1496
  .filter((one) => one.genre === genre)
1486
1497
  .map((one) => ({
1487
1498
  key: one.key, name: one.name, genre: one.genre, bio: one.bio,
1499
+ members: this.cast(one).map((member) => ({ slug: member.slug, name: member.name, role: member.role, bio: member.bio })),
1488
1500
  albums: one.albums
1489
1501
  .filter((album) => album.songs.some((song) => song.file))
1490
1502
  .map((album) => ({
@@ -1520,6 +1532,67 @@ export class AiLabel {
1520
1532
  return null;
1521
1533
  }
1522
1534
 
1535
+ /** The artist's folder: <root>/<genre>/<artist>/, where its albums and profile pages live. */
1536
+ folderOf(artist: Pick<LabelArtist, "genre" | "name">): string {
1537
+ return join(this.root, genreSlug(artist.genre), fileName(artist.name));
1538
+ }
1539
+
1540
+ /** The artist's people as their pages say now (hand edits win). */
1541
+ cast(artist: LabelArtist): Member[] {
1542
+ return readMembers(this.folderOf(artist), artist.members ?? []);
1543
+ }
1544
+
1545
+ /** The people in one line, for a prompt; "" before they are cast. */
1546
+ castOf(artist: LabelArtist): string {
1547
+ return castLine(this.cast(artist));
1548
+ }
1549
+
1550
+ /**
1551
+ * The artist's profile: its members invented once (and their portraits
1552
+ * drawn), and artist.md written again with what it has released.
1553
+ */
1554
+ async ensureProfile(artist: LabelArtist): Promise<void> {
1555
+ const folder = this.folderOf(artist);
1556
+ mkdirSync(folder, { recursive: true });
1557
+ const band = { name: artist.name, genre: artist.genre, holder: this.settings.holder };
1558
+ const draw = this.deps.image === undefined ? (prompt: string) => workersAiCover(prompt) : this.deps.image;
1559
+ if (!artist.members?.length && this.canAsk()) {
1560
+ const invented = await inventMembers(artist, this.deps.ask ?? askJson);
1561
+ const written = await writeMembers(folder, invented, band, draw);
1562
+ artist.members = written.map((one) => one.slug);
1563
+ this.save();
1564
+ this.log(`${artist.name}: ${written.map((one) => `${one.name} (${one.role})`).join(", ")}`);
1565
+ } else if (artist.members?.length) {
1566
+ // Portraits that are missing (a page added by hand, a failed drawing) are drawn now.
1567
+ await writeMembers(folder, this.cast(artist), band, draw);
1568
+ }
1569
+ writeFileSync(join(folder, "artist.md"), bandMarkdown({
1570
+ ...artist, holder: this.settings.holder, members: this.cast(artist),
1571
+ albums: artist.albums.filter((one) => one.doneAt || one.songs.some((song) => song.file)).map((one) => ({ year: one.year, title: one.title })),
1572
+ }));
1573
+ }
1574
+
1575
+ /** Every artist's profile, made or brought up to date; one at a time. */
1576
+ async profiles(): Promise<void> {
1577
+ if (this.profiling) return;
1578
+ this.profiling = true;
1579
+ try {
1580
+ for (const artist of this.list()) await this.ensureProfile(artist).catch((error: unknown) => this.log(`no profile for ${artist.name}: ${(error as Error).message}`));
1581
+ } finally {
1582
+ this.profiling = false;
1583
+ }
1584
+ }
1585
+
1586
+ /** A profile file anybody may read: artist.md, members/<slug>.md or members/<slug>.jpg. */
1587
+ profileFile(artistKey: string, what: string): { path: string; type: string } | null {
1588
+ const artist = this.artists.get(artistKey);
1589
+ if (!artist) return null;
1590
+ if (what === "artist.md") return { path: join(this.folderOf(artist), "artist.md"), type: "text/markdown; charset=utf-8" };
1591
+ const match = /^members\/([a-z0-9-]{1,40})\.(md|jpg)$/.exec(what);
1592
+ if (!match || !(artist.members ?? []).includes(match[1]!)) return null;
1593
+ return { path: join(this.folderOf(artist), "members", `${match[1]}.${match[2]}`), type: match[2] === "md" ? "text/markdown; charset=utf-8" : "image/jpeg" };
1594
+ }
1595
+
1523
1596
  /** The song's MP3 when `file` is one of the label's music videos (it holds the tags, cover and words); else `file`. */
1524
1597
  audioFor(file: string): string {
1525
1598
  if (!file.endsWith(".mp4")) return file;
@@ -1566,6 +1639,18 @@ export class AiLabel {
1566
1639
  }, null, 2)}\n`) });
1567
1640
  }
1568
1641
  if (entries.length === 0) return null;
1642
+ // Everything by an artist comes with who they are: the band's page, each member's page and portrait.
1643
+ if (scope.kind === "artist") {
1644
+ const folder = this.folderOf(artist);
1645
+ const exists = (path: string): boolean => { try { return statSync(path).isFile(); } catch { return false; } };
1646
+ if (exists(join(folder, "artist.md"))) entries.push({ name: `${top}/artist.md`, path: join(folder, "artist.md") });
1647
+ for (const slug of artist.members ?? []) {
1648
+ for (const ext of ["md", "jpg"]) {
1649
+ const path = join(folder, "members", `${slug}.${ext}`);
1650
+ if (exists(path)) entries.push({ name: `${top}/members/${slug}.${ext}`, path });
1651
+ }
1652
+ }
1653
+ }
1569
1654
  const what = scope.kind === "artist" ? "Discography" : scope.kind === "album" ? albums[0]!.title : this.songFile(scope.artist, scope.album, scope.n) ? albums[0]!.songs.find((one) => one.n === scope.n)!.title : "Song";
1570
1655
  return { name: `${fileName(artist.name)} - ${fileName(what)}.zip`, entries };
1571
1656
  }
@@ -1582,5 +1667,7 @@ export interface PublicArtist {
1582
1667
  name: string;
1583
1668
  genre: string;
1584
1669
  bio: string;
1670
+ /** The people (profile pages at /api/v1/label/<artist>/members/<slug>.md, portraits .jpg). */
1671
+ members: Array<{ slug: string; name: string; role: string; bio: string }>;
1585
1672
  albums: Array<{ key: string; title: string; year: number; concept: string; cover: boolean; complete: boolean; songs: Array<{ n: number; title: string; seconds: number; lyrics: string }> }>;
1586
1673
  }
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;