soundroo 0.7.0 → 0.8.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/AGENTS.md +3 -1
- package/README.md +11 -3
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/assets/reverb/hall.wav +0 -0
- package/assets/samples/SOURCES.md +233 -333
- package/assets/samples/samples.json +51856 -363
- package/bin/soundroo.js +25 -3
- package/docs/composing.md +24 -7
- package/docs/headless.md +19 -6
- package/package.json +1 -1
- package/src/arrangement.js +2 -1
- package/src/audio/convolution.js +121 -0
- package/src/audio/library.js +194 -0
- package/src/audio/midi-import.js +174 -0
- package/src/audio/midi.js +27 -4
- package/src/audio/sampler.js +208 -52
- package/src/audio/synth.js +129 -6
- package/src/catalog.js +6 -6
- package/src/cloud/payload.js +2 -1
- package/src/headless.js +37 -9
- package/src/identity.js +14 -4
- package/src/project.js +20 -7
- package/src/render.js +121 -46
- package/src/samples-install.js +103 -0
- package/src/score.js +72 -15
- package/src/timeline.js +50 -0
- package/src/version.js +1 -1
- package/assets/samples/brass/39-1-1.wav +0 -0
- package/assets/samples/brass/41-1-1.wav +0 -0
- package/assets/samples/brass/45-1-1.wav +0 -0
- package/assets/samples/brass/46-1-1.wav +0 -0
- package/assets/samples/brass/50-1-1.wav +0 -0
- package/assets/samples/brass/53-1-1.wav +0 -0
- package/assets/samples/brass/57-1-1.wav +0 -0
- package/assets/samples/brass/60-1-1.wav +0 -0
- package/assets/samples/brass/63-1-1.wav +0 -0
- package/assets/samples/brass/67-1-1.wav +0 -0
- package/assets/samples/brass/70-1-1.wav +0 -0
- package/assets/samples/brass/74-1-1.wav +0 -0
- package/assets/samples/brass/77-1-1.wav +0 -0
- package/assets/samples/brass/81-1-1.wav +0 -0
- package/assets/samples/closed-hat/42-1-1.wav +0 -0
- package/assets/samples/closed-hat/42-1-2.wav +0 -0
- package/assets/samples/closed-hat/42-2-1.wav +0 -0
- package/assets/samples/closed-hat/42-2-2.wav +0 -0
- package/assets/samples/closed-hat/42-3-1.wav +0 -0
- package/assets/samples/closed-hat/42-3-2.wav +0 -0
- package/assets/samples/crash/49-1-1.wav +0 -0
- package/assets/samples/crash/49-2-1.wav +0 -0
- package/assets/samples/electric-bass/24-1-1.wav +0 -0
- package/assets/samples/electric-bass/24-2-1.wav +0 -0
- package/assets/samples/electric-bass/26-1-1.wav +0 -0
- package/assets/samples/electric-bass/26-2-1.wav +0 -0
- package/assets/samples/electric-bass/29-1-1.wav +0 -0
- package/assets/samples/electric-bass/29-2-1.wav +0 -0
- package/assets/samples/electric-bass/32-1-1.wav +0 -0
- package/assets/samples/electric-bass/32-2-1.wav +0 -0
- package/assets/samples/electric-bass/35-1-1.wav +0 -0
- package/assets/samples/electric-bass/35-2-1.wav +0 -0
- package/assets/samples/electric-bass/38-1-1.wav +0 -0
- package/assets/samples/electric-bass/38-2-1.wav +0 -0
- package/assets/samples/electric-bass/41-1-1.wav +0 -0
- package/assets/samples/electric-bass/41-2-1.wav +0 -0
- package/assets/samples/electric-bass/44-1-1.wav +0 -0
- package/assets/samples/electric-bass/44-2-1.wav +0 -0
- package/assets/samples/electric-bass/47-1-1.wav +0 -0
- package/assets/samples/electric-bass/47-2-1.wav +0 -0
- package/assets/samples/electric-bass/50-1-1.wav +0 -0
- package/assets/samples/electric-bass/50-2-1.wav +0 -0
- package/assets/samples/electric-bass/53-1-1.wav +0 -0
- package/assets/samples/electric-bass/53-2-1.wav +0 -0
- package/assets/samples/electric-bass/56-1-1.wav +0 -0
- package/assets/samples/electric-bass/56-2-1.wav +0 -0
- package/assets/samples/electric-bass/59-1-1.wav +0 -0
- package/assets/samples/electric-bass/59-2-1.wav +0 -0
- package/assets/samples/electric-bass/62-1-1.wav +0 -0
- package/assets/samples/electric-bass/62-2-1.wav +0 -0
- package/assets/samples/guitar-clean/40-1-1.wav +0 -0
- package/assets/samples/guitar-clean/41-1-1.wav +0 -0
- package/assets/samples/guitar-clean/45-1-1.wav +0 -0
- package/assets/samples/guitar-clean/48-1-1.wav +0 -0
- package/assets/samples/guitar-clean/50-1-1.wav +0 -0
- package/assets/samples/guitar-clean/52-1-1.wav +0 -0
- package/assets/samples/guitar-clean/55-1-1.wav +0 -0
- package/assets/samples/guitar-clean/59-1-1.wav +0 -0
- package/assets/samples/guitar-clean/61-1-1.wav +0 -0
- package/assets/samples/guitar-clean/64-1-1.wav +0 -0
- package/assets/samples/guitar-clean/67-1-1.wav +0 -0
- package/assets/samples/guitar-clean/71-1-1.wav +0 -0
- package/assets/samples/guitar-clean/72-1-1.wav +0 -0
- package/assets/samples/guitar-clean/74-1-1.wav +0 -0
- package/assets/samples/guitar-clean/77-1-1.wav +0 -0
- package/assets/samples/guitar-clean/80-1-1.wav +0 -0
- package/assets/samples/guitar-clean/82-1-1.wav +0 -0
- package/assets/samples/guitar-clean/85-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/40-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/41-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/45-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/48-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/50-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/52-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/55-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/59-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/61-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/64-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/67-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/71-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/72-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/74-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/77-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/80-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/82-1-1.wav +0 -0
- package/assets/samples/guitar-crunch/85-1-1.wav +0 -0
- package/assets/samples/open-hat/46-1-1.wav +0 -0
- package/assets/samples/open-hat/46-2-1.wav +0 -0
- package/assets/samples/piano/102-1-1.wav +0 -0
- package/assets/samples/piano/102-2-1.wav +0 -0
- package/assets/samples/piano/105-1-1.wav +0 -0
- package/assets/samples/piano/105-2-1.wav +0 -0
- package/assets/samples/piano/108-1-1.wav +0 -0
- package/assets/samples/piano/108-2-1.wav +0 -0
- package/assets/samples/piano/21-1-1.wav +0 -0
- package/assets/samples/piano/21-2-1.wav +0 -0
- package/assets/samples/piano/24-1-1.wav +0 -0
- package/assets/samples/piano/24-2-1.wav +0 -0
- package/assets/samples/piano/27-1-1.wav +0 -0
- package/assets/samples/piano/27-2-1.wav +0 -0
- package/assets/samples/piano/30-1-1.wav +0 -0
- package/assets/samples/piano/30-2-1.wav +0 -0
- package/assets/samples/piano/33-1-1.wav +0 -0
- package/assets/samples/piano/33-2-1.wav +0 -0
- package/assets/samples/piano/36-1-1.wav +0 -0
- package/assets/samples/piano/36-2-1.wav +0 -0
- package/assets/samples/piano/39-1-1.wav +0 -0
- package/assets/samples/piano/39-2-1.wav +0 -0
- package/assets/samples/piano/42-1-1.wav +0 -0
- package/assets/samples/piano/42-2-1.wav +0 -0
- package/assets/samples/piano/45-1-1.wav +0 -0
- package/assets/samples/piano/45-2-1.wav +0 -0
- package/assets/samples/piano/48-1-1.wav +0 -0
- package/assets/samples/piano/48-2-1.wav +0 -0
- package/assets/samples/piano/51-1-1.wav +0 -0
- package/assets/samples/piano/51-2-1.wav +0 -0
- package/assets/samples/piano/54-1-1.wav +0 -0
- package/assets/samples/piano/54-2-1.wav +0 -0
- package/assets/samples/piano/57-1-1.wav +0 -0
- package/assets/samples/piano/57-2-1.wav +0 -0
- package/assets/samples/piano/60-1-1.wav +0 -0
- package/assets/samples/piano/60-2-1.wav +0 -0
- package/assets/samples/piano/63-1-1.wav +0 -0
- package/assets/samples/piano/63-2-1.wav +0 -0
- package/assets/samples/piano/66-1-1.wav +0 -0
- package/assets/samples/piano/66-2-1.wav +0 -0
- package/assets/samples/piano/69-1-1.wav +0 -0
- package/assets/samples/piano/69-2-1.wav +0 -0
- package/assets/samples/piano/72-1-1.wav +0 -0
- package/assets/samples/piano/72-2-1.wav +0 -0
- package/assets/samples/piano/75-1-1.wav +0 -0
- package/assets/samples/piano/75-2-1.wav +0 -0
- package/assets/samples/piano/78-1-1.wav +0 -0
- package/assets/samples/piano/78-2-1.wav +0 -0
- package/assets/samples/piano/81-1-1.wav +0 -0
- package/assets/samples/piano/81-2-1.wav +0 -0
- package/assets/samples/piano/84-1-1.wav +0 -0
- package/assets/samples/piano/84-2-1.wav +0 -0
- package/assets/samples/piano/87-1-1.wav +0 -0
- package/assets/samples/piano/87-2-1.wav +0 -0
- package/assets/samples/piano/90-1-1.wav +0 -0
- package/assets/samples/piano/90-2-1.wav +0 -0
- package/assets/samples/piano/93-1-1.wav +0 -0
- package/assets/samples/piano/93-2-1.wav +0 -0
- package/assets/samples/piano/96-1-1.wav +0 -0
- package/assets/samples/piano/96-2-1.wav +0 -0
- package/assets/samples/piano/99-1-1.wav +0 -0
- package/assets/samples/piano/99-2-1.wav +0 -0
- package/assets/samples/ride/51-1-1.wav +0 -0
- package/assets/samples/ride/51-2-1.wav +0 -0
- package/assets/samples/rock-kick/36-1-1.wav +0 -0
- package/assets/samples/rock-kick/36-1-2.wav +0 -0
- package/assets/samples/rock-kick/36-2-1.wav +0 -0
- package/assets/samples/rock-kick/36-2-2.wav +0 -0
- package/assets/samples/rock-kick/36-3-1.wav +0 -0
- package/assets/samples/rock-kick/36-3-2.wav +0 -0
- package/assets/samples/rock-kick/36-4-1.wav +0 -0
- package/assets/samples/rock-kick/36-4-2.wav +0 -0
- package/assets/samples/rock-snare/38-1-1.wav +0 -0
- package/assets/samples/rock-snare/38-1-2.wav +0 -0
- package/assets/samples/rock-snare/38-2-1.wav +0 -0
- package/assets/samples/rock-snare/38-2-2.wav +0 -0
- package/assets/samples/rock-snare/38-3-1.wav +0 -0
- package/assets/samples/rock-snare/38-3-2.wav +0 -0
- package/assets/samples/rock-snare/38-4-1.wav +0 -0
- package/assets/samples/rock-snare/38-4-2.wav +0 -0
- package/assets/samples/strings/36-1-1.wav +0 -0
- package/assets/samples/strings/40-1-1.wav +0 -0
- package/assets/samples/strings/43-1-1.wav +0 -0
- package/assets/samples/strings/47-1-1.wav +0 -0
- package/assets/samples/strings/50-1-1.wav +0 -0
- package/assets/samples/strings/53-1-1.wav +0 -0
- package/assets/samples/strings/55-1-1.wav +0 -0
- package/assets/samples/strings/59-1-1.wav +0 -0
- package/assets/samples/strings/62-1-1.wav +0 -0
- package/assets/samples/strings/65-1-1.wav +0 -0
- package/assets/samples/strings/69-1-1.wav +0 -0
- package/assets/samples/strings/72-1-1.wav +0 -0
- package/assets/samples/strings/76-1-1.wav +0 -0
- package/assets/samples/strings/79-1-1.wav +0 -0
- package/assets/samples/strings/83-1-1.wav +0 -0
- package/assets/samples/strings/86-1-1.wav +0 -0
- package/assets/samples/tom/41-1-1.wav +0 -0
- package/assets/samples/tom/41-2-1.wav +0 -0
- package/assets/samples/tom/45-1-1.wav +0 -0
- package/assets/samples/tom/45-2-1.wav +0 -0
- package/assets/samples/tom/48-1-1.wav +0 -0
- package/assets/samples/tom/48-2-1.wav +0 -0
- package/assets/samples/tom/50-1-1.wav +0 -0
- package/assets/samples/tom/50-2-1.wav +0 -0
package/src/render.js
CHANGED
|
@@ -2,16 +2,19 @@ import { readFile, realpath, stat } from 'node:fs/promises';
|
|
|
2
2
|
import { resolve, relative, sep } from 'node:path';
|
|
3
3
|
import { setImmediate as yieldTurn } from 'node:timers/promises';
|
|
4
4
|
import { compileScore } from './score.js';
|
|
5
|
+
import { makeTimeline } from './timeline.js';
|
|
5
6
|
import { getCatalog } from './catalog.js';
|
|
6
|
-
import { Synth, Voice, Env, WAVES,
|
|
7
|
+
import { Synth, Voice, Env, WAVES, Compressor, BLOCK } from './audio/synth.js';
|
|
7
8
|
import * as instruments from './audio/instruments.js';
|
|
8
|
-
import {
|
|
9
|
+
import { PianoPlayer, RegionPlayer } from './audio/sampler.js';
|
|
10
|
+
import { SampleLibrary, MissingSamplesError, instrumentPacks, defaultSamplesDir } from './audio/library.js';
|
|
9
11
|
import { mtof } from './audio/dsp.js';
|
|
10
12
|
import { makeRng, hashSeed } from './audio/rng.js';
|
|
11
13
|
import { parseWav, toMono, resample } from './audio/pcm.js';
|
|
12
14
|
import { tapePitch, granularVoice, vocodeVoice, chopVoice, CHOP_PATTERN } from './audio/voice-effects.js';
|
|
13
15
|
import { analyzeAudio, technicalWarnings } from './audio/analysis.js';
|
|
14
16
|
import { masterInPlace } from './audio/master.js';
|
|
17
|
+
import { convolveHall } from './audio/convolution.js';
|
|
15
18
|
import { arrangementSuggestions } from './arrangement.js';
|
|
16
19
|
import { speechAudio } from './speech.js';
|
|
17
20
|
|
|
@@ -19,6 +22,8 @@ export const RENDER_LIMITS = Object.freeze({ minSampleRate: 8000, maxSampleRate:
|
|
|
19
22
|
const presets = new Map(getCatalog().instruments.map(p => [p.id, p]));
|
|
20
23
|
// Every render is matched to the same loudness; a master volume below the default turns it down from there.
|
|
21
24
|
const DEFAULT_MASTER_VOLUME = 0.8;
|
|
25
|
+
// The hall's level at master reverb 1, matched to the Freeverb of engines before 0.8.0.
|
|
26
|
+
const HALL_LEVEL = 0.055;
|
|
22
27
|
const audioBuffer = (channels, sampleRate) => ({ length: channels[0].length, sampleRate, numberOfChannels: channels.length, getChannelData(index) { if (!Number.isInteger(index) || !channels[index]) throw new RangeError('Invalid audio channel.'); return channels[index]; } });
|
|
23
28
|
function bounded(value, min, max, label) {
|
|
24
29
|
if (!Number.isFinite(value) || value < min || value > max) throw new TypeError(`${label} must be a finite number from ${min} to ${max}.`);
|
|
@@ -61,15 +66,6 @@ function sustained(synth, lane, t, pitch, velocity, duration, id, tone, rng) {
|
|
|
61
66
|
synth.add(lane, v);
|
|
62
67
|
}
|
|
63
68
|
|
|
64
|
-
// Instruments played from recordings in assets/samples, with their level next
|
|
65
|
-
// to the synthesized ones. Drums ring out; the others follow the note length.
|
|
66
|
-
const RECORDED = {
|
|
67
|
-
piano: { level: 0.35 }, strings: { level: 0.12 }, brass: { level: 0.27 },
|
|
68
|
-
'electric-bass': { level: 0.76 }, 'guitar-clean': { level: 0.3 }, 'guitar-crunch': { level: 0.83 },
|
|
69
|
-
'rock-kick': { level: 1.23, drum: true }, 'rock-snare': { level: 0.7, drum: true }, 'closed-hat': { level: 0.084, drum: true }, 'open-hat': { level: 0.14, drum: true },
|
|
70
|
-
tom: { level: 0.57, drum: true }, crash: { level: 0.59, drum: true }, ride: { level: 0.42, drum: true },
|
|
71
|
-
};
|
|
72
|
-
|
|
73
69
|
// A score renders with recorded instruments, or with every instrument synthesized as engines before 0.6.0
|
|
74
70
|
// made them. Synthesized parts keep the tone defaults those instruments had then.
|
|
75
71
|
export const SOUNDS = ['recorded', 'synthesized'];
|
|
@@ -79,27 +75,80 @@ const SYNTHESIZED_DEFAULTS = {
|
|
|
79
75
|
};
|
|
80
76
|
const toneDefault = (instrument, name, sound) => (sound === 'synthesized' ? SYNTHESIZED_DEFAULTS[instrument]?.[name] : undefined) ?? presets.get(instrument).controls[name]?.default;
|
|
81
77
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
78
|
+
// Instruments that play from the full recordings in sample packs, with their
|
|
79
|
+
// level next to the synthesized instruments.
|
|
80
|
+
const PACKED = {
|
|
81
|
+
piano: { level: 0.3765 }, strings: { level: 0.1272 }, brass: { level: 0.3477 },
|
|
82
|
+
'electric-bass': { level: 0.7644 }, 'guitar-clean': { level: 0.5619 }, 'guitar-crunch': { level: 1.2169 },
|
|
83
|
+
'rock-kick': { level: 1.3529 }, 'rock-snare': { level: 0.7446 }, 'closed-hat': { level: 0.1489 }, 'open-hat': { level: 0.2317 },
|
|
84
|
+
tom: { level: 0.7757 }, crash: { level: 0.9958 }, ride: { level: 0.5635 },
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
// When a note's damper falls: when the note ends, or, if the sustain pedal is
|
|
88
|
+
// down then, when the pedal comes up. Pedal spans that only touch are a pedal
|
|
89
|
+
// change: the dampers fall between them.
|
|
90
|
+
function damperBeat(part, end) {
|
|
91
|
+
for (const span of part.pedal ?? []) {
|
|
92
|
+
if (span.beat > end) break;
|
|
93
|
+
if (span.beat < end && end <= span.beat + span.beats) return span.beat + span.beats;
|
|
94
|
+
}
|
|
95
|
+
return end;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// The articulation a part's tone controls ask of a recorded note, as engines before 0.8.0 played it.
|
|
99
|
+
function articulation(part, tone, pitch, start, off) {
|
|
86
100
|
const mute = tone.palmMute ?? 0;
|
|
101
|
+
// Palm muting shortens the note and darkens it, as a hand on the strings does.
|
|
87
102
|
const filter = mute > 0.05 ? { type: 'lowpass', freq: 700 + 9000 * (1 - mute) ** 2, q: 0.707 } : null;
|
|
88
103
|
if (part.instrument === 'guitar-crunch') {
|
|
89
104
|
// Overdrive keeps a fading string loud, so a distorted note fades while it is held (release sets how fast;
|
|
90
105
|
// palm muting shortens it) and is damped right after it ends; otherwise the tails of fast riffs pile up
|
|
91
|
-
// into a noisy wash. High notes are turned down, as mixes written for the earlier plucked-string guitar
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
106
|
+
// into a noisy wash. High notes are turned down, as mixes written for the earlier plucked-string guitar expect.
|
|
107
|
+
const decay = Math.max(0.06, tone.release * (1 - mute * 0.88));
|
|
108
|
+
return { off, options: { decay, release: Math.min(0.25, decay * 0.18), filter, tiltDb: -0.35 * (pitch - 57) } };
|
|
109
|
+
}
|
|
110
|
+
const length = off - start;
|
|
111
|
+
return { off: mute ? start + Math.min(length, 0.06 + length * (1 - mute)) : off, options: { release: (tone.release ?? 0.3) * (1 - mute * 0.8), attack: tone.attack ?? 0, doubled: tone.detune ?? 0, filter } };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function schedulePacked(synth, lane, part, timeline, rng, library, end, tone) {
|
|
115
|
+
const level = PACKED[part.instrument].level;
|
|
116
|
+
if (part.instrument !== 'piano') {
|
|
117
|
+
const player = new RegionPlayer(synth, lane, library, part.instrument, { level, rng });
|
|
118
|
+
for (const note of part.notes) {
|
|
119
|
+
const t = timeline.seconds(note.beat);
|
|
120
|
+
if (t >= end) break;
|
|
121
|
+
const off = Math.max(t + 0.005, timeline.seconds(damperBeat(part, note.beat + note.duration)));
|
|
122
|
+
const { off: stop, options } = articulation(part, tone, note.pitch, t, off);
|
|
123
|
+
player.note(t, note.pitch, note.velocity, stop, options);
|
|
124
|
+
}
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const player = new PianoPlayer(synth, lane, library, { level, rng });
|
|
128
|
+
const pedal = [];
|
|
129
|
+
let previousUp = -Infinity;
|
|
130
|
+
for (const span of part.pedal ?? []) {
|
|
131
|
+
const down = Math.max(timeline.seconds(span.beat), previousUp + 0.06), up = timeline.seconds(span.beat + span.beats);
|
|
132
|
+
pedal.push([down, true], [up, false]);
|
|
133
|
+
previousUp = up;
|
|
134
|
+
}
|
|
135
|
+
let p = 0;
|
|
136
|
+
for (const note of part.notes) {
|
|
137
|
+
const t = timeline.seconds(note.beat);
|
|
138
|
+
if (t >= end) break;
|
|
139
|
+
while (p < pedal.length && pedal[p][0] <= t) { player.pedal(...pedal[p]); p++; }
|
|
140
|
+
player.note(t, note.pitch, note.velocity, Math.max(t + 0.005, timeline.seconds(damperBeat(part, note.beat + note.duration))));
|
|
95
141
|
}
|
|
96
|
-
|
|
142
|
+
for (; p < pedal.length; p++) if (pedal[p][0] < end) player.pedal(...pedal[p]);
|
|
143
|
+
player.finish();
|
|
97
144
|
}
|
|
98
145
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
146
|
+
const toneOf = (part, sound) => Object.fromEntries(Object.keys(presets.get(part.instrument).controls).map(name => [name, part.tone[name] ?? toneDefault(part.instrument, name, sound)]));
|
|
147
|
+
|
|
148
|
+
function schedule(synth, lane, note, part, timeline, rng, sound) {
|
|
149
|
+
// The sustain pedal holds synthesized notes too, so both sounds of a track play the same articulation.
|
|
150
|
+
const t = timeline.seconds(note.beat), duration = timeline.seconds(damperBeat(part, note.beat + note.duration)) - t, velocity = note.velocity;
|
|
151
|
+
const tone = toneOf(part, sound);
|
|
103
152
|
const start = synth.pending.length;
|
|
104
153
|
switch (part.instrument) {
|
|
105
154
|
case 'electric-piano': instruments.epiano(synth, lane, t, note.pitch, velocity, duration); break;
|
|
@@ -190,7 +239,7 @@ async function loadSample(sample, sampleRate, bpm, projectDir, speech) {
|
|
|
190
239
|
*/
|
|
191
240
|
export async function renderScore(score, options = {}) {
|
|
192
241
|
const { from = 0, to } = options;
|
|
193
|
-
const compiled = compileScore(score), total = compiled.
|
|
242
|
+
const compiled = compileScore(score), total = makeTimeline(compiled).duration;
|
|
194
243
|
if (from === 0 && (to === undefined || to === total)) return renderRange(score, options);
|
|
195
244
|
// An excerpt plays at the level of the whole track: render it all, master it once, then cut the excerpt.
|
|
196
245
|
bounded(from, 0, total, 'from');
|
|
@@ -206,12 +255,21 @@ export async function renderScore(score, options = {}) {
|
|
|
206
255
|
return { ...full, audio, report, ...(full.stems ? { stems: Object.fromEntries(Object.entries(full.stems).map(([id, stem]) => [id, cut(stem)])) } : {}) };
|
|
207
256
|
}
|
|
208
257
|
|
|
209
|
-
async function renderRange(score,
|
|
258
|
+
async function renderRange(score, options = {}) {
|
|
259
|
+
const library = new SampleLibrary(options.samplesDir ?? defaultSamplesDir());
|
|
260
|
+
try {
|
|
261
|
+
return await renderWith(score, options, library);
|
|
262
|
+
} finally {
|
|
263
|
+
library.close();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function renderWith(score, { sampleRate = 44100, mix = {}, projectDir, stems = false, from = 0, to, progress, signal, speech, sound = 'recorded' } = {}, library) {
|
|
210
268
|
if (!SOUNDS.includes(sound)) throw new TypeError(`sound must be one of: ${SOUNDS.join(', ')}.`);
|
|
211
269
|
const expandedScore = compileScore(score);
|
|
212
270
|
bounded(sampleRate, RENDER_LIMITS.minSampleRate, RENDER_LIMITS.maxSampleRate, 'sampleRate');
|
|
213
271
|
if (!Number.isInteger(sampleRate)) throw new TypeError('sampleRate must be an integer.');
|
|
214
|
-
const
|
|
272
|
+
const timeline = makeTimeline(expandedScore), duration = timeline.duration;
|
|
215
273
|
bounded(from, 0, duration, 'from');
|
|
216
274
|
bounded(to ?? duration, 0, duration, 'to');
|
|
217
275
|
const end = to ?? duration;
|
|
@@ -224,6 +282,10 @@ async function renderRange(score, { sampleRate = 44100, mix = {}, projectDir, st
|
|
|
224
282
|
};
|
|
225
283
|
check('preparing', 0);
|
|
226
284
|
const controls = mixControls(expandedScore, mix);
|
|
285
|
+
if (sound === 'recorded') {
|
|
286
|
+
const missing = library.missing(controls.parts.filter(part => part.audible && part.notes.length && PACKED[part.instrument]).flatMap(part => instrumentPacks(part.instrument)));
|
|
287
|
+
if (missing.length) throw new MissingSamplesError(missing, library.dir);
|
|
288
|
+
}
|
|
227
289
|
const firstFrame = Math.round(from * sampleRate), lastFrame = Math.round(end * sampleRate);
|
|
228
290
|
if (lastFrame <= firstFrame) throw new RangeError('Render range must contain at least one sample.');
|
|
229
291
|
const frames = lastFrame - firstFrame;
|
|
@@ -236,18 +298,27 @@ async function renderRange(score, { sampleRate = 44100, mix = {}, projectDir, st
|
|
|
236
298
|
const cutoff = part.tone.brightness ?? toneDefault(part.instrument, 'brightness', sound);
|
|
237
299
|
const noiseHats = sound === 'synthesized' ? ['hi-hat', 'shaker', 'open-hat', 'closed-hat'] : ['hi-hat', 'shaker'];
|
|
238
300
|
const filter = noiseHats.includes(part.instrument) ? { type: 'highpass', freq: 6500 } : part.instrument === 'clap' || part.instrument === 'snare' ? { type: 'bandpass', freq: 1800, q: 0.7 } : cutoff ? { type: 'lowpass', freq: cutoff } : null;
|
|
239
|
-
const
|
|
301
|
+
const packed = sound === 'recorded' && PACKED[part.instrument];
|
|
302
|
+
// Recordings from packs keep their stereo picture (the crunch guitar's direct signal is mono and goes
|
|
303
|
+
// through the overdrive); the brightness control only filters when set below its top.
|
|
304
|
+
const laneFilter = packed ? (cutoff && cutoff < 20000 ? { type: 'lowpass', freq: cutoff } : null) : filter;
|
|
305
|
+
const lane = synth.lane({ stereo: !!packed && part.instrument !== 'guitar-crunch', gain: part.volume, pan: part.pan, filter: laneFilter, overdrive: part.instrument === 'guitar-crunch' ? (part.tone.drive ?? 0.7) : null });
|
|
240
306
|
const rng = makeRng(hashSeed(expandedScore.seed, part.id));
|
|
241
307
|
let sample, events;
|
|
242
308
|
if (part.instrument === 'sample') {
|
|
243
|
-
sample = await loadSample(part.sample, sampleRate,
|
|
244
|
-
events = part.notes.filter(n => n.beat
|
|
245
|
-
} else
|
|
309
|
+
sample = await loadSample(part.sample, sampleRate, timeline.tempoAt(0), projectDir, speech);
|
|
310
|
+
events = part.notes.filter(n => timeline.seconds(n.beat) < end).map(n => ({ start: Math.round(timeline.seconds(n.beat) * sampleRate), length: Math.min(sample.length, Math.round((timeline.seconds(n.beat + n.duration) - timeline.seconds(n.beat)) * sampleRate)), velocity: n.velocity }));
|
|
311
|
+
} else if (packed) schedulePacked(synth, lane, part, timeline, rng, library, end, toneOf(part, sound));
|
|
312
|
+
else for (const note of part.notes) if (timeline.seconds(note.beat) < end) schedule(synth, lane, note, part, timeline, rng, sound);
|
|
246
313
|
buses.push({ part, synth, sample, events, next: 0, active: [], left: new Float32Array(BLOCK), right: new Float32Array(BLOCK) });
|
|
247
314
|
check('preparing', 0);
|
|
248
315
|
}
|
|
249
|
-
|
|
250
|
-
const
|
|
316
|
+
// Band music gets a gentle glue compressor; music without drums (piano, strings, ambient) keeps its full dynamics.
|
|
317
|
+
const banded = controls.parts.some(part => part.audible && part.notes.length && presets.get(part.instrument).drums);
|
|
318
|
+
const compressor = banded ? new Compressor(sampleRate, { threshold: -12, ratio: 2, knee: 6, makeupDb: 0 }) : null;
|
|
319
|
+
// The whole dry mix and reverb send first; the hall is convolved over the whole send afterwards.
|
|
320
|
+
const dry = firstFrame === 0 ? channels : [new Float32Array(lastFrame), new Float32Array(lastFrame)];
|
|
321
|
+
const sendAll = new Float32Array(lastFrame);
|
|
251
322
|
const left = new Float32Array(BLOCK), right = new Float32Array(BLOCK), send = new Float32Array(BLOCK);
|
|
252
323
|
for (let offset = 0; offset < lastFrame; offset += BLOCK) {
|
|
253
324
|
const count = Math.min(BLOCK, lastFrame - offset);
|
|
@@ -281,24 +352,28 @@ async function renderRange(score, { sampleRate = 44100, mix = {}, projectDir, st
|
|
|
281
352
|
}
|
|
282
353
|
}
|
|
283
354
|
}
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
const frame = offset + i - firstFrame;
|
|
288
|
-
if (frame < 0) continue;
|
|
289
|
-
// File edges follow the complete musical timeline, not an excerpt boundary.
|
|
290
|
-
const time = (offset + i) / sampleRate;
|
|
291
|
-
const fade = Math.max(0, Math.min(1, time / 0.004, (duration - time - 1 / sampleRate) / 0.04));
|
|
292
|
-
channels[0][frame] = left[i] * fade;
|
|
293
|
-
channels[1][frame] = right[i] * fade;
|
|
294
|
-
}
|
|
355
|
+
dry[0].set(left.subarray(0, count), offset);
|
|
356
|
+
dry[1].set(right.subarray(0, count), offset);
|
|
357
|
+
sendAll.set(send.subarray(0, count), offset);
|
|
295
358
|
if (offset % (BLOCK * 64) === 0) { check('rendering', Math.min(end, (offset + count) / sampleRate)); await yieldTurn(); }
|
|
296
359
|
}
|
|
360
|
+
convolveHall(sendAll, dry, sampleRate, expandedScore.master.reverb * HALL_LEVEL);
|
|
361
|
+
for (let offset = 0; compressor && offset < lastFrame; offset += BLOCK) {
|
|
362
|
+
const count = Math.min(BLOCK, lastFrame - offset);
|
|
363
|
+
compressor.process(dry[0].subarray(offset, offset + count), dry[1].subarray(offset, offset + count), count);
|
|
364
|
+
}
|
|
365
|
+
for (let frame = Math.max(0, firstFrame); frame < lastFrame; frame++) {
|
|
366
|
+
// File edges follow the complete musical timeline, not an excerpt boundary.
|
|
367
|
+
const time = frame / sampleRate;
|
|
368
|
+
const fade = Math.max(0, Math.min(1, time / 0.004, (duration - time - 1 / sampleRate) / 0.04));
|
|
369
|
+
channels[0][frame - firstFrame] = dry[0][frame] * fade;
|
|
370
|
+
channels[1][frame - firstFrame] = dry[1][frame] * fade;
|
|
371
|
+
}
|
|
297
372
|
const mastered = masterInPlace(channels, sampleRate, { volume: controls.volume / DEFAULT_MASTER_VOLUME });
|
|
298
373
|
const report = analyzeAudio(channels, sampleRate);
|
|
299
374
|
report.from = from;
|
|
300
375
|
report.to = end;
|
|
301
|
-
report.sections = expandedScore.sections.map(s => ({ ...s, time: s.beat
|
|
376
|
+
report.sections = expandedScore.sections.map(s => ({ ...s, time: timeline.seconds(s.beat), duration: timeline.seconds(s.beat + s.beats) - timeline.seconds(s.beat) }));
|
|
302
377
|
report.sound = sound;
|
|
303
378
|
report.suggestions = arrangementSuggestions(expandedScore);
|
|
304
379
|
report.loudness = mastered.loudness;
|
|
@@ -306,7 +381,7 @@ async function renderRange(score, { sampleRate = 44100, mix = {}, projectDir, st
|
|
|
306
381
|
report.limitedFraction = mastered.limited;
|
|
307
382
|
report.warnings = technicalWarnings(report);
|
|
308
383
|
if (report.limitedFraction > 0.01) report.warnings.push({ code: 'squashed', message: 'The limiter turns more than 1% of the track down by over 3 dB, so loud moments sound squashed. Lower the loudest parts, usually drums or bass, and render again.' });
|
|
309
|
-
report.stemDescription = 'Dry stereo buses after part volume, pan and mute/solo, before the shared master reverb, compression, loudness matching and limiter. They do not sum to the mastered render.';
|
|
384
|
+
report.stemDescription = 'Dry stereo buses after part volume, pan and mute/solo, before the shared master reverb, compression (only in music with drums), loudness matching and limiter. They do not sum to the mastered render.';
|
|
310
385
|
check('complete', end);
|
|
311
386
|
return { audio: audioBuffer(channels, sampleRate), report, parts: expandedScore.parts.map(({ id, name, color }) => ({ id, name, color })), ...(stemBuffers ? { stems: Object.fromEntries(Object.entries(stemBuffers).map(([id, data]) => [id, audioBuffer(data, sampleRate)])) } : {}), expandedScore };
|
|
312
387
|
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// Installs the sample packs of the recorded instruments (audio/library.js).
|
|
2
|
+
// Each pack is downloaded once from the toolkit's GitHub release into the
|
|
3
|
+
// samples folder, resumes where an interrupted download stopped, and is kept
|
|
4
|
+
// only when its size and SHA-256 match assets/samples/samples.json. Nothing is
|
|
5
|
+
// uploaded; the request carries no information about the music.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import crypto from 'node:crypto';
|
|
9
|
+
import { compileScore } from './score.js';
|
|
10
|
+
import { sampleManifest, packFileName, instrumentPacks, defaultSamplesDir } from './audio/library.js';
|
|
11
|
+
|
|
12
|
+
/** Every pack: {name, file, size, installed}. */
|
|
13
|
+
export function samplesStatus({ samplesDir = defaultSamplesDir() } = {}) {
|
|
14
|
+
return Object.entries(sampleManifest().packs).sort(([a], [b]) => a.localeCompare(b)).map(([name, pack]) => {
|
|
15
|
+
const file = path.join(samplesDir, packFileName(name));
|
|
16
|
+
let installed = false;
|
|
17
|
+
try { installed = fs.statSync(file).size === pack.size; } catch { /* not installed */ }
|
|
18
|
+
return { name, file, size: pack.size, installed, instruments: Object.entries(sampleManifest().instruments).filter(([, spec]) => spec.pack === name).map(([id]) => id).sort() };
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The packs a score's recorded instruments play from. */
|
|
23
|
+
export function scorePacks(score) {
|
|
24
|
+
const compiled = compileScore(score);
|
|
25
|
+
return [...new Set(compiled.parts.filter(part => part.notes.length && part.volume > 0).flatMap(part => instrumentPacks(part.instrument)))].sort();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function packUrl(name, env) {
|
|
29
|
+
const base = env.SOUNDROO_SAMPLES_URL;
|
|
30
|
+
if (base) return `${base.replace(/\/+$/, '')}/${packFileName(name)}`;
|
|
31
|
+
const url = sampleManifest().packs[name].url;
|
|
32
|
+
if (!url) throw new Error(`No download address is known for the ${name} recordings.`);
|
|
33
|
+
return url;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function hashFile(file, hash) {
|
|
37
|
+
for await (const chunk of fs.createReadStream(file)) hash.update(chunk);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function download(name, { samplesDir, fetchImpl, log, signal, env }) {
|
|
41
|
+
const pack = sampleManifest().packs[name];
|
|
42
|
+
const file = path.join(samplesDir, packFileName(name)), part = `${file}.part`;
|
|
43
|
+
fs.mkdirSync(samplesDir, { recursive: true });
|
|
44
|
+
let have = 0;
|
|
45
|
+
try { have = fs.statSync(part).size; } catch { /* a fresh download */ }
|
|
46
|
+
if (have > pack.size) { fs.rmSync(part); have = 0; }
|
|
47
|
+
let hash = crypto.createHash('sha256');
|
|
48
|
+
if (have) await hashFile(part, hash);
|
|
49
|
+
const url = packUrl(name, env);
|
|
50
|
+
let lastReport = 0;
|
|
51
|
+
const report = done => {
|
|
52
|
+
const now = Date.now();
|
|
53
|
+
if (done === pack.size || now - lastReport > 2000) {
|
|
54
|
+
lastReport = now;
|
|
55
|
+
log?.(`Downloading the ${name} recordings: ${(done / 1e6).toFixed(0)} of ${(pack.size / 1e6).toFixed(0)} MB`);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
if (have < pack.size) {
|
|
59
|
+
const response = await fetchImpl(url, { headers: have ? { Range: `bytes=${have}-` } : {}, redirect: 'follow', signal });
|
|
60
|
+
if (have && response.status !== 206) {
|
|
61
|
+
// The server sent the whole file; start over.
|
|
62
|
+
have = 0;
|
|
63
|
+
hash = crypto.createHash('sha256');
|
|
64
|
+
}
|
|
65
|
+
if (response.status !== 200 && response.status !== 206) throw new Error(`Downloading the ${name} recordings failed: HTTP ${response.status} from ${url}.`);
|
|
66
|
+
const out = fs.createWriteStream(part, { flags: have ? 'a' : 'w' });
|
|
67
|
+
try {
|
|
68
|
+
for await (const chunk of response.body) {
|
|
69
|
+
if (have + chunk.length > pack.size) throw new Error(`The ${name} download is larger than expected; refusing it.`);
|
|
70
|
+
hash.update(chunk);
|
|
71
|
+
have += chunk.length;
|
|
72
|
+
if (!out.write(chunk)) await new Promise(resolve => out.once('drain', resolve));
|
|
73
|
+
report(have);
|
|
74
|
+
}
|
|
75
|
+
} finally {
|
|
76
|
+
await new Promise(resolve => out.end(resolve));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const digest = hash.digest('hex');
|
|
80
|
+
if (have !== pack.size || digest !== pack.sha256) {
|
|
81
|
+
fs.rmSync(part, { force: true });
|
|
82
|
+
throw new Error(`The ${name} recordings did not download intact (expected ${pack.size} bytes, SHA-256 ${pack.sha256.slice(0, 16)}…). Try again.`);
|
|
83
|
+
}
|
|
84
|
+
fs.renameSync(part, file);
|
|
85
|
+
return file;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Downloads the named packs that are missing. Options: samplesDir, log,
|
|
89
|
+
* signal, fetchImpl, env. Returns the status of those packs. */
|
|
90
|
+
export async function installPacks(names, { samplesDir = defaultSamplesDir(), log, signal, fetchImpl = globalThis.fetch, env = process.env } = {}) {
|
|
91
|
+
const wanted = [...new Set(names)];
|
|
92
|
+
for (const name of wanted) if (!sampleManifest().packs[name]) throw new Error(`Unknown sample pack ${name}. Packs: ${Object.keys(sampleManifest().packs).sort().join(', ')}.`);
|
|
93
|
+
const missing = samplesStatus({ samplesDir }).filter(pack => wanted.includes(pack.name) && !pack.installed);
|
|
94
|
+
if (missing.length && (env.SOUNDROO_OFFLINE === '1')) throw Object.assign(new Error(`The recorded instruments ${missing.map(p => p.name).join(', ')} are not installed and SOUNDROO_OFFLINE is set.`), { code: 'samples_missing' });
|
|
95
|
+
if (missing.length) log?.(`Downloading the recorded instruments once (${(missing.reduce((sum, p) => sum + p.size, 0) / 1e9).toFixed(1)} GB) into ${samplesDir}.`);
|
|
96
|
+
for (const pack of missing) await download(pack.name, { samplesDir, fetchImpl, log, signal, env });
|
|
97
|
+
return samplesStatus({ samplesDir }).filter(pack => wanted.includes(pack.name));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Installs the packs a score needs before it renders with recorded instruments. */
|
|
101
|
+
export async function prepareSamples(score, options = {}) {
|
|
102
|
+
return installPacks(scorePacks(score), options);
|
|
103
|
+
}
|
package/src/score.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { getCatalog, SAMPLE_ASSETS, SAMPLE_EFFECTS, SCORE_LIMITS, SPEECH_VOICES, DEFAULT_SPEECH_VOICE } from './catalog.js';
|
|
2
2
|
import { parsePitch, parseLine, parseSteps } from './notation.js';
|
|
3
|
+
import { makeTimeline } from './timeline.js';
|
|
3
4
|
|
|
4
5
|
export { parsePitch };
|
|
5
|
-
export const SCORE_VERSIONS = Object.freeze([1, 2]);
|
|
6
|
+
export const SCORE_VERSIONS = Object.freeze([1, 2, 3]);
|
|
6
7
|
const slug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
7
8
|
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
8
9
|
const instruments = new Map(getCatalog().instruments.map(item => [item.id, item]));
|
|
@@ -10,9 +11,10 @@ const instruments = new Map(getCatalog().instruments.map(item => [item.id, item]
|
|
|
10
11
|
// Speech text is compared and cached after collapsing whitespace.
|
|
11
12
|
export function speechText(text) { return text.trim().replace(/\s+/g, ' '); }
|
|
12
13
|
|
|
13
|
-
// Version 2 adds pattern strings (see notation.js).
|
|
14
|
-
//
|
|
15
|
-
//
|
|
14
|
+
// Version 2 adds pattern strings (see notation.js). Version 3 adds tempo
|
|
15
|
+
// changes and the sustain pedal (see timeline.js). Every version compiles to
|
|
16
|
+
// the same ordinary note lists; older engines refuse a newer version instead
|
|
17
|
+
// of silently dropping what it describes.
|
|
16
18
|
function normalize(score) {
|
|
17
19
|
const issues = [];
|
|
18
20
|
const issue = (path, message) => issues.push({ path, message });
|
|
@@ -31,11 +33,32 @@ function normalize(score) {
|
|
|
31
33
|
return value;
|
|
32
34
|
};
|
|
33
35
|
if (!object(score)) return { issues: [{ path: '$', message: 'Expected a score object.' }] };
|
|
34
|
-
if (!SCORE_VERSIONS.includes(score.version)) issue('version', 'Use score version 1,
|
|
35
|
-
const compact = score.version === 2;
|
|
36
|
+
if (!SCORE_VERSIONS.includes(score.version)) issue('version', 'Use score version 1, version 2 for pattern strings, or version 3 for those plus tempo changes and the sustain pedal.');
|
|
37
|
+
const compact = score.version === 2 || score.version === 3;
|
|
38
|
+
const expressive = score.version === 3;
|
|
36
39
|
const bpm = number(score.bpm, 'bpm', 20, 400);
|
|
37
|
-
const beats = number(score.beats, 'beats', 0, SCORE_LIMITS.maxSeconds *
|
|
38
|
-
const out = { version: 1, id: id(score.id, 'id'), title: text(score.title, 'title'), description: text(score.description, 'description'), genre: text(score.genre, 'genre'), mood: text(score.mood, 'mood'), key: text(score.key, 'key'), bpm, beats, seed: number(score.seed, 'seed', 0, 0xffffffff, 1), master: {}, sections: [], parts: [] };
|
|
40
|
+
const beats = number(score.beats, 'beats', 0, SCORE_LIMITS.maxSeconds * 400 / 60, undefined, true);
|
|
41
|
+
const out = { version: 1, id: id(score.id, 'id'), title: text(score.title, 'title'), description: text(score.description, 'description'), genre: text(score.genre, 'genre'), mood: text(score.mood, 'mood'), key: text(score.key, 'key'), bpm, beats, tempo: [], seed: number(score.seed, 'seed', 0, 0xffffffff, 1), master: {}, sections: [], parts: [] };
|
|
42
|
+
// An empty tempo list or pedal list changes nothing, so any version may carry one (compiled scores do).
|
|
43
|
+
if (score.tempo !== undefined && !(Array.isArray(score.tempo) && !score.tempo.length)) {
|
|
44
|
+
if (!expressive) issue('tempo', 'Tempo changes need score version 3.');
|
|
45
|
+
else if (!Array.isArray(score.tempo) || score.tempo.length > SCORE_LIMITS.maxTempoChanges) issue('tempo', `Expected an array of up to ${SCORE_LIMITS.maxTempoChanges} tempo changes {beat, bpm, ramp}.`);
|
|
46
|
+
else {
|
|
47
|
+
let previous = 0;
|
|
48
|
+
for (const [i, change] of score.tempo.entries()) {
|
|
49
|
+
const path = `tempo[${i}]`;
|
|
50
|
+
if (!object(change)) { issue(path, 'Expected a tempo change {beat, bpm, ramp}.'); continue; }
|
|
51
|
+
for (const key of Object.keys(change)) if (!['beat', 'bpm', 'ramp'].includes(key)) issue(`${path}.${key}`, 'A tempo change has beat, bpm and an optional ramp.');
|
|
52
|
+
const at = number(change.beat, `${path}.beat`, 0, beats, undefined, true);
|
|
53
|
+
if (at <= previous) issue(`${path}.beat`, 'Tempo changes need increasing beats after beat 0; the score\'s bpm sets the tempo at beat 0.');
|
|
54
|
+
previous = Math.max(previous, at);
|
|
55
|
+
if (change.ramp !== undefined && typeof change.ramp !== 'boolean') issue(`${path}.ramp`, 'ramp is true (glide to this tempo) or false (change at this beat).');
|
|
56
|
+
out.tempo.push({ beat: at, bpm: number(change.bpm, `${path}.bpm`, 20, 400), ramp: change.ramp === true });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const timeline = makeTimeline(out);
|
|
61
|
+
if (Number.isFinite(beats) && Number.isFinite(timeline.duration) && timeline.duration > SCORE_LIMITS.maxSeconds + 1e-6) issue('beats', `The score lasts ${Math.round(timeline.duration)} seconds; scores can last up to ${SCORE_LIMITS.maxSeconds / 60} minutes.`);
|
|
39
62
|
if (!out.title.trim()) issue('title', 'A score needs a title.');
|
|
40
63
|
if (!Number.isInteger(out.seed)) issue('seed', 'Expected an integer seed.');
|
|
41
64
|
const master = score.master ?? {};
|
|
@@ -77,6 +100,20 @@ function normalize(score) {
|
|
|
77
100
|
return [{ pitch, beat, duration, velocity }];
|
|
78
101
|
});
|
|
79
102
|
};
|
|
103
|
+
// Sustain pedal: {beat, beats} spans in which the pedal is down (score version 3).
|
|
104
|
+
const pedalSpans = (list, path, end) => {
|
|
105
|
+
if (list === undefined || (Array.isArray(list) && !list.length)) return [];
|
|
106
|
+
if (!expressive) { issue(path, 'The sustain pedal needs score version 3.'); return []; }
|
|
107
|
+
if (!Array.isArray(list) || list.length > SCORE_LIMITS.maxPedalSpans) { issue(path, `Expected an array of up to ${SCORE_LIMITS.maxPedalSpans} pedal spans {beat, beats}.`); return []; }
|
|
108
|
+
return list.flatMap((span, i) => {
|
|
109
|
+
const p = `${path}[${i}]`;
|
|
110
|
+
if (!object(span)) { issue(p, 'Expected a pedal span {beat, beats}.'); return []; }
|
|
111
|
+
for (const key of Object.keys(span)) if (key !== 'beat' && key !== 'beats') issue(`${p}.${key}`, 'A pedal span has beat and beats.');
|
|
112
|
+
const at = number(span.beat, `${p}.beat`, 0, end), length = number(span.beats, `${p}.beats`, 0, end, undefined, true);
|
|
113
|
+
if (at + length > end + 1e-8) issue(p, 'Pedal span extends past its score or pattern ending.');
|
|
114
|
+
return [{ beat: at, beats: length }];
|
|
115
|
+
});
|
|
116
|
+
};
|
|
80
117
|
const strings = (pattern, path, end) => {
|
|
81
118
|
const fields = ['line', 'steps'].filter(field => pattern[field] !== undefined);
|
|
82
119
|
if (!compact) { for (const field of fields) issue(`${path}.${field}`, 'Pattern strings need score version 2.'); return []; }
|
|
@@ -113,7 +150,7 @@ function normalize(score) {
|
|
|
113
150
|
if (!object(part)) { issue(path, 'Expected a part object.'); continue; }
|
|
114
151
|
const preset = instruments.get(part.instrument);
|
|
115
152
|
if (!preset) issue(`${path}.instrument`, 'Unknown instrument. Use getCatalog() to discover presets.');
|
|
116
|
-
const p = { id: id(part.id, `${path}.id`), name: text(part.name, `${path}.name`, part.id), instrument: part.instrument, volume: number(part.volume, `${path}.volume`, 0, 2, 1), pan: number(part.pan, `${path}.pan`, -1, 1, 0), color: text(part.color, `${path}.color`, '#8aaea0'), tone: {}, notes: notes(part.notes, `${path}.notes`, beats) };
|
|
153
|
+
const p = { id: id(part.id, `${path}.id`), name: text(part.name, `${path}.name`, part.id), instrument: part.instrument, volume: number(part.volume, `${path}.volume`, 0, 2, 1), pan: number(part.pan, `${path}.pan`, -1, 1, 0), color: text(part.color, `${path}.color`, '#8aaea0'), tone: {}, notes: notes(part.notes, `${path}.notes`, beats), pedal: pedalSpans(part.pedal, `${path}.pedal`, beats) };
|
|
117
154
|
if (partIds.has(part.id)) issue(`${path}.id`, 'Part IDs must be unique.');
|
|
118
155
|
partIds.add(part.id);
|
|
119
156
|
for (const field of ['line', 'steps']) if (part[field] !== undefined) issue(`${path}.${field}`, 'Put line and steps strings in a named pattern (score version 2), then place it with a clip.');
|
|
@@ -135,7 +172,7 @@ function normalize(score) {
|
|
|
135
172
|
const length = number(pattern.beats, `${pp}.beats`, 0, beats, undefined, true);
|
|
136
173
|
const patternNotes = notes(pattern.notes, `${pp}.notes`, length);
|
|
137
174
|
patternNotes.push(...strings(pattern, pp, length));
|
|
138
|
-
patternMap.set(name, { beats: length, notes: patternNotes });
|
|
175
|
+
patternMap.set(name, { beats: length, notes: patternNotes, pedal: pedalSpans(pattern.pedal, `${pp}.pedal`, length) });
|
|
139
176
|
}
|
|
140
177
|
}
|
|
141
178
|
const clips = part.clips ?? [];
|
|
@@ -154,16 +191,21 @@ function normalize(score) {
|
|
|
154
191
|
if (!Number.isInteger(transpose)) issue(`${cp}.transpose`, 'Expected an integer semitone transposition.');
|
|
155
192
|
if (beat + pattern.beats * repeat > beats + 1e-8) issue(cp, 'Clip extends past the score ending.');
|
|
156
193
|
if (eventCount + p.notes.length + pattern.notes.length * repeat > SCORE_LIMITS.maxEvents) { issue(cp, 'Expanded score exceeds 100000 events.'); continue; }
|
|
157
|
-
for (let r = 0; r < repeat; r++)
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
194
|
+
for (let r = 0; r < repeat; r++) {
|
|
195
|
+
for (const n of pattern.notes) {
|
|
196
|
+
const expanded = { ...n, pitch: n.pitch + transpose, beat: beat + r * pattern.beats + n.beat, velocity: n.velocity * velocity };
|
|
197
|
+
if (expanded.pitch < 0 || expanded.pitch > 127) issue(cp, 'Transposed pitch falls outside MIDI 0–127.');
|
|
198
|
+
if (expanded.velocity > 1) issue(cp, 'Scaled note velocity exceeds 1.');
|
|
199
|
+
p.notes.push(expanded);
|
|
200
|
+
}
|
|
201
|
+
for (const span of pattern.pedal) p.pedal.push({ beat: beat + r * pattern.beats + span.beat, beats: span.beats });
|
|
162
202
|
}
|
|
163
203
|
}
|
|
164
204
|
eventCount += p.notes.length;
|
|
165
205
|
if (eventCount > SCORE_LIMITS.maxEvents) issue(`${path}.notes`, 'Expanded score exceeds 100000 events.');
|
|
166
206
|
p.notes.sort((a, b) => a.beat - b.beat || a.pitch - b.pitch);
|
|
207
|
+
p.pedal = mergePedal(p.pedal);
|
|
208
|
+
if (p.pedal.length > SCORE_LIMITS.maxPedalSpans) issue(`${path}.pedal`, `Use at most ${SCORE_LIMITS.maxPedalSpans} pedal spans per part, including clips.`);
|
|
167
209
|
if (part.instrument === 'sample') {
|
|
168
210
|
const sample = part.sample;
|
|
169
211
|
if (!object(sample)) issue(`${path}.sample`, 'Sample parts need a sample configuration.');
|
|
@@ -192,9 +234,24 @@ function normalize(score) {
|
|
|
192
234
|
} else if (part.sample !== undefined) issue(`${path}.sample`, 'Sample configuration requires the sample instrument.');
|
|
193
235
|
out.parts.push(p);
|
|
194
236
|
}
|
|
237
|
+
// The compiled score says version 3 only when it uses tempo changes or the pedal, so it compiles again as itself.
|
|
238
|
+
if (out.tempo.length || out.parts.some(part => part.pedal.length)) out.version = 3;
|
|
195
239
|
return { normalized: out, issues };
|
|
196
240
|
}
|
|
197
241
|
|
|
242
|
+
// Overlapping spans join; spans that only touch stay apart, because lifting
|
|
243
|
+
// and pressing the pedal again between them lets the dampers fall for a moment.
|
|
244
|
+
function mergePedal(spans) {
|
|
245
|
+
const sorted = spans.map(span => ({ ...span })).sort((a, b) => a.beat - b.beat || a.beats - b.beats);
|
|
246
|
+
const merged = [];
|
|
247
|
+
for (const span of sorted) {
|
|
248
|
+
const last = merged[merged.length - 1];
|
|
249
|
+
if (last && span.beat < last.beat + last.beats - 1e-9) last.beats = Math.max(last.beats, span.beat + span.beats - last.beat);
|
|
250
|
+
else merged.push(span);
|
|
251
|
+
}
|
|
252
|
+
return merged;
|
|
253
|
+
}
|
|
254
|
+
|
|
198
255
|
export function validateScore(score) {
|
|
199
256
|
const { issues } = normalize(score);
|
|
200
257
|
return { valid: issues.length === 0, issues };
|
package/src/timeline.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Beats to seconds. A score plays at its bpm from beat 0; each tempo change
|
|
2
|
+
// (score version 3) takes over from its beat. A change with `ramp` glides
|
|
3
|
+
// there instead: the tempo moves evenly, beat by beat, from the tempo before
|
|
4
|
+
// it and arrives at the new one on the change's beat (a ritardando or
|
|
5
|
+
// accelerando).
|
|
6
|
+
|
|
7
|
+
// [{beat, bpm, ramp}] in beat order, starting with the score's bpm at beat 0.
|
|
8
|
+
function points(bpm, changes = []) {
|
|
9
|
+
return [{ beat: 0, bpm, ramp: false }, ...changes.map(({ beat, bpm: next, ramp = false }) => ({ beat, bpm: next, ramp: !!ramp }))];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Seconds from the start of a segment to `beats` into it.
|
|
13
|
+
function segmentSeconds(from, to, length, beats) {
|
|
14
|
+
if (!to?.ramp || to.bpm === from.bpm) return beats * 60 / from.bpm;
|
|
15
|
+
const slope = (to.bpm - from.bpm) / length;
|
|
16
|
+
return 60 / slope * Math.log((from.bpm + slope * beats) / from.bpm);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Converts between beats and seconds for a compiled score. tempoAt(beat)
|
|
20
|
+
* gives the tempo in effect at a beat. */
|
|
21
|
+
export function makeTimeline({ bpm, beats, tempo = [] }) {
|
|
22
|
+
const list = points(bpm, tempo);
|
|
23
|
+
const starts = [0];
|
|
24
|
+
for (let i = 0; i < list.length - 1; i++) {
|
|
25
|
+
const from = list[i], to = list[i + 1];
|
|
26
|
+
starts.push(starts[i] + segmentSeconds(from, to, to.beat - from.beat, to.beat - from.beat));
|
|
27
|
+
}
|
|
28
|
+
const segment = beat => {
|
|
29
|
+
let i = list.length - 1;
|
|
30
|
+
while (i > 0 && list[i].beat > beat) i--;
|
|
31
|
+
return i;
|
|
32
|
+
};
|
|
33
|
+
const seconds = beat => {
|
|
34
|
+
const i = segment(beat), from = list[i], to = list[i + 1];
|
|
35
|
+
return starts[i] + segmentSeconds(from, to?.ramp ? to : null, to ? to.beat - from.beat : 0, beat - from.beat);
|
|
36
|
+
};
|
|
37
|
+
const tempoAt = beat => {
|
|
38
|
+
const i = segment(beat), from = list[i], to = list[i + 1];
|
|
39
|
+
return to?.ramp ? from.bpm + (to.bpm - from.bpm) * (beat - from.beat) / (to.beat - from.beat) : from.bpm;
|
|
40
|
+
};
|
|
41
|
+
const beatAt = time => {
|
|
42
|
+
let i = starts.length - 1;
|
|
43
|
+
while (i > 0 && starts[i] > time) i--;
|
|
44
|
+
const from = list[i], to = list[i + 1], into = time - starts[i];
|
|
45
|
+
if (!to?.ramp || to.bpm === from.bpm) return from.beat + into * from.bpm / 60;
|
|
46
|
+
const slope = (to.bpm - from.bpm) / (to.beat - from.beat);
|
|
47
|
+
return from.beat + from.bpm * (Math.exp(into * slope / 60) - 1) / slope;
|
|
48
|
+
};
|
|
49
|
+
return { seconds, beatAt, tempoAt, duration: seconds(beats), constant: list.length === 1 };
|
|
50
|
+
}
|
package/src/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// The toolkit release. The engine hash is content-based and does not include it.
|
|
2
|
-
export const VERSION = '0.
|
|
2
|
+
export const VERSION = '0.8.0';
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|