@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
@@ -0,0 +1,2722 @@
1
+ import {
2
+ createRng
3
+ } from "./chunk-BHUT2S5G.js";
4
+ import {
5
+ beatsPerBar,
6
+ formatTimeSignature,
7
+ isStrongBeat,
8
+ metricWeight
9
+ } from "./chunk-MSWFZF7J.js";
10
+ import {
11
+ roleOf
12
+ } from "./chunk-SDM3VJJ5.js";
13
+ import {
14
+ enumerateSafePitches
15
+ } from "./chunk-A4532ZFR.js";
16
+ import {
17
+ NATURAL_MINOR_MASK,
18
+ chordPitchClasses,
19
+ chordToneRole,
20
+ createsParallelPerfect,
21
+ diatonicTriad,
22
+ isForbiddenMelodicLeap,
23
+ isScaleTone,
24
+ majorKey,
25
+ makeChord,
26
+ minorKey,
27
+ nearestScaleTone,
28
+ scaleTonesInDegreeOrder
29
+ } from "./chunk-7Y7WF64D.js";
30
+
31
+ // src/generate/bass/index.ts
32
+ var DEFAULT_TS = { numerator: 4, denominator: 4 };
33
+ var DEFAULT_STYLE = "root";
34
+ var DEFAULT_OCTAVE = 2;
35
+ var STRONG_VELOCITY = 100;
36
+ var WEAK_VELOCITY = 80;
37
+ var PICKUP_PROB = 0.35;
38
+ var EPS = 1e-9;
39
+ function pitchClass(value) {
40
+ return (Math.trunc(value) % 12 + 12) % 12;
41
+ }
42
+ function placePc(pc, anchor, low) {
43
+ const high = low + 12;
44
+ let midi = pc + 12 * Math.round((anchor - pc) / 12);
45
+ while (midi < low) {
46
+ midi += 12;
47
+ }
48
+ while (midi > high) {
49
+ midi -= 12;
50
+ }
51
+ return midi;
52
+ }
53
+ function chordTonePcs(chord) {
54
+ const seen = /* @__PURE__ */ new Set();
55
+ const pcs = [];
56
+ for (const interval of chord.intervals) {
57
+ const pc = pitchClass(chord.rootPc + interval);
58
+ if (!seen.has(pc)) {
59
+ seen.add(pc);
60
+ pcs.push(pc);
61
+ }
62
+ }
63
+ if (pcs.length === 0) {
64
+ pcs.push(pitchClass(chord.rootPc));
65
+ }
66
+ return pcs;
67
+ }
68
+ function fifthPcOf(chord) {
69
+ const fifths = new Set(chord.intervals.map((i) => pitchClass(i)));
70
+ const chosen = fifths.has(7) ? 7 : fifths.has(6) ? 6 : fifths.has(8) ? 8 : void 0;
71
+ return chosen === void 0 ? pitchClass(chord.rootPc) : pitchClass(chord.rootPc + chosen);
72
+ }
73
+ function bassPcOf(chord) {
74
+ return pitchClass(chord.bassPc ?? chord.rootPc);
75
+ }
76
+ function beatPositions(start, end) {
77
+ const positions = [];
78
+ for (let p = start; p < end - EPS; p += 1) {
79
+ positions.push(p);
80
+ }
81
+ if (positions.length === 0) {
82
+ positions.push(start);
83
+ }
84
+ return positions;
85
+ }
86
+ function emit(ctx, pos, pc, midiOverride) {
87
+ const midi = midiOverride ?? placePc(pc, ctx.prevMidi, ctx.low);
88
+ const velocity = isStrongBeat(pos, ctx.ts) ? STRONG_VELOCITY : WEAK_VELOCITY;
89
+ ctx.notes.push({ startBeat: pos, pitch: midi, velocity });
90
+ return midi;
91
+ }
92
+ function buildRoot(ctx, seg) {
93
+ ctx.prevMidi = emit(ctx, seg.startBeat, bassPcOf(seg.chord));
94
+ }
95
+ function buildRootFifth(ctx, seg) {
96
+ ctx.prevMidi = emit(ctx, seg.startBeat, bassPcOf(seg.chord));
97
+ const mid = (seg.startBeat + seg.endBeat) / 2;
98
+ if (mid > seg.startBeat + EPS && mid < seg.endBeat - EPS) {
99
+ ctx.prevMidi = emit(ctx, mid, fifthPcOf(seg.chord));
100
+ }
101
+ }
102
+ function buildPop(ctx, seg) {
103
+ const positions = beatPositions(seg.startBeat, seg.endBeat);
104
+ const rootPc = bassPcOf(seg.chord);
105
+ let emitted = false;
106
+ for (const pos of positions) {
107
+ if (isStrongBeat(pos, ctx.ts)) {
108
+ ctx.prevMidi = emit(ctx, pos, rootPc);
109
+ emitted = true;
110
+ } else if (ctx.rng.prob(PICKUP_PROB)) {
111
+ if (ctx.rng.prob(0.5)) {
112
+ const base = placePc(rootPc, ctx.prevMidi, ctx.low);
113
+ emit(ctx, pos, rootPc, Math.max(ctx.low, base - 12));
114
+ } else {
115
+ ctx.prevMidi = emit(ctx, pos, fifthPcOf(seg.chord));
116
+ }
117
+ }
118
+ }
119
+ if (!emitted) {
120
+ ctx.prevMidi = emit(ctx, seg.startBeat, rootPc);
121
+ }
122
+ }
123
+ function buildArpeggio(ctx, seg) {
124
+ const tones = chordTonePcs(seg.chord);
125
+ const positions = beatPositions(seg.startBeat, seg.endBeat);
126
+ positions.forEach((pos, i) => {
127
+ const pc = tones[i % tones.length] ?? bassPcOf(seg.chord);
128
+ ctx.prevMidi = emit(ctx, pos, pc);
129
+ });
130
+ }
131
+ function approachNote(ctx, target, from) {
132
+ const dir = from <= target ? -1 : 1;
133
+ if (ctx.rng.prob(0.5)) {
134
+ return target + dir;
135
+ }
136
+ const cand = nearestScaleTone(target + dir * 2, ctx.key);
137
+ const step = Math.abs(cand - target);
138
+ return step >= 1 && step <= 2 ? cand : target + dir;
139
+ }
140
+ function buildWalking(ctx, seg, next) {
141
+ const tones = chordTonePcs(seg.chord);
142
+ const positions = beatPositions(seg.startBeat, seg.endBeat);
143
+ const count = positions.length;
144
+ positions.forEach((pos, i) => {
145
+ if (i === 0) {
146
+ ctx.prevMidi = emit(ctx, pos, bassPcOf(seg.chord));
147
+ return;
148
+ }
149
+ if (next && count > 1 && i === count - 1) {
150
+ const nextBass = placePc(bassPcOf(next.chord), ctx.prevMidi, ctx.low);
151
+ const midi = approachNote(ctx, nextBass, ctx.prevMidi);
152
+ ctx.prevMidi = emit(ctx, pos, pitchClass(midi), midi);
153
+ return;
154
+ }
155
+ const pc = tones[i % tones.length] ?? bassPcOf(seg.chord);
156
+ ctx.prevMidi = emit(ctx, pos, pc);
157
+ });
158
+ }
159
+ function generateBassLine(opts) {
160
+ const segments = [...opts.segments].sort((a, b) => a.startBeat - b.startBeat);
161
+ if (segments.length === 0) {
162
+ return [];
163
+ }
164
+ const ts = opts.ts ?? DEFAULT_TS;
165
+ const style = opts.style ?? DEFAULT_STYLE;
166
+ const octave = opts.octave ?? DEFAULT_OCTAVE;
167
+ const low = octave * 12 + 12;
168
+ const ctx = {
169
+ ts,
170
+ low,
171
+ key: opts.key,
172
+ rng: createRng(opts.seed ?? 0),
173
+ notes: [],
174
+ prevMidi: low
175
+ };
176
+ for (let s = 0; s < segments.length; s += 1) {
177
+ const seg = segments[s];
178
+ if (!seg) {
179
+ continue;
180
+ }
181
+ switch (style) {
182
+ case "rootFifth":
183
+ buildRootFifth(ctx, seg);
184
+ break;
185
+ case "pop":
186
+ buildPop(ctx, seg);
187
+ break;
188
+ case "walking":
189
+ buildWalking(ctx, seg, segments[s + 1]);
190
+ break;
191
+ case "arpeggio":
192
+ buildArpeggio(ctx, seg);
193
+ break;
194
+ default:
195
+ buildRoot(ctx, seg);
196
+ break;
197
+ }
198
+ }
199
+ ctx.notes.sort((a, b) => a.startBeat - b.startBeat);
200
+ const lastEnd = segments.reduce((m, seg) => Math.max(m, seg.endBeat), Number.NEGATIVE_INFINITY);
201
+ const out = [];
202
+ for (let i = 0; i < ctx.notes.length; i += 1) {
203
+ const note = ctx.notes[i];
204
+ if (!note) {
205
+ continue;
206
+ }
207
+ const nextStart = ctx.notes[i + 1]?.startBeat ?? lastEnd;
208
+ const durationBeat = nextStart - note.startBeat;
209
+ if (durationBeat <= EPS) {
210
+ continue;
211
+ }
212
+ out.push({
213
+ pitch: note.pitch,
214
+ startBeat: note.startBeat,
215
+ durationBeat,
216
+ velocity: note.velocity
217
+ });
218
+ }
219
+ return out;
220
+ }
221
+
222
+ // src/generate/countermelody/index.ts
223
+ var DEFAULT_TS2 = { numerator: 4, denominator: 4 };
224
+ var EPS2 = 1e-9;
225
+ var GRID_STEP = 0.5;
226
+ var MIN_ONSET_GAP = 1;
227
+ var REGISTER_OFFSET = 12;
228
+ var DEFAULT_HALF_RANGE = 10;
229
+ var HOLD_ON_BEAT_PROB = 0.55;
230
+ var HOLD_OFF_BEAT_PROB = 0.2;
231
+ var REINFORCE_PROB = 0.35;
232
+ var DEFAULT_MELODY_VELOCITY = 96;
233
+ var VELOCITY_DROP = 16;
234
+ function isWholeBeat(beat) {
235
+ return Math.abs(beat - Math.round(beat)) < EPS2;
236
+ }
237
+ function melodyNoteAt(melody, beat) {
238
+ let found;
239
+ for (const note of melody) {
240
+ if (note.startBeat - EPS2 <= beat && beat < note.startBeat + note.durationBeat - EPS2) {
241
+ if (!found || note.startBeat > found.startBeat) {
242
+ found = note;
243
+ }
244
+ }
245
+ }
246
+ return found;
247
+ }
248
+ function melodyAttacksAt(melody, beat) {
249
+ return melody.some((note) => Math.abs(note.startBeat - beat) < EPS2);
250
+ }
251
+ function followOnsets(melody) {
252
+ return [...new Set(melody.map((note) => note.startBeat))].sort((a, b) => a - b);
253
+ }
254
+ function complementOnsets(melody, ts, spanStart, spanEnd, rng) {
255
+ const onsets = [];
256
+ const gridStart = Math.floor(spanStart / GRID_STEP) * GRID_STEP;
257
+ let last = Number.NEGATIVE_INFINITY;
258
+ for (let beat = gridStart; beat < spanEnd - EPS2; beat += GRID_STEP) {
259
+ const attacked = melodyAttacksAt(melody, beat);
260
+ const sounding = melodyNoteAt(melody, beat) !== void 0;
261
+ let place = false;
262
+ if (!attacked && !sounding) {
263
+ place = isWholeBeat(beat);
264
+ } else if (!attacked) {
265
+ place = rng.prob(isWholeBeat(beat) ? HOLD_ON_BEAT_PROB : HOLD_OFF_BEAT_PROB);
266
+ } else if (isStrongBeat(beat, ts)) {
267
+ place = rng.prob(REINFORCE_PROB);
268
+ }
269
+ if (place && beat - last >= MIN_ONSET_GAP - EPS2) {
270
+ onsets.push(beat);
271
+ last = beat;
272
+ }
273
+ }
274
+ return onsets;
275
+ }
276
+ function scoreCandidate(pitch, melPitch, melPrev, prevPitch, chord, center) {
277
+ let score = 0;
278
+ if (melPitch !== void 0) {
279
+ const ic = Math.abs(pitch - melPitch) % 12;
280
+ if (ic === 3 || ic === 4 || ic === 8 || ic === 9) {
281
+ score += 2;
282
+ } else if (ic === 0 || ic === 7) {
283
+ score += 0.5;
284
+ } else if (ic === 1 || ic === 2 || ic === 6 || ic === 10 || ic === 11) {
285
+ score -= 2;
286
+ }
287
+ }
288
+ if (chord && chordToneRole(pitch, chord) !== null) {
289
+ score += 1;
290
+ }
291
+ if (prevPitch !== void 0) {
292
+ const move = pitch - prevPitch;
293
+ const dist = Math.abs(move);
294
+ score -= dist * 0.3;
295
+ if (dist > 0 && dist <= 2) {
296
+ score += 1;
297
+ }
298
+ if (isForbiddenMelodicLeap(prevPitch, pitch)) {
299
+ score -= 6;
300
+ }
301
+ if (melPitch !== void 0 && melPrev !== void 0) {
302
+ const melMove = melPitch - melPrev;
303
+ if (move > 0 && melMove < 0 || move < 0 && melMove > 0) {
304
+ score += 2;
305
+ } else if (move === 0 || melMove === 0) {
306
+ score += 1;
307
+ } else {
308
+ score -= 1;
309
+ }
310
+ }
311
+ }
312
+ score -= Math.abs(pitch - center) * 0.02;
313
+ return score;
314
+ }
315
+ function fallbackPitch(melPitch, prevPitch, center, register, low, high, key) {
316
+ let target = prevPitch ?? Math.round(center);
317
+ if (melPitch !== void 0) {
318
+ if (register === "below" && target >= melPitch) {
319
+ target = melPitch - 5;
320
+ } else if (register === "above" && target <= melPitch) {
321
+ target = melPitch + 5;
322
+ }
323
+ }
324
+ target = Math.min(Math.max(target, low), high);
325
+ let pitch = nearestScaleTone(target, key);
326
+ if (melPitch !== void 0) {
327
+ while (register === "below" && pitch >= melPitch && pitch - 12 >= low) {
328
+ pitch -= 12;
329
+ }
330
+ while (register === "above" && pitch <= melPitch && pitch + 12 <= high) {
331
+ pitch += 12;
332
+ }
333
+ }
334
+ return Math.min(Math.max(pitch, low), high);
335
+ }
336
+ function generateCounterMelody(opts) {
337
+ const melody = [...opts.melody].sort((a, b) => a.startBeat - b.startBeat);
338
+ if (melody.length === 0) {
339
+ return [];
340
+ }
341
+ const ts = opts.ts ?? DEFAULT_TS2;
342
+ const register = opts.register ?? "below";
343
+ const rhythm = opts.rhythm ?? "complement";
344
+ const profile = opts.profile ?? "pop";
345
+ const rng = createRng(opts.seed ?? 0);
346
+ const spanStart = melody[0]?.startBeat ?? 0;
347
+ const spanEnd = melody.reduce((end, n) => Math.max(end, n.startBeat + n.durationBeat), spanStart);
348
+ const meanPitch = melody.reduce((sum, n) => sum + n.pitch, 0) / melody.length;
349
+ const defaultCenter = register === "below" ? meanPitch - REGISTER_OFFSET : meanPitch + REGISTER_OFFSET;
350
+ const low = opts.pitchLow ?? Math.round(defaultCenter) - DEFAULT_HALF_RANGE;
351
+ const high = opts.pitchHigh ?? Math.round(defaultCenter) + DEFAULT_HALF_RANGE;
352
+ const center = (low + high) / 2;
353
+ const onsets = rhythm === "follow" ? followOnsets(melody) : complementOnsets(melody, ts, spanStart, spanEnd, rng);
354
+ const out = [];
355
+ let prevPitch;
356
+ let prevOnset;
357
+ for (const beat of onsets) {
358
+ const melNote = melodyNoteAt(melody, beat);
359
+ const melPitch = melNote?.pitch;
360
+ const melPrev = prevOnset !== void 0 ? melodyNoteAt(melody, prevOnset)?.pitch : void 0;
361
+ const chord = opts.chordAt(beat);
362
+ const otherVoices = melPitch !== void 0 ? [{ pitch: melPitch, prevPitch: melPrev }] : [];
363
+ const candidates = enumerateSafePitches(
364
+ {
365
+ profile,
366
+ prevPitch,
367
+ chord,
368
+ key: opts.key,
369
+ otherVoices,
370
+ strongBeat: isStrongBeat(beat, ts),
371
+ vocalLow: low,
372
+ vocalHigh: high
373
+ },
374
+ low,
375
+ high
376
+ );
377
+ let bestPitch;
378
+ let bestScore = Number.NEGATIVE_INFINITY;
379
+ for (const candidate of candidates) {
380
+ if (melPitch !== void 0) {
381
+ if (register === "below" && candidate >= melPitch) {
382
+ continue;
383
+ }
384
+ if (register === "above" && candidate <= melPitch) {
385
+ continue;
386
+ }
387
+ if (prevPitch !== void 0 && melPrev !== void 0 && // Parallel octaves are the perfect-class-zero case of this predicate,
388
+ // so a single check covers both parallel fifths and octaves.
389
+ createsParallelPerfect(prevPitch, candidate, melPrev, melPitch)) {
390
+ continue;
391
+ }
392
+ }
393
+ const score = scoreCandidate(candidate, melPitch, melPrev, prevPitch, chord, center);
394
+ const tie = Math.abs(score - bestScore) <= EPS2 && candidate < (bestPitch ?? Number.POSITIVE_INFINITY);
395
+ if (score > bestScore + EPS2 || tie) {
396
+ bestScore = score;
397
+ bestPitch = candidate;
398
+ }
399
+ }
400
+ const pitch = bestPitch ?? fallbackPitch(melPitch, prevPitch, center, register, low, high, opts.key);
401
+ const velocity = Math.max(
402
+ 1,
403
+ Math.min(127, Math.round((melNote?.velocity ?? DEFAULT_MELODY_VELOCITY) - VELOCITY_DROP))
404
+ );
405
+ out.push({ pitch, startBeat: beat, durationBeat: GRID_STEP, velocity });
406
+ prevPitch = pitch;
407
+ prevOnset = beat;
408
+ }
409
+ for (let i = 0; i < out.length; i += 1) {
410
+ const note = out[i];
411
+ if (!note) {
412
+ continue;
413
+ }
414
+ const next = out[i + 1];
415
+ const end = next ? next.startBeat : Math.max(spanEnd, note.startBeat + GRID_STEP);
416
+ note.durationBeat = end - note.startBeat;
417
+ }
418
+ return out;
419
+ }
420
+
421
+ // src/generate/drums/internal.ts
422
+ var GM = {
423
+ BD: 36,
424
+ SD: 38,
425
+ SIDESTICK: 37,
426
+ HANDCLAP: 39,
427
+ CHH: 42,
428
+ FHH: 44,
429
+ OHH: 46,
430
+ CRASH: 49,
431
+ RIDE: 51,
432
+ TAMBOURINE: 54,
433
+ TOM_H: 50,
434
+ TOM_M: 47,
435
+ TOM_L: 45,
436
+ SHAKER: 82
437
+ };
438
+ var EIGHTH = 0.5;
439
+ var SIXTEENTH = 0.25;
440
+ var STYLE_MAP = {
441
+ // Standard pop pulse: kick on beats 1 and 3, backbeat snare on 2 and 4.
442
+ standard: { style: "standard", feel: "straight", ghostBoost: false, snareBeat3: false },
443
+ funk: { style: "upbeat", feel: "straight", ghostBoost: true, snareBeat3: false },
444
+ shuffle: { style: "standard", feel: "shuffle", ghostBoost: false, snareBeat3: false },
445
+ bossa: { style: "latin", feel: "straight", ghostBoost: false, snareBeat3: false },
446
+ trap: { style: "trap", feel: "straight", ghostBoost: false, snareBeat3: true },
447
+ halftime: { style: "sparse", feel: "straight", ghostBoost: false, snareBeat3: true },
448
+ breakbeat: { style: "rock", feel: "straight", ghostBoost: false, snareBeat3: false },
449
+ // Four-on-the-floor dance kick with idol-style auxiliary percussion.
450
+ house: { style: "fourOnFloor", feel: "straight", ghostBoost: false, snareBeat3: false },
451
+ // Synth-pop pulse with denser 16th hi-hats and busy kick syncopation.
452
+ synthpop: { style: "synth", feel: "straight", ghostBoost: true, snareBeat3: false }
453
+ };
454
+ function mapStyle(style) {
455
+ return STYLE_MAP[style];
456
+ }
457
+ function mapSection(section) {
458
+ switch (section) {
459
+ case "intro":
460
+ return "intro";
461
+ case "verse":
462
+ return "a";
463
+ case "prechorus":
464
+ return "b";
465
+ case "chorus":
466
+ return "chorus";
467
+ case "bridge":
468
+ return "bridge";
469
+ case "outro":
470
+ return "outro";
471
+ }
472
+ }
473
+ function mapDensity(density) {
474
+ if (density < 0.34) {
475
+ return "thin";
476
+ }
477
+ if (density < 0.67) {
478
+ return "normal";
479
+ }
480
+ return "thick";
481
+ }
482
+ function feelSwingAmount(feel) {
483
+ if (feel === "swing") {
484
+ return 0.33;
485
+ }
486
+ if (feel === "shuffle") {
487
+ return 0.5;
488
+ }
489
+ return 0;
490
+ }
491
+ function ghostMoodCategory(style) {
492
+ if (style === "sparse") {
493
+ return 0 /* Calm */;
494
+ }
495
+ if (style === "trap" || style === "upbeat") {
496
+ return 2 /* Energetic */;
497
+ }
498
+ return 1 /* Standard */;
499
+ }
500
+ function percMoodCategory(style) {
501
+ switch (style) {
502
+ case "sparse":
503
+ return 0 /* Calm */;
504
+ case "upbeat":
505
+ case "latin":
506
+ return 2 /* Energetic */;
507
+ case "fourOnFloor":
508
+ return 3 /* Idol */;
509
+ case "trap":
510
+ case "rock":
511
+ return 4 /* RockDark */;
512
+ default:
513
+ return 1 /* Standard */;
514
+ }
515
+ }
516
+ function sectionIndex(section) {
517
+ switch (section) {
518
+ case "intro":
519
+ return 0;
520
+ case "a":
521
+ return 1;
522
+ case "b":
523
+ return 2;
524
+ case "chorus":
525
+ return 3;
526
+ case "bridge":
527
+ return 4;
528
+ case "outro":
529
+ return 6;
530
+ }
531
+ }
532
+ function sectionEnergy(section) {
533
+ switch (section) {
534
+ case "intro":
535
+ case "outro":
536
+ return "low";
537
+ case "a":
538
+ case "bridge":
539
+ return "medium";
540
+ case "b":
541
+ return "high";
542
+ case "chorus":
543
+ return "peak";
544
+ }
545
+ }
546
+ function sectionVelocityMultiplier(section) {
547
+ switch (section) {
548
+ case "intro":
549
+ case "outro":
550
+ return 0.8;
551
+ case "a":
552
+ return 0.9;
553
+ case "b":
554
+ return 1;
555
+ case "chorus":
556
+ return 1.1;
557
+ case "bridge":
558
+ return 0.85;
559
+ }
560
+ }
561
+ function sectionDensityMultiplier(section) {
562
+ switch (section) {
563
+ case "intro":
564
+ return 0.5;
565
+ case "a":
566
+ return 0.7;
567
+ case "b":
568
+ return 0.85;
569
+ case "chorus":
570
+ return 1;
571
+ case "bridge":
572
+ return 0.6;
573
+ case "outro":
574
+ return 0.6;
575
+ }
576
+ }
577
+ function calculateVelocity(section, beat) {
578
+ const base = 80;
579
+ const beatAdj = beat === 0 ? 10 : beat === 2 ? 5 : 0;
580
+ const velocity = (base + beatAdj) * sectionVelocityMultiplier(section);
581
+ return clampVel(velocity);
582
+ }
583
+ function clampVel(velocity) {
584
+ return Math.max(1, Math.min(127, Math.round(velocity)));
585
+ }
586
+
587
+ // src/generate/drums/ghost.ts
588
+ var GHOST_DENSITY_TABLE = [
589
+ /* intro */
590
+ [0, 1, 1],
591
+ /* a */
592
+ [0, 1, 2],
593
+ /* b */
594
+ [1, 2, 2],
595
+ /* chorus */
596
+ [1, 2, 3],
597
+ /* bridge */
598
+ [1, 1, 2],
599
+ /* interlude */
600
+ [0, 1, 1],
601
+ /* outro */
602
+ [0, 1, 1]
603
+ ];
604
+ function levelToProbability(level) {
605
+ switch (level) {
606
+ case 0:
607
+ return 0;
608
+ case 1:
609
+ return 0.15;
610
+ case 2:
611
+ return 0.3;
612
+ case 3:
613
+ return 0.45;
614
+ }
615
+ }
616
+ function clampLevel(level) {
617
+ return Math.max(0, Math.min(3, level));
618
+ }
619
+ function adjustForBpm(level, bpm) {
620
+ if (bpm >= 160 && level !== 0) {
621
+ return clampLevel(level - 1);
622
+ }
623
+ if (bpm <= 90 && level !== 3) {
624
+ return clampLevel(level + 1);
625
+ }
626
+ return level;
627
+ }
628
+ function getGhostDensity(mood, section, backingDensity, bpm) {
629
+ const row = GHOST_DENSITY_TABLE[sectionIndex(section)] ?? GHOST_DENSITY_TABLE[1];
630
+ const level = adjustForBpm(row?.[mood] ?? 0, bpm);
631
+ if (backingDensity === "thin" && level !== 0) {
632
+ return levelToProbability(clampLevel(level - 1));
633
+ }
634
+ if (backingDensity === "thick" && level !== 3) {
635
+ return levelToProbability(clampLevel(level + 1));
636
+ }
637
+ return levelToProbability(level);
638
+ }
639
+ function getGhostVelocity(section, beatPosition, isAfterSnare) {
640
+ let base = 0.4;
641
+ const even = beatPosition % 2 === 0 ? 0.05 : 0;
642
+ switch (section) {
643
+ case "a":
644
+ base = 0.35 + even;
645
+ break;
646
+ case "chorus":
647
+ base = 0.5 + even;
648
+ break;
649
+ case "bridge":
650
+ base = 0.25 + even;
651
+ break;
652
+ case "b":
653
+ base = 0.4 + even;
654
+ break;
655
+ case "intro":
656
+ case "outro":
657
+ base = 0.38;
658
+ break;
659
+ }
660
+ if (isAfterSnare) {
661
+ base += 0.1;
662
+ }
663
+ return Math.max(0.25, Math.min(0.65, base));
664
+ }
665
+ function getGhostProbabilityAtPosition(beat, sixteenthInBeat) {
666
+ const nearSnare = beat === 0 && sixteenthInBeat === 3 || beat === 1 && sixteenthInBeat === 1 || beat === 2 && sixteenthInBeat === 3 || beat === 3 && sixteenthInBeat === 1;
667
+ return nearSnare ? 0.6 : 0.25;
668
+ }
669
+ function selectGhostPositions(mood, rng) {
670
+ if (mood === 2 /* Energetic */) {
671
+ return ["e", "a"];
672
+ }
673
+ if (mood === 0 /* Calm */) {
674
+ return rng.prob(0.5) ? ["e"] : [];
675
+ }
676
+ return ["e"];
677
+ }
678
+
679
+ // src/generate/drums/hihat.ts
680
+ var HH_16TH_BPM_THRESHOLD = 150;
681
+ var FHH_VEL_MIN = 45;
682
+ var FHH_VEL_MAX = 60;
683
+ var OHH_VEL_BOOST = 7;
684
+ function shouldPlayHiHat(role) {
685
+ return role !== "fxOnly";
686
+ }
687
+ function roleHiHatInstrument(role, useRide) {
688
+ if (role === "ambient") {
689
+ return GM.RIDE;
690
+ }
691
+ return useRide ? GM.RIDE : GM.CHH;
692
+ }
693
+ function sparser(level) {
694
+ if (level === "sixteenth") {
695
+ return "eighth";
696
+ }
697
+ if (level === "eighth") {
698
+ return "quarter";
699
+ }
700
+ return "quarter";
701
+ }
702
+ function denser(level) {
703
+ if (level === "quarter") {
704
+ return "eighth";
705
+ }
706
+ if (level === "eighth") {
707
+ return "sixteenth";
708
+ }
709
+ return "sixteenth";
710
+ }
711
+ function getHiHatLevel(section, style, backingDensity, bpm, rng) {
712
+ const allow16th = bpm < HH_16TH_BPM_THRESHOLD;
713
+ let base = "eighth";
714
+ if (style === "sparse") {
715
+ base = section === "chorus" ? "eighth" : "quarter";
716
+ } else if (style === "fourOnFloor") {
717
+ if (allow16th && section === "chorus" && rng.prob(0.25)) {
718
+ return "sixteenth";
719
+ }
720
+ return "eighth";
721
+ } else if (style === "synth") {
722
+ if (!allow16th) {
723
+ return "eighth";
724
+ }
725
+ if (section === "a" && rng.prob(0.2)) {
726
+ return "eighth";
727
+ }
728
+ return "sixteenth";
729
+ } else if (style === "trap") {
730
+ return allow16th ? "sixteenth" : "eighth";
731
+ } else if (style === "latin") {
732
+ if (allow16th && section === "chorus" && rng.prob(0.3)) {
733
+ return "sixteenth";
734
+ }
735
+ return "eighth";
736
+ } else {
737
+ switch (section) {
738
+ case "intro":
739
+ base = "quarter";
740
+ break;
741
+ case "outro":
742
+ base = "eighth";
743
+ break;
744
+ case "a":
745
+ base = rng.prob(0.3) ? "quarter" : "eighth";
746
+ break;
747
+ case "b":
748
+ base = allow16th && rng.prob(0.25) ? "sixteenth" : "eighth";
749
+ break;
750
+ case "chorus":
751
+ base = allow16th && rng.prob(0.35) ? "sixteenth" : "eighth";
752
+ break;
753
+ case "bridge":
754
+ base = "eighth";
755
+ break;
756
+ }
757
+ }
758
+ if (backingDensity === "thin") {
759
+ base = sparser(base);
760
+ } else if (backingDensity === "thick") {
761
+ base = denser(base);
762
+ }
763
+ if (!allow16th && base === "sixteenth") {
764
+ base = "eighth";
765
+ }
766
+ return base;
767
+ }
768
+ function hiHatVelocityMultiplier(sixteenth, rng) {
769
+ let baseValue;
770
+ switch (sixteenth) {
771
+ case 0:
772
+ baseValue = 0.95;
773
+ break;
774
+ case 2:
775
+ baseValue = 0.75;
776
+ break;
777
+ case 1:
778
+ baseValue = 0.55;
779
+ break;
780
+ default:
781
+ baseValue = 0.5;
782
+ break;
783
+ }
784
+ return baseValue * rng.float(0.95, 1.05);
785
+ }
786
+ function openHiHatBarInterval(section, style) {
787
+ if (style === "sparse") {
788
+ return section === "chorus" ? 4 : 0;
789
+ }
790
+ switch (section) {
791
+ case "intro":
792
+ return style === "fourOnFloor" ? 4 : 0;
793
+ case "a":
794
+ return style === "fourOnFloor" || style === "upbeat" ? 2 : 4;
795
+ case "b":
796
+ return 2;
797
+ case "chorus":
798
+ return style === "rock" || style === "fourOnFloor" ? 1 : 2;
799
+ case "bridge":
800
+ return 0;
801
+ case "outro":
802
+ return 4;
803
+ }
804
+ }
805
+ function openHiHatBeat(section, rng) {
806
+ if (section === "chorus") {
807
+ const choice = rng.range(0, 3);
808
+ if (choice < 2) {
809
+ return 3;
810
+ }
811
+ if (choice < 3) {
812
+ return 1;
813
+ }
814
+ return 2;
815
+ }
816
+ return 3;
817
+ }
818
+ function shouldUseFootHiHat(section, role) {
819
+ if (role === "fxOnly") {
820
+ return false;
821
+ }
822
+ switch (section) {
823
+ case "intro":
824
+ case "bridge":
825
+ case "outro":
826
+ return true;
827
+ default:
828
+ return role === "ambient" || role === "minimal";
829
+ }
830
+ }
831
+ function sectionHiHatType(section, role) {
832
+ if (role === "ambient") {
833
+ return "ride";
834
+ }
835
+ if (role === "minimal") {
836
+ return "pedal";
837
+ }
838
+ switch (section) {
839
+ case "intro":
840
+ case "a":
841
+ return "pedal";
842
+ case "b":
843
+ return "closed";
844
+ case "chorus":
845
+ return "open";
846
+ case "bridge":
847
+ return "ride";
848
+ case "outro":
849
+ return "halfOpen";
850
+ }
851
+ }
852
+ function hiHatNote(type) {
853
+ switch (type) {
854
+ case "pedal":
855
+ return GM.FHH;
856
+ case "open":
857
+ return GM.OHH;
858
+ case "ride":
859
+ return GM.RIDE;
860
+ default:
861
+ return GM.CHH;
862
+ }
863
+ }
864
+ function hiHatTypeVelocityMultiplier(type) {
865
+ switch (type) {
866
+ case "halfOpen":
867
+ return 0.75;
868
+ case "pedal":
869
+ return 0.65;
870
+ case "open":
871
+ return 1;
872
+ case "ride":
873
+ return 0.9;
874
+ default:
875
+ return 0.85;
876
+ }
877
+ }
878
+ function shouldAddOpenHHAccent(section, beat, bar, rng) {
879
+ if (section !== "chorus" && section !== "b") {
880
+ return false;
881
+ }
882
+ if (section === "chorus") {
883
+ if (beat === 1 || beat === 3) {
884
+ return rng.prob(0.6);
885
+ }
886
+ return false;
887
+ }
888
+ if (beat === 3 && bar % 2 === 1) {
889
+ return rng.prob(0.4);
890
+ }
891
+ return false;
892
+ }
893
+ function footHiHatVelocity(rng) {
894
+ return rng.range(FHH_VEL_MIN, FHH_VEL_MAX);
895
+ }
896
+ function shouldUseRideForSection(section, style) {
897
+ if (style === "rock" && section === "chorus") {
898
+ return true;
899
+ }
900
+ if (style === "sparse") {
901
+ return false;
902
+ }
903
+ return section === "bridge";
904
+ }
905
+ function shouldUseBridgeCrossStick(section, beat) {
906
+ return section === "bridge" && (beat === 1 || beat === 3);
907
+ }
908
+
909
+ // src/generate/drums/swing.ts
910
+ var SIXTEENTH2 = 0.25;
911
+ var EIGHTH2 = 0.5;
912
+ var HALF_16TH = 0.125;
913
+ var DELTA_16 = 1 / 3 - 1 / 4;
914
+ var DELTA_8 = (2 / 3 - 1 / 2) / 2 + (2 / 3 - 1 / 2) / 2;
915
+ function effectiveSwing(feel, swingAmount) {
916
+ if (feel === "straight") {
917
+ return 0;
918
+ }
919
+ if (feel === "shuffle") {
920
+ return Math.min(1, swingAmount * 1.5);
921
+ }
922
+ return swingAmount;
923
+ }
924
+ function quantizeSwing(startBeat, swing, resolution) {
925
+ const clamped = Math.max(0, Math.min(1, swing));
926
+ if (clamped <= 0) {
927
+ return startBeat;
928
+ }
929
+ const base = Math.floor(startBeat);
930
+ const offset = startBeat - base;
931
+ if (resolution === "sixteenth") {
932
+ if (offset >= HALF_16TH && offset < SIXTEENTH2 + HALF_16TH) {
933
+ return base + SIXTEENTH2 + DELTA_16 * clamped;
934
+ }
935
+ if (offset >= SIXTEENTH2 + HALF_16TH && offset < EIGHTH2 + HALF_16TH) {
936
+ return base + EIGHTH2 + DELTA_8 * clamped;
937
+ }
938
+ if (offset >= EIGHTH2 + HALF_16TH && offset < 3 * SIXTEENTH2 + HALF_16TH) {
939
+ return base + 3 * SIXTEENTH2 + DELTA_16 * clamped;
940
+ }
941
+ return startBeat;
942
+ }
943
+ if (offset >= SIXTEENTH2 && offset < 3 * SIXTEENTH2) {
944
+ return base + EIGHTH2 + DELTA_8 * clamped;
945
+ }
946
+ return startBeat;
947
+ }
948
+
949
+ // src/generate/drums/beat.ts
950
+ function swing16(tick, feel, swingAmount) {
951
+ return quantizeSwing(tick, effectiveSwing(feel, swingAmount), "sixteenth");
952
+ }
953
+ function hatSwingFactor(style) {
954
+ if (style === "trap") {
955
+ return 0;
956
+ }
957
+ if (style === "latin") {
958
+ return 0.35;
959
+ }
960
+ return 0.5;
961
+ }
962
+ function generateKickForBeat(ctx, sec, kick) {
963
+ if (ctx.inPrechorusLift) {
964
+ return;
965
+ }
966
+ const on = [kick.beat1, kick.beat2, kick.beat3, kick.beat4][ctx.beat] ?? false;
967
+ const and = [kick.beat1and, kick.beat2and, kick.beat3and, kick.beat4and][ctx.beat] ?? false;
968
+ if (on) {
969
+ ctx.track.add(GM.BD, ctx.beatTick, EIGHTH, ctx.velocity);
970
+ }
971
+ if (and) {
972
+ const andTick = swing16(ctx.beatTick + EIGHTH, sec.feel, ctx.swingAmount);
973
+ ctx.track.add(GM.BD, andTick, EIGHTH, ctx.velocity * 0.85);
974
+ }
975
+ }
976
+ function generateSnareForBeat(ctx, sec, isIntroFirst) {
977
+ if (ctx.inPrechorusLift) {
978
+ return;
979
+ }
980
+ const snareOn = sec.snareBeat3 ? ctx.beat === 2 : ctx.beat === 1 || ctx.beat === 3;
981
+ if (!snareOn || isIntroFirst) {
982
+ return;
983
+ }
984
+ if (sec.useRide && shouldUseBridgeCrossStick(ctx.section, ctx.beat)) {
985
+ return;
986
+ }
987
+ const backbeatVel = Math.min(127, ctx.velocity + 16);
988
+ const promoteSparseChorus = sec.style === "sparse" && ctx.section === "chorus" && sec.role === "full";
989
+ if (promoteSparseChorus) {
990
+ ctx.track.add(GM.SD, ctx.beatTick, EIGHTH, backbeatVel);
991
+ } else if (sec.style === "sparse" || sec.role === "ambient") {
992
+ if (sec.role !== "fxOnly" && sec.role !== "minimal") {
993
+ ctx.track.add(GM.SIDESTICK, ctx.beatTick, EIGHTH, ctx.velocity * 0.8);
994
+ }
995
+ } else {
996
+ ctx.track.add(GM.SD, ctx.beatTick, EIGHTH, backbeatVel);
997
+ }
998
+ }
999
+ function generateGhostNotesForBeat(ctx, sec) {
1000
+ if (ctx.beat !== 0 && ctx.beat !== 2) {
1001
+ return;
1002
+ }
1003
+ const positions = selectGhostPositions(sec.ghostMood, ctx.rng);
1004
+ let ghostProb = getGhostDensity(sec.ghostMood, ctx.section, sec.backingDensity, ctx.bpm);
1005
+ if (sec.ghostBoost) {
1006
+ ghostProb = Math.min(1, ghostProb * 1.4);
1007
+ }
1008
+ for (const pos of positions) {
1009
+ const sixteenthInBeat = pos === "e" ? 1 : 3;
1010
+ const posProb = getGhostProbabilityAtPosition(ctx.beat, sixteenthInBeat);
1011
+ if (!ctx.rng.prob(ghostProb * posProb)) {
1012
+ continue;
1013
+ }
1014
+ const variation = ctx.rng.float(0.85, 1.15);
1015
+ const ghostBase = getGhostVelocity(ctx.section, ctx.beat / 2, false);
1016
+ let ghostVel = ctx.velocity * ghostBase * variation;
1017
+ if (pos === "a") {
1018
+ ghostVel *= 0.9;
1019
+ }
1020
+ const offset = pos === "e" ? SIXTEENTH : 3 * SIXTEENTH;
1021
+ const tick = swing16(ctx.beatTick + offset, sec.feel, ctx.swingAmount);
1022
+ ctx.track.add(GM.SD, tick, SIXTEENTH, ghostVel);
1023
+ }
1024
+ }
1025
+ function generatePreChorusBuildup(ctx, sec, isSectionLastBar) {
1026
+ if (sec.style === "sparse") {
1027
+ if (isSectionLastBar && ctx.beat === 3) {
1028
+ ctx.track.add(GM.SD, ctx.beatTick, EIGHTH, Math.max(45, ctx.velocity * 0.75));
1029
+ ctx.track.add(GM.CRASH, ctx.beatTick + EIGHTH + SIXTEENTH, SIXTEENTH, ctx.velocity * 0.9);
1030
+ }
1031
+ return;
1032
+ }
1033
+ const barsInLift = 2;
1034
+ const barInLift = ctx.bar - (ctx.sectionBars - barsInLift);
1035
+ const progress = (barInLift * 4 + ctx.beat) / (barsInLift * 4);
1036
+ const buildupVel = ctx.velocity * (0.5 + 0.5 * progress);
1037
+ ctx.track.add(GM.SD, ctx.beatTick, EIGHTH, buildupVel);
1038
+ ctx.track.add(GM.SD, ctx.beatTick + EIGHTH, EIGHTH, buildupVel * 0.85);
1039
+ if (isSectionLastBar && ctx.beat === 3) {
1040
+ ctx.track.add(GM.CRASH, ctx.beatTick + EIGHTH + SIXTEENTH, SIXTEENTH, ctx.velocity * 1.1);
1041
+ }
1042
+ }
1043
+ function generateHiHatForBeat(ctx, sec) {
1044
+ if (!shouldPlayHiHat(sec.role)) {
1045
+ if (sec.useFootHh && (ctx.beat === 0 || ctx.beat === 2)) {
1046
+ ctx.track.add(GM.FHH, ctx.beatTick, EIGHTH, footHiHatVelocity(ctx.rng));
1047
+ }
1048
+ return;
1049
+ }
1050
+ const crossStick = sec.useRide && shouldUseBridgeCrossStick(ctx.section, ctx.beat);
1051
+ const hhInstrument = crossStick ? GM.SIDESTICK : roleHiHatInstrument(sec.role, sec.useRide);
1052
+ const hhType = sectionHiHatType(ctx.section, sec.role);
1053
+ const typeMult = hiHatTypeVelocityMultiplier(hhType);
1054
+ const isDynamicOpen = ctx.barHasOpenHh && ctx.beat === ctx.openHhBeat;
1055
+ const dm = sec.densityMult;
1056
+ if (sec.hhLevel === "quarter") {
1057
+ const introRest = ctx.section === "intro" && ctx.beat !== 0;
1058
+ if (!introRest) {
1059
+ if (isDynamicOpen) {
1060
+ ctx.track.add(
1061
+ GM.OHH,
1062
+ ctx.beatTick,
1063
+ EIGHTH,
1064
+ ctx.velocity * dm * 0.75 * typeMult + OHH_VEL_BOOST
1065
+ );
1066
+ } else {
1067
+ ctx.track.add(
1068
+ hhInstrument,
1069
+ ctx.beatTick,
1070
+ EIGHTH,
1071
+ Math.max(20, ctx.velocity * dm * 0.75 * typeMult)
1072
+ );
1073
+ }
1074
+ } else if (sec.useFootHh) {
1075
+ ctx.track.add(GM.FHH, ctx.beatTick, EIGHTH, footHiHatVelocity(ctx.rng));
1076
+ }
1077
+ return;
1078
+ }
1079
+ if (sec.hhLevel === "eighth") {
1080
+ for (let eighth = 0; eighth < 2; eighth += 1) {
1081
+ let hhTick = ctx.beatTick + eighth * EIGHTH;
1082
+ if (eighth === 1) {
1083
+ hhTick = swing16(hhTick, sec.feel, ctx.swingAmount);
1084
+ }
1085
+ if (ctx.section === "intro" && eighth === 1) {
1086
+ if (sec.useFootHh && ctx.beat % 2 === 0) {
1087
+ ctx.track.add(GM.FHH, hhTick, EIGHTH, footHiHatVelocity(ctx.rng));
1088
+ }
1089
+ continue;
1090
+ }
1091
+ const hhVel = Math.max(20, ctx.velocity * dm * typeMult * (eighth === 0 ? 0.9 : 0.65));
1092
+ if (isDynamicOpen && eighth === 0) {
1093
+ ctx.track.add(GM.OHH, hhTick, EIGHTH, hhVel + OHH_VEL_BOOST);
1094
+ continue;
1095
+ }
1096
+ let useOpen = false;
1097
+ if (sec.style === "fourOnFloor" && eighth === 1) {
1098
+ const openProb = Math.max(0.15, Math.min(0.8, 45 / ctx.bpm));
1099
+ useOpen = (ctx.beat === 1 || ctx.beat === 3) && ctx.rng.prob(openProb);
1100
+ } else if (eighth === 0) {
1101
+ useOpen = shouldAddOpenHHAccent(ctx.section, ctx.beat, ctx.bar, ctx.rng);
1102
+ }
1103
+ if (useOpen) {
1104
+ ctx.track.add(hiHatNote("open"), hhTick, EIGHTH, Math.max(20, hhVel * 1.1));
1105
+ } else {
1106
+ ctx.track.add(hhInstrument, hhTick, EIGHTH / 2, hhVel);
1107
+ }
1108
+ }
1109
+ return;
1110
+ }
1111
+ for (let sixteenth = 0; sixteenth < 4; sixteenth += 1) {
1112
+ let hhTick = ctx.beatTick + sixteenth * SIXTEENTH;
1113
+ if (sixteenth === 1 || sixteenth === 3) {
1114
+ const swung = effectiveSwing(sec.feel, ctx.swingAmount) * hatSwingFactor(sec.style);
1115
+ hhTick = quantizeSwing(hhTick, swung, "sixteenth");
1116
+ }
1117
+ const metricVel = hiHatVelocityMultiplier(sixteenth, ctx.rng);
1118
+ const hhVel = Math.max(20, ctx.velocity * dm * typeMult * metricVel);
1119
+ if (isDynamicOpen && sixteenth === 0) {
1120
+ ctx.track.add(GM.OHH, hhTick, SIXTEENTH, hhVel + OHH_VEL_BOOST);
1121
+ continue;
1122
+ }
1123
+ if (ctx.beat === 3 && sixteenth === 3) {
1124
+ const openProb = Math.max(0.1, Math.min(0.4, 30 / ctx.bpm));
1125
+ if (ctx.rng.prob(openProb)) {
1126
+ ctx.track.add(GM.OHH, hhTick, SIXTEENTH, Math.max(20, hhVel * 1.2));
1127
+ continue;
1128
+ }
1129
+ }
1130
+ ctx.track.add(hhInstrument, hhTick, SIXTEENTH / 2, hhVel);
1131
+ }
1132
+ }
1133
+
1134
+ // src/generate/drums/euclid.ts
1135
+ function euclideanRhythm(pulses, steps, rotation = 0) {
1136
+ if (steps < 1) {
1137
+ return [];
1138
+ }
1139
+ const p = Math.max(0, Math.min(pulses, steps));
1140
+ const base = bjorklund(p, steps);
1141
+ const shift = (rotation % steps + steps) % steps;
1142
+ if (shift === 0) {
1143
+ return base;
1144
+ }
1145
+ return base.map((_, i) => base[(i - shift + steps) % steps] ?? false);
1146
+ }
1147
+ function hasHit(mask, step) {
1148
+ return (mask >> step & 1) === 1;
1149
+ }
1150
+ function patternToMask(pattern) {
1151
+ let mask = 0;
1152
+ for (let i = 0; i < pattern.length; i += 1) {
1153
+ if (pattern[i]) {
1154
+ mask |= 1 << i;
1155
+ }
1156
+ }
1157
+ return mask;
1158
+ }
1159
+ function bjorklund(pulses, steps) {
1160
+ if (pulses === 0) {
1161
+ return Array.from({ length: steps }, () => false);
1162
+ }
1163
+ if (pulses >= steps) {
1164
+ return Array.from({ length: steps }, () => true);
1165
+ }
1166
+ let head = Array.from({ length: pulses }, () => [true]);
1167
+ let remainder = Array.from({ length: steps - pulses }, () => [false]);
1168
+ while (remainder.length > 1) {
1169
+ const count = Math.min(head.length, remainder.length);
1170
+ const next = [];
1171
+ for (let i = 0; i < count; i += 1) {
1172
+ next.push([...head[i] ?? [], ...remainder[i] ?? []]);
1173
+ }
1174
+ remainder = head.length > count ? head.slice(count) : remainder.slice(count);
1175
+ head = next;
1176
+ }
1177
+ return [...head.flat(), ...remainder.flat()];
1178
+ }
1179
+
1180
+ // src/generate/drums/fills.ts
1181
+ function getFillStartBeat(energy) {
1182
+ switch (energy) {
1183
+ case "low":
1184
+ return 3;
1185
+ case "medium":
1186
+ return 2;
1187
+ case "high":
1188
+ case "peak":
1189
+ return 0;
1190
+ }
1191
+ }
1192
+ function selectFillType(from, to, style, nextEnergy, rng) {
1193
+ if (style === "sparse") {
1194
+ return rng.range(0, 1) === 0 ? "simpleCrash" : "breakdownFill";
1195
+ }
1196
+ const toChorus = to === "chorus";
1197
+ const fromIntro = from === "intro";
1198
+ const highEnergy = style === "rock" || style === "fourOnFloor";
1199
+ if (nextEnergy === "low") {
1200
+ switch (rng.range(0, 2)) {
1201
+ case 0:
1202
+ return "simpleCrash";
1203
+ case 1:
1204
+ return "breakdownFill";
1205
+ default:
1206
+ return "halfTimeFill";
1207
+ }
1208
+ }
1209
+ if (toChorus) {
1210
+ const choice2 = rng.range(0, 7);
1211
+ if (highEnergy) {
1212
+ switch (choice2) {
1213
+ case 0:
1214
+ case 1:
1215
+ return "tomDescend";
1216
+ case 2:
1217
+ return "snareRoll";
1218
+ case 3:
1219
+ return "linearFill";
1220
+ case 4:
1221
+ return "bdSnareAlternate";
1222
+ case 5:
1223
+ return "flamsAndDrags";
1224
+ case 6:
1225
+ return "tomShuffle";
1226
+ default:
1227
+ return "ghostToAccent";
1228
+ }
1229
+ }
1230
+ switch (choice2) {
1231
+ case 0:
1232
+ case 1:
1233
+ return "snareTomCombo";
1234
+ case 2:
1235
+ return "tomDescend";
1236
+ case 3:
1237
+ return "ghostToAccent";
1238
+ case 4:
1239
+ return "hiHatChoke";
1240
+ case 5:
1241
+ return "linearFill";
1242
+ default:
1243
+ return "snareRoll";
1244
+ }
1245
+ }
1246
+ if (fromIntro) {
1247
+ switch (rng.range(0, 5)) {
1248
+ case 0:
1249
+ case 1:
1250
+ return "snareRoll";
1251
+ case 2:
1252
+ return "simpleCrash";
1253
+ case 3:
1254
+ return "ghostToAccent";
1255
+ case 4:
1256
+ return "breakdownFill";
1257
+ default:
1258
+ return "halfTimeFill";
1259
+ }
1260
+ }
1261
+ const choice = rng.range(0, 7);
1262
+ if (highEnergy) {
1263
+ switch (choice) {
1264
+ case 0:
1265
+ return "tomDescend";
1266
+ case 1:
1267
+ return "snareRoll";
1268
+ case 2:
1269
+ return "tomAscend";
1270
+ case 3:
1271
+ return "snareTomCombo";
1272
+ case 4:
1273
+ return "linearFill";
1274
+ case 5:
1275
+ return "bdSnareAlternate";
1276
+ case 6:
1277
+ return "flamsAndDrags";
1278
+ default:
1279
+ return "tomShuffle";
1280
+ }
1281
+ }
1282
+ switch (choice) {
1283
+ case 0:
1284
+ case 1:
1285
+ return "snareRoll";
1286
+ case 2:
1287
+ return "snareTomCombo";
1288
+ case 3:
1289
+ return "ghostToAccent";
1290
+ case 4:
1291
+ return "hiHatChoke";
1292
+ case 5:
1293
+ return "halfTimeFill";
1294
+ default:
1295
+ return "breakdownFill";
1296
+ }
1297
+ }
1298
+ function generateFill(track, beatTick, beat, fillType, velocity) {
1299
+ const fillVel = velocity * 0.9;
1300
+ const accentVel = velocity * 0.95;
1301
+ const S = SIXTEENTH;
1302
+ const E = EIGHTH;
1303
+ if (beat === 0) {
1304
+ track.add(GM.BD, beatTick, E, fillVel);
1305
+ track.add(GM.SD, beatTick + E, E, fillVel - 5);
1306
+ return;
1307
+ }
1308
+ if (beat === 1) {
1309
+ track.add(GM.SD, beatTick, E, fillVel);
1310
+ track.add(GM.TOM_H, beatTick + E, E, fillVel - 3);
1311
+ return;
1312
+ }
1313
+ switch (fillType) {
1314
+ case "snareRoll":
1315
+ if (beat === 2) {
1316
+ for (let i = 0; i < 4; i += 1) {
1317
+ track.add(GM.SD, beatTick + i * S, S, fillVel * (0.6 + 0.1 * i));
1318
+ }
1319
+ } else {
1320
+ for (let i = 0; i < 3; i += 1) {
1321
+ track.add(GM.SD, beatTick + i * S, S, fillVel * (0.7 + 0.1 * i));
1322
+ }
1323
+ track.add(GM.SD, beatTick + 3 * S, S, accentVel);
1324
+ }
1325
+ break;
1326
+ case "tomDescend":
1327
+ if (beat === 2) {
1328
+ track.add(GM.SD, beatTick, E, fillVel);
1329
+ track.add(GM.TOM_H, beatTick + E, E, fillVel - 5);
1330
+ } else {
1331
+ track.add(GM.TOM_H, beatTick, S, fillVel);
1332
+ track.add(GM.TOM_M, beatTick + S, S, fillVel - 3);
1333
+ track.add(GM.TOM_M, beatTick + E, S, fillVel - 5);
1334
+ track.add(GM.TOM_L, beatTick + E + S, S, accentVel);
1335
+ }
1336
+ break;
1337
+ case "tomAscend":
1338
+ if (beat === 2) {
1339
+ track.add(GM.SD, beatTick, E, fillVel);
1340
+ track.add(GM.TOM_L, beatTick + E, E, fillVel - 5);
1341
+ } else {
1342
+ track.add(GM.TOM_L, beatTick, S, fillVel);
1343
+ track.add(GM.TOM_M, beatTick + S, S, fillVel + 3);
1344
+ track.add(GM.TOM_M, beatTick + E, S, fillVel + 5);
1345
+ track.add(GM.TOM_H, beatTick + E + S, S, accentVel);
1346
+ }
1347
+ break;
1348
+ case "snareTomCombo":
1349
+ if (beat === 2) {
1350
+ track.add(GM.SD, beatTick, E, fillVel);
1351
+ track.add(GM.SD, beatTick + E, S, fillVel - 5);
1352
+ track.add(GM.TOM_H, beatTick + E + S, S, fillVel);
1353
+ } else {
1354
+ track.add(GM.TOM_M, beatTick, S, fillVel);
1355
+ track.add(GM.SD, beatTick + S, S, fillVel - 3);
1356
+ track.add(GM.TOM_L, beatTick + E, S, fillVel + 2);
1357
+ track.add(GM.BD, beatTick + E + S, S, accentVel);
1358
+ }
1359
+ break;
1360
+ case "simpleCrash":
1361
+ if (beat === 3) {
1362
+ track.add(GM.BD, beatTick + E + S, S, accentVel);
1363
+ track.add(GM.CRASH, beatTick + E + S, E, accentVel);
1364
+ }
1365
+ break;
1366
+ case "linearFill":
1367
+ if (beat === 2) {
1368
+ track.add(GM.BD, beatTick, S, fillVel);
1369
+ track.add(GM.SD, beatTick + S, S, fillVel);
1370
+ track.add(GM.TOM_H, beatTick + 2 * S, S, fillVel);
1371
+ track.add(GM.TOM_M, beatTick + 3 * S, S, fillVel);
1372
+ } else {
1373
+ track.add(GM.TOM_L, beatTick, S, fillVel + 3);
1374
+ track.add(GM.SD, beatTick + S, S, fillVel + 5);
1375
+ track.add(GM.BD, beatTick + 2 * S, S, fillVel + 7);
1376
+ track.add(GM.SD, beatTick + 3 * S, S, accentVel);
1377
+ }
1378
+ break;
1379
+ case "ghostToAccent":
1380
+ if (beat === 2) {
1381
+ const ghost = fillVel * 0.4;
1382
+ track.add(GM.SD, beatTick, S, ghost);
1383
+ track.add(GM.SD, beatTick + S, S, ghost + 10);
1384
+ track.add(GM.SD, beatTick + 2 * S, S, ghost + 20);
1385
+ track.add(GM.SD, beatTick + 3 * S, S, ghost + 30);
1386
+ } else {
1387
+ track.add(GM.SD, beatTick, E, fillVel);
1388
+ track.add(GM.SD, beatTick + E, E, accentVel);
1389
+ }
1390
+ break;
1391
+ case "bdSnareAlternate":
1392
+ if (beat === 2) {
1393
+ track.add(GM.BD, beatTick, S, fillVel);
1394
+ track.add(GM.SD, beatTick + S, S, fillVel);
1395
+ track.add(GM.BD, beatTick + 2 * S, S, fillVel + 3);
1396
+ track.add(GM.SD, beatTick + 3 * S, S, fillVel + 3);
1397
+ } else {
1398
+ track.add(GM.BD, beatTick, S, fillVel + 5);
1399
+ track.add(GM.SD, beatTick + S, S, fillVel + 5);
1400
+ track.add(GM.BD, beatTick + 2 * S, S, accentVel);
1401
+ track.add(GM.SD, beatTick + 3 * S, S, accentVel);
1402
+ }
1403
+ break;
1404
+ case "hiHatChoke":
1405
+ if (beat === 2) {
1406
+ track.add(GM.OHH, beatTick, E, fillVel);
1407
+ track.add(GM.OHH, beatTick + E, E, fillVel + 5);
1408
+ } else {
1409
+ track.add(GM.OHH, beatTick, S, fillVel + 8);
1410
+ track.add(GM.CHH, beatTick + S, S, accentVel);
1411
+ track.add(GM.SD, beatTick + E, E, accentVel);
1412
+ }
1413
+ break;
1414
+ case "tomShuffle":
1415
+ if (beat === 2) {
1416
+ track.add(GM.TOM_H, beatTick, E, fillVel);
1417
+ track.add(GM.TOM_M, beatTick + E + S / 2, S, fillVel - 5);
1418
+ } else {
1419
+ track.add(GM.TOM_M, beatTick, E, fillVel);
1420
+ track.add(GM.TOM_L, beatTick + E + S / 2, S, fillVel + 5);
1421
+ }
1422
+ break;
1423
+ case "breakdownFill":
1424
+ if (beat === 3) {
1425
+ track.add(GM.SD, beatTick + E, S, accentVel);
1426
+ }
1427
+ break;
1428
+ case "flamsAndDrags":
1429
+ if (beat === 2) {
1430
+ track.add(GM.SD, beatTick - S / 4, S / 4, fillVel * 0.5);
1431
+ track.add(GM.SD, beatTick, E, fillVel);
1432
+ track.add(GM.SD, beatTick + E, S / 2, fillVel * 0.6);
1433
+ track.add(GM.SD, beatTick + E + S / 2, S / 2, fillVel * 0.6);
1434
+ track.add(GM.SD, beatTick + E + S, E, fillVel);
1435
+ } else {
1436
+ track.add(GM.SD, beatTick - S / 4, S / 4, fillVel * 0.5);
1437
+ track.add(GM.SD, beatTick, 1, accentVel);
1438
+ }
1439
+ break;
1440
+ case "halfTimeFill":
1441
+ if (beat === 2) {
1442
+ track.add(GM.SD, beatTick, 1, accentVel);
1443
+ track.add(GM.BD, beatTick, 1, fillVel);
1444
+ } else if (beat === 3) {
1445
+ track.add(GM.SD, beatTick, EIGHTH, accentVel);
1446
+ track.add(GM.SD, beatTick + E, S, fillVel * 0.6);
1447
+ track.add(GM.SD, beatTick + E + S, S, accentVel);
1448
+ }
1449
+ break;
1450
+ }
1451
+ }
1452
+
1453
+ // src/generate/drums/hit.ts
1454
+ var HitList = class {
1455
+ hits = [];
1456
+ /** Append a hit, clamping velocity and dropping non-positive positions. */
1457
+ add(pitch, startBeat, durationBeat, velocity) {
1458
+ this.hits.push({
1459
+ pitch,
1460
+ startBeat: Math.max(0, startBeat),
1461
+ durationBeat,
1462
+ velocity: clampVel(velocity)
1463
+ });
1464
+ }
1465
+ /** True when a crash already sits within a 16th of `startBeat`. */
1466
+ hasCrashNear(startBeat) {
1467
+ return this.hits.some(
1468
+ (h) => h.pitch === GM.CRASH && h.startBeat >= startBeat && h.startBeat < startBeat + 0.25
1469
+ );
1470
+ }
1471
+ };
1472
+
1473
+ // src/generate/drums/kick.ts
1474
+ var EMPTY = {
1475
+ beat1: false,
1476
+ beat1and: false,
1477
+ beat2: false,
1478
+ beat2and: false,
1479
+ beat3: false,
1480
+ beat3and: false,
1481
+ beat4: false,
1482
+ beat4and: false
1483
+ };
1484
+ function isInPreChorusLift(section, bar, sectionBars, nextIsChorus) {
1485
+ if (section !== "b" || !nextIsChorus || sectionBars < 3) {
1486
+ return false;
1487
+ }
1488
+ return bar >= sectionBars - 2;
1489
+ }
1490
+ function euclideanToKickPattern(mask) {
1491
+ const slot = (step) => hasHit(mask, step) || hasHit(mask, (step + 15) % 16);
1492
+ return {
1493
+ beat1: slot(0),
1494
+ beat1and: slot(2),
1495
+ beat2: slot(4),
1496
+ beat2and: slot(6),
1497
+ beat3: slot(8),
1498
+ beat3and: slot(10),
1499
+ beat4: slot(12),
1500
+ beat4and: slot(14)
1501
+ };
1502
+ }
1503
+ function getKickPattern(section, style, bar, rng) {
1504
+ const p = { ...EMPTY };
1505
+ if (section === "outro") {
1506
+ p.beat1 = true;
1507
+ p.beat3 = true;
1508
+ return p;
1509
+ }
1510
+ switch (style) {
1511
+ case "sparse":
1512
+ p.beat1 = true;
1513
+ if (section === "chorus" && bar % 2 === 1) {
1514
+ p.beat3 = true;
1515
+ }
1516
+ break;
1517
+ case "fourOnFloor":
1518
+ p.beat1 = p.beat2 = p.beat3 = p.beat4 = true;
1519
+ if (section === "chorus" && rng.prob(0.2)) {
1520
+ p.beat2and = true;
1521
+ }
1522
+ break;
1523
+ case "upbeat":
1524
+ p.beat1 = true;
1525
+ p.beat3 = true;
1526
+ if (section === "b" || section === "chorus") {
1527
+ p.beat2and = rng.prob(0.7);
1528
+ }
1529
+ if (section === "chorus") {
1530
+ p.beat4and = rng.prob(0.6);
1531
+ }
1532
+ break;
1533
+ case "rock":
1534
+ p.beat1 = true;
1535
+ p.beat3 = true;
1536
+ if (section === "chorus") {
1537
+ p.beat2and = rng.prob(0.65);
1538
+ p.beat4and = rng.prob(0.4);
1539
+ } else if (section === "b") {
1540
+ p.beat2and = rng.prob(0.3);
1541
+ }
1542
+ break;
1543
+ case "synth":
1544
+ p.beat1 = true;
1545
+ p.beat3 = true;
1546
+ if (section === "b" || section === "chorus") {
1547
+ p.beat2and = rng.prob(0.75);
1548
+ }
1549
+ if (section === "chorus") {
1550
+ p.beat4and = rng.prob(0.65);
1551
+ }
1552
+ break;
1553
+ case "trap":
1554
+ p.beat1 = true;
1555
+ p.beat2and = rng.prob(0.8);
1556
+ p.beat3 = rng.prob(0.3);
1557
+ p.beat4and = rng.prob(0.7);
1558
+ break;
1559
+ case "latin":
1560
+ p.beat1 = true;
1561
+ p.beat2and = true;
1562
+ p.beat3 = true;
1563
+ p.beat4and = rng.prob(0.5);
1564
+ break;
1565
+ default:
1566
+ p.beat1 = true;
1567
+ p.beat3 = true;
1568
+ if (section === "b") {
1569
+ p.beat2and = rng.prob(0.5);
1570
+ } else if (section === "chorus") {
1571
+ p.beat2and = rng.prob(0.55);
1572
+ p.beat4and = rng.prob(0.35);
1573
+ }
1574
+ break;
1575
+ }
1576
+ return p;
1577
+ }
1578
+
1579
+ // src/generate/drums/percussion.ts
1580
+ var F = [false, false, false];
1581
+ var PERC_TABLE = [
1582
+ /* calm */
1583
+ [F, F, F, F, F, F, F, F, F],
1584
+ /* std */
1585
+ [F, F, [false, true, false], [true, false, true], F, F, F, F, [true, false, true]],
1586
+ /* ener */
1587
+ [
1588
+ F,
1589
+ [false, true, false],
1590
+ [false, true, false],
1591
+ [true, true, true],
1592
+ F,
1593
+ F,
1594
+ F,
1595
+ F,
1596
+ [true, true, true]
1597
+ ],
1598
+ /* idol */
1599
+ [
1600
+ F,
1601
+ [false, true, false],
1602
+ [false, true, false],
1603
+ [true, true, true],
1604
+ F,
1605
+ F,
1606
+ F,
1607
+ F,
1608
+ [true, true, true]
1609
+ ],
1610
+ /* rock */
1611
+ [F, F, F, [false, false, true], F, F, F, F, [false, false, true]]
1612
+ ];
1613
+ function getPercussionConfig(mood, section) {
1614
+ const row = PERC_TABLE[mood] ?? PERC_TABLE[1 /* Standard */];
1615
+ const act = row?.[sectionIndex(section)] ?? F;
1616
+ return {
1617
+ tambourine: act[0],
1618
+ shaker: act[1],
1619
+ handclap: act[2],
1620
+ shaker16th: act[1]
1621
+ };
1622
+ }
1623
+ function generateAuxPercussionForBar(track, barStart, config, role, densityMult, rng, bpm) {
1624
+ if (role === "minimal" || role === "fxOnly") {
1625
+ return;
1626
+ }
1627
+ if (config.tambourine) {
1628
+ for (let beat = 1; beat <= 3; beat += 2) {
1629
+ const raw = 70 * densityMult * rng.float(0.9, 1.1);
1630
+ track.add(GM.TAMBOURINE, barStart + beat, EIGHTH, Math.max(40, Math.min(90, raw)));
1631
+ }
1632
+ }
1633
+ if (config.shaker) {
1634
+ const use16th = config.shaker16th && bpm < HH_16TH_BPM_THRESHOLD;
1635
+ if (use16th) {
1636
+ const velCurve = [0.75, 0.45, 0.6, 0.45];
1637
+ for (let beat = 0; beat < 4; beat += 1) {
1638
+ for (let sub = 0; sub < 4; sub += 1) {
1639
+ const raw = 80 * (velCurve[sub] ?? 0.5) * densityMult * rng.float(0.9, 1.1);
1640
+ track.add(
1641
+ GM.SHAKER,
1642
+ barStart + beat + sub * SIXTEENTH,
1643
+ SIXTEENTH,
1644
+ Math.max(25, Math.min(85, raw))
1645
+ );
1646
+ }
1647
+ }
1648
+ } else {
1649
+ const velCurve = [0.75, 0.55];
1650
+ for (let beat = 0; beat < 4; beat += 1) {
1651
+ for (let sub = 0; sub < 2; sub += 1) {
1652
+ const raw = 80 * (velCurve[sub] ?? 0.6) * densityMult * rng.float(0.9, 1.1);
1653
+ track.add(
1654
+ GM.SHAKER,
1655
+ barStart + beat + sub * EIGHTH,
1656
+ EIGHTH,
1657
+ Math.max(25, Math.min(85, raw))
1658
+ );
1659
+ }
1660
+ }
1661
+ }
1662
+ }
1663
+ if (config.handclap) {
1664
+ for (let beat = 1; beat <= 3; beat += 2) {
1665
+ const raw = 85 * densityMult * rng.float(0.9, 1.1);
1666
+ track.add(GM.HANDCLAP, barStart + beat, EIGHTH, Math.max(50, Math.min(100, raw)));
1667
+ }
1668
+ }
1669
+ }
1670
+
1671
+ // src/generate/drums/index.ts
1672
+ function generateDrums(opts) {
1673
+ const track = new HitList();
1674
+ const rng = createRng(opts.seed ?? 0);
1675
+ const mapping = mapStyle(opts.style);
1676
+ const style = mapping.style;
1677
+ const feel = opts.feel ?? mapping.feel;
1678
+ const role = opts.role ?? "full";
1679
+ const playMainVoices = role !== "fxOnly";
1680
+ const section = mapSection(opts.section);
1681
+ const backingDensity = mapDensity(opts.density);
1682
+ const swingAmount = feelSwingAmount(feel);
1683
+ let densityMult = sectionDensityMultiplier(section);
1684
+ if (backingDensity === "thin") {
1685
+ densityMult *= 0.75;
1686
+ } else if (backingDensity === "thick") {
1687
+ densityMult *= 1.15;
1688
+ }
1689
+ const sec = {
1690
+ style,
1691
+ feel,
1692
+ densityMult,
1693
+ backingDensity,
1694
+ hhLevel: getHiHatLevel(section, style, backingDensity, opts.bpm, rng),
1695
+ useGhostNotes: (section === "b" || section === "chorus" || section === "bridge") && style !== "sparse",
1696
+ ghostBoost: mapping.ghostBoost,
1697
+ useRide: shouldUseRideForSection(section, style),
1698
+ useFootHh: shouldUseFootHiHat(section, role),
1699
+ role,
1700
+ ghostMood: ghostMoodCategory(style),
1701
+ snareBeat3: mapping.snareBeat3
1702
+ };
1703
+ const ohhBarInterval = openHiHatBarInterval(section, style);
1704
+ const energy = sectionEnergy(section);
1705
+ const fillStartBeat = getFillStartBeat(energy);
1706
+ const percMood = percMoodCategory(style);
1707
+ const nextSection = opts.nextSection ? mapSection(opts.nextSection) : section;
1708
+ const nextEnergy = sectionEnergy(nextSection);
1709
+ const euclidKick = opts.euclideanKick ? euclideanToKickPattern(
1710
+ patternToMask(
1711
+ euclideanRhythm(
1712
+ opts.euclideanKick.pulses,
1713
+ opts.euclideanKick.steps ?? 16,
1714
+ opts.euclideanKick.rotation ?? 0
1715
+ )
1716
+ )
1717
+ ) : void 0;
1718
+ const reuseSectionKick = (section === "b" || section === "chorus") && style !== "sparse";
1719
+ let sectionKick;
1720
+ for (let bar = 0; bar < opts.bars; bar += 1) {
1721
+ const barStart = bar * 4;
1722
+ const isLastBar = bar === opts.bars - 1;
1723
+ if (bar === 0 && section === "chorus") {
1724
+ track.add(GM.CRASH, barStart, 0.5, 100 * densityMult);
1725
+ }
1726
+ let barHasOpenHh = false;
1727
+ let openHhBeatIndex = 3;
1728
+ if (ohhBarInterval > 0 && bar % ohhBarInterval === ohhBarInterval - 1) {
1729
+ openHhBeatIndex = openHiHatBeat(section, rng);
1730
+ barHasOpenHh = !track.hasCrashNear(barStart + openHhBeatIndex);
1731
+ }
1732
+ let kick;
1733
+ if (euclidKick) {
1734
+ kick = euclidKick;
1735
+ } else if (reuseSectionKick) {
1736
+ sectionKick ??= getKickPattern(section, style, 0, rng);
1737
+ kick = sectionKick;
1738
+ } else {
1739
+ kick = getKickPattern(section, style, bar, rng);
1740
+ }
1741
+ const inLift = isInPreChorusLift(section, bar, opts.bars, section === "b");
1742
+ let currentFill = "snareRoll";
1743
+ for (let beat = 0; beat < 4; beat += 1) {
1744
+ const beatTick = barStart + beat;
1745
+ const velocity = calculateVelocity(section, beat);
1746
+ if (opts.fills && isLastBar && !inLift && beat >= fillStartBeat) {
1747
+ if (beat === fillStartBeat) {
1748
+ currentFill = selectFillType(section, nextSection, style, nextEnergy, rng);
1749
+ }
1750
+ if (playMainVoices) {
1751
+ const before = track.hits.length;
1752
+ generateFill(track, beatTick, beat, currentFill, velocity);
1753
+ if (track.hits.length > before) {
1754
+ continue;
1755
+ }
1756
+ } else {
1757
+ continue;
1758
+ }
1759
+ }
1760
+ const ctx = {
1761
+ track,
1762
+ beatTick,
1763
+ beat,
1764
+ velocity,
1765
+ section,
1766
+ bpm: opts.bpm,
1767
+ bar,
1768
+ sectionBars: opts.bars,
1769
+ inPrechorusLift: inLift,
1770
+ swingAmount,
1771
+ barHasOpenHh,
1772
+ openHhBeat: openHhBeatIndex,
1773
+ rng
1774
+ };
1775
+ if (playMainVoices) {
1776
+ if (inLift) {
1777
+ generatePreChorusBuildup(ctx, sec, isLastBar);
1778
+ }
1779
+ generateKickForBeat(ctx, sec, kick);
1780
+ generateSnareForBeat(ctx, sec, section === "intro" && bar === 0);
1781
+ if (sec.useGhostNotes && !inLift) {
1782
+ generateGhostNotesForBeat(ctx, sec);
1783
+ }
1784
+ }
1785
+ generateHiHatForBeat(ctx, sec);
1786
+ }
1787
+ if (sec.useFootHh && shouldPlayHiHat(role)) {
1788
+ for (let fhhBeat = 0; fhhBeat < 4; fhhBeat += 2) {
1789
+ const fhhTick = barStart + fhhBeat;
1790
+ const occupied = track.hits.some((h) => h.pitch === GM.FHH && h.startBeat === fhhTick);
1791
+ if (!occupied) {
1792
+ track.add(GM.FHH, fhhTick, 0.5, footHiHatVelocity(rng));
1793
+ }
1794
+ }
1795
+ }
1796
+ generateAuxPercussionForBar(
1797
+ track,
1798
+ barStart,
1799
+ getPercussionConfig(percMood, section),
1800
+ role,
1801
+ densityMult,
1802
+ rng,
1803
+ opts.bpm
1804
+ );
1805
+ }
1806
+ return track.hits;
1807
+ }
1808
+
1809
+ // src/generate/groove/index.ts
1810
+ var DEFAULT_TS3 = { numerator: 4, denominator: 4 };
1811
+ var DEFAULT_TIMING = 0.02;
1812
+ var DEFAULT_VELOCITY_JITTER = 8;
1813
+ var DEFAULT_ACCENT = 12;
1814
+ var DEFAULT_BASE_VELOCITY = 80;
1815
+ var MAX_METRIC_WEIGHT = 3;
1816
+ var MIN_VELOCITY = 1;
1817
+ var MAX_VELOCITY = 127;
1818
+ function humanize(events, opts = {}) {
1819
+ const ts = opts.ts ?? DEFAULT_TS3;
1820
+ const timing = opts.timing ?? DEFAULT_TIMING;
1821
+ const velocityJitter = opts.velocity ?? DEFAULT_VELOCITY_JITTER;
1822
+ const accent = opts.accent ?? DEFAULT_ACCENT;
1823
+ const baseVelocity = opts.baseVelocity ?? DEFAULT_BASE_VELOCITY;
1824
+ const rng = createRng(opts.seed ?? 0);
1825
+ return events.map((event) => {
1826
+ const timingOffset = rng.float(-timing, timing);
1827
+ const startBeat = Math.max(0, event.startBeat + timingOffset);
1828
+ const weight = metricWeight(event.startBeat, ts);
1829
+ const accentBoost = weight / MAX_METRIC_WEIGHT * accent;
1830
+ const velocityOffset = rng.float(-velocityJitter, velocityJitter);
1831
+ const rawVelocity = (event.velocity ?? baseVelocity) + accentBoost + velocityOffset;
1832
+ const velocity = Math.min(MAX_VELOCITY, Math.max(MIN_VELOCITY, Math.round(rawVelocity)));
1833
+ return {
1834
+ pitch: event.pitch,
1835
+ startBeat,
1836
+ durationBeat: event.durationBeat,
1837
+ velocity
1838
+ };
1839
+ });
1840
+ }
1841
+ function quantizeToGrid(beat, barBeats, subdivision, slotsPerBar) {
1842
+ const barIndex = Math.floor(beat / barBeats);
1843
+ const modBeat = beat - barIndex * barBeats;
1844
+ let slotIndex = Math.round(modBeat * subdivision);
1845
+ let effectiveBarIndex = barIndex;
1846
+ if (slotIndex >= slotsPerBar) {
1847
+ slotIndex = 0;
1848
+ effectiveBarIndex += 1;
1849
+ }
1850
+ return {
1851
+ quantizedBeat: effectiveBarIndex * barBeats + slotIndex / subdivision,
1852
+ slotIndex
1853
+ };
1854
+ }
1855
+ function extractGrooveTemplate(events, ts, subdivision) {
1856
+ const barBeats = beatsPerBar(ts);
1857
+ const slotsPerBar = Math.round(barBeats * subdivision);
1858
+ const offsetSums = new Array(slotsPerBar).fill(0);
1859
+ const velocitySums = new Array(slotsPerBar).fill(0);
1860
+ const counts = new Array(slotsPerBar).fill(0);
1861
+ const velocityCounts = new Array(slotsPerBar).fill(0);
1862
+ for (const event of events) {
1863
+ const { quantizedBeat, slotIndex } = quantizeToGrid(
1864
+ event.startBeat,
1865
+ barBeats,
1866
+ subdivision,
1867
+ slotsPerBar
1868
+ );
1869
+ offsetSums[slotIndex] = (offsetSums[slotIndex] ?? 0) + (event.startBeat - quantizedBeat);
1870
+ counts[slotIndex] = (counts[slotIndex] ?? 0) + 1;
1871
+ if (event.velocity !== void 0) {
1872
+ velocitySums[slotIndex] = (velocitySums[slotIndex] ?? 0) + event.velocity;
1873
+ velocityCounts[slotIndex] = (velocityCounts[slotIndex] ?? 0) + 1;
1874
+ }
1875
+ }
1876
+ const slots = [];
1877
+ for (let i = 0; i < slotsPerBar; i += 1) {
1878
+ const count = counts[i] ?? 0;
1879
+ if (count === 0) {
1880
+ slots.push({ timingOffset: 0, velocity: null });
1881
+ continue;
1882
+ }
1883
+ const velocityCount = velocityCounts[i] ?? 0;
1884
+ slots.push({
1885
+ timingOffset: (offsetSums[i] ?? 0) / count,
1886
+ velocity: velocityCount > 0 ? (velocitySums[i] ?? 0) / velocityCount : null
1887
+ });
1888
+ }
1889
+ return { subdivision, slotsPerBar, slots, ts };
1890
+ }
1891
+ function applyGrooveTemplate(events, template, ts) {
1892
+ if (template.ts && (template.ts.numerator !== ts.numerator || template.ts.denominator !== ts.denominator)) {
1893
+ throw new Error(
1894
+ `Groove template meter ${formatTimeSignature(template.ts)} does not match apply-time meter ${formatTimeSignature(ts)}`
1895
+ );
1896
+ }
1897
+ const barBeats = beatsPerBar(ts);
1898
+ return events.map((event) => {
1899
+ const { quantizedBeat, slotIndex } = quantizeToGrid(
1900
+ event.startBeat,
1901
+ barBeats,
1902
+ template.subdivision,
1903
+ template.slotsPerBar
1904
+ );
1905
+ const slot = template.slots[slotIndex];
1906
+ const startBeat = quantizedBeat + (slot?.timingOffset ?? 0);
1907
+ const velocity = slot && slot.velocity !== null && slot.velocity !== void 0 ? Math.round(slot.velocity) : event.velocity;
1908
+ return {
1909
+ pitch: event.pitch,
1910
+ startBeat,
1911
+ durationBeat: event.durationBeat,
1912
+ velocity
1913
+ };
1914
+ });
1915
+ }
1916
+
1917
+ // src/generate/harmonize/index.ts
1918
+ var FALLBACK = { rootPc: 0, quality: "maj", secondaryDominant: false, base: 0 };
1919
+ var DEFAULT_METER = { numerator: 4, denominator: 4 };
1920
+ var COMFORT_LOW = 55;
1921
+ var COMFORT_HIGH = 79;
1922
+ var TESSITURA_WEIGHT = 1e-3;
1923
+ var TIE_BREAK_JITTER = 1e-6;
1924
+ function pitchClass2(pitch) {
1925
+ return (Math.trunc(pitch) % 12 + 12) % 12;
1926
+ }
1927
+ function mulberry32(seed) {
1928
+ let state = seed >>> 0;
1929
+ return () => {
1930
+ state = state + 1831565813 >>> 0;
1931
+ let t = state;
1932
+ t = Math.imul(t ^ t >>> 15, t | 1);
1933
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
1934
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
1935
+ };
1936
+ }
1937
+ function inferKey(melody) {
1938
+ let best = majorKey(0);
1939
+ let bestScore = Number.NEGATIVE_INFINITY;
1940
+ const candidates = [];
1941
+ for (let tonic = 0; tonic < 12; tonic += 1) {
1942
+ candidates.push(majorKey(tonic), minorKey(tonic));
1943
+ }
1944
+ for (const key of candidates) {
1945
+ const tonic = pitchClass2(key.rootPc);
1946
+ const isMinor = key.modeMask12 === NATURAL_MINOR_MASK;
1947
+ const leadingTone = (tonic + 11) % 12;
1948
+ let score = 0;
1949
+ for (const n of melody) {
1950
+ const w = Math.max(0.25, n.durationBeat);
1951
+ const pc = pitchClass2(n.pitch);
1952
+ if (isScaleTone(n.pitch, key) || isMinor && pc === leadingTone) {
1953
+ score += w;
1954
+ }
1955
+ if (pc === tonic) {
1956
+ score += 0.5 * w;
1957
+ }
1958
+ }
1959
+ if (score > bestScore) {
1960
+ bestScore = score;
1961
+ best = key;
1962
+ }
1963
+ }
1964
+ return best;
1965
+ }
1966
+ function buildCandidates(key, reharmonize) {
1967
+ const tones = scaleTonesInDegreeOrder(key);
1968
+ const candidates = tones.map((rootPc, degree) => ({
1969
+ rootPc,
1970
+ quality: diatonicTriad(degree, key).quality,
1971
+ degree,
1972
+ secondaryDominant: false,
1973
+ base: 0
1974
+ }));
1975
+ const tonic = tones[0] ?? 0;
1976
+ if (reharmonize !== "diatonic") {
1977
+ for (const target of [1, 3, 4, 5]) {
1978
+ const targetRoot = tones[target] ?? 0;
1979
+ candidates.push({
1980
+ rootPc: (targetRoot + 7) % 12,
1981
+ quality: "dom7",
1982
+ secondaryDominant: true,
1983
+ targetDegree: target,
1984
+ base: 1.5
1985
+ });
1986
+ }
1987
+ }
1988
+ if (reharmonize === "borrowed") {
1989
+ candidates.push({
1990
+ rootPc: (tonic + 10) % 12,
1991
+ quality: "maj",
1992
+ secondaryDominant: false,
1993
+ base: 2
1994
+ });
1995
+ candidates.push({
1996
+ rootPc: (tonic + 8) % 12,
1997
+ quality: "maj",
1998
+ secondaryDominant: false,
1999
+ base: 2
2000
+ });
2001
+ candidates.push({
2002
+ rootPc: (tonic + 5) % 12,
2003
+ quality: "min",
2004
+ secondaryDominant: false,
2005
+ base: 2
2006
+ });
2007
+ }
2008
+ return candidates;
2009
+ }
2010
+ function emissionCost(seg, cand, melody, key) {
2011
+ const pcs = chordPitchClasses(makeChord(cand.rootPc, cand.quality));
2012
+ let cost = cand.base;
2013
+ for (const idx of seg.noteIndices) {
2014
+ const note = melody[idx];
2015
+ if (!note) {
2016
+ continue;
2017
+ }
2018
+ const overlapStart = Math.max(note.startBeat, seg.startBeat);
2019
+ const overlap = Math.min(note.startBeat + note.durationBeat, seg.endBeat) - overlapStart;
2020
+ if (overlap <= 0) {
2021
+ continue;
2022
+ }
2023
+ const w = Math.max(0.25, overlap);
2024
+ if (pcs.includes(pitchClass2(note.pitch))) {
2025
+ continue;
2026
+ }
2027
+ const strong = isStrongBeat(overlapStart, DEFAULT_METER);
2028
+ cost += (strong ? 10 : 2) * w;
2029
+ if (!isScaleTone(note.pitch, key)) {
2030
+ cost += w;
2031
+ }
2032
+ }
2033
+ return cost;
2034
+ }
2035
+ function tessituraCost(melody) {
2036
+ let cost = 0;
2037
+ for (const n of melody) {
2038
+ if (n.pitch < COMFORT_LOW) {
2039
+ cost += (COMFORT_LOW - n.pitch) * TESSITURA_WEIGHT;
2040
+ } else if (n.pitch > COMFORT_HIGH) {
2041
+ cost += (n.pitch - COMFORT_HIGH) * TESSITURA_WEIGHT;
2042
+ }
2043
+ }
2044
+ return cost;
2045
+ }
2046
+ function transitionCost(prev, cur, tonicPc) {
2047
+ let cost = 0;
2048
+ if ((prev.rootPc - cur.rootPc + 12) % 12 === 7) {
2049
+ cost -= 2;
2050
+ }
2051
+ if (prev.rootPc === (tonicPc + 7) % 12 && (prev.quality === "maj" || prev.quality === "dom7") && cur.rootPc === tonicPc) {
2052
+ cost -= 3;
2053
+ }
2054
+ if (prev.secondaryDominant) {
2055
+ cost += cur.degree === prev.targetDegree ? -3 : 2;
2056
+ }
2057
+ const dist = Math.min((prev.rootPc - cur.rootPc + 12) % 12, (cur.rootPc - prev.rootPc + 12) % 12);
2058
+ cost += dist * 0.3;
2059
+ return cost;
2060
+ }
2061
+ function harmonizeOnce(melody, key, candidates, segments, jitter) {
2062
+ const tonicPc = pitchClass2(key.rootPc);
2063
+ const n = candidates.length;
2064
+ const candAt = (i) => candidates[i] ?? FALLBACK;
2065
+ const seg0 = segments[0];
2066
+ let dp = candidates.map(
2067
+ (c, ci) => (seg0 ? emissionCost(seg0, c, melody, key) : 0) + (jitter[ci] ?? 0)
2068
+ );
2069
+ const back = [];
2070
+ for (let s = 1; s < segments.length; s += 1) {
2071
+ const seg = segments[s];
2072
+ if (!seg) {
2073
+ continue;
2074
+ }
2075
+ const next = [];
2076
+ const ptr = [];
2077
+ for (let c = 0; c < n; c += 1) {
2078
+ let best = Number.POSITIVE_INFINITY;
2079
+ let bestPrev = 0;
2080
+ for (let p = 0; p < n; p += 1) {
2081
+ const cost = (dp[p] ?? Number.POSITIVE_INFINITY) + transitionCost(candAt(p), candAt(c), tonicPc);
2082
+ if (cost < best) {
2083
+ best = cost;
2084
+ bestPrev = p;
2085
+ }
2086
+ }
2087
+ next[c] = best + emissionCost(seg, candAt(c), melody, key) + (jitter[c] ?? 0);
2088
+ ptr[c] = bestPrev;
2089
+ }
2090
+ dp = next;
2091
+ back.push(ptr);
2092
+ }
2093
+ let bestCost = Number.POSITIVE_INFINITY;
2094
+ let bestEnd = 0;
2095
+ for (let c = 0; c < n; c += 1) {
2096
+ const cadence = candAt(c).rootPc === tonicPc ? -2 : 0;
2097
+ const total = (dp[c] ?? Number.POSITIVE_INFINITY) + cadence;
2098
+ if (total < bestCost) {
2099
+ bestCost = total;
2100
+ bestEnd = c;
2101
+ }
2102
+ }
2103
+ const path = new Array(segments.length).fill(bestEnd);
2104
+ for (let s = segments.length - 2; s >= 0; s -= 1) {
2105
+ const ptr = back[s];
2106
+ const nextIdx = path[s + 1] ?? bestEnd;
2107
+ path[s] = ptr ? ptr[nextIdx] ?? bestEnd : bestEnd;
2108
+ }
2109
+ return { cost: bestCost, path };
2110
+ }
2111
+ function harmonizeMelody(opts) {
2112
+ const key = opts.key === "infer" ? inferKey(opts.melody) : opts.key;
2113
+ const candidates = buildCandidates(key, opts.reharmonize);
2114
+ const candAt = (i) => candidates[i] ?? FALLBACK;
2115
+ const rng = mulberry32(opts.seed ?? 0);
2116
+ const jitter = candidates.map(() => rng() * TIE_BREAK_JITTER);
2117
+ const melodyEnd = opts.melody.reduce((m, n) => Math.max(m, n.startBeat + n.durationBeat), 0);
2118
+ const hr = Math.max(0.25, opts.harmonicRhythm);
2119
+ const segCount = Math.max(1, Math.ceil(melodyEnd / hr));
2120
+ const segments = [];
2121
+ for (let s = 0; s < segCount; s += 1) {
2122
+ const startBeat = s * hr;
2123
+ const endBeat = startBeat + hr;
2124
+ const noteIndices = opts.melody.map((n, i) => ({ n, i })).filter(({ n }) => n.startBeat < endBeat && n.startBeat + n.durationBeat > startBeat).map(({ i }) => i);
2125
+ segments.push({ startBeat, endBeat, noteIndices });
2126
+ }
2127
+ const transposes = [0];
2128
+ if (opts.placement.transposeSearch) {
2129
+ for (let s = -6; s <= 6; s += 1) {
2130
+ if (s !== 0) {
2131
+ transposes.push(s);
2132
+ }
2133
+ }
2134
+ }
2135
+ if (opts.placement.octaveSearch) {
2136
+ for (const o of [-12, 12]) {
2137
+ if (!transposes.includes(o)) {
2138
+ transposes.push(o);
2139
+ }
2140
+ }
2141
+ }
2142
+ let bestCost = Number.POSITIVE_INFINITY;
2143
+ let bestTs = 0;
2144
+ let bestPath = [];
2145
+ let bestMelody = opts.melody;
2146
+ for (const ts of transposes) {
2147
+ const shifted = opts.melody.map((n) => ({ ...n, pitch: n.pitch + ts }));
2148
+ const { cost, path } = harmonizeOnce(shifted, key, candidates, segments, jitter);
2149
+ const total = cost + tessituraCost(shifted);
2150
+ if (total < bestCost) {
2151
+ bestCost = total;
2152
+ bestTs = ts;
2153
+ bestPath = path;
2154
+ bestMelody = shifted;
2155
+ }
2156
+ }
2157
+ const chords = bestPath.map((ci, s) => {
2158
+ const cand = candAt(ci);
2159
+ const chord = {
2160
+ rootPc: cand.rootPc,
2161
+ quality: cand.quality,
2162
+ startBeat: segments[s]?.startBeat ?? s * hr
2163
+ };
2164
+ if (cand.degree !== void 0) {
2165
+ chord.degree = cand.degree;
2166
+ }
2167
+ if (cand.secondaryDominant) {
2168
+ chord.secondaryDominant = true;
2169
+ }
2170
+ return chord;
2171
+ });
2172
+ const melodyRoles = bestMelody.map((note, noteIndex) => {
2173
+ const segIdx = Math.min(segments.length - 1, Math.max(0, Math.floor(note.startBeat / hr)));
2174
+ const cand = candAt(bestPath[segIdx] ?? 0);
2175
+ const chord = makeChord(cand.rootPc, cand.quality);
2176
+ return { noteIndex, role: roleOf(note.pitch, chord).role };
2177
+ });
2178
+ return { transposeSemitones: bestTs, key, chords, melodyRoles };
2179
+ }
2180
+
2181
+ // src/generate/motif/index.ts
2182
+ function pitchClass3(pitch) {
2183
+ return (Math.trunc(pitch) % 12 + 12) % 12;
2184
+ }
2185
+ var MIN_TILE_SPAN = 1 / 256;
2186
+ function upScaleTone(pitch, key) {
2187
+ for (let d = 1; d <= 12; d += 1) {
2188
+ if (isScaleTone(pitch + d, key)) {
2189
+ return pitch + d;
2190
+ }
2191
+ }
2192
+ return pitch + 12;
2193
+ }
2194
+ function downScaleTone(pitch, key) {
2195
+ for (let d = 1; d <= 12; d += 1) {
2196
+ if (isScaleTone(pitch - d, key)) {
2197
+ return pitch - d;
2198
+ }
2199
+ }
2200
+ return pitch - 12;
2201
+ }
2202
+ function stepDiatonic(pitch, degrees, key) {
2203
+ let p = nearestScaleTone(pitch, key);
2204
+ const steps = Math.abs(Math.trunc(degrees));
2205
+ for (let i = 0; i < steps; i += 1) {
2206
+ p = degrees >= 0 ? upScaleTone(p, key) : downScaleTone(p, key);
2207
+ }
2208
+ return p;
2209
+ }
2210
+ function nearestChordTone(pitch, chord) {
2211
+ const pcs = chordPitchClasses(chord);
2212
+ for (let d = 0; d <= 12; d += 1) {
2213
+ if (pcs.includes(pitchClass3(pitch - d))) {
2214
+ return pitch - d;
2215
+ }
2216
+ if (pcs.includes(pitchClass3(pitch + d))) {
2217
+ return pitch + d;
2218
+ }
2219
+ }
2220
+ return pitch;
2221
+ }
2222
+ function cellOrigin(notes) {
2223
+ return notes.length === 0 ? 0 : Math.min(...notes.map((n) => n.startBeat));
2224
+ }
2225
+ function cellSpan(cell) {
2226
+ if (cell.notes.length === 0) {
2227
+ return 0;
2228
+ }
2229
+ const start = cellOrigin(cell.notes);
2230
+ const end = Math.max(...cell.notes.map((n) => n.startBeat + n.durationBeat));
2231
+ return end - start;
2232
+ }
2233
+ function clone(cell) {
2234
+ return { notes: cell.notes.map((n) => ({ ...n })) };
2235
+ }
2236
+ function mulberry322(seed) {
2237
+ let state = seed >>> 0;
2238
+ return () => {
2239
+ state = state + 1831565813 >>> 0;
2240
+ let t = state;
2241
+ t = Math.imul(t ^ t >>> 15, t | 1);
2242
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
2243
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
2244
+ };
2245
+ }
2246
+ function contourOffsets(contour, count) {
2247
+ const offsets = [];
2248
+ for (let i = 0; i < count; i += 1) {
2249
+ switch (contour) {
2250
+ case "ascending":
2251
+ offsets.push(i);
2252
+ break;
2253
+ case "descending":
2254
+ offsets.push(-i);
2255
+ break;
2256
+ case "arch":
2257
+ offsets.push(Math.min(i, count - 1 - i));
2258
+ break;
2259
+ case "wave":
2260
+ offsets.push([0, 1, 0, -1][i % 4] ?? 0);
2261
+ break;
2262
+ }
2263
+ }
2264
+ return offsets;
2265
+ }
2266
+ function generateMotif(opts) {
2267
+ const contour = opts.contour ?? "arch";
2268
+ const bars = Math.max(1, Math.trunc(opts.bars));
2269
+ const totalBeats = bars * 4;
2270
+ const noteCount = Math.max(3, bars * 2);
2271
+ const beatsPerNote = totalBeats / noteCount;
2272
+ const rng = mulberry322(opts.seed ?? 0);
2273
+ const jitterProb = Math.min(1, Math.max(0, opts.jitter ?? 0));
2274
+ const tonic = pitchClass3(opts.key.rootPc) + 60;
2275
+ const offsets = contourOffsets(contour, noteCount);
2276
+ const notes = [];
2277
+ for (let i = 0; i < noteCount; i += 1) {
2278
+ let jitter = 0;
2279
+ if (jitterProb > 0 && rng() < jitterProb) {
2280
+ jitter = rng() < 0.5 ? 1 : -1;
2281
+ }
2282
+ let pitch = stepDiatonic(tonic, (offsets[i] ?? 0) + jitter, opts.key);
2283
+ const startBeat = i * beatsPerNote;
2284
+ if (opts.chord && startBeat % 4 === 0) {
2285
+ pitch = nearestChordTone(pitch, opts.chord);
2286
+ }
2287
+ notes.push({ pitch, startBeat, durationBeat: beatsPerNote });
2288
+ }
2289
+ return { notes };
2290
+ }
2291
+ function transformMotif(cell, t, amount, key) {
2292
+ const notes = cell.notes;
2293
+ switch (t) {
2294
+ case "transposeChromatic": {
2295
+ const semis = amount ?? 0;
2296
+ return { notes: notes.map((n) => ({ ...n, pitch: n.pitch + semis })) };
2297
+ }
2298
+ case "transposeDiatonic": {
2299
+ const degrees = amount ?? 1;
2300
+ return {
2301
+ notes: notes.map((n) => ({
2302
+ ...n,
2303
+ // With a key, shift by scale degrees; without one, fall back to a
2304
+ // chromatic shift of `degrees` semitones.
2305
+ pitch: key ? stepDiatonic(n.pitch, degrees, key) : n.pitch + degrees
2306
+ }))
2307
+ };
2308
+ }
2309
+ case "invert": {
2310
+ const pivot = notes[0]?.pitch ?? 0;
2311
+ return { notes: notes.map((n) => ({ ...n, pitch: 2 * pivot - n.pitch })) };
2312
+ }
2313
+ case "retrograde": {
2314
+ if (notes.length === 0) {
2315
+ return { notes: [] };
2316
+ }
2317
+ const start = cellOrigin(notes);
2318
+ const end = Math.max(...notes.map((n) => n.startBeat + n.durationBeat));
2319
+ return {
2320
+ notes: notes.map((n) => ({
2321
+ pitch: n.pitch,
2322
+ startBeat: start + (end - (n.startBeat + n.durationBeat)),
2323
+ durationBeat: n.durationBeat
2324
+ }))
2325
+ };
2326
+ }
2327
+ case "augment":
2328
+ return scaleTime(cell, amount ?? 2);
2329
+ case "diminish":
2330
+ return scaleTime(cell, 1 / (amount ?? 2));
2331
+ case "sequence": {
2332
+ const degrees = amount ?? 2;
2333
+ const span = cellSpan(cell);
2334
+ const copy = transformMotif(cell, "transposeDiatonic", degrees, key);
2335
+ const shifted = copy.notes.map((n) => ({ ...n, startBeat: n.startBeat + span }));
2336
+ return { notes: [...clone(cell).notes, ...shifted] };
2337
+ }
2338
+ }
2339
+ }
2340
+ function scaleTime(cell, factor) {
2341
+ const origin = cellOrigin(cell.notes);
2342
+ return {
2343
+ notes: cell.notes.map((n) => ({
2344
+ pitch: n.pitch,
2345
+ startBeat: origin + (n.startBeat - origin) * factor,
2346
+ durationBeat: n.durationBeat * factor
2347
+ }))
2348
+ };
2349
+ }
2350
+ function developMotif(cell, timeline, key, bars) {
2351
+ const span = cellSpan(cell);
2352
+ const totalBeats = Math.max(1, Math.trunc(bars)) * 4;
2353
+ const origin = cellOrigin(cell.notes);
2354
+ const out = [];
2355
+ if (span <= 0) {
2356
+ return clone(cell);
2357
+ }
2358
+ const tileSpan = Math.max(span, MIN_TILE_SPAN);
2359
+ const tileCount = Math.ceil(totalBeats / tileSpan);
2360
+ for (let k = 0; k < tileCount; k += 1) {
2361
+ const offset = k * tileSpan;
2362
+ for (const n of cell.notes) {
2363
+ const startBeat = offset + (n.startBeat - origin);
2364
+ if (startBeat >= totalBeats) {
2365
+ continue;
2366
+ }
2367
+ const chord = timeline.at(startBeat);
2368
+ let pitch = n.pitch;
2369
+ if (chord) {
2370
+ const isMember = chordPitchClasses(chord).includes(pitchClass3(pitch));
2371
+ pitch = isMember ? pitch : nearestChordTone(pitch, chord);
2372
+ } else {
2373
+ pitch = nearestScaleTone(pitch, key);
2374
+ }
2375
+ out.push({ pitch, startBeat, durationBeat: n.durationBeat });
2376
+ }
2377
+ }
2378
+ return { notes: out };
2379
+ }
2380
+
2381
+ // src/generate/progression/index.ts
2382
+ var PRESETS = [
2383
+ {
2384
+ id: "fourChordPop",
2385
+ name: "Four Chord Pop",
2386
+ degrees: [0, 4, 5, 3],
2387
+ functional: "loop",
2388
+ styles: ["minimal", "dance", "idol"]
2389
+ },
2390
+ {
2391
+ id: "pop1",
2392
+ name: "Pop 1",
2393
+ degrees: [0, 5, 3, 4],
2394
+ functional: "loop",
2395
+ styles: ["minimal", "dance", "idol"]
2396
+ },
2397
+ {
2398
+ id: "axis",
2399
+ name: "Axis",
2400
+ degrees: [5, 3, 0, 4],
2401
+ functional: "loop",
2402
+ styles: ["minimal", "dance", "idol", "rock"]
2403
+ },
2404
+ {
2405
+ id: "pop2",
2406
+ name: "Pop 2",
2407
+ degrees: [3, 0, 4, 5],
2408
+ functional: "loop",
2409
+ styles: ["minimal", "dance", "idol"]
2410
+ },
2411
+ {
2412
+ id: "classic",
2413
+ name: "Classic",
2414
+ degrees: [0, 3, 4, 0],
2415
+ functional: "cadenceStrong",
2416
+ styles: ["dance", "idol", "rock"]
2417
+ },
2418
+ {
2419
+ id: "pop3",
2420
+ name: "Pop 3",
2421
+ degrees: [0, 3, 5, 4],
2422
+ functional: "loop",
2423
+ styles: ["minimal", "dance", "idol"]
2424
+ },
2425
+ {
2426
+ id: "royalRoad",
2427
+ name: "Royal Road",
2428
+ degrees: [3, 4, 2, 5],
2429
+ functional: "tensionBuild",
2430
+ styles: ["dance", "idol"]
2431
+ },
2432
+ {
2433
+ id: "minor1",
2434
+ name: "Minor 1",
2435
+ degrees: [5, 4, 3, 4],
2436
+ functional: "tensionBuild",
2437
+ styles: ["idol", "rock"]
2438
+ },
2439
+ {
2440
+ id: "minor2",
2441
+ name: "Minor 2",
2442
+ degrees: [5, 3, 4, 0],
2443
+ functional: "tensionBuild",
2444
+ styles: ["idol", "rock"]
2445
+ },
2446
+ {
2447
+ id: "pop4",
2448
+ name: "Pop 4",
2449
+ degrees: [0, 4, 2, 3],
2450
+ functional: "loop",
2451
+ styles: ["minimal", "dance", "idol"]
2452
+ },
2453
+ {
2454
+ id: "pop5",
2455
+ name: "Pop 5",
2456
+ degrees: [0, 2, 3, 4],
2457
+ functional: "stable",
2458
+ styles: ["minimal", "dance", "idol"]
2459
+ },
2460
+ {
2461
+ id: "rock1",
2462
+ name: "Rock 1",
2463
+ degrees: [0, 10, 3, 0],
2464
+ functional: "tensionBuild",
2465
+ styles: ["rock"]
2466
+ },
2467
+ {
2468
+ id: "rock2",
2469
+ name: "Rock 2",
2470
+ degrees: [0, 3, 10, 0],
2471
+ functional: "tensionBuild",
2472
+ styles: ["rock"]
2473
+ },
2474
+ {
2475
+ id: "extended4",
2476
+ name: "Extended 4",
2477
+ degrees: [0, 4, 5, 2],
2478
+ functional: "stable",
2479
+ styles: ["minimal", "dance"]
2480
+ },
2481
+ {
2482
+ id: "minor3",
2483
+ name: "Minor 3",
2484
+ degrees: [5, 0, 4, 3],
2485
+ functional: "loop",
2486
+ styles: ["dance", "idol"]
2487
+ },
2488
+ {
2489
+ id: "aeolianPop",
2490
+ name: "Aeolian Pop",
2491
+ degrees: [5, 8, 10, 0],
2492
+ functional: "tensionBuild",
2493
+ styles: ["minimal", "dance", "idol", "rock"]
2494
+ },
2495
+ {
2496
+ id: "animeHighEnergy1",
2497
+ name: "Anime High Energy 1",
2498
+ degrees: [5, 2, 3, 0],
2499
+ functional: "loop",
2500
+ styles: ["dance", "idol"]
2501
+ },
2502
+ {
2503
+ id: "jazzPop",
2504
+ name: "Jazz Pop",
2505
+ degrees: [1, 4, 0, 5],
2506
+ functional: "cadenceStrong",
2507
+ styles: ["minimal", "dance"]
2508
+ },
2509
+ {
2510
+ id: "animeHighEnergy2",
2511
+ name: "Anime High Energy 2",
2512
+ degrees: [5, 1, 4, 0],
2513
+ functional: "cadenceStrong",
2514
+ styles: ["dance", "idol"]
2515
+ },
2516
+ {
2517
+ id: "cityPop",
2518
+ name: "City Pop",
2519
+ degrees: [0, 5, 1, 4],
2520
+ functional: "stable",
2521
+ styles: ["minimal", "dance"]
2522
+ },
2523
+ {
2524
+ id: "extended5",
2525
+ name: "Extended 5",
2526
+ degrees: [0, 4, 5, 2, 3],
2527
+ functional: "loop",
2528
+ styles: ["minimal", "dance", "idol"]
2529
+ },
2530
+ {
2531
+ id: "neapolitanPop",
2532
+ name: "Neapolitan Pop",
2533
+ degrees: [5, 12, 13, 4, 0],
2534
+ functional: "cadenceStrong",
2535
+ styles: ["minimal", "dance", "idol"]
2536
+ }
2537
+ ];
2538
+ var BORROWED_OFFSET = {
2539
+ 8: 8,
2540
+ // bVI
2541
+ 10: 10,
2542
+ // bVII
2543
+ 11: 3,
2544
+ // bIII
2545
+ 12: 5,
2546
+ // iv
2547
+ 13: 1,
2548
+ // bII
2549
+ 14: 6
2550
+ // #IV
2551
+ };
2552
+ function progressions() {
2553
+ return PRESETS.map((p) => ({ ...p, degrees: [...p.degrees], styles: [...p.styles] }));
2554
+ }
2555
+ function progressionsByStyle(style) {
2556
+ return progressions().filter((p) => p.styles.includes(style));
2557
+ }
2558
+ function mulberry323(seed) {
2559
+ let state = seed >>> 0;
2560
+ return () => {
2561
+ state = state + 1831565813 >>> 0;
2562
+ let t = state;
2563
+ t = Math.imul(t ^ t >>> 15, t | 1);
2564
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
2565
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
2566
+ };
2567
+ }
2568
+ function degreeToRootPc(degree, key) {
2569
+ if (degree >= 0 && degree <= 6) {
2570
+ const tones = scaleTonesInDegreeOrder(key);
2571
+ return tones.length > 0 ? tones[degree % tones.length] ?? key.rootPc % 12 : key.rootPc % 12;
2572
+ }
2573
+ const offset = BORROWED_OFFSET[degree] ?? 0;
2574
+ return ((key.rootPc % 12 + offset) % 12 + 12) % 12;
2575
+ }
2576
+ function autoQuality(degree, key) {
2577
+ if (degree >= 0 && degree <= 6) {
2578
+ return diatonicTriad(degree, key).quality;
2579
+ }
2580
+ if (degree === 14) {
2581
+ return "dim";
2582
+ }
2583
+ if (degree === 12) {
2584
+ return "min";
2585
+ }
2586
+ return "maj";
2587
+ }
2588
+ function generateProgression(opts) {
2589
+ const seed = opts.seed ?? 0;
2590
+ let preset;
2591
+ if (opts.presetId !== void 0) {
2592
+ preset = PRESETS.find((p) => p.id === opts.presetId);
2593
+ if (preset === void 0) {
2594
+ throw new Error(`Unknown progression preset: ${opts.presetId}`);
2595
+ }
2596
+ }
2597
+ if (preset === void 0) {
2598
+ const pool = PRESETS.filter((p) => p.styles.includes(opts.style));
2599
+ const candidates = pool.length > 0 ? pool : PRESETS;
2600
+ const rng = mulberry323(seed);
2601
+ const index = Math.floor(rng() * candidates.length) % candidates.length;
2602
+ preset = candidates[index] ?? PRESETS[0];
2603
+ }
2604
+ const degrees = preset?.degrees ?? [0];
2605
+ const chords = [];
2606
+ for (let bar = 0; bar < opts.bars; bar += 1) {
2607
+ const degree = degrees[bar % degrees.length] ?? 0;
2608
+ const quality = opts.ext !== void 0 && opts.ext !== "auto" ? opts.ext : autoQuality(degree, opts.key);
2609
+ const chord = {
2610
+ rootPc: degreeToRootPc(degree, opts.key),
2611
+ quality,
2612
+ startBeat: bar * 4,
2613
+ degree: degree >= 0 && degree <= 6 ? degree : void 0
2614
+ };
2615
+ chords.push(chord);
2616
+ }
2617
+ if (opts.reharmonize) {
2618
+ const tonicPc = (opts.key.rootPc % 12 + 12) % 12;
2619
+ const rrng = mulberry323((seed ^ 2654435769) >>> 0);
2620
+ for (let i = 0; i < chords.length - 1; i += 1) {
2621
+ const cur = chords[i];
2622
+ const next = chords[i + 1];
2623
+ if (!cur || !next) {
2624
+ continue;
2625
+ }
2626
+ const domRoot = (next.rootPc + 7) % 12;
2627
+ const targetsTonic = (next.rootPc - tonicPc + 12) % 12 === 0;
2628
+ const alreadySecondary = cur.rootPc === domRoot && cur.quality === "dom7";
2629
+ const isResolutionTarget = chords[i - 1]?.secondaryDominant === true;
2630
+ if (targetsTonic || alreadySecondary || isResolutionTarget) {
2631
+ continue;
2632
+ }
2633
+ if (rrng() < 0.5) {
2634
+ chords[i] = {
2635
+ rootPc: domRoot,
2636
+ quality: "dom7",
2637
+ startBeat: cur.startBeat,
2638
+ secondaryDominant: true
2639
+ };
2640
+ }
2641
+ }
2642
+ }
2643
+ return chords;
2644
+ }
2645
+
2646
+ // src/generate/rhythm/index.ts
2647
+ var DEFAULT_SUBDIVISION = 2;
2648
+ var DEFAULT_DENSITY = 0.5;
2649
+ var DEFAULT_BARS = 1;
2650
+ function onsetWeightCurve(weight) {
2651
+ switch (weight) {
2652
+ case 3:
2653
+ return 1;
2654
+ case 2:
2655
+ return 0.8;
2656
+ case 1:
2657
+ return 0.55;
2658
+ default:
2659
+ return 0.25;
2660
+ }
2661
+ }
2662
+ function generateRhythm(ts, opts = {}) {
2663
+ const seed = opts.seed ?? 0;
2664
+ const bars = opts.bars ?? DEFAULT_BARS;
2665
+ const subdivision = opts.subdivision ?? DEFAULT_SUBDIVISION;
2666
+ const density = Math.min(1, Math.max(0, opts.density ?? DEFAULT_DENSITY));
2667
+ const barBeats = beatsPerBar(ts);
2668
+ const spanBeats = barBeats * bars;
2669
+ const step = 1 / subdivision;
2670
+ const slotCount = Math.round(spanBeats * subdivision);
2671
+ const slotsPerBar = Math.round(barBeats * subdivision);
2672
+ const rng = createRng(seed);
2673
+ const positions = [];
2674
+ for (let i = 0; i < slotCount; i += 1) {
2675
+ const position = i * step;
2676
+ if (i % slotsPerBar === 0) {
2677
+ positions.push(position);
2678
+ continue;
2679
+ }
2680
+ const weight = metricWeight(position, ts);
2681
+ const probability = onsetWeightCurve(weight) * density;
2682
+ if (rng.prob(probability)) {
2683
+ positions.push(position);
2684
+ }
2685
+ }
2686
+ const events = [];
2687
+ for (let i = 0; i < positions.length; i += 1) {
2688
+ const position = positions[i] ?? 0;
2689
+ const nextPosition = positions[i + 1] ?? spanBeats;
2690
+ events.push({ position, duration: nextPosition - position });
2691
+ }
2692
+ return events;
2693
+ }
2694
+ function rhythmDensity(events, ts) {
2695
+ if (events.length === 0) {
2696
+ return 0;
2697
+ }
2698
+ const last = events[events.length - 1];
2699
+ const spanBeats = (last?.position ?? 0) + (last?.duration ?? 0);
2700
+ const bars = spanBeats / beatsPerBar(ts);
2701
+ return bars > 0 ? events.length / bars : 0;
2702
+ }
2703
+
2704
+ export {
2705
+ generateBassLine,
2706
+ generateCounterMelody,
2707
+ generateDrums,
2708
+ humanize,
2709
+ extractGrooveTemplate,
2710
+ applyGrooveTemplate,
2711
+ harmonizeMelody,
2712
+ generateMotif,
2713
+ transformMotif,
2714
+ developMotif,
2715
+ progressions,
2716
+ progressionsByStyle,
2717
+ generateProgression,
2718
+ onsetWeightCurve,
2719
+ generateRhythm,
2720
+ rhythmDensity
2721
+ };
2722
+ //# sourceMappingURL=chunk-R3S2LUBH.js.map