@hraness/dawg 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (253) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/DAWG.md +343 -116
  3. package/README.md +27 -25
  4. package/core/autotune.ts +1119 -0
  5. package/core/chords.ts +271 -23
  6. package/core/clips.ts +499 -0
  7. package/core/diff.ts +182 -104
  8. package/core/expression.ts +15 -0
  9. package/core/fx.ts +99 -29
  10. package/core/instruments.ts +19 -0
  11. package/core/keys.ts +3 -3
  12. package/core/loop.ts +5 -0
  13. package/core/lyrics.ts +297 -0
  14. package/core/master.ts +3 -3
  15. package/core/resonators.ts +16 -2
  16. package/core/routing.ts +165 -0
  17. package/core/score.ts +832 -13
  18. package/core/sdk/eval-child.ts +7 -2
  19. package/core/sdk/eval.ts +35 -6
  20. package/core/sdk/print.ts +276 -3
  21. package/core/sdk/sync-lyrics.ts +49 -0
  22. package/core/sdk/v1.ts +1849 -42
  23. package/core/sections.ts +292 -26
  24. package/core/sing.ts +815 -0
  25. package/core/style-provenance.ts +80 -0
  26. package/core/styles/africa-mena-southasia.ts +2893 -0
  27. package/core/styles/americas.ts +3810 -0
  28. package/core/styles/art.ts +4993 -0
  29. package/core/styles/base.ts +123 -0
  30. package/core/styles/cycles.ts +106 -0
  31. package/core/styles/electronic.ts +2723 -0
  32. package/core/styles/europe-asia-pacific.ts +2838 -0
  33. package/core/styles/excerpt.ts +29 -0
  34. package/core/styles/gamelan.ts +283 -0
  35. package/core/styles/generate.ts +2199 -0
  36. package/core/styles/index.ts +515 -0
  37. package/core/styles/parts.ts +106 -0
  38. package/core/styles/pop.ts +3189 -0
  39. package/core/styles/rock.ts +2993 -0
  40. package/core/styles/roots.ts +4175 -0
  41. package/core/styles/schema.ts +429 -0
  42. package/core/styles/taxonomy.ts +940 -0
  43. package/core/styles/validate.ts +528 -0
  44. package/core/tempo.ts +32 -2
  45. package/core/tuning.ts +19 -3
  46. package/core/vocoder.ts +524 -0
  47. package/guides/agent.md +29 -0
  48. package/guides/arrange.md +30 -0
  49. package/guides/audition.md +20 -14
  50. package/guides/automation.md +12 -7
  51. package/guides/chords.md +15 -15
  52. package/guides/effects.md +17 -16
  53. package/guides/faders.md +20 -16
  54. package/guides/files.md +13 -9
  55. package/guides/getting-started.md +15 -11
  56. package/guides/keys.md +19 -15
  57. package/guides/media.md +17 -12
  58. package/guides/mix.md +12 -6
  59. package/guides/music.md +23 -8
  60. package/guides/notes.md +15 -9
  61. package/guides/performance.md +15 -13
  62. package/guides/play.md +21 -13
  63. package/guides/project.md +25 -8
  64. package/guides/providers.md +20 -14
  65. package/guides/resample.md +15 -9
  66. package/guides/rhythm.md +17 -13
  67. package/guides/sessions.md +17 -7
  68. package/guides/show-me.md +31 -0
  69. package/guides/sound.md +25 -9
  70. package/guides/sounds.md +15 -13
  71. package/guides/styles.md +31 -0
  72. package/guides/tempo.md +15 -10
  73. package/guides/tracks.md +15 -10
  74. package/guides/tuning.md +32 -0
  75. package/guides/voice.md +31 -0
  76. package/guides/web-search.md +18 -8
  77. package/native/prebuilt/darwin-arm64/libdawg_sink.dylib +0 -0
  78. package/native/prebuilt/darwin-x64/libdawg_sink.dylib +0 -0
  79. package/native/prebuilt/linux-arm64/libdawg_sink.so +0 -0
  80. package/native/prebuilt/linux-x64/libdawg_sink.so +0 -0
  81. package/native/prebuilt/manifest.json +21 -0
  82. package/package.json +5 -2
  83. package/src/agent/agent.ts +126 -14
  84. package/src/agent/calibration-tools.ts +53 -0
  85. package/src/agent/clip-tools.ts +453 -0
  86. package/src/agent/command-agent.ts +369 -0
  87. package/src/agent/drum-tools.ts +2 -2
  88. package/src/agent/expression-tools.ts +1 -1
  89. package/src/agent/gateway.ts +246 -60
  90. package/src/agent/models.ts +53 -12
  91. package/src/agent/ops.ts +12 -1
  92. package/src/agent/pack-tools.ts +1 -1
  93. package/src/agent/planner.ts +13 -0
  94. package/src/agent/portable-schema.ts +80 -0
  95. package/src/agent/preview-tool.ts +4 -1
  96. package/src/agent/provider.ts +22 -8
  97. package/src/agent/rhythm-tools.ts +1 -1
  98. package/src/agent/section-tools.ts +1 -1
  99. package/src/agent/show-me.ts +497 -0
  100. package/src/agent/steer.ts +15 -0
  101. package/src/agent/style-tools.ts +217 -0
  102. package/src/agent/tool-error.ts +12 -0
  103. package/src/agent/tools.ts +108 -23
  104. package/src/agent/usage.ts +2 -2
  105. package/src/agent/voice-tools.ts +925 -0
  106. package/src/agent/xcb-agent.ts +11 -7
  107. package/src/argv.ts +38 -0
  108. package/src/audio/analysis.ts +253 -0
  109. package/src/audio/arrange.ts +37 -3
  110. package/src/audio/autotune-engine.ts +101 -0
  111. package/src/audio/autotune.ts +640 -0
  112. package/src/audio/clips.ts +240 -0
  113. package/src/audio/doctor.ts +86 -0
  114. package/src/audio/dsp/bandbank.ts +138 -0
  115. package/src/audio/dsp/envelope.ts +10 -0
  116. package/src/audio/dsp/follow.ts +120 -0
  117. package/src/audio/dsp/formant.ts +427 -0
  118. package/src/audio/dsp/glottal.ts +243 -0
  119. package/src/audio/dsp/interp.ts +7 -2
  120. package/src/audio/dsp/lpc.ts +50 -0
  121. package/src/audio/dsp/periodicity.ts +59 -0
  122. package/src/audio/dsp/pitch.ts +995 -0
  123. package/src/audio/dsp/psola.ts +199 -0
  124. package/src/audio/effects/chain.ts +3 -1
  125. package/src/audio/effects/common.ts +43 -0
  126. package/src/audio/effects/convolution.ts +7 -4
  127. package/src/audio/effects/filter.ts +48 -69
  128. package/src/audio/effects/formant.ts +263 -0
  129. package/src/audio/engine.ts +160 -28
  130. package/src/audio/fit.ts +35 -3
  131. package/src/audio/instrument-check.ts +59 -43
  132. package/src/audio/instruments.ts +4 -0
  133. package/src/audio/keys/calibration.ts +56 -0
  134. package/src/audio/keys/electric.ts +8 -1
  135. package/src/audio/keys/engine.ts +13 -1
  136. package/src/audio/keys/piano.ts +22 -2
  137. package/src/audio/kits.ts +135 -6
  138. package/src/audio/live.ts +114 -20
  139. package/src/audio/native.ts +615 -0
  140. package/src/audio/preview.ts +30 -2
  141. package/src/audio/render-worker.ts +2 -0
  142. package/src/audio/renderer.ts +2 -0
  143. package/src/audio/resample.ts +2 -1
  144. package/src/audio/sampler.ts +85 -4
  145. package/src/audio/samples.ts +20 -2
  146. package/src/audio/sing/analysis.ts +193 -0
  147. package/src/audio/sing/engine.ts +949 -0
  148. package/src/audio/strings/bow.ts +48 -5
  149. package/src/audio/strings/engine.ts +8 -2
  150. package/src/audio/synth/oscillators.ts +31 -21
  151. package/src/audio/synth/voice.ts +34 -1
  152. package/src/audio/vocoder/bank.ts +314 -0
  153. package/src/audio/vocoder/carrier.ts +165 -0
  154. package/src/audio/vocoder/control.ts +68 -0
  155. package/src/audio/vocoder/detect.ts +50 -0
  156. package/src/audio/vocoder/index.ts +304 -0
  157. package/src/audio/vocoder/talkbox.ts +143 -0
  158. package/src/audio/wav.ts +500 -77
  159. package/src/audio/winds/engine.ts +5 -1
  160. package/src/audio/winds/trim.ts +28 -4
  161. package/src/audio/winds/trims1.ts +297 -0
  162. package/src/audio/winds/voice.ts +15 -2
  163. package/src/auth/cli.ts +38 -36
  164. package/src/auth/credentials.ts +30 -1
  165. package/src/auth/login.ts +15 -9
  166. package/src/auth/tui.ts +19 -10
  167. package/src/commands/arrange.ts +44 -29
  168. package/src/commands/autotune.ts +421 -0
  169. package/src/commands/calibration.ts +74 -0
  170. package/src/commands/clips.ts +887 -0
  171. package/src/commands/drums.ts +3 -2
  172. package/src/commands/edit.ts +11 -4
  173. package/src/commands/expression.ts +1 -1
  174. package/src/commands/formant.ts +221 -0
  175. package/src/commands/fx.ts +101 -32
  176. package/src/commands/grammar.ts +558 -0
  177. package/src/commands/help.ts +610 -380
  178. package/src/commands/history.ts +18 -0
  179. package/src/commands/keys.ts +8 -8
  180. package/src/commands/modal.ts +1 -1
  181. package/src/commands/music.ts +1 -1
  182. package/src/commands/nearest.ts +53 -0
  183. package/src/commands/pack.ts +9 -2
  184. package/src/commands/param-range.ts +56 -0
  185. package/src/commands/parses.ts +130 -0
  186. package/src/commands/progression.ts +170 -0
  187. package/src/commands/rhythm.ts +3 -0
  188. package/src/commands/rig.ts +3 -24
  189. package/src/commands/sing.ts +478 -0
  190. package/src/commands/strum.ts +13 -1
  191. package/src/commands/style.ts +415 -0
  192. package/src/commands/time.ts +6 -3
  193. package/src/commands/tuning.ts +3 -3
  194. package/src/commands/vocal-pitch.ts +616 -0
  195. package/src/commands/vocal.ts +147 -0
  196. package/src/commands/vocoder.ts +627 -0
  197. package/src/commands/wind.ts +2 -2
  198. package/src/fs/durable.ts +50 -0
  199. package/src/lang/glossary.ts +493 -0
  200. package/src/launch-args.ts +163 -0
  201. package/src/main.ts +1397 -253
  202. package/src/media/cli.ts +20 -3
  203. package/src/media/import.ts +3 -1
  204. package/src/project/check.ts +21 -2
  205. package/src/project/clip-pins.ts +72 -0
  206. package/src/project/init.ts +23 -8
  207. package/src/project/sync.ts +418 -86
  208. package/src/render.ts +20 -1
  209. package/src/session/daemon.ts +3 -0
  210. package/src/session/meta.ts +14 -0
  211. package/src/session/origin.ts +154 -0
  212. package/src/session/port.ts +22 -4
  213. package/src/session/presence.ts +34 -4
  214. package/src/session/protocol.ts +5 -1
  215. package/src/session/rebase.ts +18 -5
  216. package/src/session/receipt.ts +258 -0
  217. package/src/session/store.ts +65 -43
  218. package/src/tui/arrange-menu.ts +65 -31
  219. package/src/tui/audition.ts +1 -1
  220. package/src/tui/euclid.ts +18 -13
  221. package/src/tui/fader.ts +228 -41
  222. package/src/tui/granular-menu.ts +2 -4
  223. package/src/tui/menu-clips.ts +297 -0
  224. package/src/tui/menu-time.ts +20 -13
  225. package/src/tui/menu-voice.ts +405 -0
  226. package/src/tui/menu.ts +759 -177
  227. package/src/tui/modal-menu.ts +6 -6
  228. package/src/tui/performance-menu.ts +5 -2
  229. package/src/tui/play-chords.ts +4 -2
  230. package/src/tui/play-mode.ts +15 -1
  231. package/src/tui/play-session.ts +47 -7
  232. package/src/tui/sing-menu.ts +278 -0
  233. package/src/tui/style-menu.ts +104 -0
  234. package/src/tui/vocoder-menu.ts +244 -0
  235. package/src/tui/wind-menu.ts +3 -3
  236. package/src/version.ts +8 -0
  237. package/src/web/fetch.ts +115 -29
  238. package/tui/activity.ts +180 -9
  239. package/tui/app.ts +274 -40
  240. package/tui/clip-row.ts +132 -0
  241. package/tui/delight.ts +144 -0
  242. package/tui/drawer.ts +70 -22
  243. package/tui/frame-gate.ts +76 -0
  244. package/tui/grammar.ts +112 -63
  245. package/tui/guide.ts +42 -4
  246. package/tui/highway.ts +269 -25
  247. package/tui/hints.ts +192 -0
  248. package/tui/input.ts +60 -9
  249. package/tui/keys.ts +1 -1
  250. package/tui/play-strip.ts +68 -14
  251. package/tui/prompt.ts +1 -1
  252. package/tui/screen.ts +144 -14
  253. package/tui/theme.ts +27 -0
package/core/sdk/v1.ts CHANGED
@@ -27,7 +27,7 @@
27
27
  */
28
28
 
29
29
  /** SDK release; dawg refreshes the vendored copy when its own is newer. */
30
- export const SDK_VERSION = "1.31.0";
30
+ export const SDK_VERSION = "1.33.0";
31
31
  /** Major of `SDK_VERSION`; `dawg.json` records it as `sdk`. */
32
32
  export const SDK_MAJOR = 1;
33
33
 
@@ -242,6 +242,15 @@ export type Expression = Readonly<{
242
242
  * Humanize just bars 5-8 with `expr({ humanize: { timing: 10 } }, ...)`.
243
243
  */
244
244
  humanize?: Readonly<{ timing?: number; velocity?: number; length?: number }>;
245
+ /** The sung vowel on a `sing()` track (SDK 1.32.0): `"a"` .. `"u"` or a morph `"a>o"`. */
246
+ vowel?: string;
247
+ /** The syllable sung on this note (SDK 1.32.0): no spaces, `_` holds the previous one. */
248
+ lyric?: string;
249
+ /**
250
+ * On an autotune guide note (SDK 1.33.0): the share of slow pitch drift
251
+ * removed, 0..1, overriding the track's `autotune` drift.
252
+ */
253
+ drift?: number;
245
254
  }>;
246
255
 
247
256
  /** The expression a built note carries; fields are present only when set. */
@@ -251,6 +260,9 @@ export type NoteExpressionSpec = Readonly<{
251
260
  bend?: readonly BendPoint[];
252
261
  vibrato?: Readonly<{ rate: number; depth: number; delay?: number }>;
253
262
  humanize?: Readonly<{ timing?: number; velocity?: number; length?: number }>;
263
+ vowel?: string;
264
+ lyric?: string;
265
+ drift?: number;
254
266
  }>;
255
267
 
256
268
  const DEFAULT_VIBRATO_RATE = 5.5;
@@ -265,12 +277,20 @@ function expression(
265
277
  throw new DawgSdkError(`${label} expression must be an object`);
266
278
  for (const key of Object.keys(input))
267
279
  if (
268
- !["articulation", "art", "glide", "bend", "vibrato", "humanize"].includes(
269
- key,
270
- )
280
+ ![
281
+ "articulation",
282
+ "art",
283
+ "glide",
284
+ "bend",
285
+ "vibrato",
286
+ "humanize",
287
+ "vowel",
288
+ "lyric",
289
+ "drift",
290
+ ].includes(key)
271
291
  )
272
292
  throw new DawgSdkError(
273
- `${label} expression has an unknown field "${key.slice(0, 32)}" (articulation glide bend vibrato humanize)`,
293
+ `${label} expression has an unknown field "${key.slice(0, 32)}" (articulation glide bend vibrato humanize vowel lyric drift)`,
274
294
  );
275
295
  const out: {
276
296
  articulation?: Articulation;
@@ -282,6 +302,9 @@ function expression(
282
302
  velocity?: number;
283
303
  length?: number;
284
304
  }>;
305
+ vowel?: string;
306
+ lyric?: string;
307
+ drift?: number;
285
308
  } = {};
286
309
  const articulation = input.articulation ?? input.art;
287
310
  if (articulation !== undefined) {
@@ -352,9 +375,32 @@ function expression(
352
375
  }
353
376
  out.humanize = Object.freeze(amounts);
354
377
  }
378
+ if (input.vowel !== undefined)
379
+ out.vowel = singVowel(input.vowel, `${label} vowel`);
380
+ if (input.lyric !== undefined) out.lyric = lyricInput(input.lyric, label);
381
+ if (input.drift !== undefined) {
382
+ const drift = finite(input.drift, `${label} drift`);
383
+ if (drift < 0 || drift > 1)
384
+ throw new DawgSdkError(`${label} drift must be 0..1`);
385
+ out.drift = drift;
386
+ }
355
387
  return out;
356
388
  }
357
389
 
390
+ /** A note's lyric: one syllable, no whitespace, at most 32 characters. */
391
+ function lyricInput(value: unknown, label: string): string {
392
+ if (
393
+ typeof value !== "string" ||
394
+ value.length === 0 ||
395
+ value.length > LYRIC_LIMIT ||
396
+ /\s/u.test(value)
397
+ )
398
+ throw new DawgSdkError(
399
+ `${label} lyric must be one syllable of 1..${LYRIC_LIMIT} characters without spaces`,
400
+ );
401
+ return value;
402
+ }
403
+
358
404
  /**
359
405
  * The same expression on many notes or hits (SDK 1.15.0); a note's own
360
406
  * fields win.
@@ -1166,16 +1212,36 @@ export const DRUM_PATTERNS: readonly DrumPattern[] = Object.freeze([
1166
1212
  euclid("hat", 16, 16, 0, { velocity: 0.35, accent: 0.4, accents: 4 }),
1167
1213
  ],
1168
1214
  ),
1215
+ // The blues and rock shuffle is a triplet-8th feel: each beat is three
1216
+ // 8th-note triplets with the first and third struck (long-short).
1169
1217
  drumPattern(
1170
1218
  "shuffle",
1171
- "Shuffle",
1219
+ "Shuffle (triplet 8ths)",
1172
1220
  ["blues", "shuffle", "rock"],
1173
1221
  [90, 130, 110],
1174
1222
  "acoustic",
1223
+ 0,
1224
+ [
1225
+ grid("kick", "x.....x.....", { division: "1/8t" }),
1226
+ grid("snare", "...x.....x..", { division: "1/8t" }),
1227
+ grid("hat", "X.xx.xX.xx.x", {
1228
+ division: "1/8t",
1229
+ velocity: 0.35,
1230
+ accent: 0.5,
1231
+ }),
1232
+ ],
1233
+ ),
1234
+ // The half-time shuffle swings 16ths against a backbeat on 3.
1235
+ drumPattern(
1236
+ "half-time-shuffle",
1237
+ "Half-time shuffle (swung 16ths)",
1238
+ ["shuffle", "rock", "funk"],
1239
+ [70, 100, 86],
1240
+ "acoustic",
1175
1241
  0.33,
1176
1242
  [
1177
- grid("kick", "x.......x......."),
1178
- grid("snare", "....x.......x..."),
1243
+ grid("kick", "x.........x....."),
1244
+ grid("snare", "........x......."),
1179
1245
  euclid("hat", 16, 16, 0, { velocity: 0.35, accent: 0.5, accents: 8 }),
1180
1246
  ],
1181
1247
  ),
@@ -1218,7 +1284,7 @@ export function pattern(name: string): readonly RhythmSpec[] {
1218
1284
  const found = findPattern(name);
1219
1285
  if (!found)
1220
1286
  throw new DawgSdkError(
1221
- `unknown drum pattern "${String(name).slice(0, 40)}" (${DRUM_PATTERNS.map((entry) => entry.name).join(" ")})`,
1287
+ `unknown groove "${String(name).slice(0, 40)}" (${DRUM_PATTERNS.map((entry) => entry.name).join(" ")})`,
1222
1288
  );
1223
1289
  return found.rows;
1224
1290
  }
@@ -1989,6 +2055,226 @@ export function wind(
1989
2055
  return Object.freeze(out) as WindSpec;
1990
2056
  }
1991
2057
 
2058
+ // ---- vocoder (f07-vocoder, SDK 1.32.0) ----
2059
+
2060
+ /** The instrument value of the built-in vocoder carrier (core/vocoder.ts). */
2061
+ export const VOCODER_INSTRUMENT = "vocoder";
2062
+
2063
+ /** Vocoder presets (core/vocoder.ts VOCODER_PRESET_NAMES). */
2064
+ export type VocoderPresetName =
2065
+ | "classic"
2066
+ | "robot"
2067
+ | "talkbox"
2068
+ | "choir"
2069
+ | "glass"
2070
+ | "whisper"
2071
+ | "smear"
2072
+ | "lofi";
2073
+
2074
+ const VOCODER_PRESET_WORDS: readonly string[] = Object.freeze([
2075
+ "classic",
2076
+ "robot",
2077
+ "talkbox",
2078
+ "choir",
2079
+ "glass",
2080
+ "whisper",
2081
+ "smear",
2082
+ "lofi",
2083
+ ]);
2084
+
2085
+ /** Vocoder overrides (core/vocoder.ts VOCODER_PARAMS). */
2086
+ export type VocoderParams = Readonly<{
2087
+ /** The modulator track: an id or a name slug (`"vox"`, `"lead-vox"`). */
2088
+ src?: string;
2089
+ tap?: "chain" | "dry";
2090
+ mode?: "channel" | "talkbox";
2091
+ carrier?: "saw" | "supersaw" | "pulse" | "noise";
2092
+ follow?: "notes" | "chords" | "drone";
2093
+ root?: number;
2094
+ spread?: number;
2095
+ bands?: number;
2096
+ lo?: number;
2097
+ hi?: number;
2098
+ width?: number;
2099
+ attack?: number;
2100
+ release?: number;
2101
+ formant?: number;
2102
+ unvoiced?: number;
2103
+ sens?: number;
2104
+ hiss?: number;
2105
+ gate?: number | "auto";
2106
+ enhance?: boolean;
2107
+ depth?: number;
2108
+ freeze?: boolean;
2109
+ mix?: number;
2110
+ gain?: number;
2111
+ seed?: number;
2112
+ }>;
2113
+
2114
+ const VOCODER_ENUMS: Readonly<Record<string, readonly string[]>> =
2115
+ Object.freeze({
2116
+ tap: Object.freeze(["chain", "dry"]),
2117
+ mode: Object.freeze(["channel", "talkbox"]),
2118
+ carrier: Object.freeze(["saw", "supersaw", "pulse", "noise"]),
2119
+ follow: Object.freeze(["notes", "chords", "drone"]),
2120
+ });
2121
+
2122
+ const VOCODER_RANGES: Readonly<Record<string, readonly [number, number]>> =
2123
+ Object.freeze({
2124
+ root: [24, 96],
2125
+ spread: [0, 1],
2126
+ bands: [4, 40],
2127
+ lo: [50, 1000],
2128
+ hi: [2000, 12000],
2129
+ width: [0.25, 4],
2130
+ attack: [0.0005, 0.2],
2131
+ release: [0.005, 2],
2132
+ formant: [-24, 24],
2133
+ unvoiced: [0, 1],
2134
+ sens: [0, 1],
2135
+ hiss: [0, 1],
2136
+ gate: [-90, 0],
2137
+ depth: [0, 1],
2138
+ mix: [0, 1],
2139
+ gain: [-24, 24],
2140
+ seed: [0, 2 ** 31],
2141
+ });
2142
+
2143
+ const VOCODER_INTEGERS: readonly string[] = Object.freeze([
2144
+ "root",
2145
+ "bands",
2146
+ "seed",
2147
+ ]);
2148
+
2149
+ /** Result of `vocoder()`: a track's `instrument` or its `vocoder` field. */
2150
+ export type VocoderSpec = Readonly<
2151
+ { kind: "vocoder"; preset?: VocoderPresetName } & VocoderParams
2152
+ >;
2153
+
2154
+ /**
2155
+ * A vocoder (SDK 1.32.0): another track's voice (`src`) shapes this track's
2156
+ * sound. As the `instrument` it plays the built-in carrier (a supersaw
2157
+ * following the notes); as the `vocoder` field it vocodes the track's own
2158
+ * synth or sampler. `src` takes a track id or a name slug.
2159
+ *
2160
+ * ```ts
2161
+ * instrument: vocoder("talkbox", { src: "vox", formant: 2 })
2162
+ * vocoder: vocoder({ src: "t-vox", bands: 24 })
2163
+ * ```
2164
+ */
2165
+ export function vocoder(
2166
+ preset?: VocoderPresetName | VocoderParams,
2167
+ params: VocoderParams = {},
2168
+ ): VocoderSpec {
2169
+ const overrides = isRecord(preset) ? preset : params;
2170
+ const name = isRecord(preset) ? undefined : preset;
2171
+ if (!isRecord(overrides))
2172
+ throw new DawgSdkError("vocoder params must be an object");
2173
+ const out: Record<string, unknown> = { kind: "vocoder" };
2174
+ if (name !== undefined) {
2175
+ if (typeof name !== "string" || !VOCODER_PRESET_WORDS.includes(name))
2176
+ throw new DawgSdkError(
2177
+ `vocoder preset "${String(name).slice(0, 32)}" is not one of ${VOCODER_PRESET_WORDS.join(" ")}`,
2178
+ );
2179
+ out.preset = name;
2180
+ }
2181
+ for (const key of Object.keys(overrides)) {
2182
+ const value = (overrides as Record<string, unknown>)[key];
2183
+ if (value === undefined) continue;
2184
+ const words = VOCODER_ENUMS[key];
2185
+ if (key === "src") {
2186
+ if (typeof value !== "string" || value.length === 0 || value.length > 64)
2187
+ throw new DawgSdkError("vocoder src must be a track id or name slug");
2188
+ out.src = value;
2189
+ } else if (words) {
2190
+ if (typeof value !== "string" || !words.includes(value))
2191
+ throw new DawgSdkError(
2192
+ `vocoder ${key} "${String(value).slice(0, 32)}" is not one of ${words.join(" ")}`,
2193
+ );
2194
+ out[key] = value;
2195
+ } else if (key === "enhance" || key === "freeze") {
2196
+ if (typeof value !== "boolean")
2197
+ throw new DawgSdkError(`vocoder ${key} must be true or false`);
2198
+ out[key] = value;
2199
+ } else if (key === "gate" && value === "auto") {
2200
+ out.gate = "auto";
2201
+ } else if (VOCODER_RANGES[key]) {
2202
+ const number = finite(value, `vocoder ${key}`);
2203
+ const [min, max] = VOCODER_RANGES[key]!;
2204
+ if (number < min || number > max)
2205
+ throw new DawgSdkError(`vocoder ${key} must be ${min}..${max}`);
2206
+ if (VOCODER_INTEGERS.includes(key) && !Number.isInteger(number))
2207
+ throw new DawgSdkError(`vocoder ${key} must be a whole number`);
2208
+ out[key] = number;
2209
+ } else
2210
+ throw new DawgSdkError(
2211
+ `vocoder has no parameter "${key.slice(0, 32)}" (src ${[...Object.keys(VOCODER_ENUMS), "enhance", "freeze", ...Object.keys(VOCODER_RANGES)].join(" ")})`,
2212
+ );
2213
+ }
2214
+ return Object.freeze(out) as VocoderSpec;
2215
+ }
2216
+
2217
+ /**
2218
+ * The vocoder field a track gets: its `vocoder` property, else a
2219
+ * `vocoder(...)` instrument, else `{}` for the bare word `"vocoder"` (the
2220
+ * built-in carrier with every default). `null` removes it.
2221
+ */
2222
+ function trackVocoder(
2223
+ rawInstrument: unknown,
2224
+ field: unknown,
2225
+ ): Readonly<{ preset?: VocoderPresetName } & VocoderParams> | undefined {
2226
+ const strip = (spec: unknown) => {
2227
+ if (!isRecord(spec) || spec.kind !== "vocoder")
2228
+ throw new DawgSdkError("track vocoder must come from vocoder()");
2229
+ const { kind: _kind, ...fields } = spec as VocoderSpec;
2230
+ return Object.freeze(fields);
2231
+ };
2232
+ if (field !== undefined && field !== null) return strip(field);
2233
+ if (isRecord(rawInstrument) && rawInstrument.kind === "vocoder")
2234
+ return strip(rawInstrument);
2235
+ if (rawInstrument === VOCODER_INSTRUMENT) return Object.freeze({});
2236
+ return undefined;
2237
+ }
2238
+
2239
+ /** Lowercase dash slug of a track name (core/slug.ts trackSlug). */
2240
+ function vocoderSlug(text: string): string {
2241
+ const slug = text
2242
+ .normalize("NFKD")
2243
+ .replace(/\p{M}+/gu, "")
2244
+ .toLowerCase()
2245
+ .replace(/[^a-z0-9]+/g, "-")
2246
+ .replace(/^-+|-+$/g, "")
2247
+ .slice(0, 64)
2248
+ .replace(/-+$/g, "");
2249
+ return slug.length > 0 ? slug : "track";
2250
+ }
2251
+
2252
+ /**
2253
+ * `src` as a track id: an id wins, then a unique name slug. Errors when
2254
+ * nothing matches, two tracks share the slug, or the track names itself.
2255
+ */
2256
+ function resolveVocoderSrc(
2257
+ tracks: readonly Readonly<{ id: string; name: string }>[],
2258
+ self: string,
2259
+ src: string,
2260
+ ): string {
2261
+ const byId = tracks.find((track) => track.id === src);
2262
+ const matches = byId
2263
+ ? [byId]
2264
+ : tracks.filter((track) => vocoderSlug(track.name) === vocoderSlug(src));
2265
+ if (matches.length === 0)
2266
+ throw new DawgSdkError(
2267
+ `track ${self}: vocoder src "${src.slice(0, 64)}" names no track; delete src (the carrier plays alone) or point it at a track in this song`,
2268
+ );
2269
+ if (matches.length > 1)
2270
+ throw new DawgSdkError(
2271
+ `track ${self}: vocoder src "${src.slice(0, 64)}" matches ${matches.length} tracks; use an id`,
2272
+ );
2273
+ if (matches[0]!.id === self)
2274
+ throw new DawgSdkError(`track ${self}: a track cannot vocode itself`);
2275
+ return matches[0]!.id;
2276
+ }
2277
+
1992
2278
  /**
1993
2279
  * The wind field an instrument makes: `wind(...)`, or a wind preset word
1994
2280
  * (`"flute"`, `"saxophone"`). The bare word `"wind"` keeps its pre-0.6.1
@@ -2008,6 +2294,354 @@ function trackWind(
2008
2294
  return Object.freeze({ preset: meaning.preset as WindPresetName });
2009
2295
  }
2010
2296
 
2297
+ // ---- sing (f07-sing, SDK 1.32.0) ----
2298
+
2299
+ /** The instrument value of the singing voice (core/sing.ts). */
2300
+ export const SING_INSTRUMENT = "sing";
2301
+
2302
+ /** Sing presets (core/sing.ts SING_PRESET_NAMES). */
2303
+ export type SingPresetName =
2304
+ | "aah"
2305
+ | "ooh"
2306
+ | "choir"
2307
+ | "oohchoir"
2308
+ | "chorale"
2309
+ | "airy"
2310
+ | "glass"
2311
+ | "lament"
2312
+ | "soprano"
2313
+ | "basso"
2314
+ | "drone"
2315
+ | "khoomei"
2316
+ | "sygyt"
2317
+ | "kargyraa";
2318
+
2319
+ const SING_PRESET_WORDS: readonly string[] = Object.freeze([
2320
+ "aah",
2321
+ "ooh",
2322
+ "choir",
2323
+ "oohchoir",
2324
+ "chorale",
2325
+ "airy",
2326
+ "glass",
2327
+ "lament",
2328
+ "soprano",
2329
+ "basso",
2330
+ "drone",
2331
+ "khoomei",
2332
+ "sygyt",
2333
+ "kargyraa",
2334
+ ]);
2335
+
2336
+ /** Sing overrides (core/sing.ts SING_PARAMS). */
2337
+ export type SingParams = Readonly<{
2338
+ voice?: "auto" | "soprano" | "alto" | "tenor" | "bass";
2339
+ /** `"a"`, `"e"`, `"i"`, `"o"`, `"u"` or a morph `"a>o"`. */
2340
+ vowel?: string;
2341
+ morph?: number;
2342
+ formant?: number;
2343
+ bright?: number;
2344
+ breath?: number;
2345
+ jitter?: number;
2346
+ shimmer?: number;
2347
+ attack?: number;
2348
+ release?: number;
2349
+ vib?: number;
2350
+ vibmod?: number;
2351
+ vibdelay?: number;
2352
+ voices?: number;
2353
+ spread?: number;
2354
+ ring?: number;
2355
+ /** Throat drone: a note name (`"D3"`) or MIDI 36..67. */
2356
+ drone?: string | number;
2357
+ overtone?: number;
2358
+ /** Throat melody harmonic range `[lo, hi]`, 2..24. */
2359
+ harmonics?: readonly [number, number];
2360
+ sub?: number;
2361
+ gain?: number;
2362
+ }>;
2363
+
2364
+ const SING_VOWEL_LETTERS: readonly string[] = Object.freeze([
2365
+ "a",
2366
+ "e",
2367
+ "i",
2368
+ "o",
2369
+ "u",
2370
+ ]);
2371
+
2372
+ /** Numeric ranges (core/sing.ts SING_PARAMS min..max). */
2373
+ const SING_RANGES: Readonly<Record<string, readonly [number, number]>> =
2374
+ Object.freeze({
2375
+ morph: [0, 1],
2376
+ formant: [-12, 12],
2377
+ bright: [0, 1],
2378
+ breath: [0, 1],
2379
+ jitter: [0, 3],
2380
+ shimmer: [0, 1],
2381
+ attack: [0.005, 2],
2382
+ release: [0.01, 4],
2383
+ vib: [0, 9],
2384
+ vibmod: [0, 1],
2385
+ vibdelay: [0, 2],
2386
+ voices: [1, 8],
2387
+ spread: [0, 40],
2388
+ ring: [0, 1],
2389
+ overtone: [0, 1],
2390
+ sub: [0, 1],
2391
+ gain: [0, 2],
2392
+ });
2393
+
2394
+ /** Result of `sing()`; pass it as a track's `instrument`. */
2395
+ export type SingSpec = Readonly<
2396
+ { kind: "sing"; preset?: SingPresetName } & SingParams
2397
+ >;
2398
+
2399
+ /** `"a"` or `"a>o"`, lower-cased; throws otherwise. */
2400
+ function singVowel(value: unknown, label: string): string {
2401
+ const parts =
2402
+ typeof value === "string" ? value.trim().toLowerCase().split(">") : [];
2403
+ if (
2404
+ (parts.length === 1 || parts.length === 2) &&
2405
+ parts.every((part) => SING_VOWEL_LETTERS.includes(part))
2406
+ )
2407
+ return parts.join(">");
2408
+ throw new DawgSdkError(
2409
+ `${label} must be one of ${SING_VOWEL_LETTERS.join(" ")} or a morph like a>o`,
2410
+ );
2411
+ }
2412
+
2413
+ /**
2414
+ * The built-in singing voice (SDK 1.32.0): an LF glottal source through
2415
+ * SATB formants, choirs, and Tuvan throat singing. A preset word alone
2416
+ * (`instrument: "choir"`) is the same as `sing("choir")`. Notes sing their
2417
+ * `vowel` (`note("A3", 0, 2, 0.8, { vowel: "a>o" })`), else their lyric's
2418
+ * vowel, else the track's.
2419
+ *
2420
+ * ```ts
2421
+ * instrument: sing("choir", { vowel: "o" })
2422
+ * instrument: sing("khoomei", { drone: "D3" }) // notes pick the overtone
2423
+ * instrument: sing({ voices: 4, breath: 0.3 }) // default preset (aah)
2424
+ * ```
2425
+ */
2426
+ export function sing(
2427
+ preset?: SingPresetName | SingParams,
2428
+ params: SingParams = {},
2429
+ ): SingSpec {
2430
+ const overrides = isRecord(preset) ? preset : params;
2431
+ const name = isRecord(preset) ? undefined : preset;
2432
+ if (!isRecord(overrides))
2433
+ throw new DawgSdkError("sing params must be an object");
2434
+ const out: Record<string, unknown> = { kind: "sing" };
2435
+ if (name !== undefined) {
2436
+ if (typeof name !== "string" || !SING_PRESET_WORDS.includes(name))
2437
+ throw new DawgSdkError(
2438
+ `sing preset "${String(name).slice(0, 32)}" is not one of ${SING_PRESET_WORDS.join(" ")}`,
2439
+ );
2440
+ out.preset = name;
2441
+ }
2442
+ for (const key of Object.keys(overrides)) {
2443
+ const value = (overrides as Record<string, unknown>)[key];
2444
+ if (value === undefined) continue;
2445
+ if (key === "voice") {
2446
+ const voices = ["auto", "soprano", "alto", "tenor", "bass"];
2447
+ if (typeof value !== "string" || !voices.includes(value))
2448
+ throw new DawgSdkError(`sing voice must be one of ${voices.join(" ")}`);
2449
+ out.voice = value;
2450
+ } else if (key === "vowel") out.vowel = singVowel(value, "sing vowel");
2451
+ else if (key === "drone") {
2452
+ const midiValue =
2453
+ typeof value === "number" ? value : midi(value as Pitch);
2454
+ if (!Number.isInteger(midiValue) || midiValue < 36 || midiValue > 67)
2455
+ throw new DawgSdkError(
2456
+ 'sing drone must be a note name C2..G4 (e.g. "D3") or MIDI 36..67',
2457
+ );
2458
+ out.drone = midiValue;
2459
+ } else if (key === "harmonics") {
2460
+ if (
2461
+ !Array.isArray(value) ||
2462
+ value.length !== 2 ||
2463
+ !value.every((h) => Number.isInteger(h) && h >= 2 && h <= 24) ||
2464
+ value[0] >= value[1]
2465
+ )
2466
+ throw new DawgSdkError(
2467
+ "sing harmonics must be [lo, hi], whole numbers 2..24 with lo < hi",
2468
+ );
2469
+ out.harmonics = Object.freeze([value[0], value[1]]);
2470
+ } else if (SING_RANGES[key]) {
2471
+ const number = finite(value, `sing ${key}`);
2472
+ const [min, max] = SING_RANGES[key]!;
2473
+ if (number < min || number > max)
2474
+ throw new DawgSdkError(`sing ${key} must be ${min}..${max}`);
2475
+ if (key === "voices" && !Number.isInteger(number))
2476
+ throw new DawgSdkError("sing voices must be a whole number");
2477
+ out[key] = number;
2478
+ } else
2479
+ throw new DawgSdkError(
2480
+ `sing has no parameter "${key.slice(0, 32)}" (voice vowel drone harmonics ${Object.keys(SING_RANGES).join(" ")})`,
2481
+ );
2482
+ }
2483
+ return Object.freeze(out) as SingSpec;
2484
+ }
2485
+
2486
+ /**
2487
+ * The sing field an instrument makes: `sing(...)`, or a sing preset word
2488
+ * (`"choir"`, `"khoomei"`); `"sing"` alone is the default preset.
2489
+ */
2490
+ function trackSing(
2491
+ raw: unknown,
2492
+ ): Readonly<{ preset?: SingPresetName } & SingParams> | undefined {
2493
+ if (isRecord(raw) && raw.kind === "sing") {
2494
+ const { kind: _kind, ...fields } = raw as SingSpec;
2495
+ return Object.freeze(fields);
2496
+ }
2497
+ if (typeof raw !== "string") return undefined;
2498
+ const meaning = resolveInstrumentWord(raw);
2499
+ if (meaning?.instrument !== SING_INSTRUMENT) return undefined;
2500
+ return Object.freeze(
2501
+ meaning.preset ? { preset: meaning.preset as SingPresetName } : {},
2502
+ );
2503
+ }
2504
+
2505
+ // ---- autotune (f07-autotune, SDK 1.33.0) ----
2506
+
2507
+ /** Autotune presets, gentle to hard (core/autotune.ts AUTOTUNE_PRESETS). */
2508
+ export type AutotunePresetName =
2509
+ | "hard"
2510
+ | "robot"
2511
+ | "warble"
2512
+ | "trap"
2513
+ | "pop"
2514
+ | "natural"
2515
+ | "gentle"
2516
+ | "guided"
2517
+ | "locked";
2518
+
2519
+ const AUTOTUNE_PRESET_WORDS: readonly string[] = Object.freeze([
2520
+ "hard",
2521
+ "robot",
2522
+ "warble",
2523
+ "trap",
2524
+ "pop",
2525
+ "natural",
2526
+ "gentle",
2527
+ "guided",
2528
+ "locked",
2529
+ ]);
2530
+
2531
+ /** Autotune fields; dawg checks the ranges (core/autotune.ts AUTOTUNE_PARAMS). */
2532
+ export type AutotuneParams = Readonly<{
2533
+ /** Targets: `scale` (song or track key, else chromatic), `chromatic`, `chord`, `notes`. */
2534
+ to?: "scale" | "chromatic" | "chord" | "notes";
2535
+ /** Guide track id for `to: "notes"` (a vocal track may use its own notes). */
2536
+ from?: string;
2537
+ /** Scale for this track, e.g. `"D bayati"`; default the song key. */
2538
+ key?: string;
2539
+ /** Retune time in ms, 0..400; 0 is instant and stepped. */
2540
+ speed?: number;
2541
+ /** 0..1 slower retune on held notes. */
2542
+ relax?: number;
2543
+ /** ms 50..1000 before a note counts as held. */
2544
+ hold?: number;
2545
+ /** 0..100: higher only pulls notes already near a target. */
2546
+ flex?: number;
2547
+ /** Seconds 0..0.5 to move between targets. */
2548
+ glide?: number;
2549
+ /** 0..1 correction strength. */
2550
+ amount?: number;
2551
+ /** Added vibrato rate in Hz, 0..12 (0 off). */
2552
+ vib?: number;
2553
+ /** Added vibrato depth in semitones, 0..1. */
2554
+ vibmod?: number;
2555
+ /** Notes mode: 0..1 how far each note's middle moves to the written pitch. */
2556
+ center?: number;
2557
+ /** Notes mode: 0..1 share of slow drift removed. */
2558
+ drift?: number;
2559
+ /** Tracker range: `auto`, `bass`, `tenor`, `alto`, `soprano`. */
2560
+ voice?: "auto" | "bass" | "tenor" | "alto" | "soprano";
2561
+ }>;
2562
+
2563
+ /** Stored autotune settings: a preset and any fields that override it. */
2564
+ export type AutotuneSettings = Readonly<
2565
+ { preset?: AutotunePresetName } & AutotuneParams
2566
+ >;
2567
+
2568
+ /** Result of `autotune()`; pass it as a track's `autotune`. */
2569
+ export type AutotuneSpec = Readonly<{ kind: "autotune" } & AutotuneSettings>;
2570
+
2571
+ const AUTOTUNE_PARAM_KEYS: readonly string[] = Object.freeze([
2572
+ "to",
2573
+ "from",
2574
+ "key",
2575
+ "speed",
2576
+ "relax",
2577
+ "hold",
2578
+ "flex",
2579
+ "glide",
2580
+ "amount",
2581
+ "vib",
2582
+ "vibmod",
2583
+ "center",
2584
+ "drift",
2585
+ "voice",
2586
+ ]);
2587
+
2588
+ /**
2589
+ * Pitch correction (SDK 1.33.0), from `gentle` to `hard`; the preset word
2590
+ * alone also works as a track's `autotune`. Fields override the preset.
2591
+ *
2592
+ * autotune: "hard"
2593
+ * autotune: autotune("pop", { speed: 40, key: "D bayati" })
2594
+ * autotune: autotune("guided", { from: "lead" })
2595
+ */
2596
+ export function autotune(
2597
+ preset?: AutotunePresetName | AutotuneParams,
2598
+ params?: AutotuneParams,
2599
+ ): AutotuneSpec {
2600
+ const fields =
2601
+ typeof preset === "object" && preset !== null ? preset : (params ?? {});
2602
+ const name = typeof preset === "string" ? preset : undefined;
2603
+ return Object.freeze({
2604
+ kind: "autotune" as const,
2605
+ ...autotuneInput(
2606
+ { ...(name ? { preset: name } : {}), ...fields },
2607
+ "autotune",
2608
+ ),
2609
+ });
2610
+ }
2611
+
2612
+ function autotuneInput(raw: unknown, where: string): AutotuneSettings {
2613
+ if (typeof raw === "string") raw = { preset: raw };
2614
+ if (!isRecord(raw))
2615
+ throw new DawgSdkError(
2616
+ `${where} autotune must be a preset word or autotune()`,
2617
+ );
2618
+ const out: Record<string, unknown> = {};
2619
+ for (const [key, value] of Object.entries(raw)) {
2620
+ if (key === "kind" || value === undefined) continue;
2621
+ if (key === "preset") {
2622
+ if (typeof value !== "string" || !AUTOTUNE_PRESET_WORDS.includes(value))
2623
+ throw new DawgSdkError(
2624
+ `${where} autotune preset "${String(value).slice(0, 32)}" is not one of ${AUTOTUNE_PRESET_WORDS.join(" ")}`,
2625
+ );
2626
+ out.preset = value;
2627
+ } else if (!AUTOTUNE_PARAM_KEYS.includes(key)) {
2628
+ throw new DawgSdkError(
2629
+ `${where} autotune has no field "${key.slice(0, 32)}" (preset ${AUTOTUNE_PARAM_KEYS.join(" ")})`,
2630
+ );
2631
+ } else if (["to", "from", "key", "voice"].includes(key)) {
2632
+ if (typeof value !== "string")
2633
+ throw new DawgSdkError(`${where} autotune ${key} must be a string`);
2634
+ out[key] = value;
2635
+ } else out[key] = finite(value, `${where} autotune ${key}`);
2636
+ }
2637
+ if (Object.keys(out).length === 0)
2638
+ throw new DawgSdkError(`${where} autotune needs a preset or fields`);
2639
+ const ordered: Record<string, unknown> = {};
2640
+ for (const key of ["preset", ...AUTOTUNE_PARAM_KEYS])
2641
+ if (out[key] !== undefined) ordered[key] = out[key];
2642
+ return Object.freeze(ordered) as AutotuneSettings;
2643
+ }
2644
+
2011
2645
  /**
2012
2646
  * `count` equal slices of one file as voices `prefix0 … prefixN-1`, for
2013
2647
  * chopped breaks: `sampler(slices("samples/break.wav", 8, "brk"))`, then
@@ -2645,12 +3279,25 @@ export type TrackInput = Readonly<{
2645
3279
  | StringSpec
2646
3280
  | GranularSpec
2647
3281
  | ModalSpec
2648
- | WindSpec;
3282
+ | WindSpec
3283
+ | SingSpec
3284
+ | VocoderSpec;
3285
+ /**
3286
+ * A vocoder on this track (SDK 1.32.0): `vocoder({ src: "vox" })` lets
3287
+ * the vox track's voice shape this track's sound; `null` removes it.
3288
+ */
3289
+ vocoder?: VocoderSpec | null;
2649
3290
  /**
2650
3291
  * The sampler a `granular(...)` track keeps while it grains one of its
2651
3292
  * voices (SDK 1.23.0); `grain off` plays it again.
2652
3293
  */
2653
3294
  sampler?: SamplerSpec | null;
3295
+ /**
3296
+ * The `wavetable(...)` a track keeps after it left the wavetable
3297
+ * instrument (SDK 1.32.0), so switching back restores it. A wavetable
3298
+ * track takes its table from `instrument` instead.
3299
+ */
3300
+ wavetable?: WavetableSpec | null;
2654
3301
  /**
2655
3302
  * Granular engine (SDK 1.23.0) for an `instrument: "granular"` track, or
2656
3303
  * use `instrument: granular("cloud", {...})` or a word (`"cloud"`).
@@ -2677,6 +3324,19 @@ export type TrackInput = Readonly<{
2677
3324
  * `{ ref: 432 }` alone keeps the song's table at another pitch.
2678
3325
  */
2679
3326
  tuning?: TuningInput | null;
3327
+ /**
3328
+ * Wind engine settings as a field (SDK 1.32.0): a preset word or
3329
+ * `{ preset, ...params }`, the same as `instrument: wind(...)`. Use with
3330
+ * `instrument` omitted or `"wind"`.
3331
+ */
3332
+ wind?:
3333
+ WindPresetName | Readonly<{ preset?: WindPresetName } & WindParams> | null;
3334
+ /**
3335
+ * Singing voice settings as a field (SDK 1.32.0), the same as
3336
+ * `instrument: sing(...)`. Use with `instrument` omitted or `"sing"`.
3337
+ */
3338
+ sing?:
3339
+ SingPresetName | Readonly<{ preset?: SingPresetName } & SingParams> | null;
2680
3340
  /** Synth voice parameters, Strudel names (`{ attack: 0.01, lpf: 800 }`). */
2681
3341
  synth?: SynthInput;
2682
3342
  /**
@@ -2726,6 +3386,14 @@ export type TrackInput = Readonly<{
2726
3386
  * holds only the keys already down when it presses.
2727
3387
  */
2728
3388
  sostenuto?: readonly (readonly [number, "down" | "up"])[];
3389
+ /**
3390
+ * Audio clips on the timeline (SDK 1.32.0): `audio("samples/lead.wav",
3391
+ * { at: 8 })`, or `...repeatAudio(audio(...), { every: 8, until: 64 })`.
3392
+ * They sound on any instrument; on `vocal` the notes are silent guides.
3393
+ */
3394
+ clips?: readonly (AudioSpec | readonly AudioSpec[])[];
3395
+ /** Takes the clips play from (SDK 1.32.0): `take("take-1", "takes/take-1.wav", {...})`. */
3396
+ takes?: readonly TakeSpec[];
2729
3397
  /**
2730
3398
  * Velocity response (SDK 1.15.0): `soft` (quiet notes louder), `hard`
2731
3399
  * (needs a firm touch), `fixed` (every note at 0.8, like an organ) or
@@ -2750,6 +3418,11 @@ export type TrackInput = Readonly<{
2750
3418
  * it changes no sound by itself.
2751
3419
  */
2752
3420
  guitar?: GuitarInput;
3421
+ /**
3422
+ * Pitch correction on this track's clips and samples (SDK 1.32.0): a
3423
+ * preset word (`"hard"`), or `autotune("pop", { speed: 40 })`.
3424
+ */
3425
+ autotune?: AutotunePresetName | AutotuneSpec;
2753
3426
  /** `note()`/`seq()` for pitched tracks, `hit()`/`hits()` for kits and one-shot samplers. */
2754
3427
  notes?: readonly (NoteSpec | HitSpec)[];
2755
3428
  /**
@@ -2882,6 +3555,16 @@ export type TrackSpec = Readonly<{
2882
3555
  guitar?: GuitarSetup;
2883
3556
  /** Wind settings (SDK 1.30.0); present only on a wind-engine track. */
2884
3557
  wind?: Readonly<{ preset?: WindPresetName } & WindParams>;
3558
+ /** Sing settings (SDK 1.32.0); present only on a sing track. */
3559
+ sing?: Readonly<{ preset?: SingPresetName } & SingParams>;
3560
+ /** Audio clips (SDK 1.32.0), flattened, paths project-relative; present only when set. */
3561
+ clips?: readonly AudioSpec[];
3562
+ /** Takes (SDK 1.32.0); present only when set. */
3563
+ takes?: readonly TakeSpec[];
3564
+ /** Vocoder settings (SDK 1.32.0); `src` as written until `song()`. */
3565
+ vocoder?: Readonly<{ preset?: VocoderPresetName } & VocoderParams>;
3566
+ /** Pitch correction (SDK 1.32.0); present only when set. */
3567
+ autotune?: AutotuneSettings;
2885
3568
  }>;
2886
3569
 
2887
3570
  export type GlideMode = "legato" | "mono" | "poly";
@@ -3087,6 +3770,40 @@ const ZZFX_SHAPES = Object.freeze([
3087
3770
  * Sample paths without a `tracks/` prefix are made project-relative under
3088
3771
  * this track's `tracks/<slug>/`.
3089
3772
  */
3773
+ /**
3774
+ * `wind:` or `sing:` on track() as the engine spec, so the field is never
3775
+ * silently dropped: it needs `instrument` omitted or the engine's own word.
3776
+ */
3777
+ function engineField(
3778
+ input: TrackInput,
3779
+ name: string,
3780
+ ): WindSpec | SingSpec | undefined {
3781
+ const fields = [
3782
+ ["wind", WIND_INSTRUMENT, wind] as const,
3783
+ ["sing", SING_INSTRUMENT, sing] as const,
3784
+ ].filter(([key]) => input[key] !== undefined && input[key] !== null);
3785
+ if (fields.length === 0) return undefined;
3786
+ if (fields.length > 1)
3787
+ throw new DawgSdkError(`track ${name}: use wind: or sing:, not both`);
3788
+ const [key, word, make] = fields[0]!;
3789
+ if (input.instrument !== undefined && input.instrument !== word)
3790
+ throw new DawgSdkError(
3791
+ `track ${name}: ${key}: needs instrument "${word}" or none (got ${typeof input.instrument === "string" ? `"${input.instrument.slice(0, 32)}"` : "an engine spec"})`,
3792
+ );
3793
+ const value = input[key] as unknown;
3794
+ if (typeof value === "string")
3795
+ return (make as (p: string) => WindSpec | SingSpec)(value);
3796
+ if (!isRecord(value))
3797
+ throw new DawgSdkError(
3798
+ `track ${name}: ${key}: must be a preset word or an object`,
3799
+ );
3800
+ const { preset, ...params } = value as Record<string, unknown>;
3801
+ return (make as (p: unknown, q: object) => WindSpec | SingSpec)(
3802
+ preset ?? params,
3803
+ preset === undefined ? {} : params,
3804
+ );
3805
+ }
3806
+
3090
3807
  export function track(input: TrackInput): TrackSpec {
3091
3808
  if (!isRecord(input)) throw new DawgSdkError("track() needs an object");
3092
3809
  if (typeof input.name !== "string" || input.name.trim().length === 0)
@@ -3098,7 +3815,7 @@ export function track(input: TrackInput): TrackSpec {
3098
3815
  const id = input.id ?? slug;
3099
3816
  if (typeof id !== "string" || id.length === 0 || id.length > 64)
3100
3817
  throw new DawgSdkError(`track ${name}: id must be 1..64 characters`);
3101
- const rawInstrument = input.instrument ?? "sine";
3818
+ const rawInstrument = engineField(input, name) ?? input.instrument ?? "sine";
3102
3819
  // A granular track may keep the sampler it grains (`grain off` goes back).
3103
3820
  const keptSampler =
3104
3821
  isRecord(input.sampler) &&
@@ -3115,9 +3832,24 @@ export function track(input: TrackInput): TrackSpec {
3115
3832
  isRecord(rawInstrument) && rawInstrument.kind === "sampler"
3116
3833
  ? localizeSampler(rawInstrument as SamplerSpec, slug)
3117
3834
  : keptSampler;
3118
- const wavetableSpec =
3119
- isRecord(rawInstrument) && rawInstrument.kind === "wavetable"
3120
- ? localizeWavetable(rawInstrument as WavetableSpec, slug)
3835
+ const playedWavetable =
3836
+ isRecord(rawInstrument) && rawInstrument.kind === "wavetable";
3837
+ if (input.wavetable !== undefined && input.wavetable !== null) {
3838
+ if (!isRecord(input.wavetable) || input.wavetable.kind !== "wavetable")
3839
+ throw new DawgSdkError(`track ${name}: wavetable: takes wavetable(...)`);
3840
+ if (
3841
+ playedWavetable ||
3842
+ (typeof rawInstrument === "string" &&
3843
+ rawInstrument.trim().toLowerCase() === WAVETABLE_INSTRUMENT)
3844
+ )
3845
+ throw new DawgSdkError(
3846
+ `track ${name}: a wavetable track sets its table in instrument: wavetable(...)`,
3847
+ );
3848
+ }
3849
+ const wavetableSpec = playedWavetable
3850
+ ? localizeWavetable(rawInstrument as WavetableSpec, slug)
3851
+ : isRecord(input.wavetable)
3852
+ ? localizeWavetable(input.wavetable as WavetableSpec, slug)
3121
3853
  : null;
3122
3854
  const stringFromInstrument =
3123
3855
  isRecord(rawInstrument) && rawInstrument.kind === "string"
@@ -3134,11 +3866,13 @@ export function track(input: TrackInput): TrackSpec {
3134
3866
  const modalSpec = trackModal(rawInstrument);
3135
3867
  const guitarSpec = guitarInput(input.guitar, `track ${name}`);
3136
3868
  const windSpec = trackWind(rawInstrument);
3869
+ const singSpec = trackSing(rawInstrument);
3870
+ const vocoderSpec = trackVocoder(rawInstrument, input.vocoder);
3137
3871
  const instrument = granularFromInstrument
3138
3872
  ? GRANULAR_INSTRUMENT
3139
3873
  : samplerSpec
3140
3874
  ? SAMPLER_INSTRUMENT
3141
- : wavetableSpec
3875
+ : playedWavetable
3142
3876
  ? WAVETABLE_INSTRUMENT
3143
3877
  : stringFromInstrument
3144
3878
  ? STRING_INSTRUMENT
@@ -3146,9 +3880,13 @@ export function track(input: TrackInput): TrackSpec {
3146
3880
  ? MODAL_INSTRUMENT
3147
3881
  : windSpec
3148
3882
  ? WIND_INSTRUMENT
3149
- : typeof rawInstrument === "string"
3150
- ? (word?.instrument ?? rawInstrument)
3151
- : undefined;
3883
+ : singSpec
3884
+ ? SING_INSTRUMENT
3885
+ : isRecord(rawInstrument) && rawInstrument.kind === "vocoder"
3886
+ ? VOCODER_INSTRUMENT
3887
+ : typeof rawInstrument === "string"
3888
+ ? (word?.instrument ?? rawInstrument)
3889
+ : undefined;
3152
3890
  // A granular word (`"cloud"`) turns the engine on with its preset.
3153
3891
  const granularSpec =
3154
3892
  granularInput(input.granular, name, slug) ??
@@ -3191,7 +3929,7 @@ export function track(input: TrackInput): TrackSpec {
3191
3929
  if (pitch === undefined)
3192
3930
  throw new DawgSdkError(
3193
3931
  kit
3194
- ? `track ${name}: unknown drum voice "${spec.voice}" (kick snare clap rim tom hat openhat)`
3932
+ ? `track ${name}: unknown drum "${spec.voice}" (kick snare clap rim tom hat openhat)`
3195
3933
  : slots
3196
3934
  ? `track ${name}: unknown sampler voice "${spec.voice}" (${[...slots.keys()].join(" ")})`
3197
3935
  : `track ${name}: hit("${spec.voice}") needs instrument "kit" or sampler(...)`,
@@ -3373,6 +4111,12 @@ export function track(input: TrackInput): TrackSpec {
3373
4111
  ...(modalSpec ? { modal: modalSpec } : {}),
3374
4112
  ...(guitarSpec ? { guitar: guitarSpec } : {}),
3375
4113
  ...(windSpec ? { wind: windSpec } : {}),
4114
+ ...(singSpec ? { sing: singSpec } : {}),
4115
+ ...trackClips(input, name, slug),
4116
+ ...(vocoderSpec ? { vocoder: vocoderSpec } : {}),
4117
+ ...(input.autotune !== undefined
4118
+ ? { autotune: autotuneInput(input.autotune, `track ${name}`) }
4119
+ : {}),
3376
4120
  });
3377
4121
  }
3378
4122
 
@@ -3803,6 +4547,12 @@ export type SongInput = Readonly<{
3803
4547
  tracks: readonly TrackSpec[];
3804
4548
  /** Master chain and loudness target after every track and orbit bus (SDK 1.17.0); omit for none. */
3805
4549
  master?: MasterInput;
4550
+ /**
4551
+ * Which style and seed made the song (SDK 1.33.0), from `style()`:
4552
+ * `style: style("deep-house", { seed: 3, bars: 8 })`. A record only: the
4553
+ * notes are the tracks above; `/style` in dawg generates them.
4554
+ */
4555
+ style?: StyleSpec;
3806
4556
  /**
3807
4557
  * Named bar ranges (SDK 1.18.0): `{ name: "chorus", startBar: 8, bars: 8 }`,
3808
4558
  * optionally with `mute: ["pad"]` and `vary: { lead: { transpose: 12 } }`.
@@ -3816,6 +4566,13 @@ export type SongInput = Readonly<{
3816
4566
  form?: string | readonly (string | SongFormEntry)[];
3817
4567
  /** The section playback loops (SDK 1.18.0); export ignores it. */
3818
4568
  loopSection?: string;
4569
+ /**
4570
+ * Sound calibration (SDK 1.32.0): `1` renders the 0.7 level, pitch and
4571
+ * drum-kit fixes (hat choke, tuned toms, crash and ride, level keys,
4572
+ * steady brass). Omit it to keep an older song's sound byte-identical;
4573
+ * `dawg init` writes the latest.
4574
+ */
4575
+ calibration?: number;
3819
4576
  }>;
3820
4577
 
3821
4578
  /** A song section (SDK 1.18.0); bars are 0-based like beats. */
@@ -3880,8 +4637,12 @@ export type ScoreNote = Readonly<{
3880
4637
  bend?: readonly Readonly<{ at: number; cents: number }>[];
3881
4638
  vibrato?: Readonly<{ rate: number; depth: number; delay?: number }>;
3882
4639
  humanize?: Readonly<{ timing?: number; velocity?: number; length?: number }>;
4640
+ /** Autotune guide drift share (SDK 1.32.0). */
4641
+ drift?: number;
3883
4642
  /** Static cents offset (SDK 1.16.0); absent is 0. */
3884
4643
  cents?: number;
4644
+ /** Sung vowel (SDK 1.32.0); absent sings the lyric's or the track's. */
4645
+ vowel?: string;
3885
4646
  }>;
3886
4647
 
3887
4648
  /** A stored automation point: integer tick. */
@@ -3968,6 +4729,12 @@ export type ScoreTrack = Readonly<{
3968
4729
  guitar?: GuitarSetup;
3969
4730
  /** Wind settings (SDK 1.30.0). */
3970
4731
  wind?: TrackSpec["wind"];
4732
+ /** Sing settings (SDK 1.32.0). */
4733
+ sing?: TrackSpec["sing"];
4734
+ /** Vocoder settings (SDK 1.32.0); `src` is a track id. */
4735
+ vocoder?: TrackSpec["vocoder"];
4736
+ /** Pitch correction (SDK 1.32.0). */
4737
+ autotune?: AutotuneSettings;
3971
4738
  glide?: TrackSpec["glide"];
3972
4739
  pedal?: readonly Readonly<{ tick: number; state: PedalState }>[];
3973
4740
  softPedal?: readonly Readonly<{ tick: number; state: PedalState }>[];
@@ -3996,14 +4763,80 @@ export type Song = Readonly<{
3996
4763
  tracks: readonly ScoreTrack[];
3997
4764
  notes: readonly ScoreNote[];
3998
4765
  master?: MasterInput;
4766
+ /** Present only when the song names a style (SDK 1.33.0). */
4767
+ style?: StyleSpec;
3999
4768
  /** Present only when the song has sections (SDK 1.18.0). */
4000
4769
  sections?: readonly SongSection[];
4001
4770
  /** Present only when the song has a form (SDK 1.18.0). */
4002
4771
  form?: readonly SongFormEntry[];
4003
4772
  /** Present only when a section loops (SDK 1.18.0). */
4004
4773
  loopSection?: string;
4774
+ /** Present only when the song sets one (SDK 1.32.0). */
4775
+ calibration?: number;
4005
4776
  }>;
4006
4777
 
4778
+ /** A song's style provenance (SDK 1.33.0); see `style()`. */
4779
+ export type StyleSpec = Readonly<{
4780
+ id: string;
4781
+ seed: number;
4782
+ bars: number;
4783
+ blend?: Readonly<{ id: string; weight: number }>;
4784
+ }>;
4785
+
4786
+ export type StyleOptions = Readonly<{
4787
+ /** Generator seed, integer 0..2147483647, default 1. */
4788
+ seed?: number;
4789
+ /** Bars generated, 1..256, default 8. */
4790
+ bars?: number;
4791
+ /** Blend partner and its weight 0..1: `blend: ["bebop", 0.3]`. */
4792
+ blend?: readonly [string, number];
4793
+ }>;
4794
+
4795
+ const STYLE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
4796
+
4797
+ /**
4798
+ * Which style and seed made a song (SDK 1.33.0), for `song({ style })`:
4799
+ *
4800
+ * ```ts
4801
+ * style("deep-house", { seed: 3, bars: 8 })
4802
+ * style("bebop", { seed: 7, blend: ["bossa-nova", 0.3] })
4803
+ * ```
4804
+ *
4805
+ * The id is a taxonomy id (`dawg` lists them with `/style list`). It is a
4806
+ * record of where the song came from; the notes live in the tracks.
4807
+ */
4808
+ export function style(id: string, options: StyleOptions = {}): StyleSpec {
4809
+ if (typeof id !== "string" || !STYLE_ID_PATTERN.test(id))
4810
+ throw new DawgSdkError(
4811
+ `style id must be lowercase words joined by hyphens, like "deep-house"; got ${JSON.stringify(id)}`,
4812
+ );
4813
+ if (!isRecord(options))
4814
+ throw new DawgSdkError("style options must be an object");
4815
+ const seed = options.seed ?? 1;
4816
+ if (!Number.isInteger(seed) || seed < 0 || seed > 2147483647)
4817
+ throw new DawgSdkError("style seed must be an integer 0..2147483647");
4818
+ const bars = options.bars ?? 8;
4819
+ if (!Number.isInteger(bars) || bars < 1 || bars > 256)
4820
+ throw new DawgSdkError("style bars must be an integer 1..256");
4821
+ let blend: StyleSpec["blend"];
4822
+ if (options.blend !== undefined) {
4823
+ const pair = options.blend;
4824
+ if (
4825
+ !Array.isArray(pair) ||
4826
+ pair.length !== 2 ||
4827
+ typeof pair[0] !== "string" ||
4828
+ !STYLE_ID_PATTERN.test(pair[0]) ||
4829
+ typeof pair[1] !== "number" ||
4830
+ !(pair[1] >= 0 && pair[1] <= 1)
4831
+ )
4832
+ throw new DawgSdkError(
4833
+ 'style blend must be ["style-id", weight 0..1], like ["bebop", 0.3]',
4834
+ );
4835
+ blend = Object.freeze({ id: pair[0], weight: pair[1] });
4836
+ }
4837
+ return Object.freeze({ id, seed, bars, ...(blend ? { blend } : {}) });
4838
+ }
4839
+
4007
4840
  /** A stored song `time`: ticks, and 0-based bar indexes. */
4008
4841
  export type ScoreTime = Readonly<{
4009
4842
  tempo?: readonly Readonly<{
@@ -4019,6 +4852,24 @@ export type ScoreTime = Readonly<{
4019
4852
  fermatas?: readonly Readonly<{ tick: number; beats: number }>[];
4020
4853
  }>;
4021
4854
 
4855
+ /** `song({ style })`: the `style()` record, re-checked for hand-written objects. */
4856
+ function songStyle(input: unknown): { style?: StyleSpec } {
4857
+ if (input === undefined || input === null) return {};
4858
+ if (!isRecord(input))
4859
+ throw new DawgSdkError('song style must come from style("id", { seed })');
4860
+ const blend = input.blend;
4861
+ const spec = style(input.id as string, {
4862
+ seed: input.seed as number,
4863
+ bars: input.bars as number,
4864
+ ...(blend !== undefined && blend !== null
4865
+ ? isRecord(blend)
4866
+ ? { blend: [blend.id, blend.weight] as unknown as [string, number] }
4867
+ : { blend: blend as [string, number] }
4868
+ : {}),
4869
+ });
4870
+ return { style: spec };
4871
+ }
4872
+
4022
4873
  const MASTER_KEYS = ["eq", "glue", "tape", "width", "limiter", "target"];
4023
4874
 
4024
4875
  /** Shape checks only; dawg validates every value when it loads the song. */
@@ -4155,6 +5006,9 @@ function songSections(
4155
5006
  * lengths at least one tick), and every note gets a deterministic id from
4156
5007
  * its track and content, so two evaluations of the same files agree.
4157
5008
  */
5009
+ /** The newest `song({ calibration })` (mirrors core CALIBRATION_LATEST). */
5010
+ export const SONG_CALIBRATION_LATEST = 1;
5011
+
4158
5012
  export function song(input: SongInput): Song {
4159
5013
  if (!isRecord(input)) throw new DawgSdkError("song() needs an object");
4160
5014
  const tempoBpm = finite(input.tempo ?? 120, "song tempo");
@@ -4180,6 +5034,16 @@ export function song(input: SongInput): Song {
4180
5034
  throw new DawgSdkError("song key must be a string or null");
4181
5035
  const songTuning = tuningSpec(input.tuning, "song");
4182
5036
  const master = masterData(input.master);
5037
+ const calibration = input.calibration ?? 0;
5038
+ if (
5039
+ typeof calibration !== "number" ||
5040
+ !Number.isInteger(calibration) ||
5041
+ calibration < 0 ||
5042
+ calibration > SONG_CALIBRATION_LATEST
5043
+ )
5044
+ throw new DawgSdkError(
5045
+ `song calibration must be an integer 0..${SONG_CALIBRATION_LATEST}`,
5046
+ );
4183
5047
  if (!Array.isArray(input.tracks))
4184
5048
  throw new DawgSdkError("song tracks must be an array of track()");
4185
5049
  if (input.tracks.length > 64)
@@ -4281,6 +5145,29 @@ export function song(input: SongInput): Song {
4281
5145
  if (t.modal) stored.modal = t.modal;
4282
5146
  if (t.guitar) stored.guitar = t.guitar;
4283
5147
  if (t.wind) stored.wind = t.wind;
5148
+ if (t.sing) stored.sing = t.sing;
5149
+ if (t.clips && t.clips.length > 0)
5150
+ stored.clips = Object.freeze(
5151
+ t.clips.map((clip, index) => storedClip(clip, index, ticks)),
5152
+ );
5153
+ if (t.takes && t.takes.length > 0)
5154
+ stored.takes = Object.freeze(
5155
+ t.takes.map((spec) => storedTake(spec, ticks)),
5156
+ );
5157
+ if (t.vocoder)
5158
+ stored.vocoder = Object.freeze(
5159
+ t.vocoder.src === undefined
5160
+ ? t.vocoder
5161
+ : {
5162
+ ...t.vocoder,
5163
+ src: resolveVocoderSrc(
5164
+ input.tracks as TrackSpec[],
5165
+ t.id,
5166
+ t.vocoder.src,
5167
+ ),
5168
+ },
5169
+ );
5170
+ if (t.autotune) stored.autotune = t.autotune;
4284
5171
  if (t.rhythm && t.rhythm.length > 0)
4285
5172
  stored.rhythm = Object.freeze(
4286
5173
  t.rhythm.map((row) => {
@@ -4320,7 +5207,10 @@ export function song(input: SongInput): Song {
4320
5207
  : {}),
4321
5208
  ...(n.vibrato ? { vibrato: n.vibrato } : {}),
4322
5209
  ...(n.humanize ? { humanize: n.humanize } : {}),
5210
+ ...(n.drift !== undefined ? { drift: n.drift } : {}),
4323
5211
  ...(n.cents ? { cents: n.cents } : {}),
5212
+ ...(n.vowel ? { vowel: n.vowel } : {}),
5213
+ ...(n.lyric !== undefined ? { lyric: n.lyric } : {}),
4324
5214
  }),
4325
5215
  );
4326
5216
  }
@@ -4383,7 +5273,9 @@ export function song(input: SongInput): Song {
4383
5273
  tracks: Object.freeze(tracks),
4384
5274
  notes: Object.freeze(notes),
4385
5275
  ...(master ? { master } : {}),
5276
+ ...songStyle(input.style),
4386
5277
  ...arrangement,
5278
+ ...(calibration ? { calibration } : {}),
4387
5279
  });
4388
5280
  }
4389
5281
 
@@ -4896,7 +5788,7 @@ function songTime(
4896
5788
  * an object with at most one table source (`edo`, `ratios`, `cents` or
4897
5789
  * `scl`). Library names: `12-tet`, `19-edo`, `24-edo`, `31-edo`,
4898
5790
  * `pythagorean`, `just` (5-limit), `7-limit`, `well-tuned-piano`, `pelog`,
4899
- * `slendro`, `nyamaropa`, `shruti`, maqam and dastgah sets (`bayati`,
5791
+ * `slendro`, `nyamaropa`, `thai`, `shruti`, maqam and dastgah sets (`bayati`,
4900
5792
  * `rast`, `saba`, `shur`, `homayoun`, `chahargah`) and raga intonations
4901
5793
  * (`yaman`, `bhairav`, `kafi`, `todi`, …); `dawg` lists them with
4902
5794
  * `/tuning list`. dawg checks every value when the song loads.
@@ -5296,6 +6188,298 @@ export function strum(
5296
6188
  return progression(chords, { ...options, perform: "guitar" });
5297
6189
  }
5298
6190
 
6191
+ // BEGIN lyrics: generated from core/lyrics.ts by core/sdk/sync-lyrics.ts
6192
+ /** Longest lyric on one note (SCORE_LIMITS.maxLyricLength). */
6193
+ const LYRIC_LIMIT = 32;
6194
+
6195
+ /** One lyric token: a syllable, a held note (`_`) or a skipped note (`~`). */
6196
+ type LyricToken = Readonly<{
6197
+ syl: string;
6198
+ /** Index of the word the token belongs to. */
6199
+ word: number;
6200
+ /** First syllable of its word. */
6201
+ first: boolean;
6202
+ kind: "syl" | "hold" | "rest";
6203
+ }>;
6204
+
6205
+ /**
6206
+ * The lyric grammar: words split by spaces, syllables by `-`, `_` holds the
6207
+ * previous syllable over the next note (melisma), `~` skips a note.
6208
+ * "sun-lit morn-ing _ glow" gives sun lit morn ing _ glow.
6209
+ */
6210
+ function parseLyric(text: string): LyricToken[] {
6211
+ const out: LyricToken[] = [];
6212
+ let word = -1;
6213
+ for (const raw of text.trim().split(/\s+/u)) {
6214
+ if (raw === "") continue;
6215
+ if (raw === "_") out.push({ syl: "_", word, first: false, kind: "hold" });
6216
+ else if (raw === "~")
6217
+ out.push({ syl: "~", word, first: false, kind: "rest" });
6218
+ else {
6219
+ word += 1;
6220
+ raw
6221
+ .split("-")
6222
+ .filter(Boolean)
6223
+ .forEach((syl, index) =>
6224
+ out.push({ syl, word, first: index === 0, kind: "syl" }),
6225
+ );
6226
+ }
6227
+ }
6228
+ return out;
6229
+ }
6230
+
6231
+ const VOWEL = /[aeiouàáâäèéêëìíîïòóôöùúûü]/u;
6232
+ /** Consonant pairs that sound as one consonant and are never split. */
6233
+ const SYL_DIGRAPHS = new Set(["th", "sh", "ch", "ph", "wh", "ng", "ck", "gh"]);
6234
+ /** Digraphs that end a syllable (no English word starts with them). */
6235
+ const SYL_CODA_ONLY = new Set(["ng", "ck", "gh", "x"]);
6236
+ /** Consonant clusters a syllable may start with (maximal onset). */
6237
+ const SYL_ONSETS = new Set(
6238
+ (
6239
+ "bl br cl cr dr fl fr gl gr pl pr sc sk sl sm sn sp st sw tr tw dw " +
6240
+ "thr shr chr phr phl spl spr str scr squ skr"
6241
+ ).split(" "),
6242
+ );
6243
+ /** Common words ending in a silent `e` that start compounds (some-thing). */
6244
+ const SYL_SILENT_E_HEADS = (
6245
+ "some home life time love fire side care where there here more one " +
6246
+ "make lone like name game base wide grace face place space stone bone"
6247
+ ).split(" ");
6248
+ /** Suffixes kept whole after a silent `e` (love-ly, care-ful). */
6249
+ const SYL_SUFFIXES = ["ly", "ful", "less", "ness", "ment"];
6250
+ /** Unstressed endings that close a short vowel before them (nev-er). */
6251
+ const SYL_CLOSING_ENDINGS = new Set([
6252
+ "er",
6253
+ "en",
6254
+ "el",
6255
+ "et",
6256
+ "ed",
6257
+ "es",
6258
+ "est",
6259
+ "ing",
6260
+ ]);
6261
+
6262
+ /**
6263
+ * Syllables of a word typed without hyphens: a guess for English, which a
6264
+ * hyphen always overrides (`nev-er`). Each run of vowels (and `y` after a
6265
+ * consonant) is one syllable; a final silent `e` does not count, but a
6266
+ * consonant plus `le` is its own syllable (lit-tle, ta-ble). Consonant
6267
+ * pairs that sound as one (th sh ch ph wh ng ck gh) never split. Between
6268
+ * vowels a cluster gives the next syllable the longest onset English
6269
+ * allows (mon-ster, chil-dren); one consonant goes with the next vowel
6270
+ * (ba-by, to-night) unless the previous vowel is short before an
6271
+ * unstressed ending (nev-er, sing-ing). "something" gives some thing,
6272
+ * "forever" for ev er.
6273
+ */
6274
+ function autoSyllabify(word: string): string[] {
6275
+ const w = word.toLowerCase();
6276
+ // Compounds and suffixes after a silent e: some-thing, love-ly.
6277
+ if (w.length >= 6) {
6278
+ for (const head of SYL_SILENT_E_HEADS)
6279
+ if (w.startsWith(head) && VOWEL.test(w.slice(head.length)))
6280
+ return [
6281
+ word.slice(0, head.length),
6282
+ ...autoSyllabify(word.slice(head.length)),
6283
+ ];
6284
+ for (const suffix of SYL_SUFFIXES) {
6285
+ const stem = w.slice(0, -suffix.length);
6286
+ if (
6287
+ w.endsWith(suffix) &&
6288
+ stem.length >= 3 &&
6289
+ stem.endsWith("e") &&
6290
+ !VOWEL.test(stem[stem.length - 2]!)
6291
+ )
6292
+ return [
6293
+ ...autoSyllabify(word.slice(0, stem.length)),
6294
+ word.slice(stem.length),
6295
+ ];
6296
+ }
6297
+ }
6298
+ // Letters into units: a vowel, a consonant, a digraph, or `qu`.
6299
+ type Unit = { at: number; text: string; vowel: boolean };
6300
+ const units: Unit[] = [];
6301
+ for (let i = 0; i < w.length;) {
6302
+ const pair = w.slice(i, i + 2);
6303
+ if (pair === "qu" || SYL_DIGRAPHS.has(pair)) {
6304
+ units.push({ at: i, text: pair, vowel: false });
6305
+ i += 2;
6306
+ continue;
6307
+ }
6308
+ const ch = w[i]!;
6309
+ const prev = units.at(-1);
6310
+ const vowel =
6311
+ VOWEL.test(ch) || (ch === "y" && prev !== undefined && !prev.vowel);
6312
+ units.push({ at: i, text: ch, vowel });
6313
+ i += 1;
6314
+ }
6315
+ // Vowel groups as [first unit, last unit].
6316
+ const groups: [number, number][] = [];
6317
+ for (let u = 0; u < units.length;) {
6318
+ if (units[u]!.vowel) {
6319
+ let v = u;
6320
+ while (v + 1 < units.length && units[v + 1]!.vowel) v += 1;
6321
+ groups.push([u, v]);
6322
+ u = v + 1;
6323
+ } else u += 1;
6324
+ }
6325
+ const lastUnit = units.length - 1;
6326
+ const finalLe =
6327
+ w.endsWith("le") &&
6328
+ units.length >= 3 &&
6329
+ units[lastUnit - 1]!.text === "l" &&
6330
+ !units[lastUnit - 2]!.vowel;
6331
+ const last = groups.at(-1);
6332
+ if (
6333
+ groups.length > 1 &&
6334
+ last &&
6335
+ last[0] === lastUnit &&
6336
+ last[1] === lastUnit &&
6337
+ units[lastUnit]!.text === "e" &&
6338
+ !units[lastUnit - 1]!.vowel &&
6339
+ !finalLe
6340
+ )
6341
+ groups.pop();
6342
+ if (groups.length <= 1) return [word];
6343
+ const cuts: number[] = [];
6344
+ for (let g = 1; g < groups.length; g += 1) {
6345
+ const prev = groups[g - 1]!;
6346
+ const next = groups[g]!;
6347
+ const cluster = units.slice(prev[1] + 1, next[0]);
6348
+ const n = cluster.length;
6349
+ const isLast = g === groups.length - 1;
6350
+ let onset: number; // units of the cluster that start the next syllable
6351
+ if (isLast && finalLe && n >= 2)
6352
+ onset = cluster[n - 2]!.text === "ck" ? 1 : 2;
6353
+ else if (n === 1) {
6354
+ const unit = cluster[0]!.text;
6355
+ const prevText = units
6356
+ .slice(prev[0], prev[1] + 1)
6357
+ .map((u) => u.text)
6358
+ .join("");
6359
+ const ending = w.slice(units[next[0]]!.at);
6360
+ const short = prevText.length === 1 && "eiou".includes(prevText);
6361
+ const closes =
6362
+ SYL_CODA_ONLY.has(unit) ||
6363
+ (short && isLast && SYL_CLOSING_ENDINGS.has(ending)) ||
6364
+ (unit === "r" && short && units[next[0]]!.text === "e");
6365
+ onset = closes ? 0 : 1;
6366
+ } else {
6367
+ onset = 1;
6368
+ for (let k = n - 1; k >= 2; k -= 1)
6369
+ if (
6370
+ SYL_ONSETS.has(
6371
+ cluster
6372
+ .slice(n - k)
6373
+ .map((u) => u.text)
6374
+ .join(""),
6375
+ )
6376
+ ) {
6377
+ onset = k;
6378
+ break;
6379
+ }
6380
+ if (SYL_CODA_ONLY.has(cluster[n - 1]!.text)) onset = 0;
6381
+ }
6382
+ const first = units[next[0] - onset]!;
6383
+ cuts.push(onset === 0 ? units[next[0]]!.at : first.at);
6384
+ }
6385
+ const out: string[] = [];
6386
+ let at = 0;
6387
+ for (const cut of cuts) {
6388
+ out.push(word.slice(at, cut));
6389
+ at = cut;
6390
+ }
6391
+ out.push(word.slice(at));
6392
+ return out.filter(Boolean);
6393
+ }
6394
+
6395
+ /** What `assignLyrics` put on each note, and what did not fit. */
6396
+ type LyricAssignment = Readonly<{
6397
+ /** Note id to its lyric (`_` holds); notes `~` skipped are absent. */
6398
+ lyrics: ReadonlyMap<string, string>;
6399
+ /** Syllables left over after the last note. */
6400
+ dropped: readonly string[];
6401
+ /** Words split automatically. */
6402
+ split: readonly string[];
6403
+ }>;
6404
+
6405
+ /**
6406
+ * Lyrics onto `notes` in time order. Hyphens split syllables as typed;
6407
+ * when the text has fewer syllables than there are notes, words typed
6408
+ * whole are split by `autoSyllabify`, and any notes still left hold the
6409
+ * last syllable (melisma) instead of failing. Syllables past the last note
6410
+ * are reported in `dropped`. Notes sharing an onset take one token, on
6411
+ * the top note, with `_` on the others. Each lyric is cut to the 32-character limit.
6412
+ */
6413
+ function assignLyrics(
6414
+ text: string,
6415
+ notes: readonly Readonly<{ id: string; startTick: number; pitch: number }>[],
6416
+ ): LyricAssignment {
6417
+ const sorted = [...notes].sort(
6418
+ (a, b) => a.startTick - b.startTick || b.pitch - a.pitch,
6419
+ );
6420
+ // Notes sharing an onset (a chord or a doubled note) take one token: the
6421
+ // top note carries it and the rest hold.
6422
+ const ordered: (typeof sorted)[number][] = [];
6423
+ const under = new Map<string, string[]>();
6424
+ for (const note of sorted) {
6425
+ const top = ordered.at(-1);
6426
+ if (top && top.startTick === note.startTick)
6427
+ under.get(top.id)!.push(note.id);
6428
+ else {
6429
+ ordered.push(note);
6430
+ under.set(note.id, []);
6431
+ }
6432
+ }
6433
+ let tokens = parseLyric(text);
6434
+ const split: string[] = [];
6435
+ if (tokens.length < ordered.length) {
6436
+ // Split every word typed whole; keep the split only if it still fits.
6437
+ const out: LyricToken[] = [];
6438
+ const words: string[] = [];
6439
+ for (const token of tokens) {
6440
+ const whole =
6441
+ token.kind === "syl" &&
6442
+ token.first &&
6443
+ !tokens.some((t) => t.word === token.word && !t.first);
6444
+ if (!whole) {
6445
+ out.push(token);
6446
+ continue;
6447
+ }
6448
+ const parts = autoSyllabify(token.syl);
6449
+ if (parts.length > 1) words.push(token.syl);
6450
+ parts.forEach((syl, index) =>
6451
+ out.push({ syl, word: token.word, first: index === 0, kind: "syl" }),
6452
+ );
6453
+ }
6454
+ if (out.length <= ordered.length) {
6455
+ tokens = out;
6456
+ split.push(...words);
6457
+ }
6458
+ }
6459
+ const lyrics = new Map<string, string>();
6460
+ const limit = LYRIC_LIMIT;
6461
+ ordered.forEach((note, index) => {
6462
+ const token = tokens[index];
6463
+ if (!token) {
6464
+ if (tokens.length > 0)
6465
+ for (const id of [note.id, ...under.get(note.id)!]) lyrics.set(id, "_");
6466
+ return;
6467
+ }
6468
+ if (token.kind === "rest") return;
6469
+ lyrics.set(
6470
+ note.id,
6471
+ token.kind === "hold" ? "_" : token.syl.slice(0, limit),
6472
+ );
6473
+ for (const id of under.get(note.id)!) lyrics.set(id, "_");
6474
+ });
6475
+ const dropped = tokens
6476
+ .slice(ordered.length)
6477
+ .filter((token) => token.kind === "syl")
6478
+ .map((token) => token.syl);
6479
+ return { lyrics, dropped, split };
6480
+ }
6481
+ // END lyrics
6482
+
5299
6483
  // BEGIN instrument words: generated from core/instruments.ts by core/sdk/sync-instruments.ts
5300
6484
  /** What an instrument word stores on a track. */
5301
6485
  type InstrumentWord = Readonly<{
@@ -5695,6 +6879,25 @@ const INSTRUMENT_WORDS: readonly InstrumentWordRow[] = Object.freeze([
5695
6879
  { word: "frenchhorn", instrument: "wind", field: "wind", preset: "horn" },
5696
6880
  { word: "mutedtrumpet", instrument: "wind", field: "wind", preset: "harmon" },
5697
6881
  { word: "wahtrumpet", instrument: "wind", field: "wind", preset: "plunger" },
6882
+ // f07-sing: the built-in singing voice (core/sing.ts).
6883
+ { word: "sing", instrument: "sing", field: "sing" },
6884
+ { word: "aah", instrument: "sing", field: "sing", preset: "aah" },
6885
+ { word: "ooh", instrument: "sing", field: "sing", preset: "ooh" },
6886
+ { word: "choir", instrument: "sing", field: "sing", preset: "choir" },
6887
+ { word: "chorale", instrument: "sing", field: "sing", preset: "chorale" },
6888
+ { word: "khoomei", instrument: "sing", field: "sing", preset: "khoomei" },
6889
+ { word: "sygyt", instrument: "sing", field: "sing", preset: "sygyt" },
6890
+ { word: "kargyraa", instrument: "sing", field: "sing", preset: "kargyraa" },
6891
+ // f07-clips: a track of audio clips; its notes are guides.
6892
+ { word: "vocal", instrument: "vocal" },
6893
+ // f07-vocoder: the built-in carrier (core/vocoder.ts); set a source with
6894
+ // `/vocoder src <track>`.
6895
+ {
6896
+ word: "vocoder",
6897
+ instrument: "vocoder",
6898
+ field: "vocoder",
6899
+ preset: "classic",
6900
+ },
5698
6901
  ]);
5699
6902
 
5700
6903
  /**
@@ -5750,6 +6953,7 @@ const QUALITIES = [
5750
6953
  "mb6",
5751
6954
  "b6",
5752
6955
  "7#9",
6956
+ "b5",
5753
6957
  ] as const;
5754
6958
  type Quality = (typeof QUALITIES)[number];
5755
6959
 
@@ -5766,6 +6970,7 @@ const QUALITY_INTERVALS: Readonly<Record<Quality, readonly number[]>> =
5766
6970
  mb6: [0, 3, 7, 8],
5767
6971
  b6: [0, 4, 7, 8],
5768
6972
  "7#9": [0, 4, 7, 10, 15],
6973
+ b5: [0, 4, 6],
5769
6974
  });
5770
6975
 
5771
6976
  /**
@@ -5818,6 +7023,11 @@ type Chord = Readonly<{
5818
7023
  * such as `C11`, `G13` or `A7b9` carry them (0.6.1).
5819
7024
  */
5820
7025
  tensions?: readonly number[] | undefined;
7026
+ /**
7027
+ * The root's letter, 0..6 for C..B, when a roman numeral spelled it:
7028
+ * `bVII` in C names Bb (not A#) and `vii` in F# names E# (not F).
7029
+ */
7030
+ letter?: number | undefined;
5821
7031
  }>;
5822
7032
 
5823
7033
  function makeChord(
@@ -5896,6 +7106,25 @@ function noteName(pc: number, flats = false): string {
5896
7106
  return (flats ? FLAT_NAMES : SHARP_NAMES)[mod12(pc)]!;
5897
7107
  }
5898
7108
 
7109
+ const LETTERS = "CDEFGAB";
7110
+ const LETTER_PCS = [0, 2, 4, 5, 7, 9, 11] as const;
7111
+
7112
+ /**
7113
+ * `pc` spelled on letter `letter` (0..6, C..B) with one accidental at
7114
+ * most (E#, Cb, Bb); undefined when that would need a double accidental.
7115
+ */
7116
+ function spellOnLetter(pc: number, letter: number): string | undefined {
7117
+ const l = ((Math.trunc(letter) % 7) + 7) % 7;
7118
+ const diff = ((mod12(pc) - LETTER_PCS[l]! + 18) % 12) - 6;
7119
+ if (Math.abs(diff) > 1) return undefined;
7120
+ return `${LETTERS[l]}${diff === 1 ? "#" : diff === -1 ? "b" : ""}`;
7121
+ }
7122
+
7123
+ /** The letter (0..6, C..B) a key's tonic is spelled on. */
7124
+ function tonicLetter(key: Key): number {
7125
+ return LETTERS.indexOf(noteName(key.tonic, keyUsesFlats(key))[0]!);
7126
+ }
7127
+
5899
7128
  const SECRET_SUFFIX: Readonly<Partial<Record<Quality, string>>> = Object.freeze(
5900
7129
  { madd4: "m(add4)", mb6: "m(b6)", b6: "(b6)", "7#9": "7#9" },
5901
7130
  );
@@ -5974,6 +7203,9 @@ function chordSuffix(chord: Chord): string {
5974
7203
  base = `${seventh}(no3)`;
5975
7204
  if (nine) extras.push("9");
5976
7205
  break;
7206
+ case "b5":
7207
+ base = `${ninth}b5`;
7208
+ break;
5977
7209
  default:
5978
7210
  base = seventh; // secret qualities returned above
5979
7211
  }
@@ -5992,6 +7224,7 @@ function chordSuffix(chord: Chord): string {
5992
7224
  mb6: "m(b6)",
5993
7225
  b6: "(b6)",
5994
7226
  "7#9": "7#9",
7227
+ b5: "(b5)",
5995
7228
  };
5996
7229
  base = triad[q];
5997
7230
  if (six && nine && (q === "maj" || q === "min")) return `${base}6/9`;
@@ -6011,7 +7244,11 @@ function chordSuffix(chord: Chord): string {
6011
7244
  function chordName(chord: Chord, flats = false): string {
6012
7245
  const slash =
6013
7246
  chord.bass === undefined ? "" : `/${noteName(chord.bass, flats)}`;
6014
- return `${noteName(chord.root, flats)}${chordSuffix(chord)}${slash}`;
7247
+ const root =
7248
+ (chord.letter === undefined
7249
+ ? undefined
7250
+ : spellOnLetter(chord.root, chord.letter)) ?? noteName(chord.root, flats);
7251
+ return `${root}${chordSuffix(chord)}${slash}`;
6015
7252
  }
6016
7253
 
6017
7254
  /** Suffix → quality and extensions, longest first when parsing. */
@@ -6076,6 +7313,31 @@ const SUFFIXES: readonly (readonly [string, Quality, readonly Extension[]])[] =
6076
7313
  ["(b6)", "b6", []],
6077
7314
  ["addb6", "b6", []],
6078
7315
  ["7#9", "7#9", []],
7316
+ // 0.7: more spellings of the same chords.
7317
+ ["-maj7", "min", ["M7"]],
7318
+ ["mmaj7", "min", ["M7"]],
7319
+ ["mMaj7", "min", ["M7"]],
7320
+ ["m(maj7)", "min", ["M7"]],
7321
+ ["-Δ7", "min", ["M7"]],
7322
+ ["mΔ7", "min", ["M7"]],
7323
+ ["add2", "maj", ["9"]],
7324
+ ["2", "maj", ["9"]],
7325
+ ["madd2", "min", ["9"]],
7326
+ ["6add9", "maj", ["6", "9"]],
7327
+ ["m6add9", "min", ["6", "9"]],
7328
+ ["-6", "min", ["6"]],
7329
+ ["-9", "min", ["m7", "9"]],
7330
+ ["dom9", "maj", ["m7", "9"]],
7331
+ ["aug(maj7)", "aug", ["M7"]],
7332
+ ["augmaj7", "aug", ["M7"]],
7333
+ ["+maj7", "aug", ["M7"]],
7334
+ ["aug9", "aug", ["m7", "9"]],
7335
+ ["+9", "aug", ["m7", "9"]],
7336
+ ["m(maj9)", "min", ["M7", "9"]],
7337
+ ["mmaj9", "min", ["M7", "9"]],
7338
+ ["dim(maj7)", "dim", ["M7"]],
7339
+ ["7(no3)", "5", ["m7"]],
7340
+ ["maj7(no3)", "5", ["M7"]],
6079
7341
  ];
6080
7342
 
6081
7343
  /** Typed upper-tension chords (0.6.1): suffix, quality, buttons, tensions. */
@@ -6110,10 +7372,7 @@ const TENSION_NAMES: Readonly<Record<number, string>> = Object.freeze({
6110
7372
  21: "13",
6111
7373
  });
6112
7374
 
6113
- const SUFFIX_TABLE = new Map<
6114
- string,
6115
- { quality: Quality; ext: readonly Extension[]; tensions?: readonly number[] }
6116
- >([
7375
+ const SUFFIX_TABLE = new Map<string, SuffixEntry>([
6117
7376
  ...SUFFIXES.map(
6118
7377
  ([suffix, quality, ext]) => [suffix, { quality, ext }] as const,
6119
7378
  ),
@@ -6146,6 +7405,81 @@ function parsePitchClass(text: string): number | undefined {
6146
7405
  return mod12(LETTER[match[1]!.toLowerCase()]! + accidental);
6147
7406
  }
6148
7407
 
7408
+ /** Alteration → upper tension (semitones above the root). */
7409
+ const ALTERATION_TENSION: Readonly<Record<string, number>> = Object.freeze({
7410
+ b9: 13,
7411
+ "#9": 15,
7412
+ "11": 17,
7413
+ "#11": 18,
7414
+ "+11": 18,
7415
+ b13: 20,
7416
+ "13": 21,
7417
+ });
7418
+
7419
+ const TOKEN = "b5|#5|\\+5|b9|#9|#11|\\+11|b13|alt|add9|add11|add13|11|13|9|6";
7420
+ /** Bare alterations or parenthesized comma lists of them, in any order. */
7421
+ const ALTERATIONS = new RegExp(
7422
+ `^(?:(?:${TOKEN})|\\((?:${TOKEN})(?:,(?:${TOKEN}))*\\))+$`,
7423
+ );
7424
+
7425
+ type SuffixEntry = {
7426
+ quality: Quality;
7427
+ ext: readonly Extension[];
7428
+ tensions?: readonly number[];
7429
+ };
7430
+
7431
+ /**
7432
+ * A suffix the table does not list, read as a listed base followed by
7433
+ * alterations, bare or in parentheses: `7#5`, `9#11`, `13#11`, `7b9b13`,
7434
+ * `9b5`, `maj7+5`, `7alt`, `7(b9,#9)`. A raised fifth makes the triad
7435
+ * augmented, a lowered one makes a major triad `b5` (a minor one
7436
+ * diminished); `alt` is b9, #9, #11 and b13 over a dominant seventh.
7437
+ */
7438
+ function parseAlteredSuffix(suffix: string): SuffixEntry | undefined {
7439
+ for (let cut = suffix.length - 1; cut >= 0; cut -= 1) {
7440
+ const base = SUFFIX_TABLE.get(suffix.slice(0, cut));
7441
+ if (!base) continue;
7442
+ const raw = suffix.slice(cut);
7443
+ if (!ALTERATIONS.test(raw)) continue;
7444
+ const rest = raw.replace(/[(),]/g, "");
7445
+ const tokens = rest.match(
7446
+ /b5|#5|\+5|b9|#9|#11|\+11|b13|alt|add9|add11|add13|11|13|9|6/g,
7447
+ );
7448
+ if (!tokens || tokens.join("") !== rest) continue;
7449
+ let quality: Quality = base.quality;
7450
+ const ext = new Set<Extension>(base.ext);
7451
+ const tensions = new Set<number>(base.tensions ?? []);
7452
+ let ok = true;
7453
+ for (const token of tokens) {
7454
+ if (token === "#5" || token === "+5") {
7455
+ if (quality === "maj" || quality === "aug") quality = "aug";
7456
+ else ok = false;
7457
+ } else if (token === "b5") {
7458
+ if (quality === "maj" || quality === "b5") quality = "b5";
7459
+ else if (quality === "min" || quality === "dim") quality = "dim";
7460
+ else ok = false;
7461
+ } else if (token === "alt") {
7462
+ if (quality !== "maj") ok = false;
7463
+ ext.add("m7");
7464
+ for (const step of [13, 15, 18, 20]) tensions.add(step);
7465
+ } else if (token === "9" || token === "add9") ext.add("9");
7466
+ else if (token === "6") ext.add("6");
7467
+ else {
7468
+ const step = ALTERATION_TENSION[token.replace(/^add/, "")];
7469
+ if (step === undefined) ok = false;
7470
+ else tensions.add(step);
7471
+ }
7472
+ }
7473
+ if (!ok) continue;
7474
+ return {
7475
+ quality,
7476
+ ext: [...ext],
7477
+ tensions: [...tensions].sort((a, b) => a - b),
7478
+ };
7479
+ }
7480
+ return undefined;
7481
+ }
7482
+
6149
7483
  /** Parse a chord symbol (`Cm7`, `F#dim`, `Bbmaj9`, `G7sus4`, `C/E`). */
6150
7484
  function parseChord(symbol: string): Chord | undefined {
6151
7485
  if (typeof symbol !== "string" || symbol.length > 24) return undefined;
@@ -6156,7 +7490,8 @@ function parseChord(symbol: string): Chord | undefined {
6156
7490
  const match = trimmed.match(/^([A-Ga-g])(#|b|♯|♭)?([^/]*)(?:\/(.+))?$/);
6157
7491
  if (!match) return undefined;
6158
7492
  const root = parsePitchClass(`${match[1]}${match[2] ?? ""}`);
6159
- const entry = SUFFIX_TABLE.get(match[3] ?? "");
7493
+ const entry =
7494
+ SUFFIX_TABLE.get(match[3] ?? "") ?? parseAlteredSuffix(match[3] ?? "");
6160
7495
  if (root === undefined || !entry) return undefined;
6161
7496
  let bass: number | undefined;
6162
7497
  if (match[4] !== undefined) {
@@ -6216,7 +7551,15 @@ const MODE_ALIASES: Readonly<Record<string, ModeName>> = Object.freeze({
6216
7551
  });
6217
7552
 
6218
7553
  type ScaleFamily =
6219
- "pentatonic" | "blues" | "maqam" | "dastgah" | "raga" | "messiaen";
7554
+ | "pentatonic"
7555
+ | "blues"
7556
+ | "maqam"
7557
+ | "dastgah"
7558
+ | "raga"
7559
+ | "messiaen"
7560
+ | "chromatic"
7561
+ | "overtone"
7562
+ | "quarter-tone";
6220
7563
 
6221
7564
  /**
6222
7565
  * Scales beyond the chord modes, for keys such as `D bayati`, `C yaman` or
@@ -6263,6 +7606,12 @@ const SCALES = Object.freeze({
6263
7606
  family: "blues",
6264
7607
  aliases: ["major blues"],
6265
7608
  },
7609
+ "yonanuki-minor": {
7610
+ steps: [0, 2, 3, 7, 8],
7611
+ mode: "minor",
7612
+ family: "pentatonic",
7613
+ aliases: ["yonanuki", "yonanuki minor", "enka minor"],
7614
+ },
6266
7615
  hijaz: {
6267
7616
  steps: [0, 1, 4, 5, 7, 8, 10],
6268
7617
  mode: "phrygian-dominant",
@@ -6439,6 +7788,32 @@ const SCALES = Object.freeze({
6439
7788
  mode: "harmonic-minor",
6440
7789
  family: "messiaen",
6441
7790
  },
7791
+ // All twelve pitch classes: the field of free atonality and the row.
7792
+ chromatic: {
7793
+ steps: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
7794
+ mode: "minor",
7795
+ family: "chromatic",
7796
+ aliases: ["twelve-tone", "aggregate"],
7797
+ },
7798
+ // Partials 8 to 15 of the harmonic series over the tonic (Grisey,
7799
+ // Murail): the acoustic scale with the 11th and 13th partials' and the
7800
+ // 7th's just pitches, which its named tuning applies.
7801
+ "harmonic-series": {
7802
+ steps: [0, 2, 4, 6, 7, 9, 10, 11],
7803
+ mode: "mixolydian",
7804
+ family: "overtone",
7805
+ intonation: [0, 204, 386, 551, 702, 841, 969, 1088],
7806
+ aliases: ["overtone", "overtone-scale", "partials"],
7807
+ },
7808
+ // Each tempered degree of the major scale beside its quarter-tone
7809
+ // shadow (Haba, Wyschnegradsky): neutral 2nd, 3rd, 6th and 7th and a
7810
+ // quarter-sharp 4th, sounded as note cents over twelve-tone keys.
7811
+ "quarter-tone": {
7812
+ steps: [0, 1.5, 2, 3.5, 4, 5, 5.5, 7, 8.5, 9, 10.5],
7813
+ mode: "major",
7814
+ family: "quarter-tone",
7815
+ aliases: ["quartertone", "24-tone"],
7816
+ },
6442
7817
  } as const satisfies Record<string, ScaleInfo>);
6443
7818
  type ScaleName = keyof typeof SCALES;
6444
7819
  const SCALE_NAMES = Object.keys(SCALES) as ScaleName[];
@@ -6641,9 +8016,14 @@ function romanOf(key: Key, chord: Chord): string {
6641
8016
  if (degree < 0) {
6642
8017
  // Name chromatic roots against the major scale: bIII, #iv°.
6643
8018
  const major = MODES.major.map((step) => mod12(key.tonic + step));
8019
+ const natural = major.indexOf(chord.root);
6644
8020
  const flat = major.indexOf(mod12(chord.root + 1));
6645
8021
  const sharp = major.indexOf(mod12(chord.root - 1));
6646
- if (flat >= 0) {
8022
+ if (natural >= 0) {
8023
+ // A major-scale note the mode alters: ♮II in Phrygian.
8024
+ degree = natural;
8025
+ accidental = "♮";
8026
+ } else if (flat >= 0) {
6647
8027
  degree = flat;
6648
8028
  accidental = "b";
6649
8029
  } else {
@@ -6654,7 +8034,6 @@ function romanOf(key: Key, chord: Chord): string {
6654
8034
  const lower =
6655
8035
  chord.quality === "min" ||
6656
8036
  chord.quality === "dim" ||
6657
- chord.quality === "5" ||
6658
8037
  chord.quality === "madd4" ||
6659
8038
  chord.quality === "mb6";
6660
8039
  const numeral = NUMERALS[degree]!;
@@ -6671,7 +8050,33 @@ function romanOf(key: Key, chord: Chord): string {
6671
8050
  : ext.has("M7")
6672
8051
  ? "maj7"
6673
8052
  : "";
6674
- return `${accidental}${body}${mark}${seventh}`;
8053
+ // The short numeral when it reads back as this chord; else the chord's
8054
+ // own suffix in brackets (`I[7]`, `i[m6]`, `V[7#9]`), which is exact.
8055
+ const plain = `${accidental}${body}${mark}${seventh}`;
8056
+ const bare = makeChord(
8057
+ chord.root,
8058
+ chord.quality,
8059
+ chord.extensions,
8060
+ undefined,
8061
+ chord.tensions,
8062
+ );
8063
+ for (const candidate of [
8064
+ plain,
8065
+ `${accidental}${body}${mark}${seventh === "7" ? "dom7" : seventh}`,
8066
+ ])
8067
+ if (sameChord(parseRoman(key, candidate), bare)) return candidate;
8068
+ return `${accidental}${body}[${chordSuffix(bare)}]`;
8069
+ }
8070
+
8071
+ function sameChord(a: Chord | undefined, b: Chord): boolean {
8072
+ return (
8073
+ a !== undefined &&
8074
+ a.root === b.root &&
8075
+ a.quality === b.quality &&
8076
+ a.bass === b.bass &&
8077
+ a.extensions.join() === b.extensions.join() &&
8078
+ (a.tensions ?? []).join() === (b.tensions ?? []).join()
8079
+ );
6675
8080
  }
6676
8081
 
6677
8082
  /**
@@ -6684,31 +8089,64 @@ function romanOf(key: Key, chord: Chord): string {
6684
8089
  * major). `7` adds the diatonic seventh; `maj7`/`M7` and `dom7` are exact.
6685
8090
  */
6686
8091
  function parseRoman(key: Key, text: string): Chord | undefined {
6687
- if (typeof text !== "string" || text.length > 16) return undefined;
8092
+ return romanIn(key, text, tonicLetter(key));
8093
+ }
8094
+
8095
+ /** `parseRoman` with the tonic spelled on `tonic` (0..6, C..B). */
8096
+ function romanIn(key: Key, text: string, tonic: number): Chord | undefined {
8097
+ if (typeof text !== "string" || text.length > 32) return undefined;
6688
8098
  const trimmed = text.trim();
8099
+ const exact = trimmed.match(
8100
+ /^(b|#|♭|♯|♮)?(vii|vi|v|iv|iii|ii|i|VII|VI|V|IV|III|II|I)\[([^\]]*)\]$/,
8101
+ );
8102
+ if (exact) {
8103
+ // `I[7]`: the numeral names the root, the bracket is a chord suffix.
8104
+ const degree = NUMERALS.indexOf(exact[2]!.toLowerCase());
8105
+ const shift =
8106
+ exact[1] === "b" || exact[1] === "♭"
8107
+ ? -1
8108
+ : exact[1] === "♮" || !exact[1]
8109
+ ? 0
8110
+ : 1;
8111
+ const root = !exact[1]
8112
+ ? scaleOf(key)[degree]
8113
+ : mod12(key.tonic + MODES.major[degree]! + shift);
8114
+ if (root === undefined) return undefined;
8115
+ const letter = (tonic + degree) % 7;
8116
+ const chord = parseChord(
8117
+ `${spellOnLetter(root, letter) ?? noteName(root)}${exact[3]!}`,
8118
+ );
8119
+ return chord && Object.freeze({ ...chord, letter });
8120
+ }
6689
8121
  const slash = trimmed.match(/^(.+)\/(.+)$/);
6690
8122
  if (slash) {
6691
8123
  // V/x: the chord built on the degree of x in the key (secondary function).
6692
- const target = parseRoman(key, slash[2]!);
8124
+ const target = romanIn(key, slash[2]!, tonic);
6693
8125
  if (!target) return undefined;
6694
- const sub = parseRoman({ tonic: target.root, mode: "major" }, slash[1]!);
6695
- return sub;
8126
+ return romanIn(
8127
+ { tonic: target.root, mode: "major" },
8128
+ slash[1]!,
8129
+ target.letter ?? tonic,
8130
+ );
6696
8131
  }
6697
8132
  const match = trimmed.match(
6698
- /^(b|#|♭|♯)?(vii|vi|v|iv|iii|ii|i|VII|VI|V|IV|III|II|I)(°|o|ø|\+)?(maj7|M7|dom7|7|9|maj9|6|sus4|sus2|sus|add9)?$/,
8133
+ /^(b|#|♭|♯|♮)?(vii|vi|v|iv|iii|ii|i|VII|VI|V|IV|III|II|I)(°|o|ø|\+)?(maj7|M7|dom7|7|9|maj9|6|sus4|sus2|sus|add9)?$/,
6699
8134
  );
6700
8135
  if (!match) return undefined;
6701
8136
  const accidental =
6702
- match[1] === "b" || match[1] === "♭" ? -1 : match[1] ? 1 : 0;
8137
+ match[1] === "b" || match[1] === "♭"
8138
+ ? -1
8139
+ : match[1] === "#" || match[1] === "♯"
8140
+ ? 1
8141
+ : 0;
6703
8142
  const numeral = match[2]!;
6704
8143
  const lower = numeral === numeral.toLowerCase();
6705
8144
  const degree = NUMERALS.indexOf(numeral.toLowerCase());
6706
8145
  const mark = match[3];
6707
8146
  const suffix = match[4] ?? "";
6708
- const root =
6709
- accidental === 0
6710
- ? scaleOf(key)[degree]!
6711
- : mod12(key.tonic + MODES.major[degree]! + accidental);
8147
+ const root = !match[1]
8148
+ ? scaleOf(key)[degree]!
8149
+ : mod12(key.tonic + MODES.major[degree]! + accidental);
6712
8150
  const inKey = degreeOf(key, root);
6713
8151
  const triad = inKey === undefined ? undefined : diatonicChord(key, inKey);
6714
8152
  const seventh =
@@ -6762,7 +8200,10 @@ function parseRoman(key: Key, text: string): Chord | undefined {
6762
8200
  quality = "sus2";
6763
8201
  break;
6764
8202
  }
6765
- return makeChord(root, quality, ext);
8203
+ return Object.freeze({
8204
+ ...makeChord(root, quality, ext),
8205
+ letter: (tonic + degree) % 7,
8206
+ });
6766
8207
  }
6767
8208
 
6768
8209
  // ---------------------------------------------------------------------------
@@ -6804,7 +8245,17 @@ function rotate(pitches: readonly number[], steps: number): number[] {
6804
8245
 
6805
8246
  function rootPosition(chord: Chord, anchor = 60): number[] {
6806
8247
  const rootPitch = anchor + mod12(chord.root - anchor);
6807
- return chordIntervals(chord).map((step) => rootPitch + step);
8248
+ const steps = chordIntervals(chord);
8249
+ // A natural 11 over a major 3rd and a 7th is the avoid-note clash (E
8250
+ // under F a minor 9th up in C11), so the voicing drops the 3rd: C11 is
8251
+ // C G Bb D F, the sus voicing; C13 already leaves the 11 out.
8252
+ const clash =
8253
+ steps.includes(4) &&
8254
+ steps.includes(17) &&
8255
+ (steps.includes(10) || steps.includes(11));
8256
+ return steps
8257
+ .filter((step) => !(clash && step === 4))
8258
+ .map((step) => rootPitch + step);
6808
8259
  }
6809
8260
 
6810
8261
  /** Open voicings: `open` drops the second voice from the top an octave
@@ -8160,6 +9611,362 @@ function renderProgression(options: RenderOptions): RenderedProgression {
8160
9611
  }
8161
9612
  // END chord engine
8162
9613
 
9614
+ // ---------------------------------------------------------------------------
9615
+ // Audio clips, takes and lyrics (SDK 1.32.0)
9616
+
9617
+ /** Options for `audio()`: times in beats, offsets and lengths in seconds. */
9618
+ export type AudioOptions = Readonly<{
9619
+ /** Stable clip id; defaults to `clip`, `clip2`, ... by position. */
9620
+ id?: string;
9621
+ /** Beat the clip starts on, default 0. */
9622
+ at?: number;
9623
+ /** Seconds into the file where the clip starts, default 0. */
9624
+ offset?: number;
9625
+ /** Seconds of the file it plays, default to the end. */
9626
+ dur?: number;
9627
+ /** Linear gain 0..4, default 1. */
9628
+ gain?: number;
9629
+ /** Equal-power fade in, seconds (default 5 ms). */
9630
+ fadeInTime?: number;
9631
+ /** Equal-power fade out, seconds (default 5 ms). */
9632
+ fadeTime?: number;
9633
+ /** Play the slice backwards. */
9634
+ rev?: boolean;
9635
+ /** The track take this clip plays from (its clock drift applies). */
9636
+ take?: string;
9637
+ mute?: boolean;
9638
+ /** The words sung in the clip, for the highway and lyrics. */
9639
+ text?: string;
9640
+ /** A text-to-speech clip's time map (0.7.1); kept as written. */
9641
+ say?: Readonly<Record<string, unknown>>;
9642
+ /** The file's pin; dawg fills it from the file when absent. */
9643
+ sha256?: string;
9644
+ }>;
9645
+
9646
+ /** One audio clip as `audio()` builds it. */
9647
+ export type AudioSpec = Readonly<
9648
+ { kind: "audio"; src: string; at: number } & Omit<AudioOptions, "at">
9649
+ >;
9650
+
9651
+ const AUDIO_KEYS = [
9652
+ "id",
9653
+ "at",
9654
+ "offset",
9655
+ "dur",
9656
+ "gain",
9657
+ "fadeInTime",
9658
+ "fadeTime",
9659
+ "rev",
9660
+ "take",
9661
+ "mute",
9662
+ "text",
9663
+ "say",
9664
+ "sha256",
9665
+ ] as const;
9666
+
9667
+ /**
9668
+ * An audio file on the track's timeline (SDK 1.32.0). `src` is relative
9669
+ * to the track folder (`samples/lead.wav`) or the project
9670
+ * (`tracks/vox/samples/lead.wav`).
9671
+ *
9672
+ * ```ts
9673
+ * clips: [audio("samples/verse.wav", { at: 16, gain: 0.8, fadeTime: 0.2 })]
9674
+ * ```
9675
+ */
9676
+ export function audio(src: string, options: AudioOptions = {}): AudioSpec {
9677
+ const file = text(src, "audio src");
9678
+ if (!isRecord(options))
9679
+ throw new DawgSdkError("audio options must be an object");
9680
+ for (const key of Object.keys(options))
9681
+ if (!(AUDIO_KEYS as readonly string[]).includes(key))
9682
+ throw new DawgSdkError(
9683
+ `audio has an unknown option "${key.slice(0, 32)}" (${AUDIO_KEYS.join(" ")})`,
9684
+ );
9685
+ const out: Record<string, unknown> = {
9686
+ kind: "audio",
9687
+ src: file,
9688
+ at: beat(options.at ?? 0, "audio at"),
9689
+ };
9690
+ if (options.id !== undefined) out.id = text(options.id, "audio id");
9691
+ for (const key of [
9692
+ "offset",
9693
+ "dur",
9694
+ "gain",
9695
+ "fadeInTime",
9696
+ "fadeTime",
9697
+ ] as const)
9698
+ if (options[key] !== undefined) {
9699
+ const value = finite(options[key], `audio ${key}`);
9700
+ if (value < 0) throw new DawgSdkError(`audio ${key} must be ≥ 0`);
9701
+ out[key] = value;
9702
+ }
9703
+ for (const key of ["rev", "mute"] as const)
9704
+ if (options[key] !== undefined) {
9705
+ if (typeof options[key] !== "boolean")
9706
+ throw new DawgSdkError(`audio ${key} must be true or false`);
9707
+ if (options[key]) out[key] = true;
9708
+ }
9709
+ if (options.take !== undefined) out.take = text(options.take, "audio take");
9710
+ if (options.text !== undefined) {
9711
+ if (typeof options.text !== "string" || options.text.length > 2000)
9712
+ throw new DawgSdkError("audio text must be at most 2000 characters");
9713
+ out.text = options.text;
9714
+ }
9715
+ if (options.say !== undefined) {
9716
+ if (!isRecord(options.say))
9717
+ throw new DawgSdkError("audio say must be an object");
9718
+ out.say = options.say;
9719
+ }
9720
+ if (options.sha256 !== undefined) {
9721
+ if (
9722
+ typeof options.sha256 !== "string" ||
9723
+ !/^[0-9a-f]{64}$/.test(options.sha256)
9724
+ )
9725
+ throw new DawgSdkError(
9726
+ "audio sha256 must be 64 lowercase hex characters",
9727
+ );
9728
+ out.sha256 = options.sha256;
9729
+ }
9730
+ return Object.freeze(out) as AudioSpec;
9731
+ }
9732
+
9733
+ /**
9734
+ * Copies of `clip` every `every` beats after it while they start before
9735
+ * `until` (SDK 1.32.0), the clip first: `...repeatAudio(hook, { every: 8,
9736
+ * until: 64 })`. Copies of a clip with an id get `<id>-r2`, `<id>-r3`, ...
9737
+ */
9738
+ export function repeatAudio(
9739
+ clip: AudioSpec,
9740
+ options: Readonly<{ every: number; until: number }>,
9741
+ ): readonly AudioSpec[] {
9742
+ if (!isRecord(clip) || clip.kind !== "audio")
9743
+ throw new DawgSdkError("repeatAudio needs a clip from audio()");
9744
+ if (!isRecord(options))
9745
+ throw new DawgSdkError("repeatAudio needs { every, until } in beats");
9746
+ const every = positive(options.every, "repeatAudio every");
9747
+ const until = beat(options.until, "repeatAudio until");
9748
+ const out: AudioSpec[] = [clip];
9749
+ for (
9750
+ let at = clip.at + every, pass = 2;
9751
+ at < until - 1e-9 && out.length < 256;
9752
+ at += every, pass += 1
9753
+ )
9754
+ out.push(
9755
+ Object.freeze({
9756
+ ...clip,
9757
+ at,
9758
+ ...(clip.id !== undefined ? { id: `${clip.id}-r${pass}` } : {}),
9759
+ }) as AudioSpec,
9760
+ );
9761
+ return Object.freeze(out);
9762
+ }
9763
+
9764
+ /** Options for `take()`: `at`, `in` and `out` in beats, the rest in seconds. */
9765
+ export type TakeOptions = Readonly<{
9766
+ /** Beat the recording's first sample lines up with. */
9767
+ at?: number;
9768
+ /** Punch range in beats, default `at` to `at + 4`. */
9769
+ in?: number;
9770
+ out?: number;
9771
+ /** Seconds into the file where the take starts. */
9772
+ offset?: number;
9773
+ /** Round-trip latency compensated, seconds. */
9774
+ latency?: number;
9775
+ latencyAssumed?: boolean;
9776
+ /** Clock drift in parts per million (±1000). */
9777
+ ppm?: number;
9778
+ /** 0..1 fit of the alignment. */
9779
+ fit?: number;
9780
+ warn?: string;
9781
+ /** Manual nudge in milliseconds (±250). */
9782
+ nudge?: number;
9783
+ sha256?: string;
9784
+ }>;
9785
+
9786
+ /** One take as `take()` builds it. */
9787
+ export type TakeSpec = Readonly<
9788
+ {
9789
+ kind: "take";
9790
+ name: string;
9791
+ src: string;
9792
+ at: number;
9793
+ in: number;
9794
+ out: number;
9795
+ } & Omit<TakeOptions, "at" | "in" | "out">
9796
+ >;
9797
+
9798
+ const TAKE_KEYS = [
9799
+ "at",
9800
+ "in",
9801
+ "out",
9802
+ "offset",
9803
+ "latency",
9804
+ "latencyAssumed",
9805
+ "ppm",
9806
+ "fit",
9807
+ "warn",
9808
+ "nudge",
9809
+ "sha256",
9810
+ ] as const;
9811
+
9812
+ /**
9813
+ * A take (SDK 1.32.0): one recorded or imported pass the track's clips can
9814
+ * play from (`audio(src, { take: "take-1" })`). Recording itself is 0.7.1.
9815
+ */
9816
+ export function take(
9817
+ name: string,
9818
+ src: string,
9819
+ options: TakeOptions = {},
9820
+ ): TakeSpec {
9821
+ const label = `take ${text(name, "take name")}`;
9822
+ if (!isRecord(options))
9823
+ throw new DawgSdkError(`${label} options must be an object`);
9824
+ for (const key of Object.keys(options))
9825
+ if (!(TAKE_KEYS as readonly string[]).includes(key))
9826
+ throw new DawgSdkError(
9827
+ `${label} has an unknown option "${key.slice(0, 32)}" (${TAKE_KEYS.join(" ")})`,
9828
+ );
9829
+ const at = beat(options.at ?? 0, `${label} at`);
9830
+ const from = beat(options.in ?? at, `${label} in`);
9831
+ const to = beat(options.out ?? from + 4, `${label} out`);
9832
+ if (to <= from) throw new DawgSdkError(`${label}: out must be after in`);
9833
+ const out: Record<string, unknown> = {
9834
+ kind: "take",
9835
+ name,
9836
+ src: text(src, `${label} src`),
9837
+ at,
9838
+ in: from,
9839
+ out: to,
9840
+ };
9841
+ for (const key of ["offset", "latency", "ppm", "fit", "nudge"] as const)
9842
+ if (options[key] !== undefined)
9843
+ out[key] = finite(options[key], `${label} ${key}`);
9844
+ if (options.latencyAssumed) out.latencyAssumed = true;
9845
+ if (options.warn !== undefined)
9846
+ out.warn = text(options.warn, `${label} warn`);
9847
+ if (options.sha256 !== undefined)
9848
+ out.sha256 = text(options.sha256 as unknown, `${label} sha256`);
9849
+ return Object.freeze(out) as TakeSpec;
9850
+ }
9851
+
9852
+ /**
9853
+ * Sings `text` on `notes` in time order (SDK 1.32.0): spaces split words,
9854
+ * `-` splits syllables, `_` holds the previous syllable over the next note
9855
+ * (melisma), `~` skips a note. With fewer syllables than notes, words typed
9856
+ * whole split by vowel groups and leftover notes hold the last syllable;
9857
+ * syllables past the last note are dropped. Same rules as `/lyrics`.
9858
+ *
9859
+ * ```ts
9860
+ * notes: lyrics("sun-lit morn-ing glow", seq("C4 D4 E4 G4 E4"))
9861
+ * ```
9862
+ */
9863
+ export function lyrics<N extends NoteSpec>(
9864
+ text: string,
9865
+ notes: readonly N[],
9866
+ ): readonly N[] {
9867
+ if (typeof text !== "string" || text.length > 2000)
9868
+ throw new DawgSdkError("lyrics text must be at most 2000 characters");
9869
+ if (!Array.isArray(notes))
9870
+ throw new DawgSdkError("lyrics needs an array of notes");
9871
+ const keyed = notes.map((n, index) => ({
9872
+ id: String(index),
9873
+ startTick: Math.round(n.start * 960),
9874
+ pitch: n.pitch,
9875
+ }));
9876
+ const { lyrics: sung } = assignLyrics(text, keyed);
9877
+ return Object.freeze(
9878
+ notes.map((n, index) => {
9879
+ const lyric = sung.get(String(index));
9880
+ if (lyric === undefined) {
9881
+ const { lyric: _drop, ...rest } = n as N & { lyric?: string };
9882
+ return Object.freeze(rest) as unknown as N;
9883
+ }
9884
+ return Object.freeze({ ...n, lyric }) as N;
9885
+ }),
9886
+ );
9887
+ }
9888
+
9889
+ /** A clip for `song()`, ticks resolved and its default id filled. */
9890
+ function storedClip(
9891
+ clip: AudioSpec,
9892
+ index: number,
9893
+ ticks: (beats: number) => number,
9894
+ ): Record<string, unknown> {
9895
+ const { kind: _kind, at, id, ...rest } = clip;
9896
+ return Object.freeze({
9897
+ id: id ?? defaultClipId(index),
9898
+ ...rest,
9899
+ startTick: ticks(at),
9900
+ });
9901
+ }
9902
+
9903
+ /** The id a clip without one gets: `clip`, `clip2`, `clip3`, ... */
9904
+ export function defaultClipId(index: number): string {
9905
+ return index === 0 ? "clip" : `clip${index + 1}`;
9906
+ }
9907
+
9908
+ function storedTake(
9909
+ spec: TakeSpec,
9910
+ ticks: (beats: number) => number,
9911
+ ): Record<string, unknown> {
9912
+ const { kind: _kind, at, in: from, out: to, ...rest } = spec;
9913
+ return Object.freeze({
9914
+ offset: 0,
9915
+ latency: 0,
9916
+ ...rest,
9917
+ startTick: ticks(at),
9918
+ inTick: ticks(from),
9919
+ outTick: ticks(to),
9920
+ });
9921
+ }
9922
+
9923
+ /** `track({ clips, takes })` as TrackSpec fields, paths project-relative. */
9924
+ function trackClips(
9925
+ input: TrackInput,
9926
+ name: string,
9927
+ slug: string,
9928
+ ): { clips?: readonly AudioSpec[]; takes?: readonly TakeSpec[] } {
9929
+ const local = (src: string) => {
9930
+ const path = src.replace(/^\.\//, "");
9931
+ return path.startsWith("tracks/") || path.startsWith("pack:")
9932
+ ? path
9933
+ : `tracks/${slug}/${path}`;
9934
+ };
9935
+ const out: { clips?: readonly AudioSpec[]; takes?: readonly TakeSpec[] } = {};
9936
+ if (input.clips !== undefined) {
9937
+ if (!Array.isArray(input.clips))
9938
+ throw new DawgSdkError(
9939
+ `track ${name}: clips must be an array of audio()`,
9940
+ );
9941
+ const flat = (input.clips as readonly unknown[]).flat();
9942
+ const clips = flat.map((item, index) => {
9943
+ if (!isRecord(item) || item.kind !== "audio")
9944
+ throw new DawgSdkError(
9945
+ `track ${name}: clips[${index}] must come from audio() or repeatAudio()`,
9946
+ );
9947
+ const clip = item as AudioSpec;
9948
+ return Object.freeze({ ...clip, src: local(clip.src) }) as AudioSpec;
9949
+ });
9950
+ if (clips.length > 256)
9951
+ throw new DawgSdkError(`track ${name}: at most 256 clips`);
9952
+ if (clips.length > 0) out.clips = Object.freeze(clips);
9953
+ }
9954
+ if (input.takes !== undefined) {
9955
+ if (!Array.isArray(input.takes))
9956
+ throw new DawgSdkError(`track ${name}: takes must be an array of take()`);
9957
+ const takes = input.takes.map((item, index) => {
9958
+ if (!isRecord(item) || item.kind !== "take")
9959
+ throw new DawgSdkError(
9960
+ `track ${name}: takes[${index}] must come from take()`,
9961
+ );
9962
+ const spec = item as TakeSpec;
9963
+ return Object.freeze({ ...spec, src: local(spec.src) }) as TakeSpec;
9964
+ });
9965
+ if (takes.length > 0) out.takes = Object.freeze(takes);
9966
+ }
9967
+ return out;
9968
+ }
9969
+
8163
9970
  // ---------------------------------------------------------------------------
8164
9971
  // Internals
8165
9972