@motionhub/runtime 0.2.0 → 0.3.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/README.md +4 -0
- package/package.json +5 -2
- package/sound.d.ts +13 -0
- package/sound.js +172 -0
package/README.md
CHANGED
|
@@ -22,4 +22,8 @@ You do not use this package on its own: an engine binding provides it.
|
|
|
22
22
|
|
|
23
23
|
A component colours with `var(--color-<name>)` and sets type with `var(--font-<name>)`, reads its time from `useTime()`, never from a clock, a timer or `Math.random`, and takes what changes (words, a progress from 0 to 1, a video's `src`) as props. So the same moment draws the same picture every time.
|
|
24
24
|
|
|
25
|
+
## Sound
|
|
26
|
+
|
|
27
|
+
`@motionhub/runtime/sound` synthesises a motion's sound, with no React and no audio API: `renderSound({seconds, cues, sound, rate})` returns mono samples from the motion's `react/sound.json` (a bed at a tempo, and a voice for each role: `land`, `move`, `draw`, `count`, `cut`, `out`) and a list of cues (`[{at, role, dur}]`, a reel's `export const cues`). The same input gives the same samples, so a player plays them and a renderer can write them to a WAV for Remotion's `<Audio>` or a HyperFrames track.
|
|
28
|
+
|
|
25
29
|
An engine binding passes `<MotionRuntimeProvider value>` an object with `useTime` and `useCompositionTime` (hooks returning seconds), `fps`, `width`, `height`, `tokens` (resolved) and, if it plays video, `Video`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@motionhub/runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "What a motion's React components draw with (time, frame, tokens, seeded randomness, video, caption), in any engine that provides it.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -17,12 +17,15 @@
|
|
|
17
17
|
"types": "./index.d.ts",
|
|
18
18
|
"default": "./index.js"
|
|
19
19
|
},
|
|
20
|
-
"./package.json": "./package.json"
|
|
20
|
+
"./package.json": "./package.json",
|
|
21
|
+
"./sound": "./sound.js"
|
|
21
22
|
},
|
|
22
23
|
"files": [
|
|
23
24
|
"index.js",
|
|
24
25
|
"tokens.js",
|
|
26
|
+
"sound.js",
|
|
25
27
|
"index.d.ts",
|
|
28
|
+
"sound.d.ts",
|
|
26
29
|
"README.md"
|
|
27
30
|
],
|
|
28
31
|
"scripts": {
|
package/sound.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export type Role = 'land' | 'move' | 'draw' | 'count' | 'cut' | 'out';
|
|
2
|
+
/** One thing that happens in the picture: when (seconds), what kind, and for how long (a move or a stroke) */
|
|
3
|
+
export type Cue = {at: number; role: Role; dur?: number};
|
|
4
|
+
/** A voice and its settings: `{voice: 'click', lo: 1500, hi: 5000, len: 0.03, gain: 0.7}`; several layer into one sound */
|
|
5
|
+
export type Voice = {voice: string; gain?: number; [setting: string]: unknown};
|
|
6
|
+
/** A motion's react/sound.json */
|
|
7
|
+
export type Sound = {bpm?: number; root?: number; kit?: string[]; bed?: number; roles: Partial<Record<Role, Voice | Voice[]>>};
|
|
8
|
+
export declare const ROLES: Role[];
|
|
9
|
+
export declare const VOICES: string[];
|
|
10
|
+
export declare const KIT: string[];
|
|
11
|
+
/** The sound of `seconds` with `cues` in `sound`, as mono samples at `rate` (44100): the same input gives the same samples */
|
|
12
|
+
export declare function renderSound(options: {seconds: number; cues?: Cue[]; sound: Sound; rate?: number}): Float32Array;
|
|
13
|
+
export declare function soundIssues(sound: unknown): string[];
|
package/sound.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// @motionhub/runtime/sound: a motion's sound, synthesised. A motion describes how its world sounds in react/sound.json (a
|
|
2
|
+
// rhythmic bed and a voice for each kind of thing that happens: something lands, moves, draws, counts, cuts or leaves), and
|
|
3
|
+
// a reel lists when those things happen (`export const cues`). `renderSound` turns the two into samples, the same every time,
|
|
4
|
+
// in any JavaScript engine: a player plays them, a renderer can write them to a file. No React, no Web Audio, no files.
|
|
5
|
+
|
|
6
|
+
/** The roles a cue can have: what happened in the picture */
|
|
7
|
+
export const ROLES = ['land', 'move', 'draw', 'count', 'cut', 'out'];
|
|
8
|
+
/** The voices a role can be drawn with, and the instruments a bed can use */
|
|
9
|
+
export const VOICES = ['click', 'thump', 'tone', 'pluck', 'swish', 'scratch', 'chime', 'marimba', 'square', 'squares', 'swell', 'keys', 'noise'];
|
|
10
|
+
export const KIT = ['kick', 'hat', 'rim', 'bass', 'arp', 'pluck', 'chip', 'pad', 'room'];
|
|
11
|
+
|
|
12
|
+
const mulberry = (seed) => () => {
|
|
13
|
+
seed = (seed + 0x6d2b79f5) >>> 0;
|
|
14
|
+
let t = seed;
|
|
15
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
16
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
17
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** A synthesiser at `rate` samples a second, with its own seeded noise */
|
|
21
|
+
function synth(rate, seed = 7) {
|
|
22
|
+
const rand = mulberry(seed);
|
|
23
|
+
const gauss = () => { let u = 0; while (!u) u = rand(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * rand()); };
|
|
24
|
+
const n = (s) => Math.max(1, Math.round(s * rate));
|
|
25
|
+
|
|
26
|
+
// RBJ biquads, run twice for a steeper slope
|
|
27
|
+
const biquad = (x, type, f) => {
|
|
28
|
+
const w = (2 * Math.PI * Math.min(f, rate * 0.45)) / rate, c = Math.cos(w), a = Math.sin(w) / (2 * Math.SQRT1_2);
|
|
29
|
+
const [b0, b1, b2] = type === 'low' ? [(1 - c) / 2, 1 - c, (1 - c) / 2] : [(1 + c) / 2, -(1 + c), (1 + c) / 2];
|
|
30
|
+
const a0 = 1 + a, a1 = -2 * c, a2 = 1 - a;
|
|
31
|
+
const y = new Float32Array(x.length);
|
|
32
|
+
let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
|
|
33
|
+
for (let i = 0; i < x.length; i++) {
|
|
34
|
+
const v = (b0 * x[i] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2) / a0;
|
|
35
|
+
x2 = x1; x1 = x[i]; y2 = y1; y1 = v; y[i] = v;
|
|
36
|
+
}
|
|
37
|
+
return y;
|
|
38
|
+
};
|
|
39
|
+
const band = (x, lo, hi) => biquad(biquad(biquad(biquad(x, 'high', lo), 'high', lo), 'low', hi), 'low', hi);
|
|
40
|
+
const noise = (s) => Float32Array.from({length: n(s)}, gauss);
|
|
41
|
+
const env = (len, attack = 0.002, decay = 0.2, curve = 4) => Float32Array.from({length: len}, (_, i) => {
|
|
42
|
+
const t = i / rate;
|
|
43
|
+
return Math.min(1, t / Math.max(attack, 1e-4)) * Math.exp((-curve * t) / Math.max(decay, 1e-4));
|
|
44
|
+
});
|
|
45
|
+
const mul = (x, y) => x.map((v, i) => v * (typeof y === 'number' ? y : y[i] ?? 0));
|
|
46
|
+
const shape = (len, f) => Float32Array.from({length: len}, (_, i) => f(i / Math.max(1, len - 1)));
|
|
47
|
+
|
|
48
|
+
const tone = (freq, s, partials = [[1, 1]], decay = 0.6, attack = 0.003, glide = 0) => {
|
|
49
|
+
const len = n(s), out = new Float32Array(len), e = env(len, attack, s * 4, 0);
|
|
50
|
+
let phase = 0;
|
|
51
|
+
for (let i = 0; i < len; i++) {
|
|
52
|
+
const t = i / rate;
|
|
53
|
+
phase += (2 * Math.PI * freq * (1 - glide * Math.min(t / s, 1))) / rate;
|
|
54
|
+
let v = 0;
|
|
55
|
+
for (const [r, g] of partials) v += g * Math.sin(r * phase) * Math.exp((-t * r) / Math.max(decay, 1e-3));
|
|
56
|
+
out[i] = v * e[i];
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
};
|
|
60
|
+
const V = {
|
|
61
|
+
click: ({lo = 2000, hi = 8000, len = 0.025}) => { const x = band(noise(len), lo, hi); return mul(x, env(x.length, 0.0005, len * 0.4)); },
|
|
62
|
+
thump: ({freq = 70, len = 0.35, drop = 0.5}) => tone(freq, len, [[1, 1], [2, 0.15]], len * 0.5, 0.001, drop),
|
|
63
|
+
tone: ({freq = 440, len = 0.2, decay = 0.08, partials = [[1, 1], [2, 0.3]]}) => tone(freq, len, partials, decay, 0.0005),
|
|
64
|
+
pluck: ({freq = 440, len = 0.9, bright = 0.5}) => {
|
|
65
|
+
const len_ = n(len), period = Math.max(2, Math.round(rate / freq)), buf = Float32Array.from({length: period}, () => (rand() * 2 - 1) * bright + (rand() * 2 - 1) * (1 - bright) * 0.3);
|
|
66
|
+
const out = new Float32Array(len_);
|
|
67
|
+
for (let i = 0; i < len_; i++) { const k = i % period; out[i] = buf[k]; buf[k] = 0.4985 * (buf[k] + buf[(k + 1) % period]); }
|
|
68
|
+
return out;
|
|
69
|
+
},
|
|
70
|
+
swish: ({lo = 300, hi = 3000, rise = 0.5}, dur) => { const x = band(noise(Math.max(dur, 0.25)), lo, hi); return mul(x, shape(x.length, (t) => (t < rise ? t / rise : (1 - t) / (1 - rise)) ** 1.6)); },
|
|
71
|
+
scratch: ({lo = 1800, hi = 6000}, dur) => {
|
|
72
|
+
const x = band(noise(Math.max(dur, 0.25)), lo, hi);
|
|
73
|
+
let ph = 0;
|
|
74
|
+
return x.map((v, i) => { ph += (2 * Math.PI * (18 + rand() * 22)) / rate; const t = i / x.length; return v * (0.55 + 0.45 * Math.abs(Math.sin(ph))) * Math.min(1, Math.min(t, 1 - t) * 12); });
|
|
75
|
+
},
|
|
76
|
+
chime: ({freq = 1046, len = 1.2}) => tone(freq, len, [[1, 1], [2.76, 0.4], [5.4, 0.2], [8.9, 0.08]], len * 0.45),
|
|
77
|
+
marimba: ({freq = 392, len = 0.6}) => tone(freq, len, [[1, 1], [4, 0.25], [9.2, 0.06]], len * 0.35, 0.001),
|
|
78
|
+
square: ({freq = 880, len = 0.08}) => { const l = n(len), e = env(l, 0.001, len, 2); return Float32Array.from({length: l}, (_, i) => Math.sign(Math.sin((2 * Math.PI * freq * i) / rate)) * e[i] * 0.5); },
|
|
79
|
+
squares: ({freqs = [440, 554, 659], len = 0.06}) => concat(freqs.map((freq) => V.square({freq, len}))),
|
|
80
|
+
swell: ({freq = 110}, dur) => {
|
|
81
|
+
const s = Math.max(dur, 0.6), l = n(s), ph = [rand(), rand(), rand(), rand()].map((v) => v * 6);
|
|
82
|
+
return Float32Array.from({length: l}, (_, i) => {
|
|
83
|
+
const t = i / rate;
|
|
84
|
+
const v = [[1, 1], [1.5, 0.5], [2, 0.35], [3, 0.12]].reduce((a, [r, g], k) => a + Math.sin(2 * Math.PI * freq * r * t + ph[k]) * g, 0);
|
|
85
|
+
return v * Math.sin(Math.PI * Math.min(t / s, 1)) ** 2;
|
|
86
|
+
});
|
|
87
|
+
},
|
|
88
|
+
keys: (_, dur) => {
|
|
89
|
+
const s = Math.max(dur, 0.2), out = new Float32Array(n(s + 0.1));
|
|
90
|
+
for (let t = 0; t < s; t += 0.07 + rand() * 0.04) { const x = V.click({lo: 2500, hi: 8000, len: 0.018}), at = n(t), g = 0.6 + rand() * 0.4; for (let i = 0; i < x.length && at + i < out.length; i++) out[at + i] += x[i] * g; }
|
|
91
|
+
return out;
|
|
92
|
+
},
|
|
93
|
+
noise: ({lo = 300, hi = 3000, len, fade = 'hit'}, dur) => {
|
|
94
|
+
const s = len ?? Math.max(dur, 0.1), x = band(noise(s), lo, hi);
|
|
95
|
+
return mul(x, fade === 'hit' ? env(x.length, 0.002, s * 0.4) : fade === 'out' ? shape(x.length, (t) => 1 - t) : shape(x.length, (t) => Math.sin(Math.PI * t)));
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
const concat = (parts) => { const out = new Float32Array(parts.reduce((a, p) => a + p.length, 0)); let at = 0; for (const p of parts) { out.set(p, at); at += p.length; } return out; };
|
|
99
|
+
return {V, n, band, noise, env, tone};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const peak = (x) => x.reduce((m, v) => Math.max(m, Math.abs(v)), 1e-9);
|
|
103
|
+
const add = (out, x, at, g) => { for (let i = 0; i < x.length && at + i < out.length; i++) if (at + i >= 0) out[at + i] += x[i] * g; };
|
|
104
|
+
|
|
105
|
+
/** A voice spec (one layer or several) drawn for a cue of `dur` seconds */
|
|
106
|
+
function voice(S, spec, dur) {
|
|
107
|
+
const layers = [].concat(spec);
|
|
108
|
+
const parts = layers.map((l) => { const make = S.V[l.voice]; if (!make) throw new Error(`no voice "${l.voice}": one of ${VOICES.join(', ')}`); const x = make(l, dur); return [x, l.gain ?? 1]; });
|
|
109
|
+
const out = new Float32Array(Math.max(...parts.map(([x]) => x.length)));
|
|
110
|
+
for (const [x, g] of parts) add(out, x, 0, g / peak(x));
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The bed: a pattern at `bpm` over `seconds`, from the instruments in `kit` (KIT), on the note `root` (Hz) */
|
|
115
|
+
function bed(S, rate, seconds, {bpm = 90, root = 147, kit = []}) {
|
|
116
|
+
const out = new Float32Array(Math.ceil((seconds + 1) * rate)), beat = 60 / bpm, scale = [0, 3, 5, 7, 10, 12];
|
|
117
|
+
const put = (x, t, g) => add(out, x, Math.round(t * rate), g);
|
|
118
|
+
const has = (k) => kit.includes(k);
|
|
119
|
+
for (let s = 0; s * beat / 2 < seconds; s++) {
|
|
120
|
+
const t = (s * beat) / 2, on = s % 2 === 0, step = s % 8;
|
|
121
|
+
if (has('kick') && (step === 0 || step === 4)) put(S.V.thump({freq: 55, len: 0.4, drop: 0.6}), t, 0.7);
|
|
122
|
+
if (has('hat') && !on) put(S.V.click({lo: 6000, hi: 14000, len: 0.03}), t, 0.18);
|
|
123
|
+
if (has('rim') && (step === 2 || step === 6)) put(S.V.click({lo: 900, hi: 4000, len: 0.04}), t, 0.35);
|
|
124
|
+
if (has('bass') && step === 0) put(S.tone(root / 2, beat * 3.5, [[1, 1], [2, 0.2]], beat * 3), t, 0.35);
|
|
125
|
+
if (has('arp') && on) put(S.V.marimba({freq: root * 2 ** (scale[(s / 2) % scale.length | 0] / 12) * 2, len: beat}), t, 0.12);
|
|
126
|
+
if (has('pluck') && [0, 3, 6].includes(step)) put(S.V.pluck({freq: root * 2 ** (scale[(s * 5) % scale.length] / 12) * 2, len: beat * 2}), t, 0.2);
|
|
127
|
+
if (has('chip') && on) put(S.V.square({freq: root * 2 ** (scale[(s / 2 | 0) % 4] / 12) * 2, len: beat * 0.4}), t, 0.1);
|
|
128
|
+
}
|
|
129
|
+
if (has('pad')) for (let k = 0; k * beat * 8 < seconds; k++) put(S.V.swell({freq: root * [1, 1.2, 0.84, 1.12][k % 4]}, beat * 8), k * beat * 8, 0.1);
|
|
130
|
+
if (has('room')) put(S.band(S.noise(seconds + 1), 80, 1200), 0, 0.05);
|
|
131
|
+
return out.subarray(0, Math.ceil(seconds * rate));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The sound of `seconds` with `cues` ([{at, role, dur}]) in the motion's `sound` (react/sound.json: {bpm, root, kit, roles: {land: voice, …}}), as
|
|
136
|
+
* mono samples at `rate`: the cues' voices over the bed, faded in and out at the ends, at a steady loudness. The same input gives the same samples.
|
|
137
|
+
*/
|
|
138
|
+
export function renderSound({seconds, cues = [], sound, rate = 44100}) {
|
|
139
|
+
const S = synth(rate);
|
|
140
|
+
const len = Math.ceil(seconds * rate), hits = new Float32Array(len + rate * 4);
|
|
141
|
+
for (const c of cues) {
|
|
142
|
+
const spec = sound.roles?.[c.role];
|
|
143
|
+
if (!spec || c.at >= seconds) continue;
|
|
144
|
+
const x = voice(S, spec, c.dur ?? 0);
|
|
145
|
+
add(hits, x, Math.round(c.at * rate), ({land: 0.8, move: 0.9, draw: 0.8, count: 0.8, cut: 0.6, out: 0.5})[c.role] ?? 0.7);
|
|
146
|
+
}
|
|
147
|
+
const b = bed(S, rate, seconds, sound), h = peak(hits.subarray(0, len)), p = peak(b);
|
|
148
|
+
const out = new Float32Array(len), fadeIn = 0.25 * rate, fadeOut = 1.5 * rate;
|
|
149
|
+
for (let i = 0; i < len; i++) {
|
|
150
|
+
let v = (hits[i] / h) * 0.9 + (b[i] / p) * (sound.bed ?? 0.45);
|
|
151
|
+
if (i < fadeIn) v *= i / fadeIn;
|
|
152
|
+
if (i > len - fadeOut) v *= ((len - i) / fadeOut) ** 2;
|
|
153
|
+
out[i] = Math.tanh(v * 1.2) / Math.tanh(1.2);
|
|
154
|
+
}
|
|
155
|
+
const top = peak(out);
|
|
156
|
+
for (let i = 0; i < len; i++) out[i] *= 0.8 / top;
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** What is wrong with a sound.json, one sentence each */
|
|
161
|
+
export function soundIssues(sound) {
|
|
162
|
+
const issues = [];
|
|
163
|
+
if (!sound || typeof sound !== 'object') return ['sound.json is an object: {bpm, root, kit, roles}'];
|
|
164
|
+
if (sound.bpm !== undefined && !(sound.bpm >= 40 && sound.bpm <= 200)) issues.push('bpm is 40 to 200');
|
|
165
|
+
if (sound.root !== undefined && !(sound.root >= 40 && sound.root <= 2000)) issues.push('root is a note in Hz, 40 to 2000');
|
|
166
|
+
for (const k of [].concat(sound.kit ?? [])) if (!KIT.includes(k)) issues.push(`kit has no "${k}": ${KIT.join(', ')}`);
|
|
167
|
+
for (const [role, spec] of Object.entries(sound.roles ?? {})) {
|
|
168
|
+
if (!ROLES.includes(role)) issues.push(`roles has no "${role}": ${ROLES.join(', ')}`);
|
|
169
|
+
for (const l of [].concat(spec)) if (!VOICES.includes(l?.voice)) issues.push(`${role} has no voice "${l?.voice}": ${VOICES.join(', ')}`);
|
|
170
|
+
}
|
|
171
|
+
return issues;
|
|
172
|
+
}
|