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.
- package/dist/ai-label.d.ts +38 -3
- package/dist/ai-label.js +96 -5
- package/dist/channels.d.ts +20 -0
- package/dist/channels.js +24 -0
- package/dist/label-profiles.d.ts +60 -0
- package/dist/label-profiles.js +190 -0
- package/dist/label-routes.js +29 -2
- package/dist/library.d.ts +6 -0
- package/dist/library.js +11 -0
- package/dist/playlist-input.d.ts +32 -7
- package/dist/playlist-input.js +20 -2
- package/dist/server.js +9 -1
- package/dist/station-routes.d.ts +1 -0
- package/dist/station-routes.js +23 -5
- package/dist/station-runner.d.ts +48 -0
- package/dist/station-runner.js +208 -4
- package/dist/stations.d.ts +14 -0
- package/dist/stations.js +11 -0
- package/package.json +1 -1
- package/src/ai-label.ts +95 -8
- package/src/channels.ts +30 -0
- package/src/label-profiles.ts +212 -0
- package/src/label-routes.ts +30 -2
- package/src/library.ts +14 -0
- package/src/playlist-input.ts +46 -5
- package/src/server.ts +10 -1
- package/src/station-routes.ts +23 -6
- package/src/station-runner.ts +205 -4
- package/src/stations.ts +15 -0
- package/web/dist/assets/{ar-DDphLo2L.js → ar-d05d_7Df.js} +1 -1
- package/web/dist/assets/{cs-CMKLJTnw.js → cs-CclrNwa7.js} +1 -1
- package/web/dist/assets/{da-CibDEkHw.js → da-C30KTGl1.js} +1 -1
- package/web/dist/assets/{de-D1BL2QsJ.js → de-D2A2RQwi.js} +1 -1
- package/web/dist/assets/{es-Cj9qr9jo.js → es-BXFx0WZ5.js} +1 -1
- package/web/dist/assets/{fi-DqCO5i_7.js → fi-DPA3S8og.js} +1 -1
- package/web/dist/assets/{fr-DUk14AWf.js → fr-D_0wnr4h.js} +1 -1
- package/web/dist/assets/{hi-U_jzSO9-.js → hi-EfiCQnb9.js} +1 -1
- package/web/dist/assets/{hu-B28enhWa.js → hu-CK5rnxKO.js} +1 -1
- package/web/dist/assets/{id-DlGfGd_6.js → id-BgTV_4UK.js} +1 -1
- package/web/dist/assets/{it-D3HMQpf5.js → it-DGefapXn.js} +1 -1
- package/web/dist/assets/{main-D0eqtyhi.js → main-C-tWhTWo.js} +2 -2
- package/web/dist/assets/{nl-i1Y9R3xr.js → nl-Cyst29Bp.js} +1 -1
- package/web/dist/assets/{ru-DjRg1y2P.js → ru-D8G6Wynm.js} +1 -1
- package/web/dist/assets/{station-DxBlD6Yl.js → station-D6sd4DqP.js} +1 -1
- package/web/dist/assets/{sv-Dsj-93a2.js → sv-aYnDAFwz.js} +1 -1
- package/web/dist/assets/{uk-COWBdTZb.js → uk-BDtew7z3.js} +1 -1
- package/web/dist/assets/{vi-CgEMtDCA.js → vi-CRlDn2Xh.js} +1 -1
- package/web/dist/assets/{zh-CBa5mJ__.js → zh-BCAIjeQq.js} +1 -1
- package/web/dist/index.html +1 -1
- package/web/dist/station.html +1 -1
- package/web/dist/sw.js +20 -20
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who is in each AI label band: an OpenProfile page per member and one for
|
|
3
|
+
* the band, so the same people sing, appear on covers and in videos every
|
|
4
|
+
* time instead of whoever an image model draws next.
|
|
5
|
+
*
|
|
6
|
+
* <artist folder>/artist.md the band: genre, sound, members, discography
|
|
7
|
+
* <artist folder>/members/<slug>.md a member: role, look, voice, personality...
|
|
8
|
+
* <artist folder>/members/<slug>.jpg their reference portrait
|
|
9
|
+
*
|
|
10
|
+
* The pages are the source of truth once written: a person may edit a
|
|
11
|
+
* member's look or voice by hand, and what is generated next reads the page
|
|
12
|
+
* back (readMember). Members are invented once, by a language model, as
|
|
13
|
+
* fictional people; the portrait is drawn from the look and kept.
|
|
14
|
+
*/
|
|
15
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import type { askJson } from "./ai-text.ts";
|
|
18
|
+
|
|
19
|
+
export interface Member {
|
|
20
|
+
slug: string;
|
|
21
|
+
name: string;
|
|
22
|
+
/** What they do in the band: "lead vocals", "lead guitar", "drums"... */
|
|
23
|
+
role: string;
|
|
24
|
+
/** How they look, in enough detail to draw the same person again: age, face, hair, build, signature clothes. */
|
|
25
|
+
look: string;
|
|
26
|
+
/** How they sound, for a singer; how they play, for the rest. */
|
|
27
|
+
voice: string;
|
|
28
|
+
personality: string;
|
|
29
|
+
influences: string;
|
|
30
|
+
bio: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function memberSlug(name: string): string {
|
|
34
|
+
return name.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "member";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function line(text: string): string {
|
|
38
|
+
return text.replace(/[\r\n]+/g, " ").trim();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A member's OpenProfile page. */
|
|
42
|
+
export function memberMarkdown(member: Member, band: { name: string; holder: string }): string {
|
|
43
|
+
return [
|
|
44
|
+
`# ${member.name}`,
|
|
45
|
+
"",
|
|
46
|
+
"- **Kind**: fictional musician, made with AI",
|
|
47
|
+
`- **Band**: [${band.name}](../artist.md)`,
|
|
48
|
+
`- **Role**: ${line(member.role)}`,
|
|
49
|
+
`- **Avatar**: [portrait](${member.slug}.jpg)`,
|
|
50
|
+
`- **Parent**: ${band.holder}`,
|
|
51
|
+
"",
|
|
52
|
+
line(member.bio),
|
|
53
|
+
"",
|
|
54
|
+
"## Look",
|
|
55
|
+
"",
|
|
56
|
+
line(member.look),
|
|
57
|
+
"",
|
|
58
|
+
"## Voice",
|
|
59
|
+
"",
|
|
60
|
+
line(member.voice),
|
|
61
|
+
"",
|
|
62
|
+
"## Personality",
|
|
63
|
+
"",
|
|
64
|
+
line(member.personality),
|
|
65
|
+
"",
|
|
66
|
+
"## Influences",
|
|
67
|
+
"",
|
|
68
|
+
line(member.influences),
|
|
69
|
+
"",
|
|
70
|
+
].join("\n");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A member's page read back, so hand edits win; null when it is not one of ours. */
|
|
74
|
+
export function readMember(text: string, slug: string): Member | null {
|
|
75
|
+
const name = /^#\s+(.+)$/m.exec(text)?.[1]?.trim() ?? "";
|
|
76
|
+
if (!name) return null;
|
|
77
|
+
const field = (label: string): string => new RegExp(`^- \\*\\*${label}\\*\\*:\\s*(.+)$`, "m").exec(text)?.[1]?.trim() ?? "";
|
|
78
|
+
const section = (heading: string): string => {
|
|
79
|
+
const match = new RegExp(`^##\\s+${heading}\\s*$([\\s\\S]*?)(?=^##\\s|$(?![\\s\\S]))`, "m").exec(text);
|
|
80
|
+
return (match?.[1] ?? "").trim().replace(/\s+/g, " ");
|
|
81
|
+
};
|
|
82
|
+
// The bio is the prose between the fields and the first section.
|
|
83
|
+
const bio = (/^- \*\*Parent\*\*:.*$\n+([\s\S]*?)(?=^##\s)/m.exec(text)?.[1] ?? "").trim().replace(/\s+/g, " ");
|
|
84
|
+
return { slug, name, role: field("Role"), look: section("Look"), voice: section("Voice"), personality: section("Personality"), influences: section("Influences"), bio };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The band's OpenProfile page. */
|
|
88
|
+
export function bandMarkdown(band: {
|
|
89
|
+
name: string; genre: string; sound: string; voice: string; bio: string; themes: string; holder: string;
|
|
90
|
+
members: Member[]; albums: Array<{ year: number; title: string }>;
|
|
91
|
+
}): string {
|
|
92
|
+
return [
|
|
93
|
+
`# ${band.name}`,
|
|
94
|
+
"",
|
|
95
|
+
"- **Kind**: band, fictional, made with AI",
|
|
96
|
+
`- **Genre**: ${band.genre}`,
|
|
97
|
+
`- **Label**: ${band.holder}`,
|
|
98
|
+
`- **Members**: ${band.members.map((one) => `[${one.name}](members/${one.slug}.md) (${one.role})`).join(", ")}`,
|
|
99
|
+
"",
|
|
100
|
+
line(band.bio),
|
|
101
|
+
"",
|
|
102
|
+
"## Sound",
|
|
103
|
+
"",
|
|
104
|
+
line(band.sound),
|
|
105
|
+
"",
|
|
106
|
+
"## Lead voice",
|
|
107
|
+
"",
|
|
108
|
+
line(band.voice),
|
|
109
|
+
"",
|
|
110
|
+
"## Themes",
|
|
111
|
+
"",
|
|
112
|
+
line(band.themes),
|
|
113
|
+
"",
|
|
114
|
+
"## Discography",
|
|
115
|
+
"",
|
|
116
|
+
...(band.albums.length ? band.albums.map((one) => `- ${one.year} · ${one.title}`) : ["- (first album on its way)"]),
|
|
117
|
+
"",
|
|
118
|
+
].join("\n");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const MEMBERS_SYSTEM = [
|
|
122
|
+
"You cast the members of a fictional band (or the one person behind a solo act) for an AI record label.",
|
|
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.",
|
|
125
|
+
"Answer as JSON: {\"members\": [{\"name\": \"\", \"role\": \"\", \"look\": \"at most 300 characters\", \"voice\": \"how they sing or play, at most 150 characters\",",
|
|
126
|
+
"\"personality\": \"at most 150 characters\", \"influences\": \"styles and eras, never named artists, at most 120 characters\", \"bio\": \"one or two sentences\"}]}.",
|
|
127
|
+
].join(" ");
|
|
128
|
+
|
|
129
|
+
/** The band's people, invented once: one for a solo act, three to five for a band. */
|
|
130
|
+
export async function inventMembers(
|
|
131
|
+
band: { name: string; genre: string; sound: string; voice: string; bio: string },
|
|
132
|
+
ask: typeof askJson,
|
|
133
|
+
): Promise<Member[]> {
|
|
134
|
+
const answer = await ask({
|
|
135
|
+
system: MEMBERS_SYSTEM,
|
|
136
|
+
prompt: [
|
|
137
|
+
`Act: ${band.name} (${band.genre})`,
|
|
138
|
+
`Sound: ${band.sound}`,
|
|
139
|
+
`Lead voice: ${band.voice}`,
|
|
140
|
+
band.bio ? `Who they are: ${band.bio}` : "",
|
|
141
|
+
"If the name reads as one person's, cast that one person as the solo artist (role: vocals and the instrument that fits); otherwise cast the band, the lead singer first, matching the lead voice.",
|
|
142
|
+
].filter(Boolean).join("\n"),
|
|
143
|
+
maxTokens: 2000,
|
|
144
|
+
timeoutMs: 90_000,
|
|
145
|
+
});
|
|
146
|
+
const list = Array.isArray(answer.value["members"]) ? answer.value["members"] as Array<Record<string, unknown>> : [];
|
|
147
|
+
const seen = new Set<string>();
|
|
148
|
+
const members = list
|
|
149
|
+
.map((one) => {
|
|
150
|
+
const name = line(String(one?.["name"] ?? "")).slice(0, 60);
|
|
151
|
+
return {
|
|
152
|
+
slug: memberSlug(name), name,
|
|
153
|
+
role: line(String(one?.["role"] ?? "")).slice(0, 80),
|
|
154
|
+
look: line(String(one?.["look"] ?? "")).slice(0, 500),
|
|
155
|
+
voice: line(String(one?.["voice"] ?? "")).slice(0, 300),
|
|
156
|
+
personality: line(String(one?.["personality"] ?? "")).slice(0, 300),
|
|
157
|
+
influences: line(String(one?.["influences"] ?? "")).slice(0, 200),
|
|
158
|
+
bio: line(String(one?.["bio"] ?? "")).slice(0, 500),
|
|
159
|
+
};
|
|
160
|
+
})
|
|
161
|
+
.filter((one) => one.name && one.look.length > 20 && !seen.has(one.slug) && seen.add(one.slug))
|
|
162
|
+
.slice(0, 6);
|
|
163
|
+
if (members.length === 0) throw new Error("the model cast nobody");
|
|
164
|
+
return members;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** How the band looks on stage, for a cover or a scene: every member by name, role and look. */
|
|
168
|
+
export function castLine(members: Member[]): string {
|
|
169
|
+
return members.map((one) => `${one.name} (${one.role}): ${one.look}`).join("; ");
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The portrait prompt for a member: the same person every time it is used as a reference. */
|
|
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.`;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Writes the member pages and portraits that are missing; returns the members as the pages now say. */
|
|
178
|
+
export async function writeMembers(folder: string, members: Member[], band: { name: string; genre: string; holder: string }, draw: ((prompt: string) => Promise<Buffer | null>) | null): Promise<Member[]> {
|
|
179
|
+
const dir = join(folder, "members");
|
|
180
|
+
mkdirSync(dir, { recursive: true });
|
|
181
|
+
const out: Member[] = [];
|
|
182
|
+
for (const member of members) {
|
|
183
|
+
const page = join(dir, `${member.slug}.md`);
|
|
184
|
+
let current = member;
|
|
185
|
+
try {
|
|
186
|
+
current = readMember(readFileSync(page, "utf8"), member.slug) ?? member;
|
|
187
|
+
} catch {
|
|
188
|
+
writeFileSync(page, memberMarkdown(member, band));
|
|
189
|
+
}
|
|
190
|
+
const portrait = join(dir, `${member.slug}.jpg`);
|
|
191
|
+
let drawn = true;
|
|
192
|
+
try { readFileSync(portrait); } catch { drawn = false; }
|
|
193
|
+
if (!drawn && draw) {
|
|
194
|
+
const picture = await draw(portraitPrompt(current, band)).catch(() => null);
|
|
195
|
+
if (picture) writeFileSync(portrait, picture);
|
|
196
|
+
}
|
|
197
|
+
out.push(current);
|
|
198
|
+
}
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The members as their pages say now (hand edits included), in the order given. */
|
|
203
|
+
export function readMembers(folder: string, slugs: string[]): Member[] {
|
|
204
|
+
return slugs.flatMap((slug) => {
|
|
205
|
+
try {
|
|
206
|
+
const member = readMember(readFileSync(join(folder, "members", `${slug}.md`), "utf8"), slug);
|
|
207
|
+
return member ? [member] : [];
|
|
208
|
+
} catch {
|
|
209
|
+
return [];
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
}
|
package/src/label-routes.ts
CHANGED
|
@@ -20,9 +20,12 @@ import { adCsp, withPageAd, type GuideAds } from "./station-guide.ts";
|
|
|
20
20
|
// MP3 or a zip needs a grant from nixamp.com's store (music-store.ts).
|
|
21
21
|
const FILE = /^\/api\/v1\/label\/([a-f0-9]{10})\/([a-f0-9]{8})\/(\d{1,3}\.(?:txt|mp3)|cover\.jpg)$/;
|
|
22
22
|
|
|
23
|
+
/** An artist's OpenProfile pages and portraits: artist.md, members/<slug>.md, members/<slug>.jpg. */
|
|
24
|
+
const PROFILE = /^\/api\/v1\/label\/([a-f0-9]{10})\/(artist\.md|members\/[a-z0-9-]{1,40}\.(?:md|jpg))$/;
|
|
25
|
+
|
|
23
26
|
/** Whether this path is the label's public face (an MP3 or the zip still asks for its grant). */
|
|
24
27
|
export function isPublicLabelPath(path: string): boolean {
|
|
25
|
-
return path === "/label" || path === "/api/v1/label" || path === "/api/v1/label/zip" || FILE.test(path);
|
|
28
|
+
return path === "/label" || path === "/api/v1/label" || path === "/api/v1/label/zip" || FILE.test(path) || PROFILE.test(path);
|
|
26
29
|
}
|
|
27
30
|
|
|
28
31
|
/** nixamp.com's page that sells this: a song, an album or everything by the artist. */
|
|
@@ -146,6 +149,16 @@ export async function handleLabelRoutes(
|
|
|
146
149
|
response.end();
|
|
147
150
|
return true;
|
|
148
151
|
}
|
|
152
|
+
const profile = PROFILE.exec(path);
|
|
153
|
+
if (profile) {
|
|
154
|
+
const found = label.profileFile(profile[1]!, profile[2]!);
|
|
155
|
+
if (!found) {
|
|
156
|
+
ctx.json(response, 404, { error: "no such profile", code: "not_found" });
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
sendFile(request, response, found.path, found.type, "");
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
149
162
|
const [, artist, album, what] = FILE.exec(path)!;
|
|
150
163
|
if (what!.endsWith(".mp3")) {
|
|
151
164
|
const scope = ctx.grants && grant ? await ctx.grants.check(grant) : null;
|
|
@@ -270,6 +283,11 @@ audio{width:100%;max-width:360px;height:36px}
|
|
|
270
283
|
details{margin-top:4px}summary{cursor:pointer;color:var(--muted);font-size:.9rem}
|
|
271
284
|
pre.lyrics{white-space:pre-wrap;font:inherit;font-size:.95rem;margin:8px 0 0;padding:12px;border-radius:8px;background:var(--bg)}
|
|
272
285
|
.dl{font-size:.85rem}.soon{color:var(--muted);font-size:.85rem}
|
|
286
|
+
ul.members{list-style:none;margin:12px 0 4px;padding:0;display:flex;flex-wrap:wrap;gap:10px}
|
|
287
|
+
ul.members a{display:flex;gap:8px;align-items:center;color:var(--fg);text-decoration:none;border:1px solid var(--line);border-radius:999px;padding:4px 12px 4px 4px}
|
|
288
|
+
ul.members a:hover,ul.members a:focus-visible{border-color:var(--accent)}
|
|
289
|
+
ul.members img{width:40px;height:40px;border-radius:50%;object-fit:cover;background:var(--line)}
|
|
290
|
+
ul.members span{display:grid;line-height:1.2}ul.members .role{color:var(--muted);font-size:.8rem}
|
|
273
291
|
a.buy{display:inline-block;font-weight:700;text-decoration:none;border:1px solid var(--accent);border-radius:999px;padding:2px 10px}
|
|
274
292
|
footer{margin-top:48px;color:var(--muted);font-size:.85rem}footer a{color:inherit}
|
|
275
293
|
`;
|
|
@@ -285,6 +303,16 @@ export const LABEL_CSP = [
|
|
|
285
303
|
|
|
286
304
|
type Shop = { site: string; server: string } | undefined;
|
|
287
305
|
|
|
306
|
+
/** The band: each member's portrait, name and role, linking to their OpenProfile page. */
|
|
307
|
+
function renderMembers(artist: PublicArtist): string {
|
|
308
|
+
if (!artist.members?.length) return "";
|
|
309
|
+
const base = `/api/v1/label/${artist.key}`;
|
|
310
|
+
return `<ul class="members">${artist.members.map((member) => `<li><a href="${base}/members/${escape(member.slug)}.md" title="${escape(member.bio)}">`
|
|
311
|
+
+ `<img src="${base}/members/${escape(member.slug)}.jpg" alt="" width="56" height="56" loading="lazy">`
|
|
312
|
+
+ `<span><strong>${escape(member.name)}</strong><span class="role">${escape(member.role)}</span></span></a></li>`).join("")}</ul>`
|
|
313
|
+
+ `<p class="dl"><a href="${base}/artist.md">${escape(artist.name)}'s profile</a></p>`;
|
|
314
|
+
}
|
|
315
|
+
|
|
288
316
|
function price(cents: number): string {
|
|
289
317
|
return cents < 100 ? `${cents}¢` : `$${(cents / 100).toFixed(cents % 100 ? 2 : 0)}`;
|
|
290
318
|
}
|
|
@@ -313,7 +341,7 @@ export function renderLabel(view: ReturnType<AiLabel["publicView"]>, shop?: Shop
|
|
|
313
341
|
const nav = view.genres.length > 1 ? `<nav class="genres" aria-label="Genres">${view.genres.map((one) => `<a href="#${escape(one.genre.toLowerCase().replace(/[^a-z0-9]+/g, "-"))}">${escape(one.genre)}</a>`).join("")}</nav>` : "";
|
|
314
342
|
const sections = view.genres.map((genre) => `<section class="genre" id="${escape(genre.genre.toLowerCase().replace(/[^a-z0-9]+/g, "-"))}" aria-labelledby="g-${escape(genre.genre.toLowerCase().replace(/[^a-z0-9]+/g, "-"))}">`
|
|
315
343
|
+ `<h2 id="g-${escape(genre.genre.toLowerCase().replace(/[^a-z0-9]+/g, "-"))}">${escape(genre.genre)}${genre.station ? ` <a href="/watch/${escape(genre.station)}">Listen live, free →</a>` : ""}</h2>`
|
|
316
|
-
+ genre.artists.map((artist) => `<article class="artist"><h3>${escape(artist.name)}</h3>${artist.bio ? `<p class="bio">${escape(artist.bio)}</p>` : ""}`
|
|
344
|
+
+ genre.artists.map((artist) => `<article class="artist"><h3>${escape(artist.name)}</h3>${artist.bio ? `<p class="bio">${escape(artist.bio)}</p>` : ""}${renderMembers(artist)}`
|
|
317
345
|
+ `${shop ? `<p>${buy(shop, "artist", artist.key, "", 0, "everything by them")}</p>` : ""}`
|
|
318
346
|
+ `${artist.albums.map((album) => renderAlbum(artist, album, shop)).join("")}</article>`).join("")
|
|
319
347
|
+ `</section>`).join("");
|
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"] } : {}),
|
package/src/playlist-input.ts
CHANGED
|
@@ -39,7 +39,16 @@ export interface PlaylistInput {
|
|
|
39
39
|
* `next` answers a file to play (an advert, an ident) or null for no break
|
|
40
40
|
* this time. The break is outside the rotation and the station's history.
|
|
41
41
|
*/
|
|
42
|
-
breaks?: {
|
|
42
|
+
breaks?: {
|
|
43
|
+
everySeconds: number | (() => number);
|
|
44
|
+
next: () => Promise<string | null>;
|
|
45
|
+
/**
|
|
46
|
+
* Seconds of airtime since the last break when this stream opens, asked
|
|
47
|
+
* once per open: a station that slept with nobody listening carries its
|
|
48
|
+
* clock across, so breaks come every so often of time on the air.
|
|
49
|
+
*/
|
|
50
|
+
sinceBreak?: () => number;
|
|
51
|
+
};
|
|
43
52
|
/** Told when an entry is passed over because it would not play. */
|
|
44
53
|
onFailure?: (event: { at: number; file: string; reason: string }) => void;
|
|
45
54
|
}
|
|
@@ -51,12 +60,26 @@ export interface PlaylistInput {
|
|
|
51
60
|
*/
|
|
52
61
|
export const MAX_FAILURES_IN_A_ROW = 5;
|
|
53
62
|
|
|
63
|
+
/** An entry that started: where it sits in the stream and in its pass. */
|
|
64
|
+
interface Entry {
|
|
65
|
+
at: number;
|
|
66
|
+
file: string;
|
|
67
|
+
start: number;
|
|
68
|
+
position: number;
|
|
69
|
+
list: readonly string[];
|
|
70
|
+
/** The pass's order and how far into it the next entry is, for resumePoint. */
|
|
71
|
+
order: readonly number[];
|
|
72
|
+
step: number;
|
|
73
|
+
/** Where the break clock stood when it started. */
|
|
74
|
+
lastBreak: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
54
77
|
/** Decode each file independently; feed one persistent muxer a fixed stream
|
|
55
78
|
* profile and continuous timestamps. A concat demuxer cannot decode a list
|
|
56
79
|
* whose input codecs differ. Only one entry is encoded at a time, with pipe
|
|
57
80
|
* backpressure bounding read-ahead independently of the directory's size. */
|
|
58
81
|
export class PlaylistInputStream {
|
|
59
|
-
private entries:
|
|
82
|
+
private entries: Entry[] = [];
|
|
60
83
|
error: Error | null = null;
|
|
61
84
|
complete = false;
|
|
62
85
|
/**
|
|
@@ -68,7 +91,7 @@ export class PlaylistInputStream {
|
|
|
68
91
|
constructor(private readonly options: PlaylistInput) {}
|
|
69
92
|
|
|
70
93
|
/** Every entry that has started, in the order it started, with where it sits in the stream. */
|
|
71
|
-
get history(): ReadonlyArray<
|
|
94
|
+
get history(): ReadonlyArray<Entry> {
|
|
72
95
|
return this.entries;
|
|
73
96
|
}
|
|
74
97
|
|
|
@@ -84,6 +107,22 @@ export class PlaylistInputStream {
|
|
|
84
107
|
: { at: this.options.at, position: this.options.position, list: this.options.files };
|
|
85
108
|
}
|
|
86
109
|
|
|
110
|
+
/**
|
|
111
|
+
* Where to pick up after this point of the stream, for a station that
|
|
112
|
+
* sleeps with nobody listening: the file that is on ("" in a break), the
|
|
113
|
+
* rest of this pass in the order it was going to play, and the seconds
|
|
114
|
+
* of airtime since the last break.
|
|
115
|
+
*/
|
|
116
|
+
resumePoint(seconds: number): { file: string; upcoming: string[]; sinceBreak: number } | null {
|
|
117
|
+
const entry = this.entries.findLast(one => seconds >= one.start) ?? this.entries[0];
|
|
118
|
+
if (!entry) return null;
|
|
119
|
+
return {
|
|
120
|
+
file: entry.at >= 0 ? entry.file : "",
|
|
121
|
+
upcoming: entry.order.slice(entry.step).map((index) => entry.list[index]).filter((one): one is string => typeof one === "string"),
|
|
122
|
+
sinceBreak: entry.at < 0 ? 0 : Math.max(0, seconds - entry.lastBreak),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
87
126
|
/** The decoder for the entry that is on, so skip() can end it early. */
|
|
88
127
|
private stopCurrent: (() => void) | null = null;
|
|
89
128
|
private skipping = false;
|
|
@@ -114,7 +153,9 @@ export class PlaylistInputStream {
|
|
|
114
153
|
let step = Math.min(Math.max(0, o.at), order.length);
|
|
115
154
|
let played = 0;
|
|
116
155
|
let last = "";
|
|
117
|
-
|
|
156
|
+
// Counted back from 0 by however long it had been, so a clock carried
|
|
157
|
+
// across a sleep comes due when it would have on the air.
|
|
158
|
+
let lastBreak = -Math.max(0, o.breaks?.sinceBreak?.() ?? 0);
|
|
118
159
|
// A film cut for a break, to be picked up where it stopped.
|
|
119
160
|
let resume: { at: number; file: string; position: number } | null = null;
|
|
120
161
|
for (;;) {
|
|
@@ -179,7 +220,7 @@ export class PlaylistInputStream {
|
|
|
179
220
|
const room = o.video && !isBreak && o.breaks && every > 0 ? every - (offset - lastBreak) : Infinity;
|
|
180
221
|
const cut = room >= 1 && full - room > 5;
|
|
181
222
|
const duration = cut ? room : full;
|
|
182
|
-
this.entries.push({ at, file, start: offset, position, list: files });
|
|
223
|
+
this.entries.push({ at, file, start: offset, position, list: files, order, step, lastBreak });
|
|
183
224
|
const hasVideo = Boolean(codecs.video);
|
|
184
225
|
const extra = o.video && !hasVideo
|
|
185
226
|
? ["-f", "lavfi", "-i", `color=c=black:s=${width}x${height}:r=30`]
|
package/src/server.ts
CHANGED
|
@@ -122,7 +122,7 @@ import { Porkbun, isIPv4, isIPv6, type DnsZone } from "./dns.ts";
|
|
|
122
122
|
import { NameError, Names } from "./names.ts";
|
|
123
123
|
import { AcmeIssuer, Certs } from "./certs.ts";
|
|
124
124
|
import { claimName, fetchCert, humanizeSource, labelFor, readCertFiles, writeCertFiles } from "./naming.ts";
|
|
125
|
-
import { forbiddenLibrary, readConfig, readLibrary, writeConfig } from "./library.ts";
|
|
125
|
+
import { forbiddenLibrary, readConfig, readLibrary, stationIdleSeconds, writeConfig } from "./library.ts";
|
|
126
126
|
import { createThrottle, presentedCredential, type Throttle } from "@profullstack/throttle";
|
|
127
127
|
import { Durable } from "./durable.ts";
|
|
128
128
|
import { notifyAll, resendEmail, webPush, type Notification } from "./notify.ts";
|
|
@@ -5940,6 +5940,12 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
|
|
|
5940
5940
|
return;
|
|
5941
5941
|
}
|
|
5942
5942
|
|
|
5943
|
+
// A station asleep with nobody listening is woken by whoever asks for
|
|
5944
|
+
// its channel here too, and they are held for its first bytes.
|
|
5945
|
+
if ((action === "hls" || action === undefined) && request.method === "GET" && !channels.has(id) && stationOfChannel(id) && options.stations?.runner.isSleeping(stationOfChannel(id))) {
|
|
5946
|
+
await options.stations.runner.awake(stationOfChannel(id));
|
|
5947
|
+
}
|
|
5948
|
+
|
|
5943
5949
|
// The same channel as HLS: a playlist of short files, which is what
|
|
5944
5950
|
// Safari on an iPhone plays live -- it will not take the endless MP4
|
|
5945
5951
|
// below, and spun on it a few times before giving up. Packaged on
|
|
@@ -7455,6 +7461,8 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
|
|
|
7455
7461
|
onRestart: (id) => stationUsage.restarted(id),
|
|
7456
7462
|
onFailure: (id) => stationUsage.failed(id),
|
|
7457
7463
|
artistOf: (file) => trackFor(engine, file)?.artist ?? "",
|
|
7464
|
+
// Nobody listening for this long and a station sleeps until somebody does.
|
|
7465
|
+
idleSeconds: () => stationIdleSeconds(process.env, readConfig()),
|
|
7458
7466
|
store: stationStore,
|
|
7459
7467
|
channels,
|
|
7460
7468
|
pull: async (channelId, name, files, known) =>
|
|
@@ -7729,6 +7737,7 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
|
|
|
7729
7737
|
});
|
|
7730
7738
|
}
|
|
7731
7739
|
stationRunner.restore();
|
|
7740
|
+
stationRunner.watchIdle();
|
|
7732
7741
|
// Where each film has got to, written down every so often, so a restart
|
|
7733
7742
|
// picks it up from about there rather than from the start. Only when it
|
|
7734
7743
|
// has changed: a server carrying nothing but live television writes
|
package/src/station-routes.ts
CHANGED
|
@@ -114,14 +114,16 @@ function nowPlayingFile(ctx: StationContext, station: Station): string {
|
|
|
114
114
|
|
|
115
115
|
export function publicView(ctx: StationContext, station: Station): PublicStation {
|
|
116
116
|
const state = ctx.runner.observed(station.id);
|
|
117
|
-
|
|
117
|
+
// Asleep, what it will wake on: the first listener hears that next.
|
|
118
|
+
const asleep = ctx.runner.isSleeping?.(station.id) ?? false;
|
|
119
|
+
const file = asleep ? ctx.runner.nextUp(station.id) : state === "live" || state === "recovering" ? nowPlayingFile(ctx, station) : "";
|
|
118
120
|
// The tags the player read when it put this file on, else the library's.
|
|
119
121
|
const track = file ? (ctx.channels.tagsOf(channelOf(station.id), file) ?? ctx.trackFor(file)) : null;
|
|
120
122
|
// What the channel is carrying wins over the flag: a station made by hand
|
|
121
123
|
// from films streams video whether or not anyone said so.
|
|
122
124
|
const video = station.video || ctx.channels.kindOf(channelOf(station.id)) === "video";
|
|
123
125
|
// How far into the song (or film) on the air, by the encoder's clock, and how long it is.
|
|
124
|
-
const position = file ? ctx.channels.info(channelOf(station.id))?.position : undefined;
|
|
126
|
+
const position = file && !asleep ? ctx.channels.info(channelOf(station.id))?.position : undefined;
|
|
125
127
|
const duration = file && ctx.durationOf ? ctx.durationOf(file) : 0;
|
|
126
128
|
const progress = typeof position === "number" && duration > 0 ? { position: Math.round(Math.min(position, duration) * 10) / 10, duration: Math.round(duration * 10) / 10 } : null;
|
|
127
129
|
return {
|
|
@@ -161,11 +163,13 @@ export function guideEntries(ctx: StationContext): Array<PublicStation & { page:
|
|
|
161
163
|
return [...names].map(([slug, one]) => ({ ...publicView(ctx, one), page: links(ctx, one, base).page, m3u: links(ctx, one, base).m3u, group: guideGroup(one), radio: `${radioBase}/radio/${slug}` }));
|
|
162
164
|
}
|
|
163
165
|
|
|
164
|
-
export function ownerView(ctx: StationContext, station: Station): OwnerStation & { links: ReturnType<typeof links>; nowPlaying: string } {
|
|
166
|
+
export function ownerView(ctx: StationContext, station: Station): OwnerStation & { links: ReturnType<typeof links>; nowPlaying: string; sleeping: boolean } {
|
|
165
167
|
const { failures, idempotencyKey: _key, ...rest } = station;
|
|
166
168
|
return {
|
|
167
169
|
...rest,
|
|
168
170
|
state: ctx.runner.observed(station.id),
|
|
171
|
+
// On the air with nobody listening: no encoder until somebody does.
|
|
172
|
+
sleeping: ctx.runner.isSleeping?.(station.id) ?? false,
|
|
169
173
|
excluded: Object.entries(failures).filter(([, count]) => count >= 3).map(([file]) => file),
|
|
170
174
|
listeners: ctx.runner.listeners(station.id),
|
|
171
175
|
error: ctx.runner.error(station.id),
|
|
@@ -348,18 +352,31 @@ export async function handleStations(
|
|
|
348
352
|
return true;
|
|
349
353
|
}
|
|
350
354
|
const channelId = channelOf(station.id);
|
|
351
|
-
|
|
352
|
-
|
|
355
|
+
// Asleep, a HEAD is told what it would get without waking it.
|
|
356
|
+
if (method === "HEAD" && ctx.runner.isSleeping?.(station.id)) {
|
|
357
|
+
response.writeHead(200, { ...ctx.headers, "content-type": station.video ? "video/mp4" : "audio/mpeg", "cache-control": "no-store" });
|
|
358
|
+
response.end();
|
|
353
359
|
return true;
|
|
354
360
|
}
|
|
355
361
|
// Admitted only within the station's and the server's limits, and the
|
|
356
|
-
// month's allowance; refused with what to do about it.
|
|
362
|
+
// month's allowance; refused with what to do about it. Before waking it:
|
|
363
|
+
// a listener turned away is no reason to start the encoder.
|
|
357
364
|
const refused = method === "GET" && ctx.usage && ctx.limits ? ctx.usage.admit(station.id, ctx.limits) : null;
|
|
358
365
|
if (refused) {
|
|
359
366
|
response.writeHead(refused.status, { ...ctx.headers, "content-type": "application/json; charset=utf-8", "retry-after": String(refused.retryAfter) });
|
|
360
367
|
response.end(JSON.stringify({ error: refused.error, code: refused.code, retryAfter: refused.retryAfter }));
|
|
361
368
|
return true;
|
|
362
369
|
}
|
|
370
|
+
// The first listener wakes a sleeping station, and is held until it
|
|
371
|
+
// starts sending, so they hear it begin rather than a stream that ends.
|
|
372
|
+
let closed = false;
|
|
373
|
+
response.once("close", () => { closed = true; });
|
|
374
|
+
await ctx.runner.awake?.(station.id, undefined, () => closed);
|
|
375
|
+
if (closed) return true;
|
|
376
|
+
if (!ctx.channels.has(channelId)) {
|
|
377
|
+
ctx.json(response, 503, { error: "the station is not on the air", code: "not_live", state: ctx.runner.observed(station.id) });
|
|
378
|
+
return true;
|
|
379
|
+
}
|
|
363
380
|
// Signed in at nixamp.com: no breaks, starting a little behind live so
|
|
364
381
|
// they can be left out without a gap. Radio only (Channel.listenWithoutBreaks).
|
|
365
382
|
const pass = url.searchParams.get(PASS_PARAM) ?? "";
|