@libraz/libcantus 0.9.1 → 0.9.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.
Files changed (154) hide show
  1. package/README.md +15 -0
  2. package/dist/analyze/index.cjs +1697 -0
  3. package/dist/analyze/index.cjs.map +1 -0
  4. package/dist/analyze/index.d.cts +429 -0
  5. package/dist/analyze/index.d.ts +429 -0
  6. package/dist/analyze/index.js +51 -0
  7. package/dist/analyze/index.js.map +1 -0
  8. package/dist/chunk-5HTNMQW4.js +653 -0
  9. package/dist/chunk-5HTNMQW4.js.map +1 -0
  10. package/dist/chunk-7Y7WF64D.js +410 -0
  11. package/dist/chunk-7Y7WF64D.js.map +1 -0
  12. package/dist/chunk-A4532ZFR.js +259 -0
  13. package/dist/chunk-A4532ZFR.js.map +1 -0
  14. package/dist/chunk-BHUT2S5G.js +22 -0
  15. package/dist/chunk-BHUT2S5G.js.map +1 -0
  16. package/dist/chunk-CCBLVAPK.js +42 -0
  17. package/dist/chunk-CCBLVAPK.js.map +1 -0
  18. package/dist/chunk-COKTX2G5.js +907 -0
  19. package/dist/chunk-COKTX2G5.js.map +1 -0
  20. package/dist/chunk-DYWFNC4A.js +152 -0
  21. package/dist/chunk-DYWFNC4A.js.map +1 -0
  22. package/dist/chunk-GQKN5KDT.js +159 -0
  23. package/dist/chunk-GQKN5KDT.js.map +1 -0
  24. package/dist/chunk-LN7ZZMD2.js +530 -0
  25. package/dist/chunk-LN7ZZMD2.js.map +1 -0
  26. package/dist/chunk-MSWFZF7J.js +118 -0
  27. package/dist/chunk-MSWFZF7J.js.map +1 -0
  28. package/dist/chunk-R3S2LUBH.js +2722 -0
  29. package/dist/chunk-R3S2LUBH.js.map +1 -0
  30. package/dist/chunk-SDM3VJJ5.js +41 -0
  31. package/dist/chunk-SDM3VJJ5.js.map +1 -0
  32. package/dist/chunk-XTC3X6MS.js +816 -0
  33. package/dist/chunk-XTC3X6MS.js.map +1 -0
  34. package/dist/chunk-ZXW5YIWK.js +55 -0
  35. package/dist/chunk-ZXW5YIWK.js.map +1 -0
  36. package/dist/core/index.cjs +432 -0
  37. package/dist/core/index.cjs.map +1 -0
  38. package/dist/core/index.d.cts +210 -0
  39. package/dist/core/index.d.ts +210 -0
  40. package/dist/core/index.js +73 -0
  41. package/dist/core/index.js.map +1 -0
  42. package/dist/function-2bJW1Zp_.d.ts +187 -0
  43. package/dist/function-r2sh-jOO.d.cts +187 -0
  44. package/dist/generate/index.cjs +3787 -0
  45. package/dist/generate/index.cjs.map +1 -0
  46. package/dist/generate/index.d.cts +980 -0
  47. package/dist/generate/index.d.ts +980 -0
  48. package/dist/generate/index.js +52 -0
  49. package/dist/generate/index.js.map +1 -0
  50. package/dist/index-BMPxwjwV.d.ts +151 -0
  51. package/dist/index-BOBXBNwP.d.cts +157 -0
  52. package/dist/index-BdeQ1r_p.d.cts +56 -0
  53. package/dist/index-BreoJRw0.d.ts +127 -0
  54. package/dist/index-CGMZNCx6.d.cts +140 -0
  55. package/dist/index-CGMZNCx6.d.ts +140 -0
  56. package/dist/index-CM5W4rcm.d.ts +157 -0
  57. package/dist/index-CP3wAfEH.d.ts +56 -0
  58. package/dist/index-Cl7mhOFM.d.cts +164 -0
  59. package/dist/index-Cl7mhOFM.d.ts +164 -0
  60. package/dist/index-DZ1M21do.d.cts +127 -0
  61. package/dist/index-D_ZTUNKp.d.cts +151 -0
  62. package/dist/index.cjs +3016 -2984
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.cts +14 -3982
  65. package/dist/index.d.ts +14 -3982
  66. package/dist/index.js +170 -6504
  67. package/dist/index.js.map +1 -1
  68. package/dist/model/index.cjs +2435 -0
  69. package/dist/model/index.cjs.map +1 -0
  70. package/dist/model/index.d.cts +630 -0
  71. package/dist/model/index.d.ts +630 -0
  72. package/dist/model/index.js +21 -0
  73. package/dist/model/index.js.map +1 -0
  74. package/dist/styled-BjXtOFNk.d.cts +282 -0
  75. package/dist/styled-D7BAx3S3.d.ts +282 -0
  76. package/dist/theory/index.cjs +1677 -0
  77. package/dist/theory/index.cjs.map +1 -0
  78. package/dist/theory/index.d.cts +535 -0
  79. package/dist/theory/index.d.ts +535 -0
  80. package/dist/theory/index.js +149 -0
  81. package/dist/theory/index.js.map +1 -0
  82. package/dist/types-MGP29r3t.d.cts +30 -0
  83. package/dist/types-MGP29r3t.d.ts +30 -0
  84. package/package.json +27 -2
  85. package/src/analyze/arrange/index.ts +21 -0
  86. package/src/analyze/arrange/internal.ts +125 -0
  87. package/src/analyze/arrange/tension.ts +187 -0
  88. package/src/analyze/arrange/tracks.ts +279 -0
  89. package/src/{detect → analyze/detect}/index.ts +4 -4
  90. package/src/analyze/functional/borrowed.ts +84 -0
  91. package/src/analyze/functional/cadence.ts +66 -0
  92. package/src/analyze/functional/function.ts +184 -0
  93. package/src/analyze/functional/index.ts +23 -0
  94. package/src/analyze/functional/internal.ts +29 -0
  95. package/src/{functional/index.ts → analyze/functional/roman.ts} +9 -327
  96. package/src/analyze/index.ts +49 -0
  97. package/src/{timeline → analyze/timeline}/index.ts +7 -11
  98. package/src/{analysis → analyze/voice}/index.ts +8 -5
  99. package/src/core/index.ts +47 -0
  100. package/src/{bass → generate/bass}/index.ts +5 -5
  101. package/src/{countermelody → generate/countermelody}/index.ts +11 -11
  102. package/src/{drums → generate/drums}/index.ts +2 -2
  103. package/src/{drums → generate/drums}/rng.ts +2 -2
  104. package/src/{groove → generate/groove}/index.ts +3 -3
  105. package/src/{harmonize → generate/harmonize}/index.ts +13 -13
  106. package/src/generate/index.ts +59 -0
  107. package/src/{motif → generate/motif}/index.ts +7 -7
  108. package/src/{progression → generate/progression}/index.ts +11 -25
  109. package/src/{reharmony → generate/reharmony}/index.ts +11 -11
  110. package/src/{rhythm → generate/rhythm}/index.ts +2 -2
  111. package/src/index.ts +130 -117
  112. package/src/model/chord.ts +423 -0
  113. package/src/model/index.ts +5 -1096
  114. package/src/model/interval.ts +82 -0
  115. package/src/model/key.ts +266 -0
  116. package/src/model/note.ts +176 -0
  117. package/src/model/progression.ts +161 -0
  118. package/src/model/shared.ts +12 -0
  119. package/src/{chord → theory/chord}/index.ts +19 -1
  120. package/src/{counterpoint → theory/counterpoint}/index.ts +2 -2
  121. package/src/theory/index.ts +107 -0
  122. package/src/{safety → theory/safety}/index.ts +1 -1
  123. package/src/theory/scale/degrees.ts +123 -0
  124. package/src/theory/scale/index.ts +28 -0
  125. package/src/theory/scale/key.ts +56 -0
  126. package/src/theory/scale/masks.ts +153 -0
  127. package/src/{spelling → theory/spelling}/index.ts +3 -3
  128. package/src/{symbol → theory/symbol}/index.ts +8 -1
  129. package/src/theory/voicing/index.ts +5 -0
  130. package/src/theory/voicing/internal.ts +168 -0
  131. package/src/theory/voicing/leading.ts +112 -0
  132. package/src/theory/voicing/satb.ts +195 -0
  133. package/src/theory/voicing/styled.ts +176 -0
  134. package/src/arrange/index.ts +0 -571
  135. package/src/scale/index.ts +0 -331
  136. package/src/voicing/index.ts +0 -623
  137. /package/src/{interval → core/interval}/index.ts +0 -0
  138. /package/src/{meter → core/meter}/index.ts +0 -0
  139. /package/src/{pitch → core/pitch}/index.ts +0 -0
  140. /package/src/{random → core/random}/index.ts +0 -0
  141. /package/src/{tuning → core/tuning}/index.ts +0 -0
  142. /package/src/{types.ts → core/types.ts} +0 -0
  143. /package/src/{drums → generate/drums}/beat.ts +0 -0
  144. /package/src/{drums → generate/drums}/euclid.ts +0 -0
  145. /package/src/{drums → generate/drums}/fills.ts +0 -0
  146. /package/src/{drums → generate/drums}/ghost.ts +0 -0
  147. /package/src/{drums → generate/drums}/hihat.ts +0 -0
  148. /package/src/{drums → generate/drums}/hit.ts +0 -0
  149. /package/src/{drums → generate/drums}/internal.ts +0 -0
  150. /package/src/{drums → generate/drums}/kick.ts +0 -0
  151. /package/src/{drums → generate/drums}/percussion.ts +0 -0
  152. /package/src/{drums → generate/drums}/swing.ts +0 -0
  153. /package/src/{chordscale → theory/chordscale}/index.ts +0 -0
  154. /package/src/{harmony → theory/harmony}/index.ts +0 -0
@@ -1,623 +0,0 @@
1
- import type { Chord } from '../chord/index.js';
2
- import { chordPitchClasses, chordToneRole } from '../chord/index.js';
3
- import {
4
- createsHiddenParallelPerfect,
5
- createsParallelPerfect,
6
- createsVoiceCrossing,
7
- createsVoiceOverlap,
8
- exceedsSpacing,
9
- } from '../counterpoint/index.js';
10
-
11
- /**
12
- * An inclusive MIDI pitch range for a single voice.
13
- *
14
- * @category Voicing & Counterpoint
15
- */
16
- export type VoiceRange = {
17
- min: number;
18
- max: number;
19
- };
20
-
21
- /**
22
- * Default four-voice SATB ranges, ascending (index 0 = lowest):
23
- * bass E2–C4 (40–60), tenor C3–G4 (48–67), alto G3–D5 (55–74),
24
- * soprano C4–G5 (60–79).
25
- *
26
- * @category Voicing & Counterpoint
27
- */
28
- export const SATB_RANGES: readonly VoiceRange[] = [
29
- { min: 40, max: 60 },
30
- { min: 48, max: 67 },
31
- { min: 55, max: 74 },
32
- { min: 60, max: 79 },
33
- ];
34
-
35
- /**
36
- * Options controlling {@link voiceChord} and {@link voiceProgression}.
37
- *
38
- * @category Voicing & Counterpoint
39
- */
40
- export type VoicingOptions = {
41
- /**
42
- * Number of voices to realize. Ignored when `ranges` is given.
43
- *
44
- * @defaultValue 4
45
- */
46
- voices?: number;
47
- /** Explicit per-voice ranges, ascending (index 0 = lowest). Takes precedence over `voices`. */
48
- ranges?: VoiceRange[];
49
- /**
50
- * Maximum spacing in semitones between adjacent upper voices.
51
- *
52
- * @defaultValue 12
53
- */
54
- maxSpacing?: number;
55
- };
56
-
57
- /** Default maximum spacing between adjacent upper voices (one octave). */
58
- const DEFAULT_MAX_SPACING = 12;
59
-
60
- /** Overall pitch floor/ceiling used when deriving ranges for arbitrary voice counts. */
61
- const DERIVED_LOW = 40;
62
- const DERIVED_HIGH = 79;
63
- /** Span of each derived per-voice range in semitones. */
64
- const DERIVED_SPAN = 19;
65
-
66
- /** Score penalty per counterpoint violation between consecutive voicings. */
67
- const VIOLATION_PENALTY = 1000;
68
- /** Score penalty per chord tone absent from a voicing. */
69
- const MISSING_TONE_PENALTY = 500;
70
- /** Score penalty per doubled tone that is neither the root nor the fifth. */
71
- const POOR_DOUBLING_PENALTY = 4;
72
- /**
73
- * Moderate penalty for a hidden/direct perfect fifth or octave reached on the
74
- * outer-voice (bass–soprano) pair. Unlike a true parallel perfect it is
75
- * discouraged rather than forbidden, so the weight sits alongside voice-leading
76
- * motion rather than the hard {@link VIOLATION_PENALTY}.
77
- */
78
- const HIDDEN_PERFECT_PENALTY = 6;
79
- /** Hard cap on candidate voicings evaluated per chord, keeping the search bounded. */
80
- const MAX_CANDIDATES = 4000;
81
-
82
- /** Reduce a value to a pitch class in [0, 11]. */
83
- function pitchClass(value: number): number {
84
- return ((Math.trunc(value) % 12) + 12) % 12;
85
- }
86
-
87
- /**
88
- * Resolve the per-voice ranges implied by the options: explicit `ranges` win,
89
- * four voices use {@link SATB_RANGES}, and other counts get evenly spaced
90
- * ranges spanning roughly the bass-to-soprano compass.
91
- */
92
- function resolveRanges(opts?: VoicingOptions): VoiceRange[] {
93
- if (opts?.ranges !== undefined) {
94
- if (opts.ranges.length === 0) {
95
- throw new Error('ranges must contain at least one voice range');
96
- }
97
- return opts.ranges.map((range) => ({ ...range }));
98
- }
99
- const voices = opts?.voices ?? 4;
100
- if (voices < 1) {
101
- throw new Error('voices must be at least 1');
102
- }
103
- if (voices === 4) {
104
- return SATB_RANGES.map((range) => ({ ...range }));
105
- }
106
- if (voices === 1) {
107
- return [{ min: DERIVED_LOW, max: DERIVED_HIGH }];
108
- }
109
- const ranges: VoiceRange[] = [];
110
- for (let i = 0; i < voices; i += 1) {
111
- const min = Math.round(
112
- DERIVED_LOW + (i * (DERIVED_HIGH - DERIVED_SPAN - DERIVED_LOW)) / (voices - 1),
113
- );
114
- ranges.push({ min, max: min + DERIVED_SPAN });
115
- }
116
- return ranges;
117
- }
118
-
119
- /**
120
- * All MIDI pitches of a pitch class inside an inclusive range, ordered from the
121
- * centre of the range outward (ties break toward the lower pitch). Enumerating
122
- * centre-outward keeps the candidate set balanced around the register when it
123
- * is truncated at {@link MAX_CANDIDATES}, instead of skewing to the low octaves
124
- * that a plain ascending scan would visit first.
125
- */
126
- function pitchesForPc(pc: number, range: VoiceRange): number[] {
127
- const result: number[] = [];
128
- for (let midi = Math.ceil(range.min); midi <= range.max; midi += 1) {
129
- if (pitchClass(midi) === pc) {
130
- result.push(midi);
131
- }
132
- }
133
- const center = (range.min + range.max) / 2;
134
- return result.sort((a, b) => {
135
- const da = Math.abs(a - center);
136
- const db = Math.abs(b - center);
137
- return da === db ? a - b : da - db;
138
- });
139
- }
140
-
141
- /**
142
- * Enumerate candidate voicings for a chord: the bass takes the chord's bass
143
- * (or root) pitch class at each available octave, and each upper voice takes
144
- * any chord pitch class within its range. Candidates are built in ascending
145
- * voice order and pruned to exclude voice crossings and over-wide adjacent
146
- * spacing (the bass–tenor pair is allowed an extra octave, per convention).
147
- * Enumeration is deterministic and capped at {@link MAX_CANDIDATES}.
148
- */
149
- function enumerateVoicings(chord: Chord, ranges: VoiceRange[], maxSpacing: number): number[][] {
150
- const chordPcs = chordPitchClasses(chord);
151
- const bassPc = pitchClass(chord.bassPc ?? chord.rootPc);
152
- const results: number[][] = [];
153
- const current: number[] = [];
154
- const build = (voice: number): void => {
155
- if (results.length >= MAX_CANDIDATES) {
156
- return;
157
- }
158
- if (voice === ranges.length) {
159
- results.push([...current]);
160
- return;
161
- }
162
- const range = ranges[voice];
163
- if (range === undefined) {
164
- return;
165
- }
166
- const pcs = voice === 0 ? [bassPc] : chordPcs;
167
- const prev = current[voice - 1];
168
- for (const pc of pcs) {
169
- for (const pitch of pitchesForPc(pc, range)) {
170
- if (prev !== undefined) {
171
- if (pitch < prev) {
172
- continue; // would cross below the next lower voice
173
- }
174
- const spacingLimit = voice === 1 ? maxSpacing + 12 : maxSpacing;
175
- if (pitch - prev > spacingLimit) {
176
- continue;
177
- }
178
- }
179
- current.push(pitch);
180
- build(voice + 1);
181
- current.pop();
182
- }
183
- }
184
- };
185
- build(0);
186
- return results;
187
- }
188
-
189
- /**
190
- * Structural quality penalty of a single voicing: heavily penalize missing
191
- * chord tones, mildly penalize doubling anything other than the root or fifth.
192
- */
193
- function structuralPenalty(pitches: number[], chord: Chord): number {
194
- const counts = new Map<number, number>();
195
- for (const pitch of pitches) {
196
- const pc = pitchClass(pitch);
197
- counts.set(pc, (counts.get(pc) ?? 0) + 1);
198
- }
199
- let penalty = 0;
200
- for (const pc of chordPitchClasses(chord)) {
201
- if (!counts.has(pc)) {
202
- penalty += MISSING_TONE_PENALTY;
203
- }
204
- }
205
- const rootPc = pitchClass(chord.rootPc);
206
- const fifthPc = pitchClass(chord.rootPc + 7);
207
- for (const [pc, count] of counts) {
208
- if (count > 1 && pc !== rootPc && pc !== fifthPc) {
209
- penalty += (count - 1) * POOR_DOUBLING_PENALTY;
210
- }
211
- }
212
- return penalty;
213
- }
214
-
215
- /**
216
- * Count counterpoint violations between two consecutive voicings of equal
217
- * length: parallel perfects (fifths and octaves alike, since octaves are the
218
- * perfect-class-zero case of {@link createsParallelPerfect}) on every voice
219
- * pair, voice crossings in the new voicing, and — on adjacent pairs — voice
220
- * overlaps and over-wide spacing between upper voices.
221
- */
222
- function violationCount(prev: number[], cur: number[], maxSpacing: number): number {
223
- let count = 0;
224
- for (let lower = 0; lower < cur.length; lower += 1) {
225
- for (let upper = lower + 1; upper < cur.length; upper += 1) {
226
- const prevLower = prev[lower];
227
- const prevUpper = prev[upper];
228
- const curLower = cur[lower];
229
- const curUpper = cur[upper];
230
- if (
231
- prevLower === undefined ||
232
- prevUpper === undefined ||
233
- curLower === undefined ||
234
- curUpper === undefined
235
- ) {
236
- continue;
237
- }
238
- if (createsParallelPerfect(prevUpper, curUpper, prevLower, curLower)) {
239
- count += 1;
240
- }
241
- if (createsVoiceCrossing(curUpper, curLower)) {
242
- count += 1;
243
- }
244
- if (upper === lower + 1) {
245
- if (createsVoiceOverlap(prevUpper, curUpper, prevLower, curLower)) {
246
- count += 1;
247
- }
248
- if (lower > 0 && exceedsSpacing(curUpper, curLower, maxSpacing)) {
249
- count += 1;
250
- }
251
- }
252
- }
253
- }
254
- return count;
255
- }
256
-
257
- /**
258
- * Total voice-leading cost between two voicings: the sum of absolute semitone
259
- * motion across voices, plus a moderate {@link HIDDEN_PERFECT_PENALTY} when the
260
- * outer-voice (bass–soprano) pair reaches a hidden/direct perfect fifth or
261
- * octave by similar motion. The arrays must be the same length; when they
262
- * differ the voicings are not comparable and the cost is `Infinity`.
263
- *
264
- * @param from The previous voicing, one MIDI pitch per voice.
265
- * @param to The next voicing, one MIDI pitch per voice.
266
- * @returns The summed absolute motion (plus any hidden-perfect penalty), or
267
- * `Infinity` when lengths differ.
268
- * @category Voicing & Counterpoint
269
- */
270
- export function voiceLeadingCost(from: number[], to: number[]): number {
271
- if (from.length !== to.length) {
272
- return Number.POSITIVE_INFINITY;
273
- }
274
- let total = 0;
275
- for (let i = 0; i < from.length; i += 1) {
276
- const a = from[i];
277
- const b = to[i];
278
- if (a === undefined || b === undefined) {
279
- continue;
280
- }
281
- total += Math.abs(b - a);
282
- }
283
- // Discourage hidden/direct perfects between the outermost voices, where they
284
- // are most audible. True parallels are handled (and forbidden) elsewhere.
285
- if (from.length >= 2) {
286
- const bassPrev = from[0];
287
- const bassCur = to[0];
288
- const sopPrev = from[from.length - 1];
289
- const sopCur = to[to.length - 1];
290
- if (
291
- bassPrev !== undefined &&
292
- bassCur !== undefined &&
293
- sopPrev !== undefined &&
294
- sopCur !== undefined &&
295
- createsHiddenParallelPerfect(bassPrev, bassCur, sopPrev, sopCur)
296
- ) {
297
- total += HIDDEN_PERFECT_PENALTY;
298
- }
299
- }
300
- return total;
301
- }
302
-
303
- /**
304
- * Realize a single chord as one MIDI pitch per voice, ascending (index 0 =
305
- * lowest). The bass voice takes the chord's `bassPc` when set, otherwise the
306
- * root; upper voices take chord pitch classes, doubling the root or fifth as
307
- * needed to fill all voices. The result stays inside each voice's range, keeps
308
- * adjacent upper voices within `maxSpacing`, avoids voice crossing, and is
309
- * deterministic: a compact close-position voicing centered in the ranges.
310
- *
311
- * @param chord The chord to voice.
312
- * @param opts Voicing options; defaults to four voices in {@link SATB_RANGES}.
313
- * @returns MIDI pitches, ascending, one per voice.
314
- * @throws If no voicing fits the given ranges.
315
- * @example
316
- * ```ts
317
- * import { parseChordSymbol, voiceChord } from '@libraz/libcantus';
318
- * const chord = parseChordSymbol('Cmaj7');
319
- * voiceChord(chord); // four ascending MIDI pitches within the SATB ranges
320
- * ```
321
- * @category Voicing & Counterpoint
322
- */
323
- export function voiceChord(chord: Chord, opts?: VoicingOptions): number[] {
324
- const ranges = resolveRanges(opts);
325
- const maxSpacing = opts?.maxSpacing ?? DEFAULT_MAX_SPACING;
326
- const candidates = enumerateVoicings(chord, ranges, maxSpacing);
327
- let best: number[] | undefined;
328
- let bestScore = Number.POSITIVE_INFINITY;
329
- for (const candidate of candidates) {
330
- let score = structuralPenalty(candidate, chord);
331
- for (let i = 0; i < candidate.length; i += 1) {
332
- const pitch = candidate[i];
333
- const range = ranges[i];
334
- if (pitch === undefined || range === undefined) {
335
- continue;
336
- }
337
- // Prefer pitches near the middle of each voice's range for a centered,
338
- // compact default voicing.
339
- score += Math.abs(pitch - (range.min + range.max) / 2);
340
- }
341
- if (score < bestScore) {
342
- bestScore = score;
343
- best = candidate;
344
- }
345
- }
346
- if (best === undefined) {
347
- throw new Error('no voicing satisfies the given ranges');
348
- }
349
- return best;
350
- }
351
-
352
- /**
353
- * Voice a chord progression with smooth voice leading. The first chord is
354
- * voiced with {@link voiceChord}; each subsequent chord picks, from a bounded
355
- * deterministic candidate set, the voicing minimizing the voice-leading cost
356
- * from the previous voicing plus a large penalty per counterpoint violation
357
- * (parallel perfects/octaves, voice crossing, voice overlap, and over-wide
358
- * upper-voice spacing).
359
- *
360
- * @param chords The chords to voice in order.
361
- * @param opts Voicing options; defaults to four voices in {@link SATB_RANGES}.
362
- * @returns One voicing per chord, each ascending with one MIDI pitch per voice.
363
- * @throws If any chord admits no voicing within the given ranges.
364
- * @example
365
- * ```ts
366
- * import { parseChordSymbol, voiceProgression } from '@libraz/libcantus';
367
- * const chords = ['C', 'Am', 'F', 'G'].map((s) => parseChordSymbol(s));
368
- * voiceProgression(chords); // one four-voice voicing per chord, smoothly led
369
- * ```
370
- * @category Voicing & Counterpoint
371
- */
372
- export function voiceProgression(chords: Chord[], opts?: VoicingOptions): number[][] {
373
- const ranges = resolveRanges(opts);
374
- const maxSpacing = opts?.maxSpacing ?? DEFAULT_MAX_SPACING;
375
- const result: number[][] = [];
376
- let prev: number[] | undefined;
377
- for (const chord of chords) {
378
- if (prev === undefined) {
379
- prev = voiceChord(chord, opts);
380
- result.push(prev);
381
- continue;
382
- }
383
- const candidates = enumerateVoicings(chord, ranges, maxSpacing);
384
- let best: number[] | undefined;
385
- let bestScore = Number.POSITIVE_INFINITY;
386
- for (const candidate of candidates) {
387
- const score =
388
- structuralPenalty(candidate, chord) +
389
- voiceLeadingCost(prev, candidate) +
390
- VIOLATION_PENALTY * violationCount(prev, candidate, maxSpacing);
391
- if (score < bestScore) {
392
- bestScore = score;
393
- best = candidate;
394
- }
395
- }
396
- if (best === undefined) {
397
- throw new Error('no voicing satisfies the given ranges');
398
- }
399
- result.push(best);
400
- prev = best;
401
- }
402
- return result;
403
- }
404
-
405
- /**
406
- * A tertian voicing style for {@link voiceChordStyled}.
407
- *
408
- * - `close`: the plain close-position tertian stack.
409
- * - `drop2`: the second voice from the top dropped an octave (drop-2 voicing).
410
- * - `drop3`: the third voice from the top dropped an octave (drop-3 voicing).
411
- * - `shell`: root plus guide tones (third and seventh) for seventh chords, or
412
- * root/third/fifth for triads; the fifth and tensions are omitted.
413
- * - `rootless`: the root omitted, keeping third/fifth/seventh and tensions
414
- * (a typical left-hand jazz voicing).
415
- *
416
- * @category Voicing & Counterpoint
417
- */
418
- export type VoicingStyle = 'close' | 'drop2' | 'drop3' | 'shell' | 'rootless';
419
-
420
- /**
421
- * Options controlling {@link voiceChordStyled}.
422
- *
423
- * @category Voicing & Counterpoint
424
- */
425
- export type StyledVoicingOptions = {
426
- /**
427
- * Voicing style to build.
428
- *
429
- * @defaultValue 'close'
430
- */
431
- style?: VoicingStyle;
432
- /** Constrain the highest voice to this pitch class (0..11) when given. */
433
- topNote?: number;
434
- /**
435
- * Base octave for the close stack; the stack begins near `12 * octave`.
436
- *
437
- * @defaultValue 4
438
- */
439
- octave?: number;
440
- /**
441
- * Omit the root regardless of style (relevant for jazz voicings).
442
- *
443
- * @defaultValue false
444
- */
445
- rootless?: boolean;
446
- };
447
-
448
- /** Default base octave for a styled close-position stack. */
449
- const DEFAULT_STYLE_OCTAVE = 4;
450
-
451
- /** Return the pitch classes of a list in order, without duplicates. */
452
- function dedupePcs(pcs: number[]): number[] {
453
- const seen = new Set<number>();
454
- const result: number[] = [];
455
- for (const pc of pcs) {
456
- if (!seen.has(pc)) {
457
- seen.add(pc);
458
- result.push(pc);
459
- }
460
- }
461
- return result;
462
- }
463
-
464
- /** The lowest MIDI pitch of a pitch class at or above a floor. */
465
- function lowestPitchAtOrAbove(pc: number, floor: number): number {
466
- return floor + ((((pc - pitchClass(floor)) % 12) + 12) % 12);
467
- }
468
-
469
- /** The pitch class in `pcs` whose circular distance to `target` is smallest. */
470
- function nearestPc(target: number, pcs: number[]): number {
471
- let best = pcs[0] ?? target;
472
- let bestDist = 12;
473
- for (const pc of pcs) {
474
- const dist = Math.min((((pc - target) % 12) + 12) % 12, (((target - pc) % 12) + 12) % 12);
475
- if (dist < bestDist) {
476
- bestDist = dist;
477
- best = pc;
478
- }
479
- }
480
- return best;
481
- }
482
-
483
- /**
484
- * Realize a single chord as an explicit tertian voicing in a chosen style,
485
- * independent of the SATB range search used by {@link voiceChord}.
486
- *
487
- * The chord tones are stacked in close position from the bass (`bassPc`, else
488
- * `rootPc`) in the given scientific-pitch `octave` upward (octave 4 starts the
489
- * bass near C4 = MIDI 60, matching {@link midiToNote} and the bass module).
490
- * When `topNote` is given the stack is rotated so the highest voice's pitch
491
- * class equals that note (or the nearest chord tone). The chosen
492
- * {@link VoicingStyle} then transforms the stack, and the result is returned as
493
- * ascending MIDI pitches (index 0 = lowest).
494
- *
495
- * @param chord The chord to voice.
496
- * @param opts Styled voicing options; defaults to a close voicing at octave 4.
497
- * @returns MIDI pitches, ascending, one per retained voice.
498
- * @example
499
- * ```ts
500
- * import { parseChordSymbol, voiceChordStyled } from '@libraz/libcantus';
501
- * const chord = parseChordSymbol('Dm7');
502
- * voiceChordStyled(chord, { style: 'drop2' }); // ascending MIDI pitches, drop-2 voicing
503
- * ```
504
- * @category Voicing & Counterpoint
505
- */
506
- export function voiceChordStyled(chord: Chord, opts?: StyledVoicingOptions): number[] {
507
- const style = opts?.style ?? 'close';
508
- const base = 12 * ((opts?.octave ?? DEFAULT_STYLE_OCTAVE) + 1);
509
- const rootPc = pitchClass(chord.rootPc);
510
- const bassPc = pitchClass(chord.bassPc ?? chord.rootPc);
511
- const omitRoot = style === 'rootless' || opts?.rootless === true;
512
-
513
- // Tertian chord tones in order, with the bass tone rotated to the bottom.
514
- let order = dedupePcs(chord.intervals.map((interval) => pitchClass(chord.rootPc + interval)));
515
- const bassIndex = order.indexOf(bassPc);
516
- if (bassIndex > 0) {
517
- order = [...order.slice(bassIndex), ...order.slice(0, bassIndex)];
518
- } else if (bassIndex < 0) {
519
- order = [bassPc, ...order];
520
- }
521
-
522
- if (style === 'shell') {
523
- const roles = order.map((pc) => chordToneRole(pc, chord));
524
- // The guide tone is the seventh when present; on a sixth chord the sixth
525
- // stands in for it, and otherwise the voicing falls back to the fifth.
526
- const guide = roles.includes('seventh')
527
- ? 'seventh'
528
- : roles.includes('sixth')
529
- ? 'sixth'
530
- : 'fifth';
531
- order = order.filter((_pc, i) => {
532
- const role = roles[i];
533
- return role === 'root' || role === 'third' || role === guide;
534
- });
535
- }
536
-
537
- if (omitRoot) {
538
- order = order.filter((pc) => pc !== rootPc);
539
- }
540
-
541
- if (order.length === 0) {
542
- return [];
543
- }
544
-
545
- if (opts?.topNote !== undefined) {
546
- const target = order.includes(pitchClass(opts.topNote))
547
- ? pitchClass(opts.topNote)
548
- : nearestPc(pitchClass(opts.topNote), order);
549
- const targetIndex = order.indexOf(target);
550
- order = [...order.slice(targetIndex + 1), ...order.slice(0, targetIndex + 1)];
551
- }
552
-
553
- // Stack the ordered pitch classes upward in close position.
554
- const stack: number[] = [];
555
- let prev: number | undefined;
556
- for (const pc of order) {
557
- if (prev === undefined) {
558
- prev = lowestPitchAtOrAbove(pc, base);
559
- } else {
560
- let delta = (((pc - pitchClass(prev)) % 12) + 12) % 12;
561
- if (delta === 0) {
562
- delta = 12;
563
- }
564
- prev += delta;
565
- }
566
- stack.push(prev);
567
- }
568
-
569
- if (style === 'drop2' && stack.length >= 2) {
570
- stack[stack.length - 2] = (stack[stack.length - 2] ?? 0) - 12;
571
- } else if (style === 'drop3' && stack.length >= 3) {
572
- stack[stack.length - 3] = (stack[stack.length - 3] ?? 0) - 12;
573
- }
574
-
575
- return stack.sort((a, b) => a - b);
576
- }
577
-
578
- /**
579
- * Voice a single chord to follow smoothly from an arbitrary current voicing.
580
- *
581
- * Candidate voicings of `chord` are enumerated within ranges taken from `opts`,
582
- * or — when neither `voices` nor `ranges` is given — from a one-octave window
583
- * around each pitch of `current` (so the result matches `current`'s voice
584
- * count). Each candidate is scored by structural quality, voice-leading motion
585
- * from `current`, and a large penalty per counterpoint violation; the lowest
586
- * scoring candidate is returned, ascending.
587
- *
588
- * @param current The current voicing to lead from, ascending (index 0 = lowest).
589
- * @param chord The next chord to voice.
590
- * @param opts Voicing options; when omitted, ranges follow `current`'s span.
591
- * @returns The chosen voicing, ascending with one MIDI pitch per voice.
592
- * @throws If no voicing fits the derived ranges.
593
- * @category Voicing & Counterpoint
594
- */
595
- export function nextVoicing(current: number[], chord: Chord, opts?: VoicingOptions): number[] {
596
- const ranges =
597
- opts?.ranges !== undefined || opts?.voices !== undefined
598
- ? resolveRanges(opts)
599
- : current.map((pitch) => {
600
- // Window one octave around each current pitch, clamped so extreme-low
601
- // or extreme-high input can never yield MIDI outside [0, 127].
602
- const centre = Math.min(127, Math.max(0, pitch));
603
- return { min: Math.max(0, centre - 12), max: Math.min(127, centre + 12) };
604
- });
605
- const maxSpacing = opts?.maxSpacing ?? DEFAULT_MAX_SPACING;
606
- const candidates = enumerateVoicings(chord, ranges, maxSpacing);
607
- let best: number[] | undefined;
608
- let bestScore = Number.POSITIVE_INFINITY;
609
- for (const candidate of candidates) {
610
- const score =
611
- structuralPenalty(candidate, chord) +
612
- voiceLeadingCost(current, candidate) +
613
- VIOLATION_PENALTY * violationCount(current, candidate, maxSpacing);
614
- if (score < bestScore) {
615
- bestScore = score;
616
- best = candidate;
617
- }
618
- }
619
- if (best === undefined) {
620
- throw new Error('no voicing satisfies the given ranges');
621
- }
622
- return best;
623
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes