@zeeuw/riff 0.0.0-stage → 0.1.0-beta.2
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 +195 -2
- package/data/registry-data.js +3 -0
- package/data/signatures.js +3 -0
- package/docs/clean-room.md +450 -0
- package/package.json +69 -4
- package/src/audio/clock.js +383 -0
- package/src/audio/engine.js +678 -0
- package/src/audio/index.js +394 -0
- package/src/audio/offline.js +73 -0
- package/src/audio/params.js +397 -0
- package/src/audio/samples.js +274 -0
- package/src/audio/unlock.js +70 -0
- package/src/audio/voices.js +44 -0
- package/src/combinators.js +150 -0
- package/src/compat.js +16 -0
- package/src/constructors.js +236 -0
- package/src/controls.js +199 -0
- package/src/draw.js +252 -0
- package/src/euclid.js +57 -0
- package/src/evaluate.js +251 -0
- package/src/extras/check.js +678 -0
- package/src/extras/describe.js +433 -0
- package/src/extras/editor.js +369 -0
- package/src/extras/index.js +10 -0
- package/src/fraction.js +300 -0
- package/src/hap.js +64 -0
- package/src/helpers.js +68 -0
- package/src/index.js +74 -0
- package/src/mini/index.js +36 -0
- package/src/mini/parser.js +400 -0
- package/src/ops.js +293 -0
- package/src/outline.js +175 -0
- package/src/pattern.js +365 -0
- package/src/random.js +344 -0
- package/src/register.js +83 -0
- package/src/registry.js +52 -0
- package/src/samples.js +14 -0
- package/src/sampling.js +123 -0
- package/src/scope.js +77 -0
- package/src/signals.js +76 -0
- package/src/stepwise.js +150 -0
- package/src/structure.js +636 -0
- package/src/time.js +70 -0
- package/src/tonal.js +583 -0
- package/src/transforms.js +125 -0
- package/src/transpile.js +394 -0
- package/src/util.js +80 -0
- package/src/visuals.js +216 -0
package/src/time.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Time spans (spec/time.md section 2): half-open [begin, end) of Fractions.
|
|
2
|
+
import { Fraction, fraction } from './fraction.js';
|
|
3
|
+
|
|
4
|
+
// Is x inside s (half-open; a zero-width span contains only its own point)?
|
|
5
|
+
function holds(s, x) {
|
|
6
|
+
const b = s.begin.compare(x);
|
|
7
|
+
if (s.begin.eq(s.end)) return b === 0;
|
|
8
|
+
return b <= 0 && x.lt(s.end);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export class TimeSpan {
|
|
12
|
+
constructor(begin, end) {
|
|
13
|
+
this.begin = begin instanceof Fraction ? begin : fraction(begin);
|
|
14
|
+
this.end = end instanceof Fraction ? end : fraction(end);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Cut at every integer: [b, nextSam(b)), ..., [sam(e), e). A zero-width span
|
|
18
|
+
// comes back as itself; a span ending on an integer has no empty tail.
|
|
19
|
+
spanCycles() {
|
|
20
|
+
const end = this.end;
|
|
21
|
+
if (!this.begin.lt(end)) return [this];
|
|
22
|
+
if (end.lte(this.begin.nextSam())) return [this]; // within one cycle
|
|
23
|
+
const out = [];
|
|
24
|
+
let b = this.begin;
|
|
25
|
+
while (b.lt(end)) {
|
|
26
|
+
const next = b.nextSam();
|
|
27
|
+
const e = next.lt(end) ? next : end;
|
|
28
|
+
out.push(new TimeSpan(b, e));
|
|
29
|
+
b = e;
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
withTime(f) { return new TimeSpan(f(this.begin), f(this.end)); }
|
|
35
|
+
withEnd(f) { return new TimeSpan(this.begin, f(this.end)); }
|
|
36
|
+
withCycle(f) {
|
|
37
|
+
const sam = this.begin.sam();
|
|
38
|
+
return new TimeSpan(sam.add(f(this.begin.sub(sam))), sam.add(f(this.end.sub(sam))));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Overlap for hap purposes, or null. Spans that only touch do not overlap;
|
|
42
|
+
// a zero-width result is kept only when its point lies inside both spans.
|
|
43
|
+
// this ∩ win, or null; a zero-width overlap counts only when this span is
|
|
44
|
+
// zero-width itself (a query clipped to a window).
|
|
45
|
+
clip(win) {
|
|
46
|
+
const r = this.intersect(win);
|
|
47
|
+
if (!r || (r.begin.eq(r.end) && !this.begin.eq(this.end))) return null;
|
|
48
|
+
return r;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
intersect(o) {
|
|
52
|
+
const b = this.begin.max(o.begin);
|
|
53
|
+
const e = this.end.min(o.end);
|
|
54
|
+
const c = b.compare(e);
|
|
55
|
+
if (c > 0) return null;
|
|
56
|
+
if (c === 0 && !(holds(this, b) && holds(o, b))) return null;
|
|
57
|
+
// Spans are immutable: when one side is the overlap, return it as is.
|
|
58
|
+
if (b.eq(o.begin) && e.eq(o.end)) return o;
|
|
59
|
+
if (b.eq(this.begin) && e.eq(this.end)) return this;
|
|
60
|
+
return new TimeSpan(b, e);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Raw intersection, may be inverted (begin > end).
|
|
64
|
+
intersection(o) { return new TimeSpan(this.begin.max(o.begin), this.end.min(o.end)); }
|
|
65
|
+
|
|
66
|
+
duration() { return this.end.sub(this.begin); }
|
|
67
|
+
midpoint() { return this.begin.add(this.end).div(2); }
|
|
68
|
+
equals(o) { return this.begin.eq(o.begin) && this.end.eq(o.end); }
|
|
69
|
+
toString() { return `[${this.begin}, ${this.end})`; }
|
|
70
|
+
}
|
package/src/tonal.js
ADDED
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
// Tonal functions (plan 3.4, spec/functions/scale.md and voicing.md): note
|
|
2
|
+
// spelling, scales, chord symbols and voicing dictionaries. Every table here
|
|
3
|
+
// is RIFF's own, written from music theory and checked against the fixtures;
|
|
4
|
+
// rows the fixtures do not reach are listed in docs/decisions.md.
|
|
5
|
+
import { Pattern, pure, reify } from './pattern.js';
|
|
6
|
+
import { Hap, combineContext } from './hap.js';
|
|
7
|
+
import { register, registry } from './register.js';
|
|
8
|
+
import { noteToMidi, isControlMap } from './ops.js';
|
|
9
|
+
import { riffCompat } from './compat.js';
|
|
10
|
+
import { floorMod, toMidi } from './util.js';
|
|
11
|
+
import { alias, registerFree } from './register.js';
|
|
12
|
+
import { freqToMidi as f2m, midiToFreq as m2f } from './util.js';
|
|
13
|
+
|
|
14
|
+
// --- note names -------------------------------------------------------------
|
|
15
|
+
|
|
16
|
+
const LETTERS = 'CDEFGAB';
|
|
17
|
+
const NATURAL = [0, 2, 4, 5, 7, 9, 11];
|
|
18
|
+
const FLAT_NAMES = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B'];
|
|
19
|
+
const TONIC = /^([a-gA-G])([#b]*)(-?\d+)?$/;
|
|
20
|
+
|
|
21
|
+
// Parse a tonic like "C", "Eb2", "f#4" -> {letter, acc, octave|undefined}.
|
|
22
|
+
function parseTonic(s) {
|
|
23
|
+
const m = TONIC.exec(s);
|
|
24
|
+
if (!m) return undefined;
|
|
25
|
+
let acc = 0;
|
|
26
|
+
for (const ch of m[2]) acc += ch === '#' ? 1 : -1;
|
|
27
|
+
return { letter: LETTERS.indexOf(m[1].toUpperCase()), acc, octave: m[3] === undefined ? undefined : Number(m[3]) };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// MIDI number -> name with flats and octave ("Bb3"), the voicing spelling.
|
|
31
|
+
export function midiToNoteName(midi) {
|
|
32
|
+
return `${FLAT_NAMES[floorMod(midi, 12)]}${Math.floor(midi / 12) - 1}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Spelled note -> "Eb3" style name.
|
|
36
|
+
const spell = (letter, acc, octave) => `${LETTERS[letter]}${acc > 0 ? '#'.repeat(acc) : 'b'.repeat(-acc)}${octave}`;
|
|
37
|
+
|
|
38
|
+
export { toMidi };
|
|
39
|
+
|
|
40
|
+
// --- scales -----------------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
// Interval "3m" -> {num: 3, semis: 3}. Perfect: 1, 4, 5 (and octaves).
|
|
43
|
+
function interval(s) {
|
|
44
|
+
const num = Number(s.slice(0, -1));
|
|
45
|
+
const q = s.slice(-1);
|
|
46
|
+
const step = (num - 1) % 7;
|
|
47
|
+
const perfect = step === 0 || step === 3 || step === 4;
|
|
48
|
+
const base = NATURAL[step] + 12 * Math.floor((num - 1) / 7);
|
|
49
|
+
const shift = { P: 0, M: 0, m: -1, A: 1, d: perfect ? -1 : -2 }[q];
|
|
50
|
+
return { num, semis: base + shift };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const SCALE_TABLE = {
|
|
54
|
+
'major|ionian': '1P 2M 3M 4P 5P 6M 7M',
|
|
55
|
+
'minor|aeolian': '1P 2M 3m 4P 5P 6m 7m',
|
|
56
|
+
dorian: '1P 2M 3m 4P 5P 6M 7m',
|
|
57
|
+
phrygian: '1P 2m 3m 4P 5P 6m 7m',
|
|
58
|
+
lydian: '1P 2M 3M 4A 5P 6M 7M',
|
|
59
|
+
'mixolydian|dominant': '1P 2M 3M 4P 5P 6M 7m',
|
|
60
|
+
locrian: '1P 2m 3m 4P 5d 6m 7m',
|
|
61
|
+
'harmonic minor': '1P 2M 3m 4P 5P 6m 7M',
|
|
62
|
+
'melodic minor': '1P 2M 3m 4P 5P 6M 7M',
|
|
63
|
+
'whole tone': '1P 2M 3M 4A 5A 6A',
|
|
64
|
+
'pentatonic|major pentatonic': '1P 2M 3M 5P 6M',
|
|
65
|
+
'minor pentatonic': '1P 3m 4P 5P 7m',
|
|
66
|
+
blues: '1P 3m 4P 5d 5P 7m',
|
|
67
|
+
'major blues': '1P 2M 3m 3M 5P 6M',
|
|
68
|
+
chromatic: '1P 2m 2M 3m 3M 4P 5d 5P 6m 6M 7m 7M',
|
|
69
|
+
bebop: '1P 2M 3M 4P 5P 6M 7m 7M',
|
|
70
|
+
'bebop major': '1P 2M 3M 4P 5P 5A 6M 7M',
|
|
71
|
+
'bebop minor': '1P 2M 3m 3M 4P 5P 6M 7m',
|
|
72
|
+
altered: '1P 2m 2A 3M 4A 6m 7m',
|
|
73
|
+
diminished: '1P 2M 3m 4P 5d 6m 6M 7M',
|
|
74
|
+
'half-whole diminished': '1P 2m 3m 3M 4A 5P 6M 7m',
|
|
75
|
+
'lydian dominant': '1P 2M 3M 4A 5P 6M 7m',
|
|
76
|
+
};
|
|
77
|
+
// Aliases are separated by '|' in the key.
|
|
78
|
+
export const SCALES = new Map();
|
|
79
|
+
for (const [names, ivs] of Object.entries(SCALE_TABLE)) {
|
|
80
|
+
const list = ivs.split(' ').map(interval);
|
|
81
|
+
for (const n of names.split('|')) SCALES.set(n, list);
|
|
82
|
+
}
|
|
83
|
+
export const scaleNames = () => [...SCALES.keys()];
|
|
84
|
+
|
|
85
|
+
// Scale name value (string "C4:dorian" or mini colon array) -> scale, or null.
|
|
86
|
+
export function parseScale(name) {
|
|
87
|
+
const s = Array.isArray(name) ? name.join(':') : String(name);
|
|
88
|
+
const i = s.indexOf(':');
|
|
89
|
+
const tonicStr = i < 0 ? 'C' : s.slice(0, i);
|
|
90
|
+
const type = i < 0 ? s : s.slice(i + 1);
|
|
91
|
+
const t = parseTonic(tonicStr);
|
|
92
|
+
const intervals = SCALES.get(type);
|
|
93
|
+
if (!t || !intervals) return null;
|
|
94
|
+
const octave = t.octave ?? 3;
|
|
95
|
+
const midi = 12 * (octave + 1) + NATURAL[t.letter] + t.acc;
|
|
96
|
+
return { ...t, octave, midi, intervals };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Degree (integer) -> {midi, name} in a parsed scale.
|
|
100
|
+
export function scaleDegree(sc, degree) {
|
|
101
|
+
const len = sc.intervals.length;
|
|
102
|
+
const oct = Math.floor(degree / len);
|
|
103
|
+
const iv = sc.intervals[floorMod(degree, len)];
|
|
104
|
+
const midi = sc.midi + iv.semis + 12 * oct;
|
|
105
|
+
const steps = sc.letter + iv.num - 1;
|
|
106
|
+
const letter = steps % 7;
|
|
107
|
+
const octave = sc.octave + Math.floor(steps / 7) + oct;
|
|
108
|
+
const acc = midi - (12 * (octave + 1) + NATURAL[letter]);
|
|
109
|
+
return { midi, name: spell(letter, acc, octave) };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// MIDI note -> degree of the scale, snapping an off-scale note upwards.
|
|
113
|
+
export function degreeOf(sc, midi) {
|
|
114
|
+
const rel = midi - sc.midi;
|
|
115
|
+
let oct = Math.floor(rel / 12);
|
|
116
|
+
const r = rel - 12 * oct;
|
|
117
|
+
let i = sc.intervals.findIndex((iv) => iv.semis >= r);
|
|
118
|
+
if (i < 0) { i = 0; oct += 1; }
|
|
119
|
+
return oct * sc.intervals.length + i;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const withScale = (h, sc) => h.withContext((c) => ({ ...c, scale: sc }));
|
|
123
|
+
|
|
124
|
+
// One hap through a scale: n -> degree, note -> snapped; null drops it.
|
|
125
|
+
function scaleHap(h, sc) {
|
|
126
|
+
const v = h.value;
|
|
127
|
+
if (isControlMap(v)) {
|
|
128
|
+
if (v.n !== undefined && typeof v.n === 'number') {
|
|
129
|
+
const { n, ...rest } = v;
|
|
130
|
+
return withScale(h.withValue(() => ({ ...rest, note: scaleDegree(sc, Math.round(n)).name })), sc);
|
|
131
|
+
}
|
|
132
|
+
// 'riff' mode (improvements 11): a note name in `n` keeps the other
|
|
133
|
+
// controls; Strudel drops them (and RIFF drops the event by default).
|
|
134
|
+
if (typeof v.n === 'string' && v.note === undefined && riffCompat()) {
|
|
135
|
+
const m = toMidi(v.n);
|
|
136
|
+
if (m === undefined) return null;
|
|
137
|
+
const { n, ...rest } = v;
|
|
138
|
+
return withScale(h.withValue(() => ({ ...rest, note: scaleDegree(sc, degreeOf(sc, m)).name })), sc);
|
|
139
|
+
}
|
|
140
|
+
const midi = toMidi(v.note);
|
|
141
|
+
if (midi === undefined) return null;
|
|
142
|
+
return withScale(h.withValue(() => ({ ...v, note: scaleDegree(sc, degreeOf(sc, midi)).name })), sc);
|
|
143
|
+
}
|
|
144
|
+
if (typeof v === 'number') return withScale(h.withValue(() => scaleDegree(sc, Math.round(v)).name), sc);
|
|
145
|
+
const midi = toMidi(v);
|
|
146
|
+
if (midi === undefined) return null;
|
|
147
|
+
return withScale(h.withValue(() => scaleDegree(sc, degreeOf(sc, midi)).name), sc);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const scaleImpl = register('scale', (pat, name) => {
|
|
151
|
+
const sc = parseScale(name);
|
|
152
|
+
if (!sc) return pat.filterHaps(() => false);
|
|
153
|
+
return pat.withHaps((haps) => haps.map((h) => scaleHap(h, sc)).filter(Boolean));
|
|
154
|
+
}, { patternArgs: 1 });
|
|
155
|
+
|
|
156
|
+
// A plain JS string is one scale name, not mini-notation (spec: 'C:bebop major').
|
|
157
|
+
const nameArg = (x) => (typeof x === 'string' ? pure(x) : x);
|
|
158
|
+
const methodScale = Pattern.prototype.scale;
|
|
159
|
+
Object.defineProperty(Pattern.prototype, 'scale', {
|
|
160
|
+
value: function (name) { return methodScale.call(this, nameArg(name)); }, writable: true, configurable: true,
|
|
161
|
+
});
|
|
162
|
+
// Free form: scale(name, pat). With the name alone it is not a pattern, as in
|
|
163
|
+
// Strudel 1.2.5 (fixture scale-fn); RIFF returns a function pat -> pat.scale(name).
|
|
164
|
+
export function scale(name, ...rest) {
|
|
165
|
+
if (rest.length === 0) return (pat) => pat.scale(name);
|
|
166
|
+
return scaleImpl(nameArg(name), ...rest);
|
|
167
|
+
}
|
|
168
|
+
registry.set('scale', scale);
|
|
169
|
+
|
|
170
|
+
export const scaleTranspose = register('scaleTranspose', (pat, k) => pat.withHaps((haps) => {
|
|
171
|
+
const out = [];
|
|
172
|
+
for (const h of haps) {
|
|
173
|
+
const sc = h.context.scale;
|
|
174
|
+
if (!sc) continue;
|
|
175
|
+
const v = h.value;
|
|
176
|
+
const midi = toMidi(isControlMap(v) ? v.note : v);
|
|
177
|
+
if (midi === undefined) continue;
|
|
178
|
+
const name = scaleDegree(sc, degreeOf(sc, midi) + Math.round(Number(k))).name;
|
|
179
|
+
out.push(h.withValue(() => (isControlMap(v) ? { ...v, note: name } : name)));
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}), { patternArgs: 1 });
|
|
183
|
+
|
|
184
|
+
// --- chord symbols and voicing dictionaries ---------------------------------
|
|
185
|
+
|
|
186
|
+
const CHORD = /^([A-Ga-g])([#b]*)(.*)$/;
|
|
187
|
+
|
|
188
|
+
// "F#m7" -> {root: "F#", pc: 6, type: "m7"}; undefined if no root letter.
|
|
189
|
+
export function parseChord(sym) {
|
|
190
|
+
if (typeof sym !== 'string') return undefined;
|
|
191
|
+
const m = CHORD.exec(sym);
|
|
192
|
+
if (!m) return undefined;
|
|
193
|
+
let acc = 0;
|
|
194
|
+
for (const ch of m[2]) acc += ch === '#' ? 1 : -1;
|
|
195
|
+
return { root: m[1].toUpperCase() + m[2], pc: floorMod(NATURAL[LETTERS.indexOf(m[1].toUpperCase())] + acc, 12), type: m[3] };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Shapes: semitones above the root (first entry in [0,12)). Several shapes
|
|
199
|
+
// per chord type; placement picks one (spec/functions/voicing.md). The order
|
|
200
|
+
// of shapes breaks ties (first wins).
|
|
201
|
+
const S = (str) => str.split(' ').map(Number);
|
|
202
|
+
export const VOICING_DICTIONARIES = {
|
|
203
|
+
ireal: {
|
|
204
|
+
'': [S('0 7 12 16'), S('4 12 16 19 24'), S('0 7 12 16 19')],
|
|
205
|
+
m: [S('7 12 15 19 24'), S('0 3 7 12 15')],
|
|
206
|
+
7: [S('4 10 16 19 24'), S('0 7 10 12 16'), S('0 10 12 16 19')],
|
|
207
|
+
'^7': [S('0 16 19 23'), S('0 7 11 16 19')],
|
|
208
|
+
m7: [S('10 15 19 22 24'), S('0 3 7 10 15'), S('3 10 12 15 22'), S('0 7 10 15 19')],
|
|
209
|
+
m7b5: [S('10 15 18 22 24')],
|
|
210
|
+
o7: [S('3 12 18 21 24')],
|
|
211
|
+
'7b9': [S('10 13 16 22 24')],
|
|
212
|
+
9: [S('10 14 16 22 24')],
|
|
213
|
+
13: [S('10 14 16 21 24')],
|
|
214
|
+
6: [S('0 7 12 16 21')],
|
|
215
|
+
69: [S('0 7 14 16 21')],
|
|
216
|
+
sus: [S('0 5 7 12')],
|
|
217
|
+
aug: [S('4 12 16 20 24')],
|
|
218
|
+
'^9': [S('0 11 14 16 19')],
|
|
219
|
+
},
|
|
220
|
+
lefthand: {
|
|
221
|
+
7: [S('10 14 16 21'), S('4 9 10 14')],
|
|
222
|
+
'^7': [S('11 14 16 19'), S('4 7 11 14')],
|
|
223
|
+
m7: [S('10 14 15 19'), S('3 7 10 14')],
|
|
224
|
+
m7b5: [S('3 6 10 12')],
|
|
225
|
+
o7: [S('0 3 6 9')],
|
|
226
|
+
'7b9': [S('10 13 16 20')],
|
|
227
|
+
69: [S('4 7 10 14')],
|
|
228
|
+
},
|
|
229
|
+
// S5 (spec/functions/voicing.md, legacy): shapes derived from the output of
|
|
230
|
+
// fixtures voicing-legacy-sweep and voicing-legacy-roots (every observed
|
|
231
|
+
// placement, normalised to the root). Types the fixtures do not reach are
|
|
232
|
+
// absent, so they give no haps like the 22 spellings the oracle lacks.
|
|
233
|
+
legacy: {
|
|
234
|
+
'': [S('4 7 12'), S('0 4 7'), S('7 12 16')],
|
|
235
|
+
m: [S('3 7 12'), S('0 3 7'), S('7 12 15')],
|
|
236
|
+
o: [S('3 6 12'), S('0 3 6'), S('6 12 15')],
|
|
237
|
+
aug: [S('3 8 12'), S('0 3 8'), S('8 12 15')],
|
|
238
|
+
7: [S('10 14 16 21'), S('4 9 10 14')],
|
|
239
|
+
m7: [S('10 14 15 19'), S('3 7 10 14')],
|
|
240
|
+
'^7': [S('11 14 16 19'), S('4 7 11 14')],
|
|
241
|
+
m7b5: [S('3 6 10 12'), S('10 12 15 18')],
|
|
242
|
+
o7: [S('0 3 6 9')],
|
|
243
|
+
m6: [S('9 14 15 19')],
|
|
244
|
+
69: [S('4 7 10 14')],
|
|
245
|
+
'7b9': [S('10 13 16 20')],
|
|
246
|
+
'7#9': [S('4 10 15')],
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
// Plan 8.12 (improvements 22): common spellings the dictionaries lack. In the
|
|
251
|
+
// default 'strudel' mode they stay unknown (Strudel plays nothing for them);
|
|
252
|
+
// setCompat('riff') maps them to the dictionary's own type, and check() warns
|
|
253
|
+
// about them in either mode.
|
|
254
|
+
export const CHORD_ALIASES = Object.freeze({
|
|
255
|
+
dim: 'o', dim7: 'o7', '°': 'o', '°7': 'o7',
|
|
256
|
+
maj7: '^7', M7: '^7', 'Δ7': '^7', 'Δ': '^7', maj9: '^9', M9: '^9', maj: '', M: '',
|
|
257
|
+
min: 'm', '-': 'm', min7: 'm7', '-7': 'm7', mi7: 'm7',
|
|
258
|
+
min7b5: 'm7b5', '-7b5': 'm7b5', 'ø': 'm7b5', 'ø7': 'm7b5', h7: 'm7b5',
|
|
259
|
+
sus4: 'sus', '7sus': 'sus', '+': 'aug', dom7: '7',
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
// The dictionary shapes for a chord type, or undefined; aliases only in 'riff' mode.
|
|
263
|
+
function shapesFor(dictionary, type) {
|
|
264
|
+
const dict = VOICING_DICTIONARIES[dictionary];
|
|
265
|
+
if (!dict) return undefined;
|
|
266
|
+
if (dict[type]) return dict[type];
|
|
267
|
+
const alias = riffCompat() ? CHORD_ALIASES[type] : undefined;
|
|
268
|
+
return alias !== undefined ? dict[alias] : undefined;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Chord symbol -> MIDI notes (low to high), or undefined when the symbol or
|
|
272
|
+
// its type is not in the dictionary. A slash chord is an error (fixture
|
|
273
|
+
// saai/jazz-template-36: "Invalid argument").
|
|
274
|
+
export function voiceChord(symbol, { dictionary = 'ireal', anchor = 72, mode = 'below' } = {}) {
|
|
275
|
+
const c = parseChord(symbol);
|
|
276
|
+
if (!c) return undefined;
|
|
277
|
+
if (c.type.includes('/')) throw new Error('Invalid argument');
|
|
278
|
+
const shapes = shapesFor(dictionary, c.type);
|
|
279
|
+
if (!shapes) return undefined;
|
|
280
|
+
const A = anchor;
|
|
281
|
+
let best;
|
|
282
|
+
let bestKey;
|
|
283
|
+
const pool = mode === 'root' && shapes.some((s) => s[0] === 0) ? shapes.filter((s) => s[0] === 0) : shapes;
|
|
284
|
+
for (const s of pool) {
|
|
285
|
+
let r;
|
|
286
|
+
let key;
|
|
287
|
+
if (mode === 'above' || mode === 'root') {
|
|
288
|
+
r = c.pc + 12 * Math.ceil((A - s[0] - c.pc) / 12);
|
|
289
|
+
key = -(r + s[0]);
|
|
290
|
+
} else {
|
|
291
|
+
const top = s[s.length - 1];
|
|
292
|
+
r = c.pc + 12 * Math.floor((A - top - c.pc) / 12);
|
|
293
|
+
key = r + top;
|
|
294
|
+
}
|
|
295
|
+
if (best === undefined || key > bestKey) { best = s.map((x) => r + x); bestKey = key; }
|
|
296
|
+
}
|
|
297
|
+
if (mode === 'duck') best = best.filter((m) => m !== A);
|
|
298
|
+
return best;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// The dictionary voicing() uses when no `dict` is set; setDefaultVoicings and
|
|
302
|
+
// resetVoicings (src/tier3b.js, spec/functions/voicing-registry.md) change it.
|
|
303
|
+
export const VOICING_DEFAULT = { dictionary: 'ireal' };
|
|
304
|
+
|
|
305
|
+
const VOICING_KEYS = ['chord', 'dictionary', 'anchor', 'mode', 'n'];
|
|
306
|
+
const anchorMidi = (a) => (a === undefined ? 72 : toMidi(Array.isArray(a) ? a[0] : a) ?? 72);
|
|
307
|
+
|
|
308
|
+
// voicing(): one hap per voice (or voice n as a MIDI number).
|
|
309
|
+
export const voicing = register('voicing', (pat) => pat.withHaps((haps) => {
|
|
310
|
+
const out = [];
|
|
311
|
+
for (const h of haps) {
|
|
312
|
+
const v = h.value;
|
|
313
|
+
const map = isControlMap(v);
|
|
314
|
+
const sym = map ? v.chord : v;
|
|
315
|
+
const notes = voiceChord(sym, map ? { dictionary: v.dictionary ?? VOICING_DEFAULT.dictionary, anchor: anchorMidi(v.anchor), mode: v.mode ?? 'below' }
|
|
316
|
+
: { dictionary: VOICING_DEFAULT.dictionary });
|
|
317
|
+
if (!notes || notes.length === 0) continue;
|
|
318
|
+
const rest = {};
|
|
319
|
+
if (map) for (const k of Object.keys(v)) if (!VOICING_KEYS.includes(k)) rest[k] = v[k];
|
|
320
|
+
if (map && typeof v.n === 'number') {
|
|
321
|
+
const n = Math.round(v.n);
|
|
322
|
+
const len = notes.length;
|
|
323
|
+
out.push(h.withValue(() => ({ ...rest, note: notes[floorMod(n, len)] + 12 * Math.floor(n / len) })));
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
for (const m of notes) out.push(h.withValue(() => ({ ...rest, note: midiToNoteName(m) })));
|
|
327
|
+
}
|
|
328
|
+
return out;
|
|
329
|
+
}), { patternArgs: 0 });
|
|
330
|
+
|
|
331
|
+
// voicings(dict): the older form on chord-symbol values; plain note strings.
|
|
332
|
+
// Placement (derived from fixtures voicings-sevenths, saai/evolution-
|
|
333
|
+
// instructions-02, song-instructions-03): of all shapes in all octaves whose
|
|
334
|
+
// notes lie in the dictionary's range (VOICING_RANGES, default [F3, A4]), take the one whose top note is closest to the top
|
|
335
|
+
// note of the voicing this pattern produced last (state carried across
|
|
336
|
+
// queries, in query order); with no previous voicing, the highest top note.
|
|
337
|
+
export const VOICINGS_RANGE = [53, 69];
|
|
338
|
+
|
|
339
|
+
// Per-dictionary ranges for the older .voicings() form (addVoicings' third
|
|
340
|
+
// argument, setVoicingRange; spec/functions/voicing-registry.md). voicing()
|
|
341
|
+
// ignores them.
|
|
342
|
+
export const VOICING_RANGES = {};
|
|
343
|
+
export function setDictionaryRange(name, range) {
|
|
344
|
+
const r = Array.isArray(range) ? range.map((x) => toMidi(x)) : [];
|
|
345
|
+
if (r.length === 2 && r.every((x) => typeof x === 'number')) VOICING_RANGES[name] = r;
|
|
346
|
+
else delete VOICING_RANGES[name];
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
export function voicingCandidates(symbol, dictionary, [lo, hi] = VOICING_RANGES[dictionary] ?? VOICINGS_RANGE) {
|
|
350
|
+
const c = parseChord(symbol);
|
|
351
|
+
if (!c) return [];
|
|
352
|
+
if (c.type.includes('/')) throw new Error('Invalid argument');
|
|
353
|
+
const shapes = shapesFor(dictionary, c.type) ?? [];
|
|
354
|
+
const out = [];
|
|
355
|
+
for (const s of shapes) {
|
|
356
|
+
for (let r = c.pc + 12 * Math.ceil((lo - s[0] - c.pc) / 12); r + s[s.length - 1] <= hi; r += 12) {
|
|
357
|
+
const notes = s.map((x) => r + x);
|
|
358
|
+
// Shapes from addVoicings carry interval letter steps: spell from the
|
|
359
|
+
// root letter (D + 3M = F#4, fixture setVoicingRange-voicings-narrow).
|
|
360
|
+
if (s.steps) Object.defineProperty(notes, 'names', { value: notes.map((m, i) => spellMidi(LETTERS.indexOf(c.root[0]) + s.steps[i], m)) });
|
|
361
|
+
out.push(notes);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return out;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// MIDI number spelled on a given letter (index into LETTERS, any integer).
|
|
368
|
+
function spellMidi(L, m) {
|
|
369
|
+
const letter = floorMod(L, 7);
|
|
370
|
+
const o = Math.round((m - NATURAL[letter] - 12) / 12);
|
|
371
|
+
return spell(letter, m - (12 * (o + 1) + NATURAL[letter]), o);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const voicingsImpl = register('voicings', (pat, dict = 'ireal', state = { last: null }) => {
|
|
375
|
+
return pat.withHaps((haps) => {
|
|
376
|
+
const out = [];
|
|
377
|
+
for (const h of haps) {
|
|
378
|
+
const sym = isControlMap(h.value) ? h.value.chord : h.value;
|
|
379
|
+
let best = null;
|
|
380
|
+
let bestKey = -Infinity;
|
|
381
|
+
for (const notes of voicingCandidates(sym, dict)) {
|
|
382
|
+
const top = notes[notes.length - 1];
|
|
383
|
+
const key = state.last === null ? top : -Math.abs(top - state.last);
|
|
384
|
+
if (key > bestKey) { best = notes; bestKey = key; }
|
|
385
|
+
}
|
|
386
|
+
if (!best) continue;
|
|
387
|
+
state.last = best[best.length - 1];
|
|
388
|
+
best.forEach((m, i) => out.push(h.withValue(() => best.names?.[i] ?? midiToNoteName(m))));
|
|
389
|
+
}
|
|
390
|
+
return out;
|
|
391
|
+
});
|
|
392
|
+
}, { patternArgs: 1 });
|
|
393
|
+
// One state per voicings() call, shared by the inner join's per-hap calls.
|
|
394
|
+
const methodVoicings = Pattern.prototype.voicings;
|
|
395
|
+
Object.defineProperty(Pattern.prototype, 'voicings', {
|
|
396
|
+
value: function (dict = 'ireal') { return methodVoicings.call(this, dict, { last: null }); }, writable: true, configurable: true,
|
|
397
|
+
});
|
|
398
|
+
export const voicings = (dict, pat) => voicingsImpl(dict, { last: null }, pat);
|
|
399
|
+
registry.set('voicings', voicings);
|
|
400
|
+
|
|
401
|
+
// rootNotes(octave): chord symbol -> root note name in that octave.
|
|
402
|
+
export const rootNotes = register('rootNotes', (pat, octave) => {
|
|
403
|
+
if (octave === undefined) return pat.filterHaps(() => false);
|
|
404
|
+
return pat.withHaps((haps) => {
|
|
405
|
+
const out = [];
|
|
406
|
+
for (const h of haps) {
|
|
407
|
+
const c = parseChord(isControlMap(h.value) ? h.value.chord : h.value);
|
|
408
|
+
if (c) out.push(h.withValue(() => `${c.root}${octave}`));
|
|
409
|
+
}
|
|
410
|
+
return out;
|
|
411
|
+
});
|
|
412
|
+
}, { patternArgs: 1 });
|
|
413
|
+
|
|
414
|
+
// --- arp and transpose (Tier 2) ---------------------------------------------
|
|
415
|
+
|
|
416
|
+
// One chord element per index hap: chords are the haps of pat sharing a whole
|
|
417
|
+
// (pat's own order); element i mod size. Any negative index silences the
|
|
418
|
+
// whole query (spec/functions/arp.md).
|
|
419
|
+
export const arp = register('arp', (pat, indices) => {
|
|
420
|
+
const ix = reify(indices);
|
|
421
|
+
return new Pattern((state) => {
|
|
422
|
+
const ihs = ix.query(state);
|
|
423
|
+
for (const ih of ihs) if (Number(ih.value) < 0) return [];
|
|
424
|
+
const out = [];
|
|
425
|
+
for (const ih of ihs) {
|
|
426
|
+
const chords = new Map();
|
|
427
|
+
for (const h of pat.query(state.setSpan(ih.wholeOrPart()))) {
|
|
428
|
+
const w = h.wholeOrPart();
|
|
429
|
+
const key = `${w.begin} ${w.end}`;
|
|
430
|
+
let c = chords.get(key);
|
|
431
|
+
if (!c) chords.set(key, (c = []));
|
|
432
|
+
c.push(h);
|
|
433
|
+
}
|
|
434
|
+
const i = Number(ih.value);
|
|
435
|
+
for (const c of chords.values()) {
|
|
436
|
+
const h = c[i % c.length];
|
|
437
|
+
const part = ih.part.intersect(h.part);
|
|
438
|
+
if (part) out.push(new Hap(ih.whole, part, h.value, combineContext(ih.context, h.context)));
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return out;
|
|
442
|
+
});
|
|
443
|
+
}, { patternArgs: 0, curry: 1 });
|
|
444
|
+
|
|
445
|
+
// Semitone size -> interval steps (letter moves). 6 moves four letters both
|
|
446
|
+
// ways (d5): fixture transpose-semitones-neg has c4 - 6 = F#3, eb4 - 6 = A3
|
|
447
|
+
// (spec/functions/transpose.md says A4 down; the fixture wins).
|
|
448
|
+
const STEPS = [0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6];
|
|
449
|
+
const INTERVAL_NAME = /^(-?)(\d+)([PMmAd])$/;
|
|
450
|
+
|
|
451
|
+
// x (semitones or an interval name) -> {steps, semis}, signed, or undefined.
|
|
452
|
+
function transposeInterval(x) {
|
|
453
|
+
if (typeof x === 'string') {
|
|
454
|
+
const m = INTERVAL_NAME.exec(x.trim());
|
|
455
|
+
if (m) {
|
|
456
|
+
const { num, semis } = interval(`${m[2]}${m[3]}`);
|
|
457
|
+
const sign = m[1] ? -1 : 1;
|
|
458
|
+
return { steps: sign * (num - 1), semis: sign * semis };
|
|
459
|
+
}
|
|
460
|
+
x = Number(x);
|
|
461
|
+
}
|
|
462
|
+
if (typeof x !== 'number' || !Number.isInteger(x)) return undefined;
|
|
463
|
+
const a = Math.abs(x), sign = x < 0 ? -1 : 1;
|
|
464
|
+
const size = a % 12, oct = Math.floor(a / 12);
|
|
465
|
+
return { steps: sign * (STEPS[size] + 7 * oct), semis: x };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// A note value moved by x: numbers add, names are re-spelled ("" when x is
|
|
469
|
+
// not a whole interval).
|
|
470
|
+
function transposeNote(v, x) {
|
|
471
|
+
if (typeof v === 'number') {
|
|
472
|
+
const iv = transposeInterval(x);
|
|
473
|
+
return v + (typeof x === 'number' ? x : iv ? iv.semis : 0);
|
|
474
|
+
}
|
|
475
|
+
const t = typeof v === 'string' ? parseTonic(v) : undefined;
|
|
476
|
+
if (!t) return v;
|
|
477
|
+
const iv = transposeInterval(x);
|
|
478
|
+
if (!iv) return '';
|
|
479
|
+
const oct = t.octave ?? 4;
|
|
480
|
+
const L = oct * 7 + t.letter + iv.steps;
|
|
481
|
+
const P = oct * 12 + NATURAL[t.letter] + t.acc + iv.semis;
|
|
482
|
+
const letter = floorMod(L, 7), o = Math.floor(L / 7);
|
|
483
|
+
return spell(letter, P - (o * 12 + NATURAL[letter]), t.octave === undefined ? '' : o);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
export const transpose = register('transpose', (pat, x) =>
|
|
487
|
+
pat.fmap((v) => (isControlMap(v) ? ('note' in v ? { ...v, note: transposeNote(v.note, x) } : v) : transposeNote(v, x))),
|
|
488
|
+
{ memo: true, curry: 1 });
|
|
489
|
+
|
|
490
|
+
// --- moved here from the Tier 2/3 batch modules (audit 6) ---------------------
|
|
491
|
+
|
|
492
|
+
// Hz of a MIDI number or note name (A4 = 69 = 440 Hz).
|
|
493
|
+
export function getFreq(x) {
|
|
494
|
+
const m = typeof x === 'string' ? noteToMidi(x) : x;
|
|
495
|
+
if (typeof m !== 'number' || Number.isNaN(m)) throw new Error(`not a note: "${String(x)}"`);
|
|
496
|
+
return 440 * 2 ** ((m - 69) / 12);
|
|
497
|
+
}
|
|
498
|
+
registerFree('getFreq', getFreq);
|
|
499
|
+
|
|
500
|
+
// addVoicings(name, {type: ['3M 5P', ...]}, range): a voicing dictionary for
|
|
501
|
+
// .dict(name).voicing(). Shapes are interval names above the root.
|
|
502
|
+
const STEP = [0, 2, 4, 5, 7, 9, 11];
|
|
503
|
+
function intervalSemitones(s) {
|
|
504
|
+
const mt = /^(\d+)([PMmAd]+)$/.exec(s) ?? /^([PMmAd]+)(\d+)$/.exec(s)?.slice(0, 3).reverse();
|
|
505
|
+
if (!mt) throw new Error(`invalid interval: ${s}`);
|
|
506
|
+
const num = Number(/^\d+$/.test(mt[1]) ? mt[1] : mt[2]);
|
|
507
|
+
const q = /^\d+$/.test(mt[1]) ? mt[2] : mt[1];
|
|
508
|
+
const deg = (num - 1) % 7;
|
|
509
|
+
const perfect = deg === 0 || deg === 3 || deg === 4;
|
|
510
|
+
let semis = STEP[deg] + 12 * Math.floor((num - 1) / 7);
|
|
511
|
+
if (q[0] === 'm') semis -= 1;
|
|
512
|
+
else if (q[0] === 'A') semis += q.length;
|
|
513
|
+
else if (q[0] === 'd') semis -= perfect ? q.length : q.length + 1;
|
|
514
|
+
return semis;
|
|
515
|
+
}
|
|
516
|
+
// The range is read only by the older .voicings() form (S5). Each shape keeps
|
|
517
|
+
// its interval letter steps for spelling there.
|
|
518
|
+
const intervalSteps = (s) => (Number(/\d+/.exec(s)[0]) - 1);
|
|
519
|
+
export function addVoicings(name, dictionary, range) {
|
|
520
|
+
const dict = {};
|
|
521
|
+
for (const [type, shapes] of Object.entries(dictionary ?? {})) {
|
|
522
|
+
dict[type] = shapes.map((s) => {
|
|
523
|
+
const parts = String(s).trim().split(/\s+/);
|
|
524
|
+
const shape = parts.map(intervalSemitones);
|
|
525
|
+
Object.defineProperty(shape, 'steps', { value: parts.map(intervalSteps) });
|
|
526
|
+
return shape;
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
VOICING_DICTIONARIES[name] = dict;
|
|
530
|
+
setDictionaryRange(name, range);
|
|
531
|
+
}
|
|
532
|
+
registerFree('addVoicings', addVoicings);
|
|
533
|
+
|
|
534
|
+
// Tier 3 alias (spec/functions/tier3-aliases.md): the target's own function.
|
|
535
|
+
export const strans = alias('strans', 'scaleTranspose');
|
|
536
|
+
|
|
537
|
+
// Tier 3 alias (spec/functions/tier3-aliases.md): the target's own function.
|
|
538
|
+
export const scaleTrans = alias('scaleTrans', 'scaleTranspose');
|
|
539
|
+
|
|
540
|
+
// Tier 3 alias (spec/functions/tier3-aliases.md): the target's own function.
|
|
541
|
+
export const trans = alias('trans', 'transpose');
|
|
542
|
+
|
|
543
|
+
// Tier 3 alias (spec/functions/tier3-aliases.md): the target's own function.
|
|
544
|
+
export const registerVoicings = alias('registerVoicings', 'addVoicings');
|
|
545
|
+
|
|
546
|
+
// --- note and number helpers (spec/functions/note-helpers.md) ----------------------
|
|
547
|
+
// Plain functions, not patternable.
|
|
548
|
+
const FLATS = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B'];
|
|
549
|
+
export const midiToFreq = registerFree('midiToFreq', (m) => m2f(Number(m)));
|
|
550
|
+
export const freqToMidi = registerFree('freqToMidi', (f) => f2m(Number(f)));
|
|
551
|
+
export const midi2note = registerFree('midi2note', (m) => {
|
|
552
|
+
const x = Number(m);
|
|
553
|
+
if (!Number.isFinite(x)) return String(x);
|
|
554
|
+
return `${FLATS[floorMod(Math.round(x), 12)]}${Math.floor(Math.round(x) / 12) - 1}`;
|
|
555
|
+
});
|
|
556
|
+
export const sol2note = registerFree('sol2note', midi2note);
|
|
557
|
+
const NOTE_TOKEN = /^([a-gA-G])([#b]*)(-?\d+)?$/;
|
|
558
|
+
export const tokenizeNote = registerFree('tokenizeNote', (s) => {
|
|
559
|
+
const m = NOTE_TOKEN.exec(String(s));
|
|
560
|
+
return m ? [m[1], m[2], m[3] === undefined ? undefined : Number(m[3])] : [];
|
|
561
|
+
});
|
|
562
|
+
export const isNote = registerFree('isNote', (s) => NOTE_TOKEN.test(String(s)));
|
|
563
|
+
export const isNoteWithOctave = registerFree('isNoteWithOctave', (s) => {
|
|
564
|
+
const m = NOTE_TOKEN.exec(String(s));
|
|
565
|
+
return !!m && m[3] !== undefined;
|
|
566
|
+
});
|
|
567
|
+
export const valueToMidi = registerFree('valueToMidi', (v) => {
|
|
568
|
+
if (v?.freq !== undefined) return freqToMidi(v.freq);
|
|
569
|
+
if (v?.note !== undefined) return typeof v.note === 'number' ? v.note : noteToMidi(String(v.note));
|
|
570
|
+
throw new Error('valueToMidi: expected freq or note to be set');
|
|
571
|
+
});
|
|
572
|
+
export const clamp = registerFree('clamp', (x, lo, hi) => Math.min(Math.max(x, lo), hi));
|
|
573
|
+
|
|
574
|
+
// --- voicing registry (spec/functions/voicing-registry.md) -------------------------
|
|
575
|
+
// The `legacy` dictionary lives in src/tonal.js. Ranges are read only by the
|
|
576
|
+
// older .voicings() form; voicing() places by its anchor (S5).
|
|
577
|
+
export const setVoicingRange = registerFree('setVoicingRange', (name, range) => { setDictionaryRange(name, range); });
|
|
578
|
+
export const setDefaultVoicings = registerFree('setDefaultVoicings', (name) => { VOICING_DEFAULT.dictionary = name; });
|
|
579
|
+
export const resetVoicings = registerFree('resetVoicings', () => { VOICING_DEFAULT.dictionary = 'ireal'; });
|
|
580
|
+
// A second key for an entry in each dictionary object (a name string throws).
|
|
581
|
+
export const voicingAlias = registerFree('voicingAlias', (symbol, aliasName, dicts) => {
|
|
582
|
+
for (const d of dicts) d[aliasName] = d[symbol];
|
|
583
|
+
});
|