@nodetool-ai/timeline 0.8.19 → 0.8.21

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 (337) hide show
  1. package/dist/.nodetool-build-stamp +1 -1
  2. package/dist/autoCrossfade.d.ts +30 -0
  3. package/dist/autoCrossfade.d.ts.map +1 -0
  4. package/dist/autoCrossfade.js +130 -0
  5. package/dist/autoCrossfade.js.map +1 -0
  6. package/dist/automation.d.ts +32 -1
  7. package/dist/automation.d.ts.map +1 -1
  8. package/dist/automation.js +78 -1
  9. package/dist/automation.js.map +1 -1
  10. package/dist/automationRanges.d.ts +375 -0
  11. package/dist/automationRanges.d.ts.map +1 -0
  12. package/dist/automationRanges.js +375 -0
  13. package/dist/automationRanges.js.map +1 -0
  14. package/dist/clipAudio.d.ts +3 -1
  15. package/dist/clipAudio.d.ts.map +1 -1
  16. package/dist/clipAudio.js.map +1 -1
  17. package/dist/clipLoop.d.ts +67 -0
  18. package/dist/clipLoop.d.ts.map +1 -0
  19. package/dist/clipLoop.js +339 -0
  20. package/dist/clipLoop.js.map +1 -0
  21. package/dist/clipSpeed.d.ts.map +1 -1
  22. package/dist/clipSpeed.js +7 -0
  23. package/dist/clipSpeed.js.map +1 -1
  24. package/dist/defaults.d.ts.map +1 -1
  25. package/dist/defaults.js +9 -0
  26. package/dist/defaults.js.map +1 -1
  27. package/dist/dropResolve.d.ts.map +1 -1
  28. package/dist/dropResolve.js +56 -17
  29. package/dist/dropResolve.js.map +1 -1
  30. package/dist/harmony/chordChart.d.ts +25 -0
  31. package/dist/harmony/chordChart.d.ts.map +1 -0
  32. package/dist/harmony/chordChart.js +99 -0
  33. package/dist/harmony/chordChart.js.map +1 -0
  34. package/dist/harmony/chordRange.d.ts +9 -0
  35. package/dist/harmony/chordRange.d.ts.map +1 -0
  36. package/dist/harmony/chordRange.js +32 -0
  37. package/dist/harmony/chordRange.js.map +1 -0
  38. package/dist/harmony/chordSymbols.d.ts +28 -0
  39. package/dist/harmony/chordSymbols.d.ts.map +1 -0
  40. package/dist/harmony/chordSymbols.js +147 -0
  41. package/dist/harmony/chordSymbols.js.map +1 -0
  42. package/dist/harmony/chordTrack.d.ts +13 -0
  43. package/dist/harmony/chordTrack.d.ts.map +1 -0
  44. package/dist/harmony/chordTrack.js +11 -0
  45. package/dist/harmony/chordTrack.js.map +1 -0
  46. package/dist/harmony/detect.d.ts +35 -0
  47. package/dist/harmony/detect.d.ts.map +1 -0
  48. package/dist/harmony/detect.js +138 -0
  49. package/dist/harmony/detect.js.map +1 -0
  50. package/dist/harmony/detectAudio.d.ts +62 -0
  51. package/dist/harmony/detectAudio.d.ts.map +1 -0
  52. package/dist/harmony/detectAudio.js +226 -0
  53. package/dist/harmony/detectAudio.js.map +1 -0
  54. package/dist/harmony/expand.d.ts +7 -12
  55. package/dist/harmony/expand.d.ts.map +1 -1
  56. package/dist/harmony/expand.js +63 -11
  57. package/dist/harmony/expand.js.map +1 -1
  58. package/dist/harmony/index.d.ts +7 -0
  59. package/dist/harmony/index.d.ts.map +1 -1
  60. package/dist/harmony/index.js +7 -0
  61. package/dist/harmony/index.js.map +1 -1
  62. package/dist/harmony/progressionLibrary.d.ts +33 -0
  63. package/dist/harmony/progressionLibrary.d.ts.map +1 -0
  64. package/dist/harmony/progressionLibrary.js +71 -0
  65. package/dist/harmony/progressionLibrary.js.map +1 -0
  66. package/dist/harmony/summary.d.ts +4 -0
  67. package/dist/harmony/summary.d.ts.map +1 -0
  68. package/dist/harmony/summary.js +22 -0
  69. package/dist/harmony/summary.js.map +1 -0
  70. package/dist/index.d.ts +3 -0
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +3 -0
  73. package/dist/index.js.map +1 -1
  74. package/dist/interchange.d.ts.map +1 -1
  75. package/dist/interchange.js +72 -12
  76. package/dist/interchange.js.map +1 -1
  77. package/dist/loopWindow.d.ts +17 -0
  78. package/dist/loopWindow.d.ts.map +1 -0
  79. package/dist/loopWindow.js +34 -0
  80. package/dist/loopWindow.js.map +1 -0
  81. package/dist/midi/cacheKey.d.ts +11 -2
  82. package/dist/midi/cacheKey.d.ts.map +1 -1
  83. package/dist/midi/cacheKey.js +69 -9
  84. package/dist/midi/cacheKey.js.map +1 -1
  85. package/dist/midi/controllerEdit.d.ts +35 -0
  86. package/dist/midi/controllerEdit.d.ts.map +1 -0
  87. package/dist/midi/controllerEdit.js +94 -0
  88. package/dist/midi/controllerEdit.js.map +1 -0
  89. package/dist/midi/controllerRange.d.ts +13 -0
  90. package/dist/midi/controllerRange.d.ts.map +1 -0
  91. package/dist/midi/controllerRange.js +13 -0
  92. package/dist/midi/controllerRange.js.map +1 -0
  93. package/dist/midi/controllers.d.ts +95 -0
  94. package/dist/midi/controllers.d.ts.map +1 -0
  95. package/dist/midi/controllers.js +421 -0
  96. package/dist/midi/controllers.js.map +1 -0
  97. package/dist/midi/curveCut.d.ts +17 -0
  98. package/dist/midi/curveCut.d.ts.map +1 -0
  99. package/dist/midi/curveCut.js +45 -0
  100. package/dist/midi/curveCut.js.map +1 -0
  101. package/dist/midi/edit.d.ts +13 -1
  102. package/dist/midi/edit.d.ts.map +1 -1
  103. package/dist/midi/edit.js +19 -3
  104. package/dist/midi/edit.js.map +1 -1
  105. package/dist/midi/engines/bl1.d.ts +10 -1
  106. package/dist/midi/engines/bl1.d.ts.map +1 -1
  107. package/dist/midi/engines/bl1.js +26 -6
  108. package/dist/midi/engines/bl1.js.map +1 -1
  109. package/dist/midi/engines/dr1.d.ts +11 -1
  110. package/dist/midi/engines/dr1.d.ts.map +1 -1
  111. package/dist/midi/engines/dr1.js +21 -3
  112. package/dist/midi/engines/dr1.js.map +1 -1
  113. package/dist/midi/engines/dsp.d.ts +1 -1
  114. package/dist/midi/engines/dsp.d.ts.map +1 -1
  115. package/dist/midi/engines/dsp.js +10 -2
  116. package/dist/midi/engines/dsp.js.map +1 -1
  117. package/dist/midi/engines/wt1.d.ts +10 -1
  118. package/dist/midi/engines/wt1.d.ts.map +1 -1
  119. package/dist/midi/engines/wt1.js +28 -5
  120. package/dist/midi/engines/wt1.js.map +1 -1
  121. package/dist/midi/events.d.ts +13 -4
  122. package/dist/midi/events.d.ts.map +1 -1
  123. package/dist/midi/events.js +33 -6
  124. package/dist/midi/events.js.map +1 -1
  125. package/dist/midi/expression.d.ts +25 -0
  126. package/dist/midi/expression.d.ts.map +1 -0
  127. package/dist/midi/expression.js +69 -0
  128. package/dist/midi/expression.js.map +1 -0
  129. package/dist/midi/index.d.ts +8 -0
  130. package/dist/midi/index.d.ts.map +1 -1
  131. package/dist/midi/index.js +8 -0
  132. package/dist/midi/index.js.map +1 -1
  133. package/dist/midi/instrument.d.ts.map +1 -1
  134. package/dist/midi/instrument.js +4 -0
  135. package/dist/midi/instrument.js.map +1 -1
  136. package/dist/midi/noteFunctions.d.ts +29 -0
  137. package/dist/midi/noteFunctions.d.ts.map +1 -0
  138. package/dist/midi/noteFunctions.js +213 -0
  139. package/dist/midi/noteFunctions.js.map +1 -0
  140. package/dist/midi/notes.d.ts +7 -1
  141. package/dist/midi/notes.d.ts.map +1 -1
  142. package/dist/midi/notes.js +43 -1
  143. package/dist/midi/notes.js.map +1 -1
  144. package/dist/midi/notesEdit.d.ts +13 -0
  145. package/dist/midi/notesEdit.d.ts.map +1 -1
  146. package/dist/midi/notesEdit.js +73 -2
  147. package/dist/midi/notesEdit.js.map +1 -1
  148. package/dist/midi/presets.d.ts +1 -1
  149. package/dist/midi/regionParams.d.ts +41 -0
  150. package/dist/midi/regionParams.d.ts.map +1 -0
  151. package/dist/midi/regionParams.js +164 -0
  152. package/dist/midi/regionParams.js.map +1 -0
  153. package/dist/midi/sampler.d.ts +2 -2
  154. package/dist/midi/sampler.d.ts.map +1 -1
  155. package/dist/midi/sampler.js +99 -21
  156. package/dist/midi/sampler.js.map +1 -1
  157. package/dist/midi/stepEditor.d.ts +50 -0
  158. package/dist/midi/stepEditor.d.ts.map +1 -0
  159. package/dist/midi/stepEditor.js +118 -0
  160. package/dist/midi/stepEditor.js.map +1 -0
  161. package/dist/midi/stepPattern.d.ts +173 -0
  162. package/dist/midi/stepPattern.d.ts.map +1 -0
  163. package/dist/midi/stepPattern.js +1390 -0
  164. package/dist/midi/stepPattern.js.map +1 -0
  165. package/dist/midi/stepPatternExpand.d.ts +149 -0
  166. package/dist/midi/stepPatternExpand.d.ts.map +1 -0
  167. package/dist/midi/stepPatternExpand.js +1068 -0
  168. package/dist/midi/stepPatternExpand.js.map +1 -0
  169. package/dist/midi/stepPatternLibrary.d.ts +65 -0
  170. package/dist/midi/stepPatternLibrary.d.ts.map +1 -0
  171. package/dist/midi/stepPatternLibrary.js +640 -0
  172. package/dist/midi/stepPatternLibrary.js.map +1 -0
  173. package/dist/midi/tempo.d.ts.map +1 -1
  174. package/dist/midi/tempo.js +3 -0
  175. package/dist/midi/tempo.js.map +1 -1
  176. package/dist/midi/voice.d.ts +51 -5
  177. package/dist/midi/voice.d.ts.map +1 -1
  178. package/dist/midi/voice.js +191 -21
  179. package/dist/midi/voice.js.map +1 -1
  180. package/dist/model3dBake.d.ts +13 -0
  181. package/dist/model3dBake.d.ts.map +1 -1
  182. package/dist/model3dBake.js +25 -0
  183. package/dist/model3dBake.js.map +1 -1
  184. package/dist/model3dCameraDescription.d.ts +11 -6
  185. package/dist/model3dCameraDescription.d.ts.map +1 -1
  186. package/dist/model3dCameraDescription.js +112 -30
  187. package/dist/model3dCameraDescription.js.map +1 -1
  188. package/dist/model3dReference.d.ts +25 -4
  189. package/dist/model3dReference.d.ts.map +1 -1
  190. package/dist/model3dReference.js +19 -6
  191. package/dist/model3dReference.js.map +1 -1
  192. package/dist/music/align.d.ts +111 -0
  193. package/dist/music/align.d.ts.map +1 -0
  194. package/dist/music/align.js +282 -0
  195. package/dist/music/align.js.map +1 -0
  196. package/dist/music/cut.d.ts +33 -0
  197. package/dist/music/cut.d.ts.map +1 -0
  198. package/dist/music/cut.js +50 -0
  199. package/dist/music/cut.js.map +1 -0
  200. package/dist/music/frames.d.ts +51 -0
  201. package/dist/music/frames.d.ts.map +1 -0
  202. package/dist/music/frames.js +110 -0
  203. package/dist/music/frames.js.map +1 -0
  204. package/dist/music/gain.d.ts +24 -0
  205. package/dist/music/gain.d.ts.map +1 -0
  206. package/dist/music/gain.js +38 -0
  207. package/dist/music/gain.js.map +1 -0
  208. package/dist/music/index.d.ts +9 -0
  209. package/dist/music/index.d.ts.map +1 -0
  210. package/dist/music/index.js +9 -0
  211. package/dist/music/index.js.map +1 -0
  212. package/dist/music/plan.d.ts +104 -0
  213. package/dist/music/plan.d.ts.map +1 -0
  214. package/dist/music/plan.js +300 -0
  215. package/dist/music/plan.js.map +1 -0
  216. package/dist/music/process.d.ts +9 -0
  217. package/dist/music/process.d.ts.map +1 -0
  218. package/dist/music/process.js +9 -0
  219. package/dist/music/process.js.map +1 -0
  220. package/dist/music/roles.d.ts +14 -0
  221. package/dist/music/roles.d.ts.map +1 -0
  222. package/dist/music/roles.js +30 -0
  223. package/dist/music/roles.js.map +1 -0
  224. package/dist/music/splice.d.ts +37 -0
  225. package/dist/music/splice.d.ts.map +1 -0
  226. package/dist/music/splice.js +67 -0
  227. package/dist/music/splice.js.map +1 -0
  228. package/dist/music/tempoRules.d.ts +41 -0
  229. package/dist/music/tempoRules.d.ts.map +1 -0
  230. package/dist/music/tempoRules.js +59 -0
  231. package/dist/music/tempoRules.js.map +1 -0
  232. package/dist/ops/apply.d.ts.map +1 -1
  233. package/dist/ops/apply.js +856 -234
  234. package/dist/ops/apply.js.map +1 -1
  235. package/dist/ops/automation.d.ts +6 -0
  236. package/dist/ops/automation.d.ts.map +1 -0
  237. package/dist/ops/automation.js +217 -0
  238. package/dist/ops/automation.js.map +1 -0
  239. package/dist/ops/barTime.d.ts +14 -0
  240. package/dist/ops/barTime.d.ts.map +1 -0
  241. package/dist/ops/barTime.js +33 -0
  242. package/dist/ops/barTime.js.map +1 -0
  243. package/dist/ops/chords.d.ts +43 -0
  244. package/dist/ops/chords.d.ts.map +1 -0
  245. package/dist/ops/chords.js +691 -0
  246. package/dist/ops/chords.js.map +1 -0
  247. package/dist/ops/groupBake.d.ts +24 -0
  248. package/dist/ops/groupBake.d.ts.map +1 -0
  249. package/dist/ops/groupBake.js +81 -0
  250. package/dist/ops/groupBake.js.map +1 -0
  251. package/dist/ops/index.d.ts +7 -0
  252. package/dist/ops/index.d.ts.map +1 -1
  253. package/dist/ops/index.js +5 -0
  254. package/dist/ops/index.js.map +1 -1
  255. package/dist/ops/join.d.ts +20 -0
  256. package/dist/ops/join.d.ts.map +1 -0
  257. package/dist/ops/join.js +265 -0
  258. package/dist/ops/join.js.map +1 -0
  259. package/dist/ops/loop.d.ts +29 -0
  260. package/dist/ops/loop.d.ts.map +1 -0
  261. package/dist/ops/loop.js +107 -0
  262. package/dist/ops/loop.js.map +1 -0
  263. package/dist/ops/midiMix.d.ts +41 -0
  264. package/dist/ops/midiMix.d.ts.map +1 -0
  265. package/dist/ops/midiMix.js +522 -0
  266. package/dist/ops/midiMix.js.map +1 -0
  267. package/dist/ops/op.d.ts +61 -11
  268. package/dist/ops/op.d.ts.map +1 -1
  269. package/dist/ops/op.js +60 -1
  270. package/dist/ops/op.js.map +1 -1
  271. package/dist/ops/parse.d.ts.map +1 -1
  272. package/dist/ops/parse.js +308 -4
  273. package/dist/ops/parse.js.map +1 -1
  274. package/dist/ops/pasteRange.d.ts +46 -0
  275. package/dist/ops/pasteRange.d.ts.map +1 -0
  276. package/dist/ops/pasteRange.js +276 -0
  277. package/dist/ops/pasteRange.js.map +1 -0
  278. package/dist/ops/plugin.d.ts +57 -0
  279. package/dist/ops/plugin.d.ts.map +1 -0
  280. package/dist/ops/plugin.js +875 -0
  281. package/dist/ops/plugin.js.map +1 -0
  282. package/dist/ops/sections.d.ts +98 -0
  283. package/dist/ops/sections.d.ts.map +1 -0
  284. package/dist/ops/sections.js +930 -0
  285. package/dist/ops/sections.js.map +1 -0
  286. package/dist/ops/serialize.d.ts +79 -1
  287. package/dist/ops/serialize.d.ts.map +1 -1
  288. package/dist/ops/serialize.js +85 -3
  289. package/dist/ops/serialize.js.map +1 -1
  290. package/dist/ops/stepPattern.d.ts +44 -0
  291. package/dist/ops/stepPattern.d.ts.map +1 -0
  292. package/dist/ops/stepPattern.js +2106 -0
  293. package/dist/ops/stepPattern.js.map +1 -0
  294. package/dist/ops/stepPatternFolders.d.ts +54 -0
  295. package/dist/ops/stepPatternFolders.d.ts.map +1 -0
  296. package/dist/ops/stepPatternFolders.js +299 -0
  297. package/dist/ops/stepPatternFolders.js.map +1 -0
  298. package/dist/ops/types.d.ts +238 -2
  299. package/dist/ops/types.d.ts.map +1 -1
  300. package/dist/rippleEdit.d.ts +5 -1
  301. package/dist/rippleEdit.d.ts.map +1 -1
  302. package/dist/rippleEdit.js +24 -9
  303. package/dist/rippleEdit.js.map +1 -1
  304. package/dist/script.d.ts +2 -1
  305. package/dist/script.d.ts.map +1 -1
  306. package/dist/script.js +3 -2
  307. package/dist/script.js.map +1 -1
  308. package/dist/splitClip.d.ts +29 -1
  309. package/dist/splitClip.d.ts.map +1 -1
  310. package/dist/splitClip.js +231 -1
  311. package/dist/splitClip.js.map +1 -1
  312. package/dist/storyboard.d.ts +14 -0
  313. package/dist/storyboard.d.ts.map +1 -1
  314. package/dist/storyboard.js +31 -0
  315. package/dist/storyboard.js.map +1 -1
  316. package/dist/testing/host-ops.js +3 -3
  317. package/dist/testing/host-ops.js.map +1 -1
  318. package/dist/testing/ops.d.ts +6 -1
  319. package/dist/testing/ops.d.ts.map +1 -1
  320. package/dist/testing/ops.js +823 -11
  321. package/dist/testing/ops.js.map +1 -1
  322. package/dist/timeRemap.d.ts +2 -2
  323. package/dist/timeRemap.d.ts.map +1 -1
  324. package/dist/timeRemap.js +18 -0
  325. package/dist/timeRemap.js.map +1 -1
  326. package/dist/trimClip.d.ts +1 -1
  327. package/dist/trimClip.d.ts.map +1 -1
  328. package/dist/trimClip.js +41 -7
  329. package/dist/trimClip.js.map +1 -1
  330. package/dist/types.d.ts +307 -16
  331. package/dist/types.d.ts.map +1 -1
  332. package/dist/types.js.map +1 -1
  333. package/package.json +11 -5
  334. package/dist/render/curveFitting.d.ts +0 -28
  335. package/dist/render/curveFitting.d.ts.map +0 -1
  336. package/dist/render/curveFitting.js +0 -94
  337. package/dist/render/curveFitting.js.map +0 -1
@@ -0,0 +1,691 @@
1
+ /**
2
+ * The chord ops: write, clear, transpose and detect chords on a chord track,
3
+ * make midi clips follow it, and bake notes into its chords. Pure document
4
+ * edits, shared by every host through `applyTimelineOp`.
5
+ */
6
+ import { ARP_ORDERS, barTicks, chordAtTick, chordChart, chordMask, chordScale, CHORD_QUALITIES, chordSymbol, clearChordRange, COMP_LIBRARY, chordsFromChromaWindows, detectChordsFromNotes, findProgression, harmonySummary, isHarmonyActive, keyScale, listProgressionInfo, parseChordChart, parseChordSymbol, parseKey, progressionId, PROGRESSIONS, remapNote, scaleMask, scaleRemap, sortChords, tonicPitchClass, mixWindowChroma, windowChroma } from "../harmony/index.js";
7
+ import { transposeNotes } from "../midi/edit.js";
8
+ import { expandMidiLoop } from "../clipLoop.js";
9
+ import { sortNotes, visibleNotes } from "../midi/notes.js";
10
+ import { resolveTempo } from "../midi/tempo.js";
11
+ import { MIDI_PPQ, msToTicks, ticksToMs } from "../midi/ticks.js";
12
+ import { timeRemapAudioSegments } from "../timeRemap.js";
13
+ const MAX_LISTED = 12;
14
+ function tempoOf(scope) {
15
+ return resolveTempo(scope.state);
16
+ }
17
+ function beatTicks(tempo) {
18
+ return Math.round((MIDI_PPQ * 4) / tempo.timeSignature.beatUnit);
19
+ }
20
+ /** A chord id unused on the track. Ids stay the document's own: the host id minter has no chord kind. */
21
+ function chordIdMinter(existing) {
22
+ const used = new Set(existing.map((c) => c.id));
23
+ let n = 0;
24
+ return () => {
25
+ let id;
26
+ do {
27
+ id = `chord_${(++n).toString(36)}`;
28
+ } while (used.has(id));
29
+ used.add(id);
30
+ return id;
31
+ };
32
+ }
33
+ /** The chord track an op writes to. `create` adds one when the document has none. */
34
+ function resolveChordTrack(scope, trackId, create) {
35
+ const chordTracks = scope.tracks.filter((t) => t.type === "chord");
36
+ if (trackId !== undefined) {
37
+ const track = scope.resolveTrack(trackId);
38
+ if (track.type !== "chord") {
39
+ throw new Error(`Track "${track.name}" is a ${track.type} track, not a chord track. ` +
40
+ (chordTracks.length
41
+ ? scope.validUnits(chordTracks, "chord track")
42
+ : "The document has no chord track. Omit trackId and set_chords creates one."));
43
+ }
44
+ scope.assertWritable([], track.id);
45
+ return { track, created: false };
46
+ }
47
+ const first = chordTracks[0];
48
+ if (first) {
49
+ scope.assertWritable([], first.id);
50
+ return { track: first, created: false };
51
+ }
52
+ if (!create) {
53
+ throw new Error("The document has no chord track. Write chords with set_chords or apply_progression, which create one.");
54
+ }
55
+ const track = scope.addTrack("chord", "Chords");
56
+ track.chords = [];
57
+ return { track, created: true };
58
+ }
59
+ /** The chord track a clip follows, read-only. */
60
+ function readChordTrack(scope, trackId) {
61
+ if (trackId !== undefined) {
62
+ const track = scope.resolveTrack(trackId);
63
+ if (track.type !== "chord") {
64
+ const chordTracks = scope.tracks.filter((t) => t.type === "chord");
65
+ throw new Error(`Track "${track.name}" is a ${track.type} track, not a chord track. ` +
66
+ (chordTracks.length
67
+ ? scope.validUnits(chordTracks, "chord track")
68
+ : "The document has no chord track yet. Write one with set_chords."));
69
+ }
70
+ return track;
71
+ }
72
+ return scope.tracks.find((t) => t.type === "chord");
73
+ }
74
+ function rangeTicks(tempo, startBar, endBar) {
75
+ const bar = barTicks(tempo);
76
+ const from = ((startBar ?? 1) - 1) * bar;
77
+ const to = endBar === undefined ? Number.POSITIVE_INFINITY : endBar * bar;
78
+ if (to <= from) {
79
+ throw new Error(`endBar ${String(endBar)} comes before startBar ${String(startBar ?? 1)}. Bars count from 1 and both are included.`);
80
+ }
81
+ return { from, to };
82
+ }
83
+ /** The whole-track chart: bar 1 to the bar that holds the last chord. */
84
+ export function trackChordChart(tempo, chords) {
85
+ if (chords.length === 0)
86
+ return "";
87
+ const end = Math.max(...chords.map((c) => c.startTick + c.durationTick));
88
+ return chordChart(chords, 0, end, tempo);
89
+ }
90
+ /** "A minor", or undefined when the document has no key. */
91
+ export function keyLabel(tempo) {
92
+ return tempo.key ? `${tempo.key.tonic} ${tempo.key.mode}` : undefined;
93
+ }
94
+ export function signatureLabel(tempo) {
95
+ return `${tempo.timeSignature.beatsPerBar}/${tempo.timeSignature.beatUnit}`;
96
+ }
97
+ function chordsOut(chords) {
98
+ return sortChords(chords).map((c) => ({
99
+ id: c.id,
100
+ symbol: chordSymbol(c),
101
+ startTick: c.startTick,
102
+ durationTick: c.durationTick
103
+ }));
104
+ }
105
+ function writeResult(scope, track, created, from, to, extra = {}) {
106
+ const tempo = tempoOf(scope);
107
+ const chords = track.chords ?? [];
108
+ const bar = barTicks(tempo);
109
+ return {
110
+ ok: true,
111
+ trackId: track.id,
112
+ createdTrack: created,
113
+ chart: trackChordChart(tempo, chords),
114
+ chordCount: chords.length,
115
+ written: { startBar: from / bar + 1, endBar: Math.max(from / bar + 1, Math.ceil(to / bar - 1e-9)) },
116
+ ...extra
117
+ };
118
+ }
119
+ /** Replaces `[from, to)` of the track with `incoming`. */
120
+ function writeRange(track, from, to, incoming, mint) {
121
+ const cleared = clearChordRange(track.chords ?? [], from, to, mint);
122
+ // The range is empty and `incoming` is disjoint inside it, so no chord needs placing.
123
+ track.chords = sortChords([...cleared, ...incoming]);
124
+ }
125
+ export function runSetChords(scope, op) {
126
+ const hasChart = op.chart !== undefined && op.chart.trim() !== "";
127
+ if (hasChart === (op.chords !== undefined)) {
128
+ throw new Error('Send exactly one of `chart` (a bar string such as "| Am | F | C G |") or `chords` (a list such as [{"symbol":"Am","bars":1}]).');
129
+ }
130
+ const tempo = tempoOf(scope);
131
+ const { track, created } = resolveChordTrack(scope, op.trackId, true);
132
+ const bar = barTicks(tempo);
133
+ const from = ((op.startBar ?? 1) - 1) * bar;
134
+ const mint = chordIdMinter(track.chords ?? []);
135
+ let incoming;
136
+ let to;
137
+ if (hasChart) {
138
+ const parsed = parseChordChart(op.chart, from, tempo, mint);
139
+ if (!parsed.ok)
140
+ throw new Error(parsed.error);
141
+ incoming = parsed.chords;
142
+ to = from + parsed.bars * bar;
143
+ }
144
+ else {
145
+ incoming = [];
146
+ let at = from;
147
+ (op.chords ?? []).forEach((item, i) => {
148
+ const parsed = parseChordSymbol(item.symbol);
149
+ if (!parsed.ok)
150
+ throw new Error(`chords[${i}]: ${parsed.error}`);
151
+ const len = item.bars === undefined && item.beats === undefined
152
+ ? bar
153
+ : Math.round((item.bars ?? 0) * bar + (item.beats ?? 0) * beatTicks(tempo));
154
+ if (len <= 0)
155
+ throw new Error(`chords[${i}] has no length. Give \`bars\` or \`beats\` above 0.`);
156
+ incoming.push({
157
+ id: mint(),
158
+ startTick: at,
159
+ durationTick: len,
160
+ root: parsed.root,
161
+ quality: parsed.quality,
162
+ inversion: parsed.inversion
163
+ });
164
+ at += len;
165
+ });
166
+ if (incoming.length === 0)
167
+ throw new Error("`chords` is empty. List at least one chord.");
168
+ to = at;
169
+ }
170
+ writeRange(track, from, to, incoming, mint);
171
+ return writeResult(scope, track, created, from, to);
172
+ }
173
+ export function runClearChords(scope, op) {
174
+ const tempo = tempoOf(scope);
175
+ if (op.trackId === undefined && !scope.tracks.some((t) => t.type === "chord")) {
176
+ return {
177
+ ok: true,
178
+ removedChordCount: 0,
179
+ chordCount: 0,
180
+ chart: "",
181
+ note: "The document has no chord track, so there was nothing to clear. set_chords creates one."
182
+ };
183
+ }
184
+ const { track } = resolveChordTrack(scope, op.trackId, false);
185
+ const { from, to } = rangeTicks(tempo, op.startBar, op.endBar);
186
+ const before = track.chords?.length ?? 0;
187
+ track.chords = clearChordRange(track.chords ?? [], from, to, chordIdMinter(track.chords ?? []));
188
+ return {
189
+ ok: true,
190
+ trackId: track.id,
191
+ removedChordCount: Math.max(0, before - track.chords.length),
192
+ chart: trackChordChart(tempo, track.chords),
193
+ chordCount: track.chords.length
194
+ };
195
+ }
196
+ export function runListProgressions() {
197
+ return {
198
+ ok: true,
199
+ progressions: listProgressionInfo(),
200
+ hint: "Pass an id or a name to apply_progression. Numerals count from the key tonic, so a minor key wants a minor progression such as i-VI-III-VII."
201
+ };
202
+ }
203
+ export function runApplyProgression(scope, op) {
204
+ const progression = findProgression(op.progression);
205
+ if (!progression) {
206
+ const ids = PROGRESSIONS.slice(0, MAX_LISTED).map(progressionId);
207
+ throw new Error(`No progression matches "${op.progression}". Call list_progressions for all ${PROGRESSIONS.length}. ` +
208
+ `Valid ids include ${ids.join(", ")}.`);
209
+ }
210
+ const tempo = tempoOf(scope);
211
+ let tonic = 0;
212
+ let mode = "major";
213
+ if (op.key !== undefined) {
214
+ const key = parseKey(op.key);
215
+ if (!key.ok)
216
+ throw new Error(key.error);
217
+ tonic = key.tonic;
218
+ mode = key.mode;
219
+ }
220
+ else if (tempo.key) {
221
+ tonic = tonicPitchClass(tempo.key.tonic) ?? 0;
222
+ mode = tempo.key.mode;
223
+ }
224
+ const { track, created } = resolveChordTrack(scope, op.trackId, true);
225
+ const bar = barTicks(tempo);
226
+ const from = ((op.startBar ?? 1) - 1) * bar;
227
+ const mint = chordIdMinter(track.chords ?? []);
228
+ const incoming = [];
229
+ let at = from;
230
+ for (let pass = 0; pass < (op.repeat ?? 1); pass++) {
231
+ for (const [degree, quality, beats] of progression.steps) {
232
+ const len = Math.round(op.barsPerChord !== undefined ? op.barsPerChord * bar : (beats / 4) * bar);
233
+ if (len <= 0) {
234
+ throw new Error(`barsPerChord ${String(op.barsPerChord)} is too short: a chord needs at least 1 tick. Use 0.25 (one beat in 4/4) or more.`);
235
+ }
236
+ incoming.push({
237
+ id: mint(),
238
+ startTick: at,
239
+ durationTick: len,
240
+ root: (((tonic + degree) % 12) + 12) % 12,
241
+ quality,
242
+ inversion: 0
243
+ });
244
+ at += len;
245
+ }
246
+ }
247
+ writeRange(track, from, at, incoming, mint);
248
+ // The tonic chord (degree 0) tells the mode of the progression. One with no tonic chord gets no note.
249
+ const tonicStep = progression.steps.find((step) => step[0] === 0);
250
+ const tonicMinor = tonicStep ? CHORD_QUALITIES[tonicStep[1]].iv[1] === 3 : undefined;
251
+ const note = mode === "minor" && tonicMinor === false
252
+ ? `"${progression.name}" has a major tonic chord, so its chords are built on the tonic as a major-key progression. For a minor sound pick one of the MINOR progressions.`
253
+ : mode === "major" && tonicMinor === true
254
+ ? `"${progression.name}" has a minor tonic chord, so its chords are built on the tonic as a minor-key progression.`
255
+ : undefined;
256
+ const extra = { progression: progressionId(progression) };
257
+ if (note)
258
+ extra.note = note;
259
+ return writeResult(scope, track, created, from, at, extra);
260
+ }
261
+ /** Whether a clip's harmony makes it play from the chord track. */
262
+ function followsChords(clip) {
263
+ const h = clip.harmony;
264
+ if (!isHarmonyActive(h))
265
+ return false;
266
+ return (h.style !== "off" && h.input === "chords") || h.scale === "chords";
267
+ }
268
+ /** Document tick of content tick 0 of `clip`. */
269
+ function clipShift(clip, tempo) {
270
+ return Math.round(msToTicks(clip.startMs - (clip.inPointMs ?? 0) - tempo.offsetMs, tempo.bpm));
271
+ }
272
+ export function runTransposeChords(scope, op) {
273
+ const tempo = tempoOf(scope);
274
+ const hasChordTrack = op.trackId !== undefined || scope.tracks.some((t) => t.type === "chord");
275
+ if (!hasChordTrack && !op.includeNotes) {
276
+ throw new Error("The document has no chord track to transpose. Write chords with set_chords, or send includeNotes: true to move written notes.");
277
+ }
278
+ const track = hasChordTrack ? resolveChordTrack(scope, op.trackId, false).track : undefined;
279
+ const { from, to } = rangeTicks(tempo, op.startBar, op.endBar);
280
+ let moved = 0;
281
+ if (track) {
282
+ // A chord that crosses an edge splits there, so the notes and the chord move together.
283
+ const mint = chordIdMinter(track.chords ?? []);
284
+ let chords = sortChords(track.chords ?? []);
285
+ for (const cut of [from, to]) {
286
+ if (!Number.isFinite(cut))
287
+ continue;
288
+ chords = chords.flatMap((c) => {
289
+ const end = c.startTick + c.durationTick;
290
+ return c.startTick < cut && end > cut
291
+ ? [
292
+ { ...c, durationTick: cut - c.startTick },
293
+ { ...c, id: mint(), startTick: cut, durationTick: end - cut }
294
+ ]
295
+ : [c];
296
+ });
297
+ }
298
+ track.chords = chords.map((c) => {
299
+ if (c.startTick < from || c.startTick >= to)
300
+ return c;
301
+ moved++;
302
+ return { ...c, root: (((c.root + op.semitones) % 12) + 12) % 12 };
303
+ });
304
+ }
305
+ let noteCount = 0;
306
+ const clipIds = [];
307
+ if (op.includeNotes) {
308
+ for (const clip of scope.clips) {
309
+ if (clip.mediaType !== "midi" || !clip.notes?.length || followsChords(clip))
310
+ continue;
311
+ const shift = clipShift(clip, tempo);
312
+ const inRange = (startTick) => shift + startTick >= from && shift + startTick < to;
313
+ // Only the notes in the clip's window sound, so only they move.
314
+ const moving = visibleNotes(clip, tempo.bpm).filter((n) => inRange(n.startTick));
315
+ if (moving.length === 0)
316
+ continue;
317
+ scope.assertWritable([clip]);
318
+ const movedNotes = new Map(transposeNotes(moving, op.semitones).map((n) => [n.id, n]));
319
+ noteCount += moving.length;
320
+ clip.notes = clip.notes.map((n) => movedNotes.get(n.id) ?? n);
321
+ clipIds.push(clip.id);
322
+ scope.touch(clip.id);
323
+ }
324
+ }
325
+ return {
326
+ ok: true,
327
+ trackId: track?.id ?? null,
328
+ transposedChordCount: moved,
329
+ transposedNoteCount: noteCount,
330
+ noteClipIds: clipIds,
331
+ chart: track ? trackChordChart(tempo, track.chords ?? []) : ""
332
+ };
333
+ }
334
+ /** Shortest slice of a clip (ms) that counts as sound inside a window. */
335
+ const MIN_AUDIO_SLICE_MS = 50;
336
+ export async function runDetectChords(scope, op) {
337
+ if (!op.clipIds?.length && !op.trackIds?.length) {
338
+ throw new Error("Say what to read: `clipIds` (midi or audio clips by id or name) or `trackIds` (every clip on those tracks).");
339
+ }
340
+ const tempo = tempoOf(scope);
341
+ const sources = new Map();
342
+ const isAudio = (c) => c.mediaType === "audio";
343
+ for (const ref of op.clipIds ?? []) {
344
+ const clip = scope.resolveClip(ref);
345
+ if (clip.mediaType !== "midi" && !isAudio(clip)) {
346
+ throw new Error(`Clip "${clip.name}" is a ${clip.mediaType} clip. Chords are read from midi and audio clips.`);
347
+ }
348
+ sources.set(clip.id, clip);
349
+ }
350
+ for (const ref of op.trackIds ?? []) {
351
+ const track = scope.resolveTrack(ref);
352
+ // A drum stem, a drum rack and a muted track have no harmony to read, so a track list leaves them out.
353
+ if (track.muted || track.musicRole === "drums" || track.instrument?.type === "drum")
354
+ continue;
355
+ for (const clip of scope.clips) {
356
+ if (clip.trackId !== track.id || clip.muted)
357
+ continue;
358
+ if (clip.mediaType === "midi" || isAudio(clip))
359
+ sources.set(clip.id, clip);
360
+ }
361
+ }
362
+ if (sources.size === 0) {
363
+ throw new Error("No midi or audio clips to read. Pass clips in `clipIds`, or tracks that hold them in `trackIds` (drum tracks are skipped).");
364
+ }
365
+ const audioClips = [...sources.values()].filter(isAudio);
366
+ if (audioClips.length > 0 && audioClips.length < sources.size) {
367
+ throw new Error("Read midi clips and audio clips in separate calls. Their weights do not mix.");
368
+ }
369
+ const notes = [];
370
+ let firstTick = Number.POSITIVE_INFINITY;
371
+ let lastTick = 0;
372
+ let lastClipEnd = 0;
373
+ for (const clip of sources.values()) {
374
+ const shift = clipShift(clip, tempo);
375
+ const clipEnd = Math.round(msToTicks(clip.startMs + clip.durationMs - tempo.offsetMs, tempo.bpm));
376
+ if (isAudio(clip)) {
377
+ firstTick = Math.min(firstTick, Math.round(msToTicks(clip.startMs - tempo.offsetMs, tempo.bpm)));
378
+ lastTick = Math.max(lastTick, clipEnd);
379
+ lastClipEnd = Math.max(lastClipEnd, clipEnd);
380
+ continue;
381
+ }
382
+ for (const n of visibleNotes(expandMidiLoop(clip, tempo.bpm, tempo.offsetMs), tempo.bpm)) {
383
+ // Playback gates a note at the clip end, so detection does too.
384
+ const start = shift + n.startTick;
385
+ const end = Math.min(start + n.durationTick, clipEnd);
386
+ if (end <= start)
387
+ continue;
388
+ notes.push({ pitch: n.pitch, startTick: start, durationTick: end - start, muted: n.muted });
389
+ if (!n.muted) {
390
+ firstTick = Math.min(firstTick, start);
391
+ lastTick = Math.max(lastTick, end);
392
+ }
393
+ }
394
+ lastClipEnd = Math.max(lastClipEnd, clipEnd);
395
+ }
396
+ // The default end is the bar that holds the last note, not the end of a long clip window.
397
+ if (lastTick === 0)
398
+ lastTick = lastClipEnd;
399
+ const bar = barTicks(tempo);
400
+ // Without startBar the range starts at the bar of the first sounding note, so chords before the source stay.
401
+ // A source that starts before bar 1 (a count-in) still reads from bar 1: chord ticks are never negative.
402
+ const startBar = op.startBar ?? (Number.isFinite(firstTick) ? Math.max(1, Math.floor(firstTick / bar + 1e-6) + 1) : 1);
403
+ const from = (startBar - 1) * bar;
404
+ const to = op.endBar !== undefined ? op.endBar * bar : Math.max(from + bar, Math.ceil(lastTick / bar - 1e-6) * bar);
405
+ if (to <= from) {
406
+ throw new Error(`endBar ${String(op.endBar)} comes before startBar ${String(startBar)}.`);
407
+ }
408
+ const resolution = op.resolution ?? "bar";
409
+ const step = resolution === "bar" ? bar : resolution === "half" ? Math.round(bar / 2) : beatTicks(tempo);
410
+ const windows = [];
411
+ for (let at = from; at < to; at += step)
412
+ windows.push({ startTick: at, endTick: Math.min(at + step, to) });
413
+ const detected = audioClips.length > 0
414
+ ? await detectFromAudioClips(scope, audioClips, windows, tempo)
415
+ : detectChordsFromNotes(notes, windows, (i) => `detected_${i}`);
416
+ const write = op.write ?? true;
417
+ const baseOf = (chords) => ({
418
+ ok: true,
419
+ written: false,
420
+ resolution,
421
+ range: { startBar, endBar: to / bar },
422
+ chart: chordChart(chords, from, to, tempo),
423
+ chordCount: chords.length,
424
+ chords: chordsOut(chords)
425
+ });
426
+ if (detected.length === 0) {
427
+ return {
428
+ ...baseOf(detected),
429
+ message: audioClips.length > 0
430
+ ? "No sound in the range, so no chords were found and the chord track is unchanged."
431
+ : "No sounding notes in the range, so no chords were found and the chord track is unchanged."
432
+ };
433
+ }
434
+ if (!write)
435
+ return baseOf(detected);
436
+ const { track, created } = resolveChordTrack(scope, op.chordTrackId, true);
437
+ const mint = chordIdMinter(track.chords ?? []);
438
+ const incoming = detected.map((c) => ({ ...c, id: mint() }));
439
+ writeRange(track, from, to, incoming, mint);
440
+ // Return the chords as written, with the ids they have on the track.
441
+ return { ...baseOf(incoming), written: true, trackId: track.id, createdTrack: created };
442
+ }
443
+ /** The source spans (ms) a clip plays under the timeline span [a, b]. Reverse and freeze stretches have no sound. */
444
+ function sourcePieces(clip, a, b) {
445
+ const pieces = [];
446
+ for (const seg of timeRemapAudioSegments(clip)) {
447
+ if (seg.reverse)
448
+ continue;
449
+ const ta = Math.max(a, seg.timelineStartMs);
450
+ const tb = Math.min(b, seg.timelineEndMs);
451
+ if (tb <= ta)
452
+ continue;
453
+ pieces.push([
454
+ seg.sourceStartMs + (ta - seg.timelineStartMs) * seg.rate,
455
+ seg.sourceStartMs + (tb - seg.timelineStartMs) * seg.rate
456
+ ]);
457
+ }
458
+ return pieces;
459
+ }
460
+ /** Hands the thread back, so a long analysis does not freeze a browser tab. */
461
+ const yieldThread = () => new Promise((resolve) => setTimeout(resolve, 0));
462
+ const SLICE_BUDGET_MS = 12;
463
+ /**
464
+ * Chords of audio clips. The host decodes the source audio each window needs.
465
+ * A window reads the source spans the clip plays under it (in-point, speed and
466
+ * time remap, forward stretches only), so the analysis follows the clip's own
467
+ * timing. The source is read at its own pitch, whatever the playback speed.
468
+ * Clips of one asset share one decode of the union of their spans.
469
+ */
470
+ async function detectFromAudioClips(scope, clips, windows, tempo) {
471
+ const decode = scope.ctx.decodeClipAudio;
472
+ if (!decode) {
473
+ throw new Error("This host cannot decode audio, so it cannot detect chords from an audio clip. Detect from a midi clip, or write the chords with set_chords.");
474
+ }
475
+ const toMs = (tick) => ticksToMs(tick, tempo.bpm) + tempo.offsetMs;
476
+ // Plan: the source spans of every window and clip, and the range each asset needs.
477
+ const plan = windows.map((w) => {
478
+ const ws = toMs(w.startTick);
479
+ const we = toMs(w.endTick);
480
+ return clips.map((clip) => {
481
+ const a = Math.max(ws, clip.startMs);
482
+ const b = Math.min(we, clip.startMs + clip.durationMs);
483
+ return b - a < MIN_AUDIO_SLICE_MS ? [] : sourcePieces(clip, a, b);
484
+ });
485
+ });
486
+ const assetKey = (clip) => clip.currentAssetId ?? clip.id;
487
+ const ranges = new Map();
488
+ clips.forEach((clip, ci) => {
489
+ for (const row of plan) {
490
+ for (const [lo, hi] of row[ci]) {
491
+ const key = assetKey(clip);
492
+ const r = ranges.get(key);
493
+ if (!r)
494
+ ranges.set(key, { startMs: lo, endMs: hi, clip });
495
+ else {
496
+ r.startMs = Math.min(r.startMs, lo);
497
+ r.endMs = Math.max(r.endMs, hi);
498
+ }
499
+ }
500
+ }
501
+ });
502
+ const decoded = new Map();
503
+ for (const [key, r] of ranges) {
504
+ const range = { startMs: Math.max(0, r.startMs - 20), endMs: r.endMs + 20 };
505
+ const audio = await decode(r.clip, range);
506
+ if (!audio || audio.samples.length === 0) {
507
+ throw new Error(`Could not read the audio of clip "${r.clip.name}". Check that the clip has an audio source.`);
508
+ }
509
+ decoded.set(key, { samples: audio.samples, sampleRate: audio.sampleRate, startMs: audio.startMs ?? 0 });
510
+ }
511
+ const chroma = [];
512
+ let sliceStart = Date.now();
513
+ for (let wi = 0; wi < windows.length; wi++) {
514
+ const w = windows[wi];
515
+ const heard = [];
516
+ clips.forEach((clip, ci) => {
517
+ const audio = decoded.get(assetKey(clip));
518
+ const pieces = plan[wi][ci];
519
+ if (!audio || pieces.length === 0)
520
+ return;
521
+ const sr = audio.sampleRate;
522
+ const spans = pieces.map(([lo, hi]) => [
523
+ Math.round(((lo - audio.startMs) * sr) / 1000),
524
+ Math.round(((hi - audio.startMs) * sr) / 1000)
525
+ ]);
526
+ let c;
527
+ if (spans.length === 1) {
528
+ c = windowChroma(audio.samples, sr, spans[0][0], spans[0][1]);
529
+ }
530
+ else {
531
+ // A remapped window plays several stretches. Join them in playing order.
532
+ const parts = spans.map(([from, to]) => audio.samples.subarray(Math.max(0, from), Math.min(audio.samples.length, Math.max(from, to))));
533
+ const joined = new Float32Array(parts.reduce((n, p) => n + p.length, 0));
534
+ let at = 0;
535
+ for (const part of parts) {
536
+ joined.set(part, at);
537
+ at += part.length;
538
+ }
539
+ c = windowChroma(joined, sr, 0, joined.length);
540
+ }
541
+ if (c)
542
+ heard.push(c);
543
+ });
544
+ chroma.push({ startTick: w.startTick, endTick: w.endTick, chroma: mixWindowChroma(heard) });
545
+ if (Date.now() - sliceStart > SLICE_BUDGET_MS) {
546
+ await yieldThread();
547
+ sliceStart = Date.now();
548
+ }
549
+ }
550
+ return chordsFromChromaWindows(chroma, (i) => `detected_${i}`);
551
+ }
552
+ function suggestPresets(text) {
553
+ const t = text.toLowerCase();
554
+ return COMP_LIBRARY.filter((e) => e.name.toLowerCase().includes(t) || e.family.toLowerCase().includes(t))
555
+ .slice(0, MAX_LISTED)
556
+ .map((e) => e.name);
557
+ }
558
+ export function runSetClipHarmony(scope, op) {
559
+ const clip = scope.resolveMidiClip(op.clipId);
560
+ scope.assertWritable([clip]);
561
+ const next = { ...(clip.harmony ?? { style: "off", input: "chords" }) };
562
+ if (op.preset !== undefined) {
563
+ const lower = op.preset.trim().toLowerCase();
564
+ const entry = COMP_LIBRARY.find((e) => e.name.toLowerCase() === lower);
565
+ if (!entry) {
566
+ const close = suggestPresets(op.preset);
567
+ const families = [...new Set(COMP_LIBRARY.map((e) => e.family))];
568
+ throw new Error(`No comp preset named "${op.preset}". Call list_harmony_presets for all ${COMP_LIBRARY.length} names. ` +
569
+ (close.length
570
+ ? `Close names: ${close.join(", ")}.`
571
+ : `Families: ${families.join(", ")}. Examples: ${COMP_LIBRARY.slice(0, 5).map((e) => e.name).join(", ")}.`));
572
+ }
573
+ next.comp = [...entry.comp];
574
+ next.ties = [...entry.ties];
575
+ next.accents = [...entry.accents];
576
+ next.rate = entry.rate;
577
+ next.gate = entry.gate;
578
+ next.strumMs = entry.strum;
579
+ next.strumDirection = entry.strumDir;
580
+ next.voicing = entry.voicing;
581
+ if (op.style === undefined) {
582
+ next.style = "comp";
583
+ next.input = "chords";
584
+ }
585
+ }
586
+ if (op.style !== undefined) {
587
+ next.style = op.style;
588
+ if (op.style !== "off")
589
+ next.input = "chords";
590
+ }
591
+ if (op.order !== undefined)
592
+ next.order = op.order;
593
+ if (op.scale !== undefined)
594
+ next.scale = op.scale;
595
+ if (op.octave !== undefined)
596
+ next.octave = op.octave;
597
+ if (op.chordTrackId !== undefined) {
598
+ const track = readChordTrack(scope, op.chordTrackId);
599
+ if (track)
600
+ next.chordTrackId = track.id;
601
+ }
602
+ clip.harmony = next;
603
+ scope.touch(clip.id);
604
+ const hasChords = scope.tracks.some((t) => t.type === "chord" && (t.chords?.length ?? 0) > 0);
605
+ const result = {
606
+ ok: true,
607
+ clip: scope.clipOut(clip),
608
+ harmony: harmonySummary(next) ?? "off"
609
+ };
610
+ if (!hasChords && followsChords(clip)) {
611
+ result.note =
612
+ "The document has no chords yet, so the clip plays nothing until you write some with set_chords or apply_progression.";
613
+ }
614
+ return result;
615
+ }
616
+ export function runListHarmonyPresets() {
617
+ const families = new Map();
618
+ for (const e of COMP_LIBRARY) {
619
+ const list = families.get(e.family) ?? [];
620
+ list.push(e.name);
621
+ families.set(e.family, list);
622
+ }
623
+ return {
624
+ ok: true,
625
+ compPresets: [...families].map(([family, names]) => ({ family, names })),
626
+ arpOrders: [...ARP_ORDERS],
627
+ styles: ["off", "arp", "comp"],
628
+ scales: ["off", "key", "chords"],
629
+ hint: "Pass a comp name as `preset` and an arp order as `order` to set_clip_harmony."
630
+ };
631
+ }
632
+ export function runFitNotesToChords(scope, op) {
633
+ const tempo = tempoOf(scope);
634
+ const track = readChordTrack(scope, op.chordTrackId);
635
+ const chords = sortChords(track?.chords ?? []);
636
+ const mode = op.mode ?? "scale";
637
+ const clips = op.clipIds.map((ref) => scope.resolveMidiClip(ref));
638
+ if (chords.length === 0) {
639
+ return {
640
+ ok: true,
641
+ mode,
642
+ movedNoteCount: 0,
643
+ clips: [],
644
+ note: "There are no chords to fit to, so no note moved. Write chords with set_chords or apply_progression, then call this again."
645
+ };
646
+ }
647
+ const key = tempo.key ? (tonicPitchClass(tempo.key.tonic) ?? chords[0].root) : chords[0].root;
648
+ // The document key names its mode. Only a document with no key infers one from the chords.
649
+ const keyMask = scaleMask(key, tempo.key ? tempo.key.mode : keyScale(chords, key));
650
+ const tables = new Map();
651
+ const tableFor = (c) => {
652
+ const id = `${c.root}|${c.quality}`;
653
+ let t = tables.get(id);
654
+ if (!t) {
655
+ t = mode === "scale" ? scaleRemap(scaleMask(c.root, chordScale(c, keyMask))) : scaleRemap(chordMask(c));
656
+ tables.set(id, t);
657
+ }
658
+ return t;
659
+ };
660
+ scope.assertWritable(clips);
661
+ let total = 0;
662
+ const perClip = [];
663
+ for (const clip of clips) {
664
+ const shift = clipShift(clip, tempo);
665
+ let moved = 0;
666
+ // Notes outside the clip's window never sound, so they stay as they are.
667
+ const visible = new Set(visibleNotes(clip, tempo.bpm).map((n) => n.id));
668
+ // A clip transposes at playback (CE6). The fit reads the pitch that is
669
+ // heard and stores the pitch the transpose lifts to it.
670
+ const transpose = Math.round(clip.transpose ?? 0);
671
+ const fitted = (clip.notes ?? []).map((n) => {
672
+ if (!visible.has(n.id))
673
+ return n;
674
+ const c = chordAtTick(chords, shift + n.startTick + 1e-6);
675
+ if (!c)
676
+ return n;
677
+ const heard = Math.min(127, Math.max(0, n.pitch + transpose));
678
+ const fittedPitch = remapNote(tableFor(c), heard);
679
+ if (fittedPitch === heard)
680
+ return n;
681
+ moved++;
682
+ return { ...n, pitch: Math.min(127, Math.max(0, fittedPitch - transpose)) };
683
+ });
684
+ clip.notes = sortNotes(fitted);
685
+ total += moved;
686
+ perClip.push({ clipId: clip.id, movedNoteCount: moved });
687
+ scope.touch(clip.id);
688
+ }
689
+ return { ok: true, mode, movedNoteCount: total, clips: perClip };
690
+ }
691
+ //# sourceMappingURL=chords.js.map