Skip to content
Source
Sign inSign up
fuko/rive-preview-player
Open History to see the last commit

mix.mjs

128 lines5.5 KB

1// The audio mix set in the player: up to three tracks (volume, mute, solo) and, per sound
2// effect, which track it is on and its own gain. Saved to <feedback root>/mix.json so it
3// survives reloads and the MCP server can hand it to the coding agent.
4//
5// The player never changes the Rive project. What a sound effect plays at in the preview is
6// asset volume (from the .riv) × clip gain × track volume (0 when muted or another track is soloed)
7import { randomBytes } from 'node:crypto';
8import { existsSync } from 'node:fs';
9import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
10import path from 'node:path';
11import { feedbackRoot, feedbackTop } from './feedback.mjs';
12​
13export const MAX_TRACKS = 3;
14const MAX_CLIPS = 5000;
15// A clip key is a JSON tuple of artboard, animation and event names plus an index; names have
16// no length limit of their own, so allow long ones (escaping included).
17const MAX_KEY = 8192;
18const MAX_GAIN = 1; // the player's clip volume slider runs 0–100%
19const MAX_TRACK_VOLUME = 2;
20​
21const num = (v, lo, hi, dflt) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : dflt);
22const str = (v, max, dflt = null) => (typeof v === 'string' ? v.slice(0, max) : dflt);
23​
24export function defaultMix() {
25 return { version: 1, tracks: [{ name: 'Track 1', volume: 1, muted: false, solo: false }], clips: {} };
27​
28/** Keep only values of the expected shape: the mix comes from the browser. */
29export function sanitizeMix(input) {
30 const out = defaultMix();
31 if (!input || typeof input !== 'object') return out;
32 const tracks = Array.isArray(input.tracks) ? input.tracks.slice(0, MAX_TRACKS) : [];
33 if (tracks.length) {
34 out.tracks = tracks.map((t, i) => ({
35 name: str(t?.name, 40) || `Track ${i + 1}`,
36 volume: num(t?.volume, 0, MAX_TRACK_VOLUME, 1),
37 muted: t?.muted === true,
38 solo: t?.solo === true,
39 }));
40 }
41 const clips = input.clips && typeof input.clips === 'object' ? Object.entries(input.clips).slice(0, MAX_CLIPS) : [];
42 for (const [key, c] of clips) {
43 if (typeof key !== 'string' || key.length > MAX_KEY || !c || typeof c !== 'object') continue;
44 const track = Number.isSafeInteger(c.track) ? Math.min(out.tracks.length - 1, Math.max(0, c.track)) : 0;
45 const gain = num(c.gain, 0, MAX_GAIN, 1);
46 if (track === 0 && gain === 1) continue; // default: nothing to keep
47 out.clips[key] = {
48 track,
49 gain,
50 // Descriptive, so the agent can tell which keyframe a clip is.
51 artboard: str(c.artboard, 200),
52 animation: str(c.animation, 200),
53 event: str(c.event, 200),
54 asset: str(c.asset, 200),
55 frame: Number.isSafeInteger(c.frame) && c.frame >= 0 ? c.frame : null,
56 time: num(c.time, 0, 1e7, null),
57 assetVolume: num(c.assetVolume, 0, 100, null),
58 };
59 }
60 return out;
62​
63const db = (g) => (g <= 0 ? '−∞ dB' : `${g >= 1 ? '+' : '−'}${Math.abs(20 * Math.log10(g)).toFixed(1)} dB`);
64const pct = (g) => `${Math.round(g * 100)}%`;
65​
66/** Markdown lines describing the mix, or [] when it is all defaults. */
67export function mixMarkdown(mix) {
68 if (!mix) return [];
69 const clips = Object.values(mix.clips || {});
70 const tracksChanged = mix.tracks.length > 1 || mix.tracks.some((t) => t.volume !== 1 || t.muted || t.solo);
71 if (!clips.length && !tracksChanged) return [];
72 const lines = [
73 '## Audio mix',
74 '',
75 'Set in the preview player; the Rive project is unchanged. In the preview a sound effect plays at',
76 'asset volume × clip gain × track volume (0 if the track is muted or another is soloed). To keep a level, put the product in the asset `volume`',
77 '(per asset) or split the sound into its own asset.',
78 '',
79 '| Track | Volume | State |',
80 '|---|---|---|',
81 ...mix.tracks.map((t, i) => `| ${i + 1}. ${t.name} | ${pct(t.volume)} (${db(t.volume)}) | ${[t.muted && 'muted', t.solo && 'solo'].filter(Boolean).join(', ') || '—'} |`),
82 '',
83 ];
84 if (clips.length) {
85 lines.push('| Sound effect | Where | Track | Clip gain | Asset volume | Plays at |', '|---|---|---|---|---|---|');
86 const anySolo = mix.tracks.some((t) => t.solo);
87 for (const c of clips.sort((a, b) => (a.time ?? 0) - (b.time ?? 0))) {
88 const t = mix.tracks[c.track] ?? mix.tracks[0];
89 const silent = t.muted || (anySolo && !t.solo);
90 const at = silent ? 0 : (c.assetVolume ?? 1) * c.gain * t.volume;
91 const where = [c.animation, c.frame != null ? `frame ${c.frame}` : null].filter(Boolean).join(' · ');
92 lines.push(`| ${c.event ?? '?'} (${c.asset ?? '?'}) | ${where} | ${c.track + 1}. ${t.name} | ${pct(c.gain)} (${db(c.gain)}) | ${+(c.assetVolume ?? 1).toFixed(3)} | ${at.toFixed(3)}${silent ? ' (track silent)' : ''} |`);
93 }
94 lines.push('');
95 }
96 return lines;
98​
99export class MixStore {
100 constructor(target) {
101 this.top = feedbackTop(target);
102 this.file = path.join(feedbackRoot(target), 'mix.json');
103 this.queue = Promise.resolve();
104 }
105​
106 async read() {
107 try {
108 return sanitizeMix(JSON.parse(await readFile(this.file, 'utf8')));
109 } catch {
110 return defaultMix();
111 }
112 }
113​
114 write(input) {
115 const run = this.queue.then(async () => {
116 const mix = sanitizeMix(input);
117 await mkdir(path.dirname(this.file), { recursive: true });
118 const gi = path.join(this.top, '.gitignore');
119 if (!existsSync(gi)) await writeFile(gi, '*\n');
120 const tmp = `${this.file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
121 await writeFile(tmp, JSON.stringify(mix, null, 2) + '\n');
122 await rename(tmp, this.file);
123 return mix;
124 });
125 this.queue = run.catch(() => {});
126 return run;
127 }