beatsheet 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +63 -2
- package/bin/beatsheet.js +14 -0
- package/bin/register-fallback.mjs +23 -0
- package/bin/resolve-fallback.mjs +83 -0
- package/package.json +45 -4
- package/player/env.d.ts +5 -0
- package/player/gallery-audio.ts +147 -0
- package/player/gallery-css.ts +144 -0
- package/player/gallery-detail.ts +385 -0
- package/player/gallery-music.ts +257 -0
- package/player/gallery-pick-state.ts +167 -0
- package/player/gallery-pick.ts +749 -0
- package/player/gallery-sounds.ts +137 -0
- package/player/gallery-state.ts +457 -0
- package/player/gallery.ts +612 -0
- package/player/index.html +49 -0
- package/player/main.ts +83 -0
- package/skill/SKILL.md +658 -0
- package/skill/examples/library/assets/tour/avatar-mk.svg +1 -0
- package/skill/examples/library/assets/tour/dashboard-insights.svg +1 -0
- package/skill/examples/library/assets/tour/dashboard.svg +1 -0
- package/skill/examples/library/assets/tour/settings.svg +1 -0
- package/skill/examples/library/library-tour.plan.md +32 -0
- package/skill/examples/library/library-tour.video.json +268 -0
- package/skill/reference/scene-techniques.md +306 -0
- package/skill/scripts/beats.ts +34 -0
- package/skill/scripts/catalogue.ts +120 -0
- package/skill/scripts/frames.ts +105 -0
- package/src/args.ts +344 -0
- package/src/cli.ts +95 -0
- package/src/commands.ts +812 -0
- package/src/default-project.config.ts +9 -0
- package/src/index.ts +47 -0
- package/src/packages.ts +17 -0
- package/src/paths.ts +32 -0
- package/src/project.ts +200 -0
- package/src/render/browser.ts +185 -0
- package/src/render/capture.ts +320 -0
- package/src/render/ffmpeg.ts +229 -0
- package/src/render/gif-info.ts +61 -0
- package/src/render/render.ts +220 -0
- package/src/samples.ts +557 -0
- package/src/server/api.ts +494 -0
- package/src/server/jobs.ts +210 -0
- package/src/server/security.ts +47 -0
- package/src/server/server.ts +191 -0
- package/src/server/sse.ts +76 -0
- package/src/server/static.ts +127 -0
- package/src/server/vite.ts +100 -0
- package/src/skill.ts +111 -0
- package/src/snap.ts +212 -0
- package/src/speech.ts +689 -0
- package/src/svg-text.ts +136 -0
- package/src/voicefx.ts +311 -0
- package/studio/3rdpartylicenses.txt +287 -0
- package/studio/favicon.ico +0 -0
- package/studio/icons/apple-touch-icon.png +0 -0
- package/studio/icons/icon-192.png +0 -0
- package/studio/icons/icon-512.png +0 -0
- package/studio/icons/icon.svg +1 -0
- package/studio/icons/maskable-512.png +0 -0
- package/studio/index.html +18 -0
- package/studio/main-KMYDBWZH.js +15 -0
- package/studio/manifest.webmanifest +17 -0
- package/studio/offline.html +92 -0
- package/studio/styles-NJ2CULOW.css +1 -0
- package/studio/sw.js +71 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/** The gallery's sound board: every theme sound by category, click to play, with its waveform. */
|
|
2
|
+
import { SOUND_CATEGORIES, h, type ProjectConfig } from '@beatsheet/core';
|
|
3
|
+
import { playSound, renderSoundOffline, silenceAll } from './gallery-audio';
|
|
4
|
+
import { groupByCategory, peaks, soundEntries, type SoundEntry } from './gallery-state';
|
|
5
|
+
|
|
6
|
+
export interface Panel {
|
|
7
|
+
el: HTMLElement;
|
|
8
|
+
/** The panel became visible. */
|
|
9
|
+
activate(): void;
|
|
10
|
+
/** The panel was hidden, or the studio switched away from the gallery: stop what plays. */
|
|
11
|
+
deactivate(): void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const WAVE_W = 240;
|
|
15
|
+
const WAVE_H = 28;
|
|
16
|
+
|
|
17
|
+
function drawWave(canvas: HTMLCanvasElement, data: Float32Array): number {
|
|
18
|
+
const dpr = Math.min(2, window.devicePixelRatio || 1);
|
|
19
|
+
const cols = Math.round(canvas.clientWidth || WAVE_W);
|
|
20
|
+
canvas.width = cols * dpr;
|
|
21
|
+
canvas.height = WAVE_H * dpr;
|
|
22
|
+
const g = canvas.getContext('2d');
|
|
23
|
+
// Length: up to the last sample above -60 dBFS.
|
|
24
|
+
let last = 0;
|
|
25
|
+
for (let i = data.length - 1; i >= 0; i--) {
|
|
26
|
+
if (Math.abs(data[i] as number) > 0.001) {
|
|
27
|
+
last = i;
|
|
28
|
+
break;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (!g) return last / 22050;
|
|
32
|
+
g.scale(dpr, dpr);
|
|
33
|
+
g.fillStyle = 'rgba(122, 162, 247, 0.75)';
|
|
34
|
+
// Drawn over the sound's own length (the text says how long that is).
|
|
35
|
+
const ps = peaks(data.subarray(0, Math.max(last + 1, 1100)), cols);
|
|
36
|
+
const mid = WAVE_H / 2;
|
|
37
|
+
ps.forEach((p, x) => {
|
|
38
|
+
const hgt = Math.max(1, p * (WAVE_H - 2));
|
|
39
|
+
g.fillRect(x, mid - hgt / 2, 1, hgt);
|
|
40
|
+
});
|
|
41
|
+
return last / 22050;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function buildSoundBoard(project: ProjectConfig): Panel {
|
|
45
|
+
const theme = project.theme;
|
|
46
|
+
const entries = soundEntries(theme.sounds);
|
|
47
|
+
const status = h('span', { class: 'g-summary', role: 'status' });
|
|
48
|
+
const el = h(
|
|
49
|
+
'div',
|
|
50
|
+
null,
|
|
51
|
+
h(
|
|
52
|
+
'p',
|
|
53
|
+
{ class: 'g-sub' },
|
|
54
|
+
`Theme "${theme.title}": ${entries.length} sounds. Click to play. `,
|
|
55
|
+
h('span', { class: 'g-badge' }, 'standard'),
|
|
56
|
+
' every theme has it · ',
|
|
57
|
+
h('span', { class: 'g-badge library' }, 'library'),
|
|
58
|
+
' synth library (scene types set a standard fallback) · ',
|
|
59
|
+
h('span', { class: 'g-badge file' }, 'file'),
|
|
60
|
+
' audio file. ',
|
|
61
|
+
status,
|
|
62
|
+
),
|
|
63
|
+
);
|
|
64
|
+
if (!entries.length) el.appendChild(h('p', { class: 'g-empty' }, 'This theme has no sounds.'));
|
|
65
|
+
const waves: { entry: SoundEntry; canvas: HTMLCanvasElement; len: HTMLElement }[] = [];
|
|
66
|
+
const buttons: { btn: HTMLButtonElement; stop(): void }[] = [];
|
|
67
|
+
|
|
68
|
+
for (const group of groupByCategory(entries, (e) => e.def.category, SOUND_CATEGORIES)) {
|
|
69
|
+
el.appendChild(h('h2', { class: 'g-cat' }, group.title, h('span', { class: 'g-count' }, String(group.items.length))));
|
|
70
|
+
const grid = h('div', { class: 'g-sound-grid' });
|
|
71
|
+
for (const entry of group.items) {
|
|
72
|
+
const canvas = h('canvas', { class: 'g-wave', width: WAVE_W, height: WAVE_H, 'aria-hidden': 'true' });
|
|
73
|
+
const len = h('span', { class: 'g-dur' });
|
|
74
|
+
const badge = entry.kind === 'file' ? h('span', { class: 'g-badge file' }, 'file') : null;
|
|
75
|
+
const origin = entry.standard ? h('span', { class: 'g-badge' }, 'standard') : entry.library ? h('span', { class: 'g-badge library' }, 'library') : null;
|
|
76
|
+
const btn = h(
|
|
77
|
+
'button',
|
|
78
|
+
// Named by the sound alone (the button's text also holds id, badges, length and description).
|
|
79
|
+
{ type: 'button', class: 'g-sound', 'data-sound': entry.id, title: `Play "${entry.id}"`, 'aria-label': `Play sound ${entry.def.title || entry.id}`, 'aria-describedby': `g-sound-desc-${entry.id}` },
|
|
80
|
+
h('span', { class: 'g-sound-icon', 'aria-hidden': 'true' }, '▶'),
|
|
81
|
+
h('span', { class: 'g-sound-name' }, h('strong', null, entry.def.title || entry.id), h('code', null, entry.id), origin, badge, len),
|
|
82
|
+
h('p', { id: `g-sound-desc-${entry.id}` }, entry.def.description ?? ''),
|
|
83
|
+
canvas,
|
|
84
|
+
);
|
|
85
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
86
|
+
btn.addEventListener('click', () => {
|
|
87
|
+
playSound(entry.id, entry.def).then(
|
|
88
|
+
(seconds) => {
|
|
89
|
+
btn.classList.add('playing');
|
|
90
|
+
clearTimeout(timer);
|
|
91
|
+
timer = setTimeout(() => btn.classList.remove('playing'), Math.max(250, seconds * 1000));
|
|
92
|
+
status.textContent = '';
|
|
93
|
+
},
|
|
94
|
+
(err: unknown) => {
|
|
95
|
+
status.textContent = `"${entry.id}" did not play: ${err instanceof Error ? err.message : String(err)}`;
|
|
96
|
+
},
|
|
97
|
+
);
|
|
98
|
+
});
|
|
99
|
+
grid.appendChild(btn);
|
|
100
|
+
waves.push({ entry, canvas, len });
|
|
101
|
+
buttons.push({
|
|
102
|
+
btn,
|
|
103
|
+
stop: (): void => {
|
|
104
|
+
clearTimeout(timer);
|
|
105
|
+
btn.classList.remove('playing');
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
el.appendChild(grid);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
let drawn = false;
|
|
113
|
+
return {
|
|
114
|
+
el,
|
|
115
|
+
activate(): void {
|
|
116
|
+
if (drawn) return;
|
|
117
|
+
drawn = true;
|
|
118
|
+
// One offline render after the other, so the page stays responsive.
|
|
119
|
+
void (async (): Promise<void> => {
|
|
120
|
+
for (const w of waves) {
|
|
121
|
+
try {
|
|
122
|
+
const data = await renderSoundOffline(w.entry.id, w.entry.def);
|
|
123
|
+
const seconds = drawWave(w.canvas, data);
|
|
124
|
+
w.len.textContent = seconds > 0 ? `${seconds.toFixed(2)} s` : '';
|
|
125
|
+
} catch (err) {
|
|
126
|
+
w.len.textContent = 'no preview';
|
|
127
|
+
console.warn(`[beatsheet gallery] waveform of "${w.entry.id}": ${err instanceof Error ? err.message : String(err)}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
})();
|
|
131
|
+
},
|
|
132
|
+
deactivate(): void {
|
|
133
|
+
silenceAll();
|
|
134
|
+
for (const b of buttons) b.stop();
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers of the gallery page (/player/?mode=gallery): URL state, loop time, grouping,
|
|
3
|
+
* filtering, tile sizes, the scene entry a sample copies as, and the music browser's timeline.
|
|
4
|
+
* No DOM here, so they run in Node tests (packages/cli/test/gallery.test.ts).
|
|
5
|
+
*/
|
|
6
|
+
import {
|
|
7
|
+
LIBRARY_SOUND_IDS,
|
|
8
|
+
STANDARD_SOUND_IDS,
|
|
9
|
+
getFormat,
|
|
10
|
+
isFileTrack,
|
|
11
|
+
samplesDoc,
|
|
12
|
+
sceneSamples,
|
|
13
|
+
type FormatId,
|
|
14
|
+
type MusicMix,
|
|
15
|
+
type MusicTrack,
|
|
16
|
+
type ProjectConfig,
|
|
17
|
+
type ResolvedSample,
|
|
18
|
+
type SampleEntry,
|
|
19
|
+
type SceneInstance,
|
|
20
|
+
type SceneType,
|
|
21
|
+
type SoundDef,
|
|
22
|
+
type VideoDoc,
|
|
23
|
+
} from '@beatsheet/core';
|
|
24
|
+
|
|
25
|
+
// ---------------------------------------------------------------------------
|
|
26
|
+
// URL state (the hash), so filters, format and the open sample survive a reload
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
export type GalleryTab = 'scenes' | 'sounds' | 'music';
|
|
30
|
+
/** A single format, or 'pair': 16:9 and 4:5 side by side. */
|
|
31
|
+
export type GalleryFormat = FormatId | 'pair';
|
|
32
|
+
export type TileSize = 's' | 'm' | 'l';
|
|
33
|
+
|
|
34
|
+
export interface GalleryState {
|
|
35
|
+
tab: GalleryTab;
|
|
36
|
+
format: GalleryFormat;
|
|
37
|
+
size: TileSize;
|
|
38
|
+
/** Selected scene categories ('other' for types without one); empty = all. */
|
|
39
|
+
categories: string[];
|
|
40
|
+
query: string;
|
|
41
|
+
hideStress: boolean;
|
|
42
|
+
/** The sample open in the large view: `${typeId}/${sampleId}`. */
|
|
43
|
+
open: string | null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const DEFAULT_STATE: GalleryState = {
|
|
47
|
+
tab: 'scenes',
|
|
48
|
+
format: '16:9',
|
|
49
|
+
size: 'm',
|
|
50
|
+
categories: [],
|
|
51
|
+
query: '',
|
|
52
|
+
hideStress: false,
|
|
53
|
+
open: null,
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const TABS: readonly GalleryTab[] = ['scenes', 'sounds', 'music'];
|
|
57
|
+
export const GALLERY_FORMATS: readonly GalleryFormat[] = ['16:9', '4:5', '1:1', '9:16', 'pair'];
|
|
58
|
+
const SIZES: readonly TileSize[] = ['s', 'm', 'l'];
|
|
59
|
+
|
|
60
|
+
function oneOf<T extends string>(value: string | null, allowed: readonly T[], fallback: T): T {
|
|
61
|
+
return value !== null && (allowed as readonly string[]).includes(value) ? (value as T) : fallback;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Reads the state from a location hash ('#tab=sounds&format=pair&cat=demo,proof...'); unknown values fall back to defaults. */
|
|
65
|
+
export function parseState(hash: string): GalleryState {
|
|
66
|
+
const params = new URLSearchParams(hash.replace(/^#/, ''));
|
|
67
|
+
const cats = params.get('cat');
|
|
68
|
+
return {
|
|
69
|
+
tab: oneOf(params.get('tab'), TABS, DEFAULT_STATE.tab),
|
|
70
|
+
format: oneOf(params.get('format'), GALLERY_FORMATS, DEFAULT_STATE.format),
|
|
71
|
+
size: oneOf(params.get('size'), SIZES, DEFAULT_STATE.size),
|
|
72
|
+
categories: cats ? [...new Set(cats.split(',').filter((c) => /^[a-z0-9-]+$/.test(c)))] : [],
|
|
73
|
+
query: params.get('q') ?? '',
|
|
74
|
+
hideStress: params.get('stress') === 'hide',
|
|
75
|
+
open: params.get('open') || null,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The hash for a state: only what differs from the defaults ('' for the default state). */
|
|
80
|
+
export function serializeState(state: GalleryState): string {
|
|
81
|
+
const params = new URLSearchParams();
|
|
82
|
+
if (state.tab !== DEFAULT_STATE.tab) params.set('tab', state.tab);
|
|
83
|
+
if (state.format !== DEFAULT_STATE.format) params.set('format', state.format);
|
|
84
|
+
if (state.size !== DEFAULT_STATE.size) params.set('size', state.size);
|
|
85
|
+
if (state.categories.length) params.set('cat', state.categories.join(','));
|
|
86
|
+
if (state.query) params.set('q', state.query);
|
|
87
|
+
if (state.hideStress) params.set('stress', 'hide');
|
|
88
|
+
if (state.open) params.set('open', state.open);
|
|
89
|
+
const s = params.toString();
|
|
90
|
+
return s ? `#${s}` : '';
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Toggles a category chip. */
|
|
94
|
+
export function toggleCategory(selected: readonly string[], id: string): string[] {
|
|
95
|
+
return selected.includes(id) ? selected.filter((c) => c !== id) : [...selected, id];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
// Loop time of a preview tile
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
/** Seconds a tile holds its last frame before it starts over. */
|
|
103
|
+
export const LOOP_HOLD = 0.8;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Scene time for a looping tile `elapsed` seconds after it started: plays 0..duration, holds the
|
|
107
|
+
* last frame for `hold` seconds, starts over. Never past the last frame (duration - 1/fps).
|
|
108
|
+
*/
|
|
109
|
+
export function loopTime(elapsed: number, duration: number, hold: number = LOOP_HOLD, fps = 30): number {
|
|
110
|
+
if (!(duration > 0) || !(elapsed > 0)) return 0;
|
|
111
|
+
const cycle = duration + Math.max(0, hold);
|
|
112
|
+
const t = elapsed % cycle;
|
|
113
|
+
return Math.min(t, Math.max(0, duration - 1 / fps));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
// Grouping and filtering
|
|
118
|
+
// ---------------------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
export interface Group<T> {
|
|
121
|
+
/** Category id, or 'other'. */
|
|
122
|
+
id: string;
|
|
123
|
+
title: string;
|
|
124
|
+
items: T[];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Groups items by category in the order of `categories`; items without a category, or with one not
|
|
129
|
+
* in the list, go to 'Other', last. Item order is kept inside a group; empty groups are left out.
|
|
130
|
+
*/
|
|
131
|
+
export function groupByCategory<T>(
|
|
132
|
+
items: readonly T[],
|
|
133
|
+
categoryOf: (item: T) => string | undefined,
|
|
134
|
+
categories: readonly { id: string; title: string }[],
|
|
135
|
+
): Group<T>[] {
|
|
136
|
+
const known = new Set(categories.map((c) => c.id));
|
|
137
|
+
const groups: Group<T>[] = [...categories.map((c) => ({ id: c.id, title: c.title, items: [] as T[] })), { id: 'other', title: 'Other', items: [] }];
|
|
138
|
+
const byId = new Map(groups.map((g) => [g.id, g]));
|
|
139
|
+
for (const item of items) {
|
|
140
|
+
const cat = categoryOf(item);
|
|
141
|
+
(byId.get(cat !== undefined && known.has(cat) ? cat : 'other') as Group<T>).items.push(item);
|
|
142
|
+
}
|
|
143
|
+
return groups.filter((g) => g.items.length > 0);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** A scene type with the samples the gallery shows for it. */
|
|
147
|
+
export interface TypeEntry {
|
|
148
|
+
type: SceneType;
|
|
149
|
+
samples: ResolvedSample[];
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export interface SceneFilter {
|
|
153
|
+
categories: readonly string[];
|
|
154
|
+
query: string;
|
|
155
|
+
hideStress: boolean;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function terms(query: string): string[] {
|
|
159
|
+
return query.toLowerCase().split(/\s+/).filter(Boolean);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The types and samples matching the filter. Every word of the query must appear in the type
|
|
164
|
+
* (id, title, description, category) or the sample (id, title): a query naming a type shows all its
|
|
165
|
+
* samples, one naming a sample shows just that sample. Types with no sample left are dropped.
|
|
166
|
+
*/
|
|
167
|
+
export function filterScenes(types: readonly SceneType[], filter: SceneFilter): TypeEntry[] {
|
|
168
|
+
const words = terms(filter.query);
|
|
169
|
+
const out: TypeEntry[] = [];
|
|
170
|
+
for (const type of types) {
|
|
171
|
+
const category = type.category ?? 'other';
|
|
172
|
+
if (filter.categories.length && !filter.categories.includes(category)) continue;
|
|
173
|
+
const typeText = [type.id, type.title, type.description ?? '', category].join(' ').toLowerCase();
|
|
174
|
+
const samples = sceneSamples(type).filter((s) => {
|
|
175
|
+
if (filter.hideStress && s.stress) return false;
|
|
176
|
+
if (!words.length) return true;
|
|
177
|
+
const text = `${typeText} ${s.id} ${s.title}`.toLowerCase();
|
|
178
|
+
return words.every((w) => text.includes(w));
|
|
179
|
+
});
|
|
180
|
+
if (samples.length) out.push({ type, samples });
|
|
181
|
+
}
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** A type's sample count for its header: what is shown, "of" all when the filter hides some. */
|
|
186
|
+
export function sampleCountLabel(shown: number, total: number): string {
|
|
187
|
+
const noun = total === 1 ? 'sample' : 'samples';
|
|
188
|
+
return shown < total ? `${shown} of ${total} ${noun}` : `${total} ${noun}`;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Scene types per category id ('other' for none), for the chip counts. */
|
|
192
|
+
export function categoryCounts(types: readonly SceneType[]): Map<string, number> {
|
|
193
|
+
const counts = new Map<string, number>();
|
|
194
|
+
for (const t of types) counts.set(t.category ?? 'other', (counts.get(t.category ?? 'other') ?? 0) + 1);
|
|
195
|
+
return counts;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ---------------------------------------------------------------------------
|
|
199
|
+
// Tiles
|
|
200
|
+
// ---------------------------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
/** Live players (createPlayer) the scene tiles keep at most; off-screen tiles over it are unmounted. */
|
|
203
|
+
export const MAX_LIVE_PLAYERS = 60;
|
|
204
|
+
|
|
205
|
+
/** A tile with its mounted players, for tilesToUnmount. */
|
|
206
|
+
export interface LiveTile {
|
|
207
|
+
key: string;
|
|
208
|
+
/** Mounted players (0: not mounted). */
|
|
209
|
+
players: number;
|
|
210
|
+
/** In view (with the observer's margin): never unmounted. */
|
|
211
|
+
visible: boolean;
|
|
212
|
+
/** When it last left the view (performance.now()). */
|
|
213
|
+
lastSeen: number;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* The tiles to unmount so at most `max` players stay live: off-screen tiles, the longest unseen
|
|
218
|
+
* first (they remount when they come back into view). Tiles in view stay, even over the cap.
|
|
219
|
+
*/
|
|
220
|
+
export function tilesToUnmount(tiles: readonly LiveTile[], max: number = MAX_LIVE_PLAYERS): string[] {
|
|
221
|
+
let live = tiles.reduce((n, t) => n + t.players, 0);
|
|
222
|
+
const out: string[] = [];
|
|
223
|
+
const idle = tiles.filter((t) => !t.visible && t.players > 0).sort((a, b) => a.lastSeen - b.lastSeen);
|
|
224
|
+
for (const t of idle) {
|
|
225
|
+
if (live <= max) break;
|
|
226
|
+
out.push(t.key);
|
|
227
|
+
live -= t.players;
|
|
228
|
+
}
|
|
229
|
+
return out;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Formats a tile shows for a gallery format. */
|
|
233
|
+
export function tileFormats(format: GalleryFormat): FormatId[] {
|
|
234
|
+
return format === 'pair' ? ['16:9', '4:5'] : [format];
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const SIZE_FACTOR: Record<TileSize, number> = { s: 0.72, m: 1, l: 1.45 };
|
|
238
|
+
/** Area of one preview at size m (320 x 180 for 16:9). */
|
|
239
|
+
const BASE_AREA = 320 * 180;
|
|
240
|
+
/** Height of each preview of a 'pair' tile at size m. */
|
|
241
|
+
const PAIR_HEIGHT = 200;
|
|
242
|
+
|
|
243
|
+
export interface PreviewBox {
|
|
244
|
+
format: FormatId;
|
|
245
|
+
/** CSS px of the scaled preview. */
|
|
246
|
+
width: number;
|
|
247
|
+
height: number;
|
|
248
|
+
/** Stage px -> CSS px. */
|
|
249
|
+
scale: number;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* The scaled previews of one tile: single formats get the same area (so a 9:16 tile is as big as a
|
|
254
|
+
* 16:9 one), the pair gets the same height for both.
|
|
255
|
+
*/
|
|
256
|
+
export function tileBoxes(format: GalleryFormat, size: TileSize): PreviewBox[] {
|
|
257
|
+
const k = SIZE_FACTOR[size];
|
|
258
|
+
return tileFormats(format).map((id) => {
|
|
259
|
+
const f = getFormat(id);
|
|
260
|
+
const height = format === 'pair' ? PAIR_HEIGHT * k : Math.sqrt((BASE_AREA * k * k * f.height) / f.width);
|
|
261
|
+
const scale = height / f.height;
|
|
262
|
+
return { format: id, width: Math.round(f.width * scale), height: Math.round(height), scale };
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Previews of these formats side by side at the same height, as large as fits a box of
|
|
268
|
+
* boxW x boxH with `gap` px between them (never above 1:1).
|
|
269
|
+
*/
|
|
270
|
+
export function fitRow(formats: readonly FormatId[], boxW: number, boxH: number, gap = 0): PreviewBox[] {
|
|
271
|
+
const fs = formats.map((id) => getFormat(id));
|
|
272
|
+
const ratioSum = fs.reduce((sum, f) => sum + f.width / f.height, 0);
|
|
273
|
+
const free = boxW - gap * Math.max(0, fs.length - 1);
|
|
274
|
+
if (!fs.length || !(free > 0) || !(boxH > 0)) return fs.map((f) => ({ format: f.id, width: 0, height: 0, scale: 0 }));
|
|
275
|
+
const height = Math.min(boxH, free / ratioSum, Math.min(...fs.map((f) => f.height)));
|
|
276
|
+
return fs.map((f) => {
|
|
277
|
+
const scale = height / f.height;
|
|
278
|
+
return { format: f.id, width: Math.floor(f.width * scale), height: Math.floor(height), scale };
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ---------------------------------------------------------------------------
|
|
283
|
+
// A sample as a scene entry and as a one-scene video
|
|
284
|
+
// ---------------------------------------------------------------------------
|
|
285
|
+
|
|
286
|
+
function kebab(value: string): string {
|
|
287
|
+
return value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'scene';
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** A ready-to-paste scene for a *.video.json: { id, type, duration, props }. */
|
|
291
|
+
export function sceneEntry(typeId: string, sample: Pick<ResolvedSample, 'id' | 'props' | 'duration'>): SceneInstance {
|
|
292
|
+
return {
|
|
293
|
+
id: kebab(sample.id === 'default' ? typeId : `${typeId}-${sample.id}`),
|
|
294
|
+
type: typeId,
|
|
295
|
+
duration: sample.duration,
|
|
296
|
+
props: structuredClone(sample.props ?? {}) as Record<string, unknown>,
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** The one-scene video a tile plays. */
|
|
301
|
+
export function singleSceneDoc(scene: SceneInstance, formats: FormatId[]): VideoDoc {
|
|
302
|
+
return { version: 1, title: scene.id, fps: 30, formats, music: null, scenes: [structuredClone(scene)] };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** `${typeId}/${sampleId}` <-> parts (type ids and sample ids are kebab-case, so '/' is free). */
|
|
306
|
+
export function sampleKey(typeId: string, sampleId: string): string {
|
|
307
|
+
return `${typeId}/${sampleId}`;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export function parseSampleKey(key: string | null): { typeId: string; sampleId: string } | null {
|
|
311
|
+
if (!key) return null;
|
|
312
|
+
const i = key.indexOf('/');
|
|
313
|
+
if (i <= 0 || i === key.length - 1) return null;
|
|
314
|
+
return { typeId: key.slice(0, i), sampleId: key.slice(i + 1) };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// ---------------------------------------------------------------------------
|
|
318
|
+
// Sounds and music
|
|
319
|
+
// ---------------------------------------------------------------------------
|
|
320
|
+
|
|
321
|
+
export interface SoundEntry {
|
|
322
|
+
id: string;
|
|
323
|
+
def: SoundDef;
|
|
324
|
+
kind: 'synth' | 'file';
|
|
325
|
+
/** One of the five ids every theme provides. */
|
|
326
|
+
standard: boolean;
|
|
327
|
+
/** One of the synth library ids. */
|
|
328
|
+
library: boolean;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export function soundEntries(sounds: Record<string, SoundDef>): SoundEntry[] {
|
|
332
|
+
return Object.entries(sounds).map(([id, def]) => ({
|
|
333
|
+
id,
|
|
334
|
+
def,
|
|
335
|
+
kind: 'url' in def && typeof def.url === 'string' ? 'file' : 'synth',
|
|
336
|
+
standard: (STANDARD_SOUND_IDS as readonly string[]).includes(id),
|
|
337
|
+
library: (LIBRARY_SOUND_IDS as readonly string[]).includes(id),
|
|
338
|
+
}));
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export interface TrackEntry {
|
|
342
|
+
id: string;
|
|
343
|
+
track: MusicTrack;
|
|
344
|
+
kind: 'generated' | 'file';
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export function trackEntries(music: Record<string, MusicTrack> | undefined): TrackEntry[] {
|
|
348
|
+
return Object.entries(music ?? {}).map(([id, track]) => ({ id, track, kind: isFileTrack(track) ? 'file' : 'generated' }));
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Scenes in the music browser's timeline. */
|
|
352
|
+
export const MUSIC_SCENES = 6;
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* The timeline a track plays over: default samples (no stress), one type per category first for
|
|
356
|
+
* variety, then the next ones in order, up to `count` scenes, kept in category order, entering with
|
|
357
|
+
* the theme's default transition. `sceneSounds: false` mutes the scene types' own sounds; `mix`
|
|
358
|
+
* levels the track's parts (music.mix, e.g. the browser's muted parts).
|
|
359
|
+
*/
|
|
360
|
+
export function musicDoc(
|
|
361
|
+
project: ProjectConfig,
|
|
362
|
+
track: string | null,
|
|
363
|
+
opts: { count?: number; sceneSounds?: boolean; mix?: MusicMix } = {},
|
|
364
|
+
): { doc: VideoDoc; entries: SampleEntry[] } {
|
|
365
|
+
const count = opts.count ?? MUSIC_SCENES;
|
|
366
|
+
const transition = project.theme.defaultTransition ?? { kind: 'dip', duration: 0.5 };
|
|
367
|
+
const all = samplesDoc(project, {
|
|
368
|
+
samples: ['default'],
|
|
369
|
+
skipStress: true,
|
|
370
|
+
formats: ['16:9'],
|
|
371
|
+
transition,
|
|
372
|
+
music: track ? (opts.mix ? { track, mix: opts.mix } : { track }) : null,
|
|
373
|
+
title: 'Music preview',
|
|
374
|
+
});
|
|
375
|
+
const picked = new Set<number>();
|
|
376
|
+
const seen = new Set<string>();
|
|
377
|
+
all.entries.forEach((e, i) => {
|
|
378
|
+
if (picked.size < count && !seen.has(e.category)) {
|
|
379
|
+
seen.add(e.category);
|
|
380
|
+
picked.add(i);
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
for (let i = 0; i < all.entries.length && picked.size < count; i++) picked.add(i);
|
|
384
|
+
const keep = [...picked].sort((a, b) => a - b);
|
|
385
|
+
const scenes = keep.map((i) => {
|
|
386
|
+
const scene = all.doc.scenes[i] as SceneInstance;
|
|
387
|
+
return opts.sceneSounds === false ? { ...scene, muteDefaultSfx: true } : scene;
|
|
388
|
+
});
|
|
389
|
+
return { doc: { ...all.doc, scenes }, entries: keep.map((i) => all.entries[i] as SampleEntry) };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** The music browser's mix for a track's muted parts: each at 0; undefined when none is muted. */
|
|
393
|
+
export function mutedMix(muted: Iterable<string>): MusicMix | undefined {
|
|
394
|
+
const parts = [...new Set(muted)].sort();
|
|
395
|
+
return parts.length ? Object.fromEntries(parts.map((p) => [p, 0])) : undefined;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Cache key of a music browser mix: the track, scene sounds on or off, and the part levels. */
|
|
399
|
+
export function musicMixKey(track: string, sceneSounds: boolean, mix: MusicMix | undefined): string {
|
|
400
|
+
const levels = mix
|
|
401
|
+
? Object.keys(mix)
|
|
402
|
+
.sort()
|
|
403
|
+
.map((p) => `${p}=${mix[p]}`)
|
|
404
|
+
.join(',')
|
|
405
|
+
: '';
|
|
406
|
+
return `${track}|${sceneSounds ? 1 : 0}|${levels}`;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** '2.4 s' for short spans, '1:05.2' from a minute on. */
|
|
410
|
+
export function formatSeconds(t: number): string {
|
|
411
|
+
const v = Math.max(0, t);
|
|
412
|
+
if (v < 60) return `${v.toFixed(1)} s`;
|
|
413
|
+
const m = Math.floor(v / 60);
|
|
414
|
+
const s = v - m * 60;
|
|
415
|
+
return `${m}:${s.toFixed(1).padStart(4, '0')}`;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Peak per pixel column, normalised to the loudest (for a waveform). */
|
|
419
|
+
export function peaks(data: Float32Array, columns: number): number[] {
|
|
420
|
+
const out: number[] = new Array<number>(columns).fill(0);
|
|
421
|
+
if (!data.length || columns <= 0) return out;
|
|
422
|
+
const per = data.length / columns;
|
|
423
|
+
let max = 0;
|
|
424
|
+
for (let c = 0; c < columns; c++) {
|
|
425
|
+
let p = 0;
|
|
426
|
+
const end = Math.min(data.length, Math.floor((c + 1) * per));
|
|
427
|
+
for (let i = Math.floor(c * per); i < end; i++) {
|
|
428
|
+
const v = Math.abs(data[i] as number);
|
|
429
|
+
if (v > p) p = v;
|
|
430
|
+
}
|
|
431
|
+
out[c] = p;
|
|
432
|
+
if (p > max) max = p;
|
|
433
|
+
}
|
|
434
|
+
return max > 0 ? out.map((p) => p / max) : out;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// ---------------------------------------------------------------------------
|
|
438
|
+
// Studio messages
|
|
439
|
+
// ---------------------------------------------------------------------------
|
|
440
|
+
|
|
441
|
+
/** What the studio posts to its gallery iframe when it switches to the editor: stop all sound. */
|
|
442
|
+
export const STUDIO_PAUSE = { source: 'beatsheet-studio', type: 'pause' } as const;
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* True for the studio's pause message: from the parent window (the studio embedding this page), of
|
|
446
|
+
* this origin, with the STUDIO_PAUSE fields. Anything else (other windows, origins, shapes) is ignored.
|
|
447
|
+
*/
|
|
448
|
+
export function isStudioPause(e: { source: unknown; origin: string; data: unknown }, parent: unknown, origin: string): boolean {
|
|
449
|
+
if (e.source !== parent || e.origin !== origin) return false;
|
|
450
|
+
const d = e.data as Partial<typeof STUDIO_PAUSE> | null;
|
|
451
|
+
return !!d && typeof d === 'object' && d.source === STUDIO_PAUSE.source && d.type === STUDIO_PAUSE.type;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** The accessible name of a music row's play button: what it does, to which track. */
|
|
455
|
+
export function trackButtonLabel(title: string, playing: boolean): string {
|
|
456
|
+
return `${playing ? 'Stop' : 'Play'} ${title}`;
|
|
457
|
+
}
|