@libraz/libcantus-wasm 0.0.0-stage → 1.4.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.
@@ -0,0 +1,2894 @@
1
+ import { T as TimeSignature, b as MeterLike, c as MeterMap } from './index-Bf0Sv8a9.js';
2
+ import { a as Articulation, h as NoteEvent } from './index-C9MYbuKS.js';
3
+ import { S as SeedPath, d as PositionalRng, I as InstrumentProfile, f as StringedProfile } from './positional-DLnfUgqG.js';
4
+ import { d as ChordQuality, e as ChordSegment, c as ChordLike, K as KeyLike, b as Chord, m as ProfileWeights, g as ChordSpan, n as ResolvedKey, r as SpelledKeyLike } from './coerce-CUhHc3Tu.js';
5
+ import { h as ChordTimeline, e as CadenceType, v as MelodicContourShape, P as MotifRelationSummary, a5 as ReferenceProfile, b as BorrowedSource, o as HarmonicFunction } from './types-7mGFwvMm.js';
6
+ import { H as HarmonyRole } from './index-C7KCaTRz.js';
7
+
8
+ /**
9
+ * The samplers a generator needs, each addressed by the position it is drawing
10
+ * for rather than by how many draws came before it.
11
+ *
12
+ * Every method is a pure function of the source and the path: asking twice
13
+ * gives the same answer, asking in a different order changes nothing, and a
14
+ * position nobody asks about costs nothing. That is what lets a caller change
15
+ * one parameter — or one bar — without redrawing the rest of the piece.
16
+ *
17
+ * @category Composition
18
+ */
19
+ type Draw = {
20
+ /** The raw draw at a position: a float in [0, 1). */
21
+ at: (...path: SeedPath) => number;
22
+ /**
23
+ * Whether an event of probability `p` happens at a position. Because the
24
+ * underlying draw is fixed by the path, raising `p` only ever turns more
25
+ * positions on.
26
+ */
27
+ prob: (p: number, ...path: SeedPath) => boolean;
28
+ /** An integer in the inclusive range [lo, hi] at a position. */
29
+ range: (lo: number, hi: number, ...path: SeedPath) => number;
30
+ /** A float in [lo, hi) at a position. */
31
+ float: (lo: number, hi: number, ...path: SeedPath) => number;
32
+ };
33
+
34
+ /** Internal drum style selected by the public groove style. */
35
+ type DrumStyle = 'sparse' | 'standard' | 'fourOnFloor' | 'upbeat' | 'rock' | 'synth' | 'trap' | 'latin';
36
+ /** Every groove feel, in declaration order. */
37
+ declare const DRUM_FEELS: readonly ["straight", "swing", "shuffle"];
38
+ /** Groove feel controlling off-beat swing. */
39
+ type Feel = (typeof DRUM_FEELS)[number];
40
+ /**
41
+ * Groove feel (the swing/straight rhythmic character), under the name the
42
+ * public surface uses.
43
+ *
44
+ * @category Composition
45
+ */
46
+ type GrooveFeel = Feel;
47
+ /**
48
+ * Every public groove style, in declaration order. The type is derived from
49
+ * this list so the runtime guard and the type can never disagree.
50
+ */
51
+ declare const GROOVE_STYLES: readonly ["standard", "funk", "shuffle", "bossa", "trap", "halftime", "breakbeat", "house", "synthpop"];
52
+ /**
53
+ * Public groove style identifiers.
54
+ *
55
+ * @category Composition
56
+ */
57
+ type GrooveStyle = (typeof GROOVE_STYLES)[number];
58
+ /** Every public role, in declaration order. */
59
+ declare const DRUM_ROLES: readonly ["full", "ambient", "minimal", "fxOnly"];
60
+ /**
61
+ * Public role identifiers gating which voices are present.
62
+ *
63
+ * @category Composition
64
+ */
65
+ type DrumRole = (typeof DRUM_ROLES)[number];
66
+ /** Every public section, in declaration order. */
67
+ declare const PUBLIC_SECTIONS: readonly ["intro", "verse", "prechorus", "chorus", "bridge", "outro"];
68
+ /**
69
+ * Public section identifiers for {@link generateDrums}.
70
+ *
71
+ * These are the names a caller writes. The generator maps them onto a
72
+ * narrower internal set the pattern tables are keyed by, which answers to
73
+ * `'a'` and `'b'` and refuses `'verse'` and `'prechorus'`. That set is not
74
+ * published: a caller who reached for it by name would be held to a
75
+ * vocabulary that is not this one.
76
+ *
77
+ * @category Composition
78
+ */
79
+ type Section = (typeof PUBLIC_SECTIONS)[number];
80
+
81
+ /**
82
+ * The shared vocabulary model: a remembered figure, plus the conditions under
83
+ * which a player would reach for it.
84
+ *
85
+ * A rule-based generator can build a correct line and still sound characterless,
86
+ * because a player does not synthesise from scales — they assemble figures they
87
+ * already know. Those figures are not derivable, so they are held as data here:
88
+ * one record per figure, carrying its own applicability conditions, so choosing
89
+ * one is a deterministic lookup rather than a branch in a generator.
90
+ *
91
+ * ## Provenance
92
+ *
93
+ * No entry may reproduce a phrase from a particular recorded song. Only figures
94
+ * that belong to nobody are admitted — the common currency of a genre, the
95
+ * things every player of that music already plays. Every entry records which
96
+ * basis it qualifies under in {@link Vocabulary.provenance}, and the field is
97
+ * required so the judgment cannot be skipped while curating.
98
+ */
99
+
100
+ /**
101
+ * Every genre name a vocabulary entry may carry, in declaration order.
102
+ *
103
+ * Each built-in dictionary stocks part of the list, not all of it: the drum
104
+ * patterns carry `motown`, `funk`, `blues`, `bossa`, `samba`, `gospel` and
105
+ * `dnb`; the bass licks carry `motown`, `soul`, `funk`, `blues`, `jazz`,
106
+ * `bossa`, `gospel`, `country` and `reggae`. Asking a dictionary for a genre it
107
+ * has nothing for selects nothing rather than failing.
108
+ *
109
+ * The list is open in spirit even though the type is closed: a caller with a
110
+ * genre of its own — or one the built-ins do not stock — supplies entries
111
+ * through the generation context rather than waiting for this list to grow.
112
+ *
113
+ * @category Composition
114
+ */
115
+ declare const GENRES: readonly ["pop", "rock", "motown", "funk", "soul", "gospel", "jazz", "blues", "bossa", "samba", "reggae", "country", "hiphop", "house", "dnb"];
116
+ /**
117
+ * The genre a figure belongs to. Genre is what selects material; it never
118
+ * deforms or rejects it.
119
+ *
120
+ * @category Composition
121
+ */
122
+ type Genre = (typeof GENRES)[number];
123
+ /**
124
+ * Every ground on which a figure may enter a dictionary, in declaration order.
125
+ *
126
+ * - `'idiom'`: a genre-defining figure no one owns, played by every player of
127
+ * that music — a backbeat, a walking approach, a two-and-four side stick.
128
+ * - `'construction'`: derived here from the genre's rhythmic grid rather than
129
+ * remembered from any performance.
130
+ * - `'traditional'`: from a folk or traditional repertoire with no author.
131
+ *
132
+ * @category Composition
133
+ */
134
+ declare const PROVENANCE_BASES: readonly ["idiom", "construction", "traditional"];
135
+ /**
136
+ * The ground on which a figure qualifies for a dictionary.
137
+ *
138
+ * @category Composition
139
+ */
140
+ type ProvenanceBasis = (typeof PROVENANCE_BASES)[number];
141
+ /**
142
+ * Why a figure may be published as vocabulary.
143
+ *
144
+ * @category Composition
145
+ */
146
+ type Provenance = {
147
+ /** Which ground the figure qualifies under. */
148
+ basis: ProvenanceBasis;
149
+ /**
150
+ * What the figure is, in the terms a player would use — "the genre's
151
+ * two-and-four side stick", not the name of a record it appears on.
152
+ */
153
+ note: string;
154
+ };
155
+ /**
156
+ * One remembered figure, together with the conditions it fits.
157
+ *
158
+ * The optional conditions are read as "no restriction" when absent: an entry
159
+ * with no `sections` fits every section, one with no `tempoRange` fits every
160
+ * tempo. {@link Vocabulary.difficulty} is on the same 1..5 scale as the
161
+ * playability report, and is compared against the difficulty ceiling: an entry
162
+ * harder than the ceiling is rejected, never simplified in place.
163
+ *
164
+ * @typeParam T - The material this kind of figure is made of: chord-relative
165
+ * degrees for a bass lick, voices on a grid for a drum pattern.
166
+ *
167
+ * @category Composition
168
+ */
169
+ type Vocabulary<T> = {
170
+ /** Stable identifier; a caller entry with the same id replaces a built-in. */
171
+ id: string;
172
+ genre: Genre;
173
+ /** The figure itself. */
174
+ material: T;
175
+ /**
176
+ * How the figure is played, over and above the material's own strokes.
177
+ *
178
+ * These are requirements, not decoration: where a query names the techniques
179
+ * the instrument can produce, an entry asking for one the instrument does not
180
+ * have is not offered. A kit with no flam is never handed flam material.
181
+ */
182
+ articulations: Articulation[];
183
+ /** Chord qualities the figure works over; absent means any chord. */
184
+ fitsOver?: ChordQuality[];
185
+ /** Sections the figure suits; absent means any section. */
186
+ sections?: Section[];
187
+ /** Inclusive tempo band in BPM; absent means any tempo. */
188
+ tempoRange?: [number, number];
189
+ /** Time signature the figure is written in; absent means any. */
190
+ ts?: TimeSignature;
191
+ /** How hard the figure is to play, from 1 to 5. */
192
+ difficulty: number;
193
+ /** Why this figure may be published; see the module documentation. */
194
+ provenance: Provenance;
195
+ };
196
+ /**
197
+ * What a generator knows about the moment it is choosing a figure for.
198
+ *
199
+ * Every field is optional and an absent field asks nothing: a query with no
200
+ * genre matches every genre, exactly as an entry with no `sections` matches
201
+ * every section.
202
+ *
203
+ * @category Composition
204
+ */
205
+ type VocabularyQuery = {
206
+ genre?: Genre;
207
+ section?: Section;
208
+ /** Tempo in BPM, matched against each entry's band. */
209
+ bpm?: number;
210
+ /** The meter in force, matched against each entry's own signature. */
211
+ ts?: MeterLike;
212
+ /** The difficulty ceiling: entries above it are rejected. */
213
+ difficulty?: number;
214
+ /** The chord in force, matched against each entry's `fitsOver`. */
215
+ quality?: ChordQuality;
216
+ /**
217
+ * The techniques the instrument this part is written for can produce, from
218
+ * its profile. An entry asking for one that is not here is not offered;
219
+ * absent asks nothing, which is the programmed case.
220
+ */
221
+ articulations?: readonly Articulation[];
222
+ };
223
+ /**
224
+ * Whether one entry answers a query.
225
+ *
226
+ * @param entry The dictionary entry.
227
+ * @param query What the generator knows about the moment.
228
+ * @returns True when every condition the entry states is met.
229
+ *
230
+ * @category Composition
231
+ */
232
+ declare function fitsQuery<T>(entry: Vocabulary<T>, query: VocabularyQuery): boolean;
233
+ /**
234
+ * Every entry of a dictionary that answers a query, in dictionary order.
235
+ *
236
+ * Order is preserved so a selection made from the result is reproducible: the
237
+ * same dictionary and the same query always offer the same candidates in the
238
+ * same positions.
239
+ *
240
+ * @param dictionary The entries to search.
241
+ * @param query What the generator knows about the moment.
242
+ * @returns The matching entries, in the order they appear in the dictionary.
243
+ *
244
+ * @example
245
+ * ```ts
246
+ * import { BASS_LICKS, selectVocabulary } from '@libraz/libcantus';
247
+ * const candidates = selectVocabulary(BASS_LICKS, { genre: 'motown', difficulty: 3 });
248
+ * ```
249
+ *
250
+ * @category Composition
251
+ */
252
+ declare function selectVocabulary<T>(dictionary: readonly Vocabulary<T>[], query: VocabularyQuery): Vocabulary<T>[];
253
+ /**
254
+ * Choose one entry from a dictionary at a position.
255
+ *
256
+ * The choice is addressed by the path, not by how many choices came before it,
257
+ * so the figure at bar 12 does not move because the figure at bar 3 changed.
258
+ *
259
+ * @param dictionary The entries to choose from.
260
+ * @param query What the generator knows about the moment.
261
+ * @param draw The position-addressed sampler.
262
+ * @param path Where the choice is being made.
263
+ * @returns The chosen entry, or undefined when nothing fits.
264
+ *
265
+ * @category Composition
266
+ */
267
+ declare function pickVocabulary<T>(dictionary: readonly Vocabulary<T>[], query: VocabularyQuery, draw: Draw, ...path: readonly (string | number)[]): Vocabulary<T> | undefined;
268
+ /**
269
+ * Merge a caller's dictionary into a built-in one.
270
+ *
271
+ * Caller entries are appended, so every built-in figure stays reachable, except
272
+ * where a caller entry carries the id of a built-in: that one is a replacement
273
+ * and takes the built-in's place, which is how a caller corrects a figure it
274
+ * disagrees with rather than having both offered.
275
+ *
276
+ * @param builtIn The library's own entries.
277
+ * @param supplied The caller's entries, if any.
278
+ * @returns The merged dictionary, built-ins first.
279
+ *
280
+ * @category Composition
281
+ */
282
+ declare function mergeVocabulary<T>(builtIn: readonly Vocabulary<T>[], supplied: readonly Vocabulary<T>[] | undefined): Vocabulary<T>[];
283
+ /**
284
+ * Narrow a mixed dictionary to the entries one part understands.
285
+ *
286
+ * A context carries a single list, because a caller thinks in terms of "the
287
+ * vocabulary of this piece" rather than of one list per generator. Each
288
+ * generator recognises its own material by shape, so an entry meant for the
289
+ * bass is invisible to the drums instead of being mis-read by it.
290
+ *
291
+ * @param entries The mixed dictionary.
292
+ * @param isMaterial Guard recognising one kind of material.
293
+ * @returns The entries whose material the guard accepts.
294
+ *
295
+ * @category Composition
296
+ */
297
+ declare function vocabularyOfKind<T>(entries: readonly Vocabulary<unknown>[], isMaterial: (material: unknown) => material is T): Vocabulary<T>[];
298
+ /**
299
+ * Reject a dictionary entry whose declared fields are outside their domains.
300
+ *
301
+ * Applied to caller-supplied entries at the point they enter a generator: an
302
+ * entry with a difficulty of 40 would otherwise pass every ceiling and be
303
+ * chosen for a beginner's part.
304
+ *
305
+ * @param entry The entry to check.
306
+ * @param label Name used in the error message.
307
+ * @returns The entry, unchanged.
308
+ * @throws If the difficulty is outside 1..5 or the tempo band is inverted.
309
+ *
310
+ * @category Composition
311
+ */
312
+ declare function assertVocabulary<T>(entry: Vocabulary<T>, label?: string): Vocabulary<T>;
313
+
314
+ /**
315
+ * The generation context: one seed, one set of dials, one tempo, shared by
316
+ * every generator.
317
+ *
318
+ * Before it, each generator carried its own idea of "how involved should this
319
+ * be" — a 0..1 density here, a style name there, a boolean somewhere else — and
320
+ * only the drums knew the tempo. A context names those things once, so a piece
321
+ * can be asked for at a given complexity in one place, and every part derives
322
+ * its own randomness from the same project seed.
323
+ */
324
+
325
+ /**
326
+ * How involved the generated music should be, on axes that do not imply one
327
+ * another.
328
+ *
329
+ * The first three ask for more of something and are continuous: moving one of
330
+ * them adds material without disturbing what is already sounding.
331
+ * {@link Complexity.difficulty} is not one of those — it is a ceiling, and it
332
+ * only ever takes candidates away.
333
+ *
334
+ * @category Composition
335
+ */
336
+ type Complexity = {
337
+ /** Subdivision and syncopation, in [0, 1]. */
338
+ rhythmic?: number;
339
+ /** Tension, substitution and passing chords, in [0, 1]. */
340
+ harmonic?: number;
341
+ /** Ghosts, flams and decoration, in [0, 1]. */
342
+ ornament?: number;
343
+ /**
344
+ * The hardest the result may be to play, from 1 (a beginner's part) to 5 (at
345
+ * the limit of the instrument). It is a ceiling rather than a strength:
346
+ * "involved but easy" and "plain but hard" are both real requests, so this
347
+ * filters what the other three proposed instead of scaling it. It governs the
348
+ * timing layer alone — whether the note exists on the instrument, and whether
349
+ * the shape can be held, follow from {@link GenerationContext.instruments} and
350
+ * apply whatever the ceiling says.
351
+ */
352
+ difficulty?: number;
353
+ };
354
+ /**
355
+ * Everything a generator needs that is not about the notes themselves.
356
+ *
357
+ * @category Composition
358
+ */
359
+ type GenerationContext = {
360
+ /**
361
+ * The project seed every part derives its own randomness from. Optional, and
362
+ * zero when left out: a context naming only a tempo is a whole request, and
363
+ * requiring the seed beside it would make the commonest context unwritable
364
+ * now that it is the only place a seed can go.
365
+ */
366
+ seed?: number;
367
+ /** The dials; see {@link Complexity}. */
368
+ complexity?: Complexity;
369
+ /**
370
+ * Draw from this source instead of one derived from `seed`. Each part still
371
+ * addresses its own namespace, so parts do not collide.
372
+ */
373
+ rng?: PositionalRng;
374
+ /**
375
+ * The instruments the parts are written for, keyed by part name — `'bass'`,
376
+ * `'drums'`. Naming one is itself the request that the part be playable on
377
+ * it, so its range and physical limits always apply.
378
+ */
379
+ instruments?: Record<string, InstrumentProfile>;
380
+ /**
381
+ * Tempo in quarter-note beats per minute. Without it no generator can judge
382
+ * whether a passage is reachable in the time available, so a ceiling on
383
+ * difficulty has nothing to measure against.
384
+ */
385
+ bpm?: number;
386
+ /**
387
+ * The algorithm version to generate under; defaults to the version this build
388
+ * produces. See {@link resolveAlgorithmVersion} for what the number promises.
389
+ */
390
+ algorithmVersion?: number;
391
+ /**
392
+ * Figures this piece may draw on, over and above the library's own.
393
+ *
394
+ * Genres are endless, which is the reason the vocabulary is data at all: a
395
+ * caller brings the dictionary for the music it is writing instead of waiting
396
+ * for the library to grow one. Entries for every part travel in one list —
397
+ * each generator recognises its own material by shape — and an entry carrying
398
+ * the id of a built-in replaces it rather than being offered alongside.
399
+ */
400
+ vocabulary?: readonly Vocabulary<unknown>[];
401
+ };
402
+ /**
403
+ * A context, or just the seed for one.
404
+ *
405
+ * A bare number is sugar for `{ seed }`: the common case is a caller who wants
406
+ * reproducible output and nothing else.
407
+ *
408
+ * @category Composition
409
+ */
410
+ type GenerationContextInput = GenerationContext | number;
411
+ /**
412
+ * A context with everything resolved: dials validated, tempo and ceiling
413
+ * settled, and a positional source ready for each part.
414
+ */
415
+ type ResolvedContext = {
416
+ seed: number;
417
+ /** Requested rhythmic density, or undefined when the caller named none. */
418
+ rhythmic: number | undefined;
419
+ /** Requested harmonic richness, or undefined when the caller named none. */
420
+ harmonic: number | undefined;
421
+ /** Requested ornament density, or undefined when the caller named none. */
422
+ ornament: number | undefined;
423
+ /** The difficulty ceiling, or undefined for no ceiling. */
424
+ difficulty: number | undefined;
425
+ /** Tempo in BPM, or undefined when the caller named none. */
426
+ bpm: number | undefined;
427
+ /** The resolved algorithm version. */
428
+ algorithmVersion: number;
429
+ /** The profile written for a part, if one was named for it. */
430
+ instrument: (part: string) => InstrumentProfile | undefined;
431
+ /** The figures the caller brought, validated; empty when it brought none. */
432
+ vocabulary: readonly Vocabulary<unknown>[];
433
+ /** The position-addressed samplers for a part. */
434
+ part: (name: string) => Draw;
435
+ };
436
+ /**
437
+ * Resolve a context (or a bare seed) into the form the generators use.
438
+ *
439
+ * The algorithm version takes part in every derivation, so two versions never
440
+ * share a draw: pinning one is what makes a saved project reopen as the piece
441
+ * it was, and a version this build does not produce is rejected rather than
442
+ * quietly rendered as another.
443
+ *
444
+ * @param input The context, the seed alone, or nothing.
445
+ * @returns The resolved context.
446
+ * @throws If the seed is not a 32-bit integer, a dial is out of range, the
447
+ * tempo is not positive, or the algorithm version is unknown.
448
+ * @example
449
+ * ```ts
450
+ * import { resolveContext } from '@libraz/libcantus';
451
+ * const ctx = resolveContext({ seed: 42, complexity: { rhythmic: 0.8 }, bpm: 96 });
452
+ * ctx.part('drums').prob(0.5, 'ghost', 1, 2); // the same answer however often it is asked
453
+ * ```
454
+ */
455
+ declare function resolveContext(input?: GenerationContextInput): ResolvedContext;
456
+
457
+ /**
458
+ * The transformation rules that deform a remembered figure into the one this
459
+ * bar needs.
460
+ *
461
+ * The division of labour is the whole point of keeping these separate from the
462
+ * dictionary: **genre selects the material, complexity deforms it, difficulty
463
+ * rejects it.** A transform therefore never consults a genre and never consults
464
+ * a ceiling — it takes the figure it is given and reshapes it, and whether the
465
+ * result is playable is decided afterwards, by {@link withinCeiling}.
466
+ *
467
+ * Every figure is a list of onsets on a sixteenth grid, whatever it is made of,
468
+ * so the rules are written once and used by both the bass and the drums.
469
+ */
470
+
471
+ /** Sixteenth steps in one 4/4 bar; the grid every figure is written on. */
472
+ declare const BAR_STEPS = 16;
473
+ /** Sixteenth steps in one quarter-note beat. */
474
+ declare const BEAT_STEPS = 4;
475
+ /** One sixteenth expressed in quarter-note beats. */
476
+ declare const STEP_BEATS: number;
477
+ /**
478
+ * An onset on the shared sixteenth grid.
479
+ *
480
+ * Both kinds of material are lists of these with their own extra fields, so a
481
+ * transform is generic over the record and only ever reads the fields named
482
+ * here.
483
+ *
484
+ * @category Composition
485
+ */
486
+ type GridEvent = {
487
+ /** Sixteenth-note index from the start of the figure. */
488
+ step: number;
489
+ /** Loudness as a factor of the passage's base velocity. */
490
+ velocity: number;
491
+ /**
492
+ * The voice this onset is played on, where the material has more than one.
493
+ * A figure written for a single voice — a bass lick — leaves it out.
494
+ */
495
+ voice?: string;
496
+ /**
497
+ * The limb that plays it, where the material names one. It outranks
498
+ * {@link GridEvent.voice} as the stream an onset belongs to, since what
499
+ * crowds a player is one limb rather than one drum.
500
+ */
501
+ limb?: string;
502
+ };
503
+ /**
504
+ * How strongly a position on the sixteenth grid is felt, from 4 (the downbeat)
505
+ * to 0 (an off sixteenth).
506
+ *
507
+ * This is the ranking the thinning rule works down: the notes a player drops
508
+ * first when asked for something easier are the ones carrying the least of the
509
+ * metre. The ranking is the meter's own — {@link metricWeight} says which
510
+ * positions are the downbeat, a secondary strong pulse, and a plain main pulse,
511
+ * and the two ranks below them are the pulse's first subdivision and everything
512
+ * off it. In 4/4 that is the downbeat, the half bar, the other quarters, the
513
+ * quavers and the semiquavers; in 6/8 it is the two dotted-quarter pulses, then
514
+ * the quavers, and the quarter-note positions a 4/4 reading would rank above
515
+ * them fall where they belong, between the beats.
516
+ *
517
+ * @param step Sixteenth index from the start of the figure.
518
+ * @param ts The meter the figure is counted in, in any form that names one.
519
+ * Asked for rather than defaulted: the built-in figures are written on a 4/4
520
+ * grid, but a caller working in 7/8 who leaves it out has no way to hear that
521
+ * the ranking they got was somebody else's bar.
522
+ * @returns The weight, 0 to 4.
523
+ *
524
+ * @category Composition
525
+ */
526
+ declare function gridMetricWeight(step: number, ts: MeterLike): number;
527
+ /**
528
+ * Drop the notes carrying the least of the metre.
529
+ *
530
+ * The easing direction: at 0 nothing is dropped, and as the amount rises whole
531
+ * ranks of positions go, off sixteenths first and the downbeat last. It is a
532
+ * ranking rather than a sampling, so the same amount always removes the same
533
+ * notes and a caller can explain which ones went.
534
+ *
535
+ * @param events The figure.
536
+ * @param amount How much to thin, in [0, 1].
537
+ * @param ts The meter the figure is counted in, in any form that names one.
538
+ * The ranks are the meter's, so a full turn of the dial leaves the downbeats
539
+ * of the bar the figure is actually in — which is why it is asked for rather
540
+ * than assumed.
541
+ * @returns The surviving events, in the order given.
542
+ *
543
+ * @category Composition
544
+ */
545
+ declare function thin<T extends GridEvent>(events: readonly T[], amount: number, ts: MeterLike): T[];
546
+ /**
547
+ * Fill in the gaps of a figure, one note per gap.
548
+ *
549
+ * Doubling is what a player does when asked for more of the same rather than
550
+ * for something different: the added note sits halfway between two onsets of
551
+ * one stream (the limb, else the voice), takes its predecessor's identity, and
552
+ * is played softer. A gap between two limbs is no gap for either of them.
553
+ *
554
+ * @param events The figure, which need not be sorted.
555
+ * @param spanSteps Length of the figure in sixteenths.
556
+ * @returns The figure with the midpoints filled, sorted by position.
557
+ *
558
+ * @category Composition
559
+ */
560
+ declare function double<T extends GridEvent>(events: readonly T[], spanSteps?: number): T[];
561
+ /**
562
+ * Stretch a figure to twice its length: everything falls half as often.
563
+ *
564
+ * @param events The figure.
565
+ * @param spanSteps Length of the figure in sixteenths; notes stretched past it
566
+ * are dropped, since the bar is the bar however the figure is felt.
567
+ * @returns The stretched figure.
568
+ *
569
+ * @category Composition
570
+ */
571
+ declare function halfTime<T extends GridEvent>(events: readonly T[], spanSteps?: number): T[];
572
+ /**
573
+ * Compress a figure to half its length and play it twice.
574
+ *
575
+ * The repeat is what makes this the mirror of {@link halfTime} rather than a
576
+ * figure with a hole in it: the bar stays full.
577
+ *
578
+ * A whole step halves onto the nearest sixteenth; an onset off the straight
579
+ * grid, a triplet, halves exactly and stays on its own grid.
580
+ *
581
+ * Halving brings positions together, and two onsets of one stream landing on
582
+ * the same step are one stroke played louder rather than two: a drum struck
583
+ * twice at the same instant is a pair of note-ons a reader turns into a hung or
584
+ * cut note, so the pair is merged and the louder of the two is what sounds.
585
+ * Streams stay apart, since two limbs striking together is a chord and not a
586
+ * repeat.
587
+ *
588
+ * @param events The figure.
589
+ * @param spanSteps Length of the figure in sixteenths.
590
+ * @returns The compressed figure, repeated to fill the span, at most one event
591
+ * per stream and step.
592
+ *
593
+ * @category Composition
594
+ */
595
+ declare function doubleTime<T extends GridEvent>(events: readonly T[], spanSteps?: number): T[];
596
+ /**
597
+ * How much a figure is syncopated, and the meter it is felt in.
598
+ *
599
+ * @category Composition
600
+ */
601
+ type SyncopateOptions = {
602
+ /** How much syncopation, in [0, 1]. */
603
+ amount: number;
604
+ /**
605
+ * The meter the figure is counted in, in any form that names one; 4/4 when
606
+ * none is named.
607
+ */
608
+ ts?: MeterLike;
609
+ };
610
+ /**
611
+ * Anticipate beats, one sixteenth early.
612
+ *
613
+ * Anticipation is the direction syncopation runs in every genre this library
614
+ * names: the note arrives before the beat it belongs to. It is written as an
615
+ * addition rather than a displacement — the anticipating stroke is softer, and
616
+ * the note it anticipates stays where it was, the way a player ties into the
617
+ * beat rather than abandoning it — because this is one of the dials that only
618
+ * ever add material. Displacing instead would move onsets around under the
619
+ * finger of anyone who puts the dial on a slider, and a saved project reopened
620
+ * one notch along would not contain the piece it was. Which beats are
621
+ * anticipated is fixed by position, so the bar next door is unaffected either
622
+ * way.
623
+ *
624
+ * A position already taken blocks the anticipation only within the same stream
625
+ * — the same limb, else the same voice. A ghost snare sitting where the hi-hat
626
+ * wants to anticipate is another hand playing, not an obstacle, and whether two
627
+ * limbs can actually strike together is the playability layer's question rather
628
+ * than this one's.
629
+ *
630
+ * @param events The figure.
631
+ * @param amount How much syncopation, in [0, 1], or the amount together with
632
+ * the meter the figure is counted in. The path is variadic, so the meter is
633
+ * named here rather than after it; naming none reads the figure in 4/4, as
634
+ * every built-in figure is written.
635
+ * @param draw The position-addressed sampler.
636
+ * @param path Where the figure sits, so the same bar always syncopates alike.
637
+ * @returns The figure with its anticipations, sorted by position.
638
+ *
639
+ * @category Composition
640
+ */
641
+ declare function syncopate<T extends GridEvent>(events: readonly T[], amount: number | SyncopateOptions, draw: Draw, ...path: readonly (string | number)[]): T[];
642
+ /**
643
+ * How much decoration a figure keeps.
644
+ *
645
+ * A decorated note — a ghost, a flam, anything the figure marks as ornament —
646
+ * survives on its own draw, so raising the dial only ever brings more of them
647
+ * back and never disturbs the ones already sounding. Notes that are not
648
+ * decoration are untouched.
649
+ *
650
+ * @param events The figure.
651
+ * @param isOrnament Which events count as decoration.
652
+ * @param amount The ornament dial, in [0, 1].
653
+ * @param draw The position-addressed sampler.
654
+ * @param path Where the figure sits.
655
+ * @returns The figure with the surviving decoration.
656
+ *
657
+ * @category Composition
658
+ */
659
+ declare function ornamentBy<T extends GridEvent>(events: readonly T[], isOrnament: (event: T) => boolean, amount: number, draw: Draw, ...path: readonly (string | number)[]): T[];
660
+ /**
661
+ * Everything the complexity dials do to a figure, in one pass.
662
+ *
663
+ * @category Composition
664
+ */
665
+ type DeformOptions = {
666
+ /**
667
+ * Subdivision and syncopation, in [0, 1]. Below the neutral middle the figure
668
+ * is thinned; above it, syncopated. The middle leaves it as the dictionary
669
+ * wrote it, which is what makes the dictionary the thing a reader can check.
670
+ */
671
+ rhythmic?: number;
672
+ /** Ghosts and decoration, in [0, 1]; absent keeps every ornament. */
673
+ ornament?: number;
674
+ /** Which events are decoration, for the ornament dial. */
675
+ isOrnament?: (event: GridEvent) => boolean;
676
+ /**
677
+ * Rate: stretch or compress the figure before the dials are applied. It is
678
+ * named for what it does to the note values, since "feel" elsewhere in the
679
+ * drum surface names the swing a figure is played with — a different
680
+ * question, asked of the same figure.
681
+ */
682
+ rate?: 'straight' | 'half' | 'double';
683
+ /** Length of the figure in sixteenths. */
684
+ spanSteps?: number;
685
+ /**
686
+ * The meter the figure is counted in, in any form that names one; 4/4 when
687
+ * none is named, which is the bar every built-in figure is written on.
688
+ *
689
+ * The dials rank a figure's positions by how much of the metre each carries,
690
+ * so a figure written in another meter has to name it or it is thinned and
691
+ * syncopated against accents its own bar does not have.
692
+ */
693
+ ts?: MeterLike;
694
+ };
695
+ /**
696
+ * Apply the complexity dials to a figure.
697
+ *
698
+ * This is the one place complexity touches vocabulary: genre has already chosen
699
+ * the material, and the ceiling has not been consulted yet.
700
+ *
701
+ * @param events The figure.
702
+ * @param opts What the dials say.
703
+ * @param draw The position-addressed sampler.
704
+ * @param path Where the figure sits.
705
+ * @returns The deformed figure, sorted by position.
706
+ *
707
+ * @example
708
+ * ```ts
709
+ * import { deform, resolveContext } from '@libraz/libcantus';
710
+ * const figure = [
711
+ * { step: 0, velocity: 1, limb: 'kick' },
712
+ * { step: 4, velocity: 0.9, limb: 'snare' },
713
+ * { step: 8, velocity: 1, limb: 'kick' },
714
+ * { step: 12, velocity: 0.9, limb: 'snare' },
715
+ * ];
716
+ * const draw = resolveContext(7).part('drums');
717
+ * const busier = deform(figure, { rhythmic: 0.9 }, draw, 'bar', 0);
718
+ * // Above the neutral middle the figure is syncopated: onsets are added off
719
+ * // the beat, and the result comes back sorted by position.
720
+ * busier.length; // 6
721
+ * busier.map((event) => event.step); // [0, 3, 4, 8, 11, 12]
722
+ * ```
723
+ *
724
+ * @category Composition
725
+ */
726
+ declare function deform<T extends GridEvent>(events: readonly T[], opts: DeformOptions, draw: Draw, ...path: readonly (string | number)[]): T[];
727
+ /**
728
+ * Whether a figure is inside the difficulty ceiling at this tempo.
729
+ *
730
+ * The ceiling is measured against the closest pair of onsets the figure asks
731
+ * one player for, which is the thing that actually stops a hand — so the pairs
732
+ * are counted within a stream (the limb, else the voice) rather than across the
733
+ * whole kit, because a hi-hat and a kick a sixteenth apart are two limbs and not
734
+ * one hand playing twice. A figure that fails is rejected — never quietly
735
+ * simplified, because a simplified figure is a different figure and the caller
736
+ * asked for this one.
737
+ *
738
+ * @param events The figure.
739
+ * @param bpm Tempo, or undefined when the caller gave none.
740
+ * @param difficulty The ceiling, or undefined for no ceiling.
741
+ * @returns True when the figure is playable at the ceiling, and whenever either
742
+ * the ceiling or the tempo is unknown.
743
+ *
744
+ * @category Composition
745
+ */
746
+ declare function withinCeiling(events: readonly GridEvent[], bpm: number | undefined, difficulty: number | undefined): boolean;
747
+
748
+ /**
749
+ * Deterministic bass-line generation over a chord placement.
750
+ *
751
+ * Given a sequence of chord segments and a key, this builds a monophonic bass
752
+ * line in a chosen low register. Several idiomatic styles are supported, from a
753
+ * single held root per segment to a quarter-note walking line that leads by
754
+ * step into each chord change. Root-position chord tones are kept in an
755
+ * octave-wide bass band `[low, low + 12]`. A slash chord's other tones sit up to
756
+ * an octave above its placed bass, so they can rise past the top of the band,
757
+ * and the `pop` octave pickup and the walking approach notes leave the band by
758
+ * design; consecutive notes can therefore lie more than an octave apart. Given
759
+ * a seed the output is fully reproducible.
760
+ *
761
+ * Positions and durations are measured in quarter-note beats, matching the
762
+ * library-wide convention.
763
+ */
764
+
765
+ /**
766
+ * A chord sounding over a half-open beat span `[startBeat, endBeat)`.
767
+ *
768
+ * The same record {@link ChordSegment} names, so a timeline segment can be fed
769
+ * straight to the bass generator.
770
+ *
771
+ * @category Composition
772
+ */
773
+ type BassSegment = ChordSegment;
774
+ /**
775
+ * Every bass-line idiom, in declaration order.
776
+ *
777
+ * @category Composition
778
+ */
779
+ declare const BASS_STYLES: readonly ["root", "rootFifth", "pop", "walking", "arpeggio"];
780
+ /**
781
+ * The bass-line idiom to generate.
782
+ *
783
+ * @category Composition
784
+ */
785
+ type BassStyle = (typeof BASS_STYLES)[number];
786
+ /**
787
+ * Options controlling {@link generateBassLine}.
788
+ *
789
+ * @category Composition
790
+ */
791
+ type BassLineOptions = {
792
+ /**
793
+ * Chord placement to follow; need not be pre-sorted. Each segment's chord may
794
+ * be written as a chord symbol as well as given as chord data.
795
+ */
796
+ segments: readonly (Omit<BassSegment, 'chord'> & {
797
+ chord: ChordLike;
798
+ })[];
799
+ /**
800
+ * Key/scale context, used for diatonic approach tones in `walking`. A key
801
+ * name such as `'C major'` is read as that key.
802
+ */
803
+ key: KeyLike;
804
+ /**
805
+ * Time signature; used for metric accents.
806
+ *
807
+ * @defaultValue `{ numerator: 4, denominator: 4 }`
808
+ */
809
+ ts?: MeterLike;
810
+ /**
811
+ * Bass-line idiom.
812
+ *
813
+ * @defaultValue `'root'`
814
+ */
815
+ style?: BassStyle;
816
+ /**
817
+ * Target register as a base MIDI octave; roots land around `octave*12+12`.
818
+ * An octave pickup in the `pop` style may drop a note into the octave below
819
+ * that band, which is where such a pickup belongs, or take the octave above
820
+ * instead on an instrument with nothing below the band to drop into.
821
+ *
822
+ * @defaultValue 2
823
+ */
824
+ octave?: number;
825
+ /**
826
+ * The instrument the line is written for. Giving one is itself the request
827
+ * that the line be playable on it: `octave` then says where in that
828
+ * instrument to aim rather than which absolute band to use, and where the two
829
+ * disagree the instrument wins — a note below the lowest string comes back an
830
+ * octave up, the way a player would take it. Leave it out for a programmed
831
+ * part, which is generated exactly as before.
832
+ */
833
+ instrument?: StringedProfile;
834
+ /**
835
+ * The generation context. Its `complexity.rhythmic` sets how often the `pop`
836
+ * style takes a weak-beat pickup, its `instruments.bass` names the instrument
837
+ * when `instrument` does not, its `bpm` together with
838
+ * `complexity.difficulty` keeps leaps the hand could not make in time out of
839
+ * the line, and its `seed` fixes every deterministic choice the line makes.
840
+ *
841
+ * @defaultValue `{ seed: 0 }`
842
+ */
843
+ ctx?: GenerationContextInput;
844
+ /**
845
+ * Maximum number of segments, and of notes, {@link generateBassLine} may
846
+ * work through. The line is built segment by segment, so this is the guard
847
+ * against an unbounded caller rather than a limit on any search.
848
+ *
849
+ * @defaultValue 1000000
850
+ */
851
+ budget?: number;
852
+ };
853
+ /**
854
+ * Generate a bass line following a chord placement.
855
+ *
856
+ * Each segment contributes notes in the chosen bass register per the selected
857
+ * style. Root-position chord tones lie in the `[low, low + 12]` band; a slash
858
+ * chord's other tones sit up to an octave above its placed bass, and the `pop`
859
+ * octave pickup and the walking approach notes leave the band, so consecutive
860
+ * notes can be more than an octave apart. Every note's duration extends to the
861
+ * next onset (the final note extends to the last segment's end). Given a seed
862
+ * the output is fully reproducible.
863
+ *
864
+ * The `pop` style's pickups are drawn per position, so raising
865
+ * `complexity.rhythmic` adds pickups without moving the notes already written.
866
+ *
867
+ * With an `instrument` the line is written for that instrument: the register
868
+ * band is moved into its range and any note still outside comes back an octave,
869
+ * so every pitch has a fret. Nothing is dropped or replaced — the rhythm and
870
+ * the note count are the same either way.
871
+ *
872
+ * @param opts Segments, key, and generation options.
873
+ * @returns Bass notes sorted by onset, non-overlapping.
874
+ *
875
+ * @example
876
+ * ```ts
877
+ * import { generateBassLine, makeChord, majorKey } from '@libraz/libcantus';
878
+ * const segments = [
879
+ * { startBeat: 0, endBeat: 4, chord: makeChord(0, 'maj') },
880
+ * { startBeat: 4, endBeat: 8, chord: makeChord(7, 'maj') },
881
+ * ];
882
+ * const notes = generateBassLine({ segments, key: majorKey(0), style: 'walking' });
883
+ * ```
884
+ *
885
+ * @category Composition
886
+ */
887
+ declare function generateBassLine(opts: BassLineOptions): NoteEvent[];
888
+
889
+ /**
890
+ * Options controlling {@link generateCounterMelody}.
891
+ *
892
+ * @category Voicing & Counterpoint
893
+ */
894
+ type CounterMelodyOptions = {
895
+ /** The lead line to write against, in ascending onset order. */
896
+ melody: readonly NoteEvent[];
897
+ /**
898
+ * The harmony to write against. A timeline carries its own segment
899
+ * boundaries, so a chord change anywhere — including off the generator's
900
+ * half-beat probe grid — is seen; prefer it over `chordAt`.
901
+ *
902
+ * Exactly one of `timeline` and `chordAt` is required; `timeline` wins when
903
+ * both are given.
904
+ */
905
+ timeline?: ChordTimeline;
906
+ /**
907
+ * Chord sounding at an absolute beat position, or null when none applies.
908
+ *
909
+ * A callback is opaque: the generator cannot see where it changes, so it
910
+ * probes a half-beat grid and otherwise relies on `chordChangeBeats`. A held
911
+ * counter note that spans an unseen change is not checked against the new
912
+ * chord.
913
+ */
914
+ chordAt?: (beat: number) => Chord | null;
915
+ /**
916
+ * Exact chord-change beats the `chordAt` callback does not expose. Ignored
917
+ * when `timeline` is given, since a timeline lists its own boundaries.
918
+ */
919
+ chordChangeBeats?: number[];
920
+ /**
921
+ * Key/scale context for scale-tone decisions. A key name such as `'C major'`
922
+ * is read as that key.
923
+ */
924
+ key: KeyLike;
925
+ /**
926
+ * Meter used for strong-beat decisions, in any form that names one.
927
+ *
928
+ * @defaultValue 4/4
929
+ */
930
+ ts?: MeterLike;
931
+ /**
932
+ * Which side of the melody the counter line occupies.
933
+ *
934
+ * @defaultValue 'below'
935
+ */
936
+ register?: 'above' | 'below';
937
+ /**
938
+ * Onset strategy: `'complement'` moves where the melody holds or rests and
939
+ * reinforces some strong beats; `'follow'` mirrors melody onsets.
940
+ *
941
+ * @defaultValue 'complement'
942
+ */
943
+ rhythm?: 'complement' | 'follow';
944
+ /**
945
+ * Style profile applied to candidate pitches. It sets what is rejected
946
+ * outright and, through {@link PROFILE_WEIGHTS}, what is preferred among the
947
+ * candidates that remain: `'strict'` seeks contrary motion and avoids
948
+ * similar, `'pop'` treats a run of parallel thirds or sixths as the harmony
949
+ * line an arranger would write.
950
+ *
951
+ * @defaultValue 'pop'
952
+ */
953
+ profile?: 'strict' | 'pop';
954
+ /**
955
+ * Per-field overrides of the profile's ranking weights, for a preference the
956
+ * two stock profiles do not express — a line that should leap more freely, or
957
+ * one that should hold a pedal wherever it can. Every field named must be a
958
+ * finite number.
959
+ */
960
+ weights?: Partial<ProfileWeights>;
961
+ /** Lowest MIDI pitch the counter line may use (default derived from `register`). */
962
+ pitchLow?: number;
963
+ /** Highest MIDI pitch the counter line may use (default derived from `register`). */
964
+ pitchHigh?: number;
965
+ /**
966
+ * The generation context, so the counter line is drawn from the same project
967
+ * source as every other part and no two parts collide.
968
+ *
969
+ * Its `seed` places the `'complement'` onsets and breaks ties between equally
970
+ * good candidate pitches; the same seed always yields the same line. Where the
971
+ * constraints leave only one good answer — which is common with
972
+ * `rhythm: 'follow'`, whose onsets are fixed by the melody — changing the seed
973
+ * changes nothing.
974
+ *
975
+ * @defaultValue `{ seed: 0 }`
976
+ */
977
+ ctx?: GenerationContextInput;
978
+ };
979
+ /**
980
+ * Generate a counter melody against a lead line.
981
+ *
982
+ * Onsets are chosen per `rhythm`: `'follow'` places one counter note on each
983
+ * melody onset; `'complement'` fills melody rests and sustains and reinforces
984
+ * an occasional strong beat, spaced at least a beat apart. Each onset's pitch
985
+ * is picked from the safe pitches in the counter register (chord tones and
986
+ * consonant tensions against the sounding melody note), rejecting candidates
987
+ * that would form a parallel perfect interval with the melody or sit on the
988
+ * wrong side of it, then ranked by the profile's weights — which is where the
989
+ * two styles part company: `'strict'` prefers contrary motion and penalizes
990
+ * similar, `'pop'` rewards a run of parallel thirds or sixths and is content
991
+ * with a pedal. Ties are broken by a seeded perturbation far
992
+ * below any real score difference (see `TIE_BREAK_JITTER`), so the same
993
+ * seed always yields the same line while a different seed can only reshuffle
994
+ * candidates that were already equally good. Notes extend to the next counter
995
+ * onset (the last to the melody's end) at a velocity slightly under the melody.
996
+ *
997
+ * @param opts The lead line, chord context callback, key, and generation knobs.
998
+ * @returns The counter line as note events sorted by onset; `[]` for an empty melody.
999
+ * @throws If an option names a value outside its range — including a weight
1000
+ * override that is not a finite number, which is rejected before any
1001
+ * candidate is scored rather than absorbed into the ranking.
1002
+ * @example
1003
+ * ```ts
1004
+ * import { generateCounterMelody, majorKey, parseChordSymbol } from '@libraz/libcantus';
1005
+ * const melody = [{ pitch: 72, startBeat: 0, durationBeat: 2 }];
1006
+ * const counter = generateCounterMelody({
1007
+ * melody,
1008
+ * chordAt: () => parseChordSymbol('C'),
1009
+ * key: majorKey(0),
1010
+ * }); // note events below the melody, in onset order
1011
+ * ```
1012
+ * @category Voicing & Counterpoint
1013
+ */
1014
+ declare function generateCounterMelody(opts: CounterMelodyOptions): NoteEvent[];
1015
+
1016
+ /**
1017
+ * The percussion voices the generator emits, as General MIDI note numbers.
1018
+ *
1019
+ * A {@link DrumHit} carries only its pitch, so splitting a kit across tracks —
1020
+ * kick to one, snare to another — means comparing against these numbers. They
1021
+ * are published so that comparison is a named constant covered by semver
1022
+ * rather than a hard-coded 36.
1023
+ *
1024
+ * @example
1025
+ * ```ts
1026
+ * import { DRUM_NOTES, generateDrums } from '@libraz/libcantus';
1027
+ * const hits = generateDrums({
1028
+ * bars: 1,
1029
+ * style: 'standard',
1030
+ * section: 'verse',
1031
+ * ctx: { bpm: 120, complexity: { rhythmic: 0.5 } },
1032
+ * });
1033
+ * const kick = hits.filter((hit) => hit.pitch === DRUM_NOTES.kick);
1034
+ * ```
1035
+ * @category Composition
1036
+ */
1037
+ declare const DRUM_NOTES: Readonly<{
1038
+ readonly kick: 36;
1039
+ readonly snare: 38;
1040
+ readonly sideStick: 37;
1041
+ readonly handClap: 39;
1042
+ readonly closedHiHat: 42;
1043
+ readonly pedalHiHat: 44;
1044
+ readonly openHiHat: 46;
1045
+ readonly crash: 49;
1046
+ readonly ride: 51;
1047
+ readonly tambourine: 54;
1048
+ readonly highTom: 50;
1049
+ readonly midTom: 47;
1050
+ readonly lowTom: 45;
1051
+ readonly shaker: 82;
1052
+ }>;
1053
+ /**
1054
+ * A percussion voice name, one key of {@link DRUM_NOTES}.
1055
+ *
1056
+ * @category Composition
1057
+ */
1058
+ type DrumVoice = keyof typeof DRUM_NOTES;
1059
+ /**
1060
+ * The voice a percussion note number names.
1061
+ *
1062
+ * @param pitch The General MIDI note number.
1063
+ * @returns The voice, or undefined for a note this generator never emits.
1064
+ * @category Composition
1065
+ */
1066
+ declare function drumVoiceOf(pitch: number): DrumVoice | undefined;
1067
+ /**
1068
+ * A single percussion onset.
1069
+ *
1070
+ * @category Composition
1071
+ */
1072
+ type DrumHit = {
1073
+ /** General MIDI note number; {@link drumVoiceOf} names it. */
1074
+ pitch: number;
1075
+ startBeat: number;
1076
+ durationBeat: number;
1077
+ velocity: number;
1078
+ /**
1079
+ * How the stroke is played, when it is more than a plain hit. A flam is one
1080
+ * onset carrying `'flam'`, not a pair of notes a fraction of a beat apart, so
1081
+ * the grace stroke is the reader's to place — as a second note, a key switch,
1082
+ * or a sample layer — and any pattern can carry one.
1083
+ */
1084
+ articulation?: Articulation;
1085
+ };
1086
+
1087
+ /**
1088
+ * A Euclidean (Bjorklund) kick pattern for {@link generateDrums}.
1089
+ *
1090
+ * @category Composition
1091
+ */
1092
+ type EuclideanKick = {
1093
+ /** Number of kick onsets, clamped to `[0, steps]`. */
1094
+ pulses: number;
1095
+ /**
1096
+ * Total steps in the bar (1..16).
1097
+ *
1098
+ * @defaultValue 16
1099
+ */
1100
+ steps?: number;
1101
+ /**
1102
+ * Steps to rotate the onsets toward later positions.
1103
+ *
1104
+ * @defaultValue 0
1105
+ */
1106
+ rotation?: number;
1107
+ };
1108
+ /**
1109
+ * Options controlling {@link generateDrums}.
1110
+ *
1111
+ * @category Composition
1112
+ */
1113
+ type DrumsOptions = {
1114
+ /**
1115
+ * Number of bars to generate.
1116
+ */
1117
+ bars: number;
1118
+ style: GrooveStyle;
1119
+ section: Section;
1120
+ /**
1121
+ * Time signature.
1122
+ *
1123
+ * Only 4/4 is accepted: every shape this generator writes — the backbeat, the
1124
+ * hi-hat subdivisions, the open-hat and crash beats, the beat a fill starts on
1125
+ * — is written against a four-beat bar, so another meter would come back with
1126
+ * 4/4 accents in a bar of the wrong length and no sign that anything was
1127
+ * wrong. A meter it cannot place is refused rather than mis-placed, and a
1128
+ * meter map is read whole: one that opens in 4/4 and changes later is refused
1129
+ * for the change, not accepted for the opening. Use {@link generateRhythm} or
1130
+ * {@link placeDrumPattern} for other meters.
1131
+ *
1132
+ * @defaultValue `{ numerator: 4, denominator: 4 }`
1133
+ */
1134
+ ts?: MeterLike;
1135
+ /**
1136
+ * Replace the final bar with a fill.
1137
+ *
1138
+ * A pre-chorus leading into a chorus builds instead: the two-bar lift takes
1139
+ * precedence over the fill, since the buildup already marks the phrase end.
1140
+ * Set `nextSection` to anything but `'chorus'` to get the fill.
1141
+ *
1142
+ * @defaultValue false
1143
+ */
1144
+ fills?: boolean;
1145
+ /**
1146
+ * The swing the groove is played with. Naming one is taken at its word by
1147
+ * every style, including the ones whose own character is straight: a feel the
1148
+ * caller asked for and did not get is worse than one it has to ask for twice.
1149
+ * Left out, the style's own feel applies.
1150
+ */
1151
+ feel?: GrooveFeel;
1152
+ /**
1153
+ * Voicing role, from busiest to sparsest:
1154
+ *
1155
+ * - `'full'`: every voice, backbeat snare at full weight.
1156
+ * - `'ambient'`: side-stick backbeat, ride instead of hi-hat.
1157
+ * - `'minimal'`: side-stick backbeat quieter still, pedal hi-hat, no
1158
+ * auxiliary percussion.
1159
+ * - `'fxOnly'`: no kick, snare, ghost notes, timekeeping hi-hat, or fills —
1160
+ * only the fx and auxiliary voices.
1161
+ *
1162
+ * Roles express orchestration priority and peak dynamics, not a strict hit
1163
+ * count: style-specific ride, foot-hi-hat, and auxiliary patterns may make a
1164
+ * sparser role emit more individual onsets in a particular bar.
1165
+ *
1166
+ * @defaultValue `'full'`
1167
+ */
1168
+ role?: DrumRole;
1169
+ /**
1170
+ * The generation context: the tempo, the complexity dials, and the kit this
1171
+ * part is written for.
1172
+ *
1173
+ * `bpm` is the tempo in quarter-note beats per minute. `complexity.rhythmic`
1174
+ * is how busy the backing is, in [0, 1]; the dial is continuous, so every
1175
+ * value moves the result and raising it only adds onsets — the ones already
1176
+ * sounding stay where they were. `complexity.ornament` sets how many ghost
1177
+ * notes survive, `complexity.difficulty` caps how fast the generator writes,
1178
+ * `instruments.drums` — a percussion profile — restricts the output to voices
1179
+ * that kit actually has, and `seed` fixes every deterministic choice.
1180
+ *
1181
+ * @defaultValue `{ seed: 0, bpm: 120, complexity: { rhythmic: 0.5 } }`
1182
+ */
1183
+ ctx?: GenerationContextInput;
1184
+ /**
1185
+ * Section the final-bar fill leads into. Shapes which fill archetype is
1186
+ * chosen (into-chorus and out-of-intro fills differ from generic ones).
1187
+ * Defaults to `section`, i.e. a within-section fill.
1188
+ */
1189
+ nextSection?: Section;
1190
+ /**
1191
+ * When set, the kick follows this Euclidean rhythm instead of the
1192
+ * style/section pattern, giving direct access to evenly spread onsets.
1193
+ */
1194
+ euclideanKick?: EuclideanKick;
1195
+ /**
1196
+ * Maximum number of onsets {@link generateDrums} may write. Generation is
1197
+ * linear in bar count, so this is the guard against an unbounded caller
1198
+ * rather than a limit on any search.
1199
+ *
1200
+ * @defaultValue 1000000
1201
+ */
1202
+ budget?: number;
1203
+ };
1204
+ /**
1205
+ * Generate a drum performance as a flat list of onsets.
1206
+ *
1207
+ * Every voice (kick, snare, ghost snares, closed/open/foot hi-hats, ride, toms,
1208
+ * crash, and auxiliary percussion) is emitted as a {@link DrumHit} distinguished
1209
+ * by its General MIDI pitch. Groove style selects an internal style and feel;
1210
+ * `complexity.rhythmic` sets the backing-density level; `section` shapes kick,
1211
+ * hi-hat, ghost, and percussion density. 16th-note hi-hats drop to 8ths at or
1212
+ * above 150 BPM. When `fills` is true the final bar is replaced with a fill whose
1213
+ * archetype is shaped by `nextSection`; a fill that would emit nothing on its
1214
+ * beat falls back to the normal groove so the phrase end is never silent.
1215
+ * `euclideanKick` overrides the kick with an evenly-spread Euclidean pattern.
1216
+ * Output is fully determined by the options plus the context's seed.
1217
+ *
1218
+ * The patterns are 4/4 only — backbeats, hi-hat subdivisions, and fills are all
1219
+ * written against a four-beat bar — so beat positions are quarter notes and bar
1220
+ * `n` starts at beat `4n`.
1221
+ *
1222
+ * @param opts Generation options.
1223
+ * @returns Percussion onsets in onset order, ties broken by pitch.
1224
+ *
1225
+ * @example
1226
+ * ```ts
1227
+ * import { generateDrums } from '@libraz/libcantus';
1228
+ * const hits = generateDrums({
1229
+ * bars: 4,
1230
+ * style: 'standard',
1231
+ * section: 'chorus',
1232
+ * fills: true,
1233
+ * ctx: { seed: 0, bpm: 120, complexity: { rhythmic: 0.6 } },
1234
+ * });
1235
+ * // Fully determined by the options plus the context's seed (defaults to 0).
1236
+ * ```
1237
+ *
1238
+ * @category Composition
1239
+ */
1240
+ declare function generateDrums(opts: DrumsOptions): DrumHit[];
1241
+
1242
+ /**
1243
+ * Groove and humanization: nudging quantized note events toward a more human
1244
+ * feel, and capturing/replaying the timing-and-velocity "feel" of a
1245
+ * performance as a reusable groove template.
1246
+ *
1247
+ * Positions and durations are measured in quarter-note beats, matching the
1248
+ * library-wide convention. Randomness, where used, always goes through the
1249
+ * seeded PRNG from the `random` module so results are fully reproducible.
1250
+ */
1251
+
1252
+ /**
1253
+ * Options controlling {@link humanize}.
1254
+ *
1255
+ * @category Rhythm & Meter
1256
+ */
1257
+ type HumanizeOptions = {
1258
+ /**
1259
+ * Time signature used to derive metric accents, in any form that names one.
1260
+ * A meter map is read bar by bar, so a note after a change is accented in the
1261
+ * signature in force where it sounds.
1262
+ *
1263
+ * @defaultValue 4/4
1264
+ */
1265
+ ts?: MeterLike;
1266
+ /**
1267
+ * Maximum timing jitter in quarter-note beats, applied as ±this value.
1268
+ *
1269
+ * @defaultValue 0.02
1270
+ */
1271
+ timing?: number;
1272
+ /**
1273
+ * Maximum velocity jitter (MIDI units), applied as ±this value.
1274
+ *
1275
+ * @defaultValue 8
1276
+ */
1277
+ velocity?: number;
1278
+ /**
1279
+ * How much louder strong beats get relative to weak ones, in MIDI velocity units.
1280
+ *
1281
+ * @defaultValue 12
1282
+ */
1283
+ accent?: number;
1284
+ /**
1285
+ * Velocity assumed for events with no `velocity` of their own.
1286
+ *
1287
+ * @defaultValue 80
1288
+ */
1289
+ baseVelocity?: number;
1290
+ /**
1291
+ * The generation context, so one project seed covers this call as well as the
1292
+ * generators that wrote the notes. Its `seed` fixes the jitter, so the same
1293
+ * seed always humanizes the same way.
1294
+ *
1295
+ * @defaultValue `{ seed: 0 }`
1296
+ */
1297
+ ctx?: GenerationContextInput;
1298
+ /**
1299
+ * The name this call draws under. Humanizing two parts from one context with
1300
+ * the same name gives notes at the same position and pitch the same jitter,
1301
+ * which is what a doubled line does not want; naming each part keeps them
1302
+ * independent.
1303
+ *
1304
+ * @defaultValue `'humanize'`
1305
+ */
1306
+ part?: string;
1307
+ };
1308
+ /**
1309
+ * Humanize a sequence of note events by nudging their timing and velocity
1310
+ * with small, deterministic (seeded) randomness plus a metric-accent shape:
1311
+ * events on strong beats (see {@link metricWeight}) come out louder on
1312
+ * average than events on weak ones.
1313
+ *
1314
+ * Each returned event is a copy; `startBeat` is jittered within
1315
+ * `[-timing, +timing]` beats — not floored at 0, because a pickup sounds before
1316
+ * the downbeat and flooring it there would play two upbeats as one — and
1317
+ * `velocity` is the event's own velocity (or `baseVelocity` if it has none) plus an
1318
+ * accent term scaled by the event's metric weight plus a jitter within
1319
+ * `[-velocity, +velocity]`, clamped to `[1, 127]` and rounded. The metric
1320
+ * weight is computed from each event's original (pre-jitter) `startBeat`.
1321
+ * `pitch` and `durationBeat` pass through unchanged, and the output keeps the
1322
+ * input order.
1323
+ *
1324
+ * The jitter is drawn from the generation context, addressed by the event's own
1325
+ * onset and pitch rather than by its position in the array: an event added or
1326
+ * removed leaves every other event's jitter exactly where it was, and a part
1327
+ * humanized under its own name is independent of the others sharing the seed.
1328
+ *
1329
+ * @param events The events to humanize.
1330
+ * @param opts Humanization options.
1331
+ * @returns Humanized copies of `events`, in input order.
1332
+ * @example
1333
+ * ```ts
1334
+ * import { humanize } from '@libraz/libcantus';
1335
+ * const events = [{ pitch: 60, startBeat: 0, durationBeat: 1, velocity: 80 }];
1336
+ * humanize(events, { ctx: 1, timing: 0.03 }); // copies with jittered timing and accented velocity
1337
+ * humanize(events, { ctx: { seed: 42 }, part: 'lead' }); // under a project context
1338
+ * ```
1339
+ * Notes with a zero or negative duration never sound and are dropped, so the
1340
+ * result can be shorter than the input.
1341
+ *
1342
+ * @category Rhythm & Meter
1343
+ */
1344
+ declare function humanize(events: readonly NoteEvent[], opts?: HumanizeOptions): NoteEvent[];
1345
+ /**
1346
+ * The recorded feel at a single grid slot: an average timing deviation and velocity.
1347
+ *
1348
+ * @category Rhythm & Meter
1349
+ */
1350
+ type GrooveSlot = {
1351
+ /** Average `actualStartBeat - quantizedBeat` (in quarter-note beats) for events landing on this slot. */
1352
+ timingOffset: number;
1353
+ /**
1354
+ * Average velocity of events landing on this slot, or `null` if no event
1355
+ * with a velocity did. `null` (not 0) is the "unrecorded" sentinel so that a
1356
+ * genuine velocity of 0 is preserved and applied like any other value.
1357
+ */
1358
+ velocity: number | null;
1359
+ };
1360
+ /**
1361
+ * A per-bar grid of timing and velocity deviations captured from a performance.
1362
+ *
1363
+ * @category Rhythm & Meter
1364
+ */
1365
+ type GrooveTemplate = {
1366
+ /** Grid resolution: equal grid steps per quarter-note beat. */
1367
+ subdivision: number;
1368
+ /** Number of grid slots per bar (`beatsPerBar(ts) * subdivision`). */
1369
+ slotsPerBar: number;
1370
+ /** One entry per grid slot, in slot-index order (slot 0 is the downbeat). */
1371
+ slots: GrooveSlot[];
1372
+ /**
1373
+ * The time signature the template was extracted under. {@link applyGrooveTemplate}
1374
+ * requires the apply-time meter to match this so the per-bar grid lines up
1375
+ * instead of silently drifting. Optional for backward compatibility with
1376
+ * templates constructed without it (in which case no check is performed).
1377
+ */
1378
+ ts?: TimeSignature;
1379
+ };
1380
+ /**
1381
+ * Extract a groove template from a set of note events: for each grid slot,
1382
+ * the average timing deviation from the quantized grid and the average
1383
+ * velocity of events landing on it. Slots with no velocity-carrying event
1384
+ * record `velocity: null` (the "unrecorded" sentinel); empty slots default to
1385
+ * `{ timingOffset: 0, velocity: null }`. The time signature is stored on the
1386
+ * template so {@link applyGrooveTemplate} can verify the meter matches.
1387
+ *
1388
+ * @param events The (typically "groovy", human-played) events to analyze.
1389
+ * @param ts The time signature, used to compute the bar length. A meter map
1390
+ * is accepted while it keeps one signature throughout.
1391
+ * @param subdivision Grid resolution: equal grid steps per quarter-note beat.
1392
+ * Defaults to a sixteenth-note grid, which is where the timing deviations a
1393
+ * template records — swing, push, drag — are audible.
1394
+ * @returns The extracted groove template.
1395
+ * @throws If `ts` changes signature.
1396
+ * @category Rhythm & Meter
1397
+ */
1398
+ declare function extractGrooveTemplate(events: readonly NoteEvent[], ts: MeterLike, subdivision?: number): GrooveTemplate;
1399
+ /**
1400
+ * Apply a groove template to a set of (typically quantized) note events: each
1401
+ * event is snapped to its grid slot and then offset by that slot's recorded
1402
+ * timing deviation, pushing stiff timing toward the template's feel.
1403
+ * Velocity is set to the slot's recorded average when it recorded one (a
1404
+ * non-`null` velocity, including a genuine 0); otherwise the event's own
1405
+ * velocity is left untouched.
1406
+ * Non-positive-duration input artefacts are omitted, so output positions do
1407
+ * not retain a one-to-one correspondence with the input array.
1408
+ *
1409
+ * If the template carries a time signature (see {@link GrooveTemplate.ts}) it
1410
+ * must match `ts`, since a differing bar length would misalign the per-bar
1411
+ * grid and drift the feel; a mismatch throws rather than corrupting timing
1412
+ * silently. `slotsPerBar` is held to the same standard, since it is what the
1413
+ * grid is read through: a template built by hand whose count does not match the
1414
+ * bar would send a note past the end of the grid and land it on the next bar's
1415
+ * downbeat. What the slots carry is checked too, so nothing this returns is a
1416
+ * note event the rest of the library would refuse.
1417
+ *
1418
+ * @param events The events to reshape.
1419
+ * @param template The groove template, from {@link extractGrooveTemplate}.
1420
+ * @param ts The time signature, used to compute the bar length. A meter map
1421
+ * is accepted while it keeps one signature throughout.
1422
+ * @returns Reshaped copies of `events`, in input order.
1423
+ * @throws If `ts` changes signature, if `template.ts` is set and does not
1424
+ * match `ts`, if `slotsPerBar` is not the number of slots a bar of `ts` holds
1425
+ * at the template's subdivision, or if a slot carries a non-finite offset or
1426
+ * a velocity outside [0, 127].
1427
+ * @example
1428
+ * ```ts
1429
+ * import { extractGrooveTemplate, applyGrooveTemplate, parseTimeSignature } from '@libraz/libcantus';
1430
+ * const ts = parseTimeSignature('4/4');
1431
+ * // Learn the feel from a loosely played performance...
1432
+ * const groovy = [
1433
+ * { pitch: 36, startBeat: 0.02, durationBeat: 1, velocity: 100 },
1434
+ * { pitch: 38, startBeat: 1.06, durationBeat: 1, velocity: 70 },
1435
+ * ];
1436
+ * const template = extractGrooveTemplate(groovy, ts, 4);
1437
+ * // ...then impose it on stiff, quantized events.
1438
+ * const quantized = [{ pitch: 36, startBeat: 0, durationBeat: 1, velocity: 80 }];
1439
+ * applyGrooveTemplate(quantized, template, ts); // events nudged toward the captured feel
1440
+ * ```
1441
+ * @category Rhythm & Meter
1442
+ */
1443
+ declare function applyGrooveTemplate(events: readonly NoteEvent[], template: GrooveTemplate, ts: MeterLike): NoteEvent[];
1444
+
1445
+ /**
1446
+ * Every production style a preset may suit, in declaration order.
1447
+ *
1448
+ * Written as a table rather than only as a union so the names exist at run time:
1449
+ * a union is checked when the caller compiles, and a style arriving from a
1450
+ * config file or a JavaScript caller is checked against this.
1451
+ */
1452
+ declare const PROG_STYLES: readonly ["minimal", "dance", "idol", "rock"];
1453
+ /**
1454
+ * Broad production style a progression preset suits.
1455
+ *
1456
+ * @category Composition
1457
+ */
1458
+ type ProgStyle = (typeof PROG_STYLES)[number];
1459
+ /**
1460
+ * Harmonic-function role of a progression as a whole.
1461
+ *
1462
+ * @category Composition
1463
+ */
1464
+ type ProgFunction = 'loop' | 'tensionBuild' | 'cadenceStrong' | 'stable';
1465
+ /**
1466
+ * A named chord-progression preset expressed in scale degrees.
1467
+ *
1468
+ * @category Composition
1469
+ */
1470
+ type ProgressionPreset = {
1471
+ id: string;
1472
+ name: string;
1473
+ /**
1474
+ * The chord roots, in order, as {@link ProgressionDegree} codes: 1..7 for the
1475
+ * key's own scale degrees, counted as a musician counts them, and
1476
+ * {@link BORROWED_DEGREES} for the borrowed ones.
1477
+ */
1478
+ degrees: ProgressionDegree[];
1479
+ functional: ProgFunction;
1480
+ styles: ProgStyle[];
1481
+ };
1482
+ /**
1483
+ * The borrowed (non-diatonic) chord roots a preset can name, as their semitone
1484
+ * code for a borrowed degree. These are stable identifiers, not semitone
1485
+ * offsets: their pitch-class offsets are resolved internally.
1486
+ *
1487
+ * Scale degrees 1..7 address the key's own chords; these codes continue the
1488
+ * numbering for the chromatic chords a pop progression borrows, so a preset is
1489
+ * one flat list of degree codes.
1490
+ *
1491
+ * @example
1492
+ * ```ts
1493
+ * import { BORROWED_DEGREES, generateProgression, majorKey } from '@libraz/libcantus';
1494
+ * generateProgression({
1495
+ * key: majorKey(0),
1496
+ * style: 'rock',
1497
+ * bars: 4,
1498
+ * preset: { degrees: [1, BORROWED_DEGREES.bVII, 4, 1] },
1499
+ * });
1500
+ * ```
1501
+ * @category Composition
1502
+ */
1503
+ declare const BORROWED_DEGREES: Readonly<{
1504
+ /** Flat submediant: bVI. */
1505
+ readonly bVI: 8;
1506
+ /** Flat subtonic: bVII. */
1507
+ readonly bVII: 10;
1508
+ /** Flat mediant: bIII. */
1509
+ readonly bIII: 11;
1510
+ /** Minor subdominant borrowed from the parallel minor: iv. */
1511
+ readonly iv: 12;
1512
+ /** Neapolitan: bII. */
1513
+ readonly bII: 13;
1514
+ /** Sharp subdominant, the diminished #IV. */
1515
+ readonly sharpIV: 14;
1516
+ }>;
1517
+ /**
1518
+ * A chord root in a preset: a scale degree 1..7, or one of
1519
+ * {@link BORROWED_DEGREES}.
1520
+ *
1521
+ * @category Composition
1522
+ */
1523
+ type ProgressionDegree = number;
1524
+ /**
1525
+ * Options controlling {@link generateProgression}.
1526
+ *
1527
+ * @category Composition
1528
+ */
1529
+ type ProgressionOptions = {
1530
+ /**
1531
+ * The key the degrees are resolved against; a key name such as `'C major'` is
1532
+ * read as that key.
1533
+ */
1534
+ key: KeyLike;
1535
+ /**
1536
+ * Which pool of built-in presets to choose from. Ignored when `preset` names
1537
+ * the progression outright.
1538
+ */
1539
+ style: ProgStyle;
1540
+ bars: number;
1541
+ /**
1542
+ * The meter the bars are counted in, in any form that names one; a meter map
1543
+ * is read as the signature it opens in. One chord is laid out per bar, so this
1544
+ * is what the chords are spaced by — a chord every three beats in 3/4, every
1545
+ * three in 6/8 — and a progression written against another bar length drifts
1546
+ * off the bar lines of the part it is played under.
1547
+ *
1548
+ * @defaultValue `4/4`
1549
+ */
1550
+ ts?: MeterLike;
1551
+ /** Pick a specific built-in preset by id instead of choosing one by style. */
1552
+ presetId?: string;
1553
+ /**
1554
+ * Use this progression rather than a built-in one. Only `degrees` is
1555
+ * required; see {@link BORROWED_DEGREES} for the non-diatonic codes.
1556
+ */
1557
+ preset?: Partial<ProgressionPreset> & {
1558
+ degrees: ProgressionDegree[];
1559
+ };
1560
+ ext?: ChordQuality | 'auto';
1561
+ /**
1562
+ * The generation context.
1563
+ *
1564
+ * Its `complexity.harmonic` sets how much of the progression is replaced by
1565
+ * the secondary dominant of what follows: 0 — the default — leaves it alone,
1566
+ * 0.5 takes about half of what the voice-leading rules allow, and 1 takes
1567
+ * every one of them. Its `seed` fixes both the preset choice and which chords
1568
+ * are replaced, so the same seed always yields the same progression.
1569
+ *
1570
+ * @defaultValue `{ seed: 0 }`
1571
+ */
1572
+ ctx?: GenerationContextInput;
1573
+ };
1574
+ /**
1575
+ * All built-in progression presets.
1576
+ *
1577
+ * @category Composition
1578
+ */
1579
+ declare function progressions(): ProgressionPreset[];
1580
+ /**
1581
+ * Presets whose style list includes the given style.
1582
+ *
1583
+ * @category Composition
1584
+ */
1585
+ declare function progressionsByStyle(style: ProgStyle): ProgressionPreset[];
1586
+ /**
1587
+ * The preset {@link generateProgression} would choose for a style and seed.
1588
+ *
1589
+ * The choice is otherwise invisible: the generator returns chords, not the
1590
+ * preset it drew them from, so a caller who wants to show or reproduce it has
1591
+ * no way to name it.
1592
+ *
1593
+ * @param style The style pool to choose from.
1594
+ * @param ctx The same context the generator would be given, or the seed alone.
1595
+ * @returns The preset that context selects.
1596
+ * @throws If no preset claims the style.
1597
+ * @example
1598
+ * ```ts
1599
+ * import { pickProgressionPreset } from '@libraz/libcantus';
1600
+ * pickProgressionPreset('dance', 3).name;
1601
+ * ```
1602
+ * @category Composition
1603
+ */
1604
+ declare function pickProgressionPreset(style: ProgStyle, ctx?: GenerationContextInput): ProgressionPreset;
1605
+ /**
1606
+ * Generate a chord progression laid out one chord per bar.
1607
+ *
1608
+ * A preset is chosen by `presetId` when given, otherwise deterministically from
1609
+ * the presets matching `style`, seeded by the context's `seed`. An unknown
1610
+ * `presetId`, or a `style` no preset claims, is a caller error and throws rather
1611
+ * than silently falling back to a random preset. The preset's degrees cycle to
1612
+ * fill `bars`; a bar is one bar of `ts`, so `startBeat` is `barIndex` bars of
1613
+ * it — four beats apart in 4/4, three in 3/4 and in 6/8 alike. Chord
1614
+ * roots come from the key's diatonic scale-degree mapping. When `ext` is
1615
+ * omitted or `'auto'`, each chord takes its diatonic triad quality; otherwise
1616
+ * `ext` is forced on every chord — except a reharmonized chord, which is a
1617
+ * secondary dominant and is therefore always a `dom7`. With
1618
+ * `complexity.harmonic` above 0, some chords are deterministically replaced with
1619
+ * the secondary dominant (V7) of the following chord, flagged with
1620
+ * `secondaryDominant`. Only a chord the key can make a local tonic is given one:
1621
+ * nothing tonicizes a diminished triad, so the supertonic of a minor key takes
1622
+ * no dominant of its own, and a dominant seventh the key already contains
1623
+ * (the tonic seventh of mixolydian) is a native chord rather than an applied
1624
+ * one, so it is not inserted. A chord that already sounds a dominant seventh
1625
+ * onto the next one is left as written.
1626
+ *
1627
+ * @param opts Generation options.
1628
+ * @returns One chord per bar in timeline order.
1629
+ * @throws If `presetId` matches no built-in preset, or `style` matches none.
1630
+ *
1631
+ * @example
1632
+ * ```ts
1633
+ * import { generateProgression, majorKey } from '@libraz/libcantus';
1634
+ * const chords = generateProgression({ key: majorKey(0), style: 'dance', bars: 4 });
1635
+ * // Deterministic for a given seed (defaults to 0); one ChordSpan per bar.
1636
+ * const richer = generateProgression({
1637
+ * key: majorKey(0),
1638
+ * style: 'dance',
1639
+ * bars: 4,
1640
+ * ctx: { seed: 3, complexity: { harmonic: 0.5 } },
1641
+ * });
1642
+ * // Some chords are now the secondary dominant of the chord that follows.
1643
+ * ```
1644
+ *
1645
+ * @category Composition
1646
+ */
1647
+ declare function generateProgression(opts: ProgressionOptions): ChordSpan[];
1648
+
1649
+ /**
1650
+ * What the stages of the harmonizer share: the shapes they pass between them,
1651
+ * the defaults they fall back on, and the two questions about a key that more
1652
+ * than one of them asks.
1653
+ */
1654
+
1655
+ /**
1656
+ * A melody note supplied to the harmonizer: a {@link NoteEvent}.
1657
+ *
1658
+ * @category Reharmonization
1659
+ */
1660
+ type MelodyNote = NoteEvent;
1661
+ /**
1662
+ * Options controlling {@link harmonizeMelody}.
1663
+ *
1664
+ * @category Reharmonization
1665
+ */
1666
+ type HarmonizePlacement = {
1667
+ /**
1668
+ * Move the melody into the key it is harmonized in. The search reports the
1669
+ * shift it chose in `transposeSemitones`; transposing the melody by that many
1670
+ * semitones puts it in the returned `key`, so melody and harmony always agree.
1671
+ *
1672
+ * Use it for a melody notated in one key that has to be sung or played in
1673
+ * another. It never changes register on its own — that is `octaveSearch`.
1674
+ *
1675
+ * @defaultValue false
1676
+ */
1677
+ transposeSearch: boolean;
1678
+ /**
1679
+ * Search octave placements as well, so a melody written too high or too low
1680
+ * is moved into a comfortable register. Octaves leave every pitch class where
1681
+ * it was, so this changes neither the key nor the chords.
1682
+ *
1683
+ * @defaultValue false
1684
+ */
1685
+ octaveSearch: boolean;
1686
+ };
1687
+ /**
1688
+ * Options controlling {@link harmonizeMelody}.
1689
+ *
1690
+ * Only `melody` is required; every other knob has the default a first call
1691
+ * wants.
1692
+ *
1693
+ * @category Reharmonization
1694
+ */
1695
+ type HarmonizeOptions = {
1696
+ /** The melody to harmonize, in any order; it is read in onset order. */
1697
+ melody: readonly MelodyNote[];
1698
+ /**
1699
+ * The key to harmonize in, or `'infer'` to estimate it from the melody's
1700
+ * pitch-class weighting — which is what a caller who has only a melody
1701
+ * wants, and so the default. A key name such as `'C major'` is read as that
1702
+ * key; `'infer'` names no key and always asks for the estimate.
1703
+ *
1704
+ * @defaultValue `'infer'`
1705
+ */
1706
+ key?: KeyLike | 'infer';
1707
+ /**
1708
+ * Length of each chord slot in beats. Harmonization places chords on a fixed
1709
+ * grid of this length — unlike {@link chordTimelineFromNotes}, which searches
1710
+ * for the boundaries an existing piece already implies. Any positive value is
1711
+ * honoured; a value fine enough to make the search explode is rejected by the
1712
+ * generation budget rather than rounded up.
1713
+ *
1714
+ * Left out, it is read from `ts`: half a bar where the half falls on a pulse,
1715
+ * and the whole bar where it does not, so a waltz changes chord on its
1716
+ * downbeats rather than across them. In 4/4 that is one chord per half bar.
1717
+ *
1718
+ * @defaultValue half a bar of `ts` — 2 in 4/4
1719
+ */
1720
+ harmonicRhythm?: number;
1721
+ /**
1722
+ * Time signature the melody is barred in. It weights the metric accents the
1723
+ * chords are chosen against and sets the default chord grid, so a waltz or a
1724
+ * jig is harmonized on its own beats rather than on a 4/4 reading of them.
1725
+ *
1726
+ * @defaultValue `4/4`
1727
+ */
1728
+ ts?: MeterLike;
1729
+ /**
1730
+ * How far beyond the key's own triads the chord vocabulary reaches:
1731
+ * `'diatonic'` uses only them, `'secondaryDominant'` adds the dominants that
1732
+ * tonicize each degree, and `'borrowed'` adds the parallel mode's chords too.
1733
+ *
1734
+ * Sugar for `ctx: { complexity: { harmonic } }` at the three dial positions
1735
+ * these names have always stood for; a context names how far the vocabulary
1736
+ * reaches instead of which of three steps it stops at, and wins where both
1737
+ * are given.
1738
+ *
1739
+ * @defaultValue `'diatonic'`
1740
+ */
1741
+ reharmonize?: 'diatonic' | 'secondaryDominant' | 'borrowed';
1742
+ /**
1743
+ * Whether to search transpositions and octave placements for the melody.
1744
+ * Both are off by default, so the melody is harmonized where it was written.
1745
+ *
1746
+ * @defaultValue both false
1747
+ */
1748
+ placement?: HarmonizePlacement;
1749
+ /**
1750
+ * Beats at which the melody's phrases end, so a longer line closes at each of
1751
+ * them instead of only at its end.
1752
+ *
1753
+ * Naming a beat asks for a close there, and three things follow from it. The
1754
+ * beat divides the chord grid, so the slot the phrase closes in ends where the
1755
+ * phrase does rather than running on into the next one. The harmony moves into
1756
+ * that slot — the chord under a named close is never the chord that was
1757
+ * already sounding, which is what makes the close audible as one. And the note
1758
+ * the phrase comes to rest on is read as a structural tone rather than as an
1759
+ * ornament of the next phrase's first note, so a phrase resting on the tonic
1760
+ * is harmonized by the tonic.
1761
+ *
1762
+ * Which cadence that close forms is still the melody's to decide: a phrase
1763
+ * coming to rest on the tonic over an approach that can carry the dominant
1764
+ * cadences authentically, and one whose approach cannot is harmonized by what
1765
+ * it sounds.
1766
+ *
1767
+ * The melody always closes where it ends, whatever this says; these are the
1768
+ * closes *inside* it. `phrasesFromTimeline` finds the phrases of a line
1769
+ * already labelled with chords, and its `endBeat` values are what this
1770
+ * expects, so a caller harmonizes a whole piece in one call rather than
1771
+ * harmonizing each phrase and joining the results.
1772
+ *
1773
+ * A boundary landing exactly on a chord-slot boundary closes the slot before
1774
+ * it — the beat a phrase ends on is where the next phrase begins.
1775
+ *
1776
+ * @defaultValue none — one close, at the end
1777
+ */
1778
+ phraseEnds?: readonly number[];
1779
+ /**
1780
+ * The generation context. Its `complexity.harmonic` is how far the chord
1781
+ * vocabulary reaches beyond the key's own triads — 0 uses them alone, 0.5 has
1782
+ * every secondary dominant, 1 the parallel mode's chords as well — and its
1783
+ * `seed` drives the deterministic tie-break perturbation.
1784
+ *
1785
+ * @defaultValue `{ seed: 0 }`
1786
+ */
1787
+ ctx?: GenerationContextInput;
1788
+ /**
1789
+ * Upper bound on the work this call may do. The search is one pass per
1790
+ * placement over every pair of candidate chords in every slot, so a long line
1791
+ * harmonized with `placement.transposeSearch` on is what needs this raised.
1792
+ *
1793
+ * @defaultValue {@link DEFAULT_GENERATION_BUDGET}
1794
+ */
1795
+ budget?: number;
1796
+ };
1797
+ /**
1798
+ * The chosen transpose, key, chord path, and per-note roles.
1799
+ *
1800
+ * @category Reharmonization
1801
+ */
1802
+ type HarmonizeResult = {
1803
+ /**
1804
+ * How far the melody was moved, in semitones. Transposing the melody by this
1805
+ * much puts it in `key`, which is the key the chords are in.
1806
+ */
1807
+ transposeSemitones: number;
1808
+ /**
1809
+ * The key the chords are in, whole.
1810
+ *
1811
+ * A key/scale alone says nothing about how it is written, so a result
1812
+ * carrying one would report whichever spelling its pitch classes read best
1813
+ * from, and an Ab minor handed in would come back out a G# minor. It matters
1814
+ * most under `key: 'infer'`, where this is the only account of which key was
1815
+ * chosen and a caller has nothing else to spell the chord spans from.
1816
+ */
1817
+ key: ResolvedKey;
1818
+ /** One span per chord change, each starting on a harmonic-rhythm boundary. */
1819
+ chords: ChordSpan[];
1820
+ /** Each melody note's role in the chord sounding under it, once chosen. */
1821
+ melodyRoles: {
1822
+ noteIndex: number;
1823
+ role: HarmonyRole;
1824
+ }[];
1825
+ };
1826
+
1827
+ /**
1828
+ * A composition plan: what a piece is going to be, before any note is chosen.
1829
+ *
1830
+ * Where a {@link ReferenceProfile} records what an existing piece did, a plan
1831
+ * records what a new one will do — the same structural dimensions (form,
1832
+ * harmony, motif derivation, rhythm), stated as targets a generator can hit
1833
+ * exactly rather than as a reading to approximate. A plan is plain data,
1834
+ * JSON-serializable end to end, and it carries the seed and algorithm version
1835
+ * a generator needs to reproduce the piece it describes: the plan is the
1836
+ * recipe, not a cache of one run of it.
1837
+ */
1838
+
1839
+ /**
1840
+ * Schema version {@link CompositionPlan} is written at.
1841
+ *
1842
+ * {@link assertCompositionPlan} rejects any other value outright rather than
1843
+ * guess at an older shape a caller's stored JSON might be in.
1844
+ *
1845
+ * @category Composition
1846
+ */
1847
+ declare const COMPOSITION_PLAN_VERSION = 1;
1848
+ /**
1849
+ * What a new piece is going to be: its keys, meter and span, the sections and
1850
+ * phrases it is built from, the harmony and motif derivations a generator
1851
+ * fills those phrases with, and the rhythmic target it aims for.
1852
+ *
1853
+ * @category Composition
1854
+ */
1855
+ type CompositionPlan = {
1856
+ /** Schema version this record is written at; see {@link COMPOSITION_PLAN_VERSION}. */
1857
+ planVersion: number;
1858
+ /** The project seed a generator following this plan draws from. */
1859
+ seed: number;
1860
+ /** The algorithm version a generator following this plan runs under. */
1861
+ algorithmVersion: number;
1862
+ /** Keys the piece passes through; index 0 is the home key harmony is read against by default. */
1863
+ keys: ResolvedKey[];
1864
+ /** The piece's meter across the planned span. */
1865
+ meters: MeterMap;
1866
+ /** The planned span. */
1867
+ span: {
1868
+ startBeat: number;
1869
+ endBeat: number;
1870
+ bars: number;
1871
+ };
1872
+ /** Sections, in time order. */
1873
+ sections: PlannedSection[];
1874
+ /** Phrases, in time order. */
1875
+ phrases: PlannedPhrase[];
1876
+ /** The harmonic progression, as a partition of the span. */
1877
+ harmony: PlannedChord[];
1878
+ /** Motifs and how they derive from one another. */
1879
+ motifs: PlannedMotif[];
1880
+ /** The rhythmic target a generator's onset placement aims for. */
1881
+ rhythm: PlannedRhythm;
1882
+ };
1883
+ /**
1884
+ * One planned section: a labelled span of the piece.
1885
+ *
1886
+ * @category Composition
1887
+ */
1888
+ type PlannedSection = {
1889
+ /** The section's label. */
1890
+ label: string;
1891
+ /** First beat of the section. */
1892
+ startBeat: number;
1893
+ /** End of the section, exclusive. */
1894
+ endBeat: number;
1895
+ };
1896
+ /**
1897
+ * One planned phrase: its span, the section it opens in, the cadence and
1898
+ * melodic shape it targets, and the motifs it carries.
1899
+ *
1900
+ * @category Composition
1901
+ */
1902
+ type PlannedPhrase = {
1903
+ /** First beat of the phrase. */
1904
+ startBeat: number;
1905
+ /** End of the phrase, exclusive. */
1906
+ endBeat: number;
1907
+ /** Index into `plan.sections` of the section this phrase's start beat falls in. */
1908
+ section: number | null;
1909
+ /** The cadence the phrase is to end on, or null for none. */
1910
+ cadence: CadenceType | null;
1911
+ /** The phrase's targeted melodic shape. */
1912
+ shape: MelodicContourShape;
1913
+ /** Onset of the phrase's targeted peak, as a fraction of the phrase's length, in [0, 1]. */
1914
+ peakPosition: number;
1915
+ /** The phrase's targeted pitch range and mean, as absolute MIDI pitches. */
1916
+ register: {
1917
+ low: number;
1918
+ high: number;
1919
+ mean: number;
1920
+ };
1921
+ /** Targeted onsets per bar within the phrase; see {@link RhythmAnalysis.onsetDensity}. */
1922
+ onsetDensity: number;
1923
+ /** Indices into `plan.motifs` of every motif statement placed in this phrase. */
1924
+ motifs: number[];
1925
+ };
1926
+ /**
1927
+ * One planned chord, placed against one of the plan's keys.
1928
+ *
1929
+ * @category Composition
1930
+ */
1931
+ type PlannedChord = {
1932
+ /** First beat of the chord. */
1933
+ startBeat: number;
1934
+ /** End of the chord, exclusive. */
1935
+ endBeat: number;
1936
+ /** Index into `plan.keys` of the key this chord is named against. */
1937
+ key: number;
1938
+ /** The chord, as a Roman numeral in that key. */
1939
+ roman: string;
1940
+ };
1941
+ /**
1942
+ * One planned motif statement: a root the generator writes new notes for, or a
1943
+ * derivation the generator obtains from an earlier statement by a named
1944
+ * transformation.
1945
+ *
1946
+ * @category Composition
1947
+ */
1948
+ type PlannedMotif = {
1949
+ /** Index into `plan.phrases` of the phrase this statement is placed in. */
1950
+ phrase: number;
1951
+ /** First beat of the statement. */
1952
+ startBeat: number;
1953
+ /** End of the statement, exclusive. */
1954
+ endBeat: number;
1955
+ /** How many notes the statement carries; a root's generated length, a derivation's inherited from its source. */
1956
+ notes: number;
1957
+ /**
1958
+ * A root's onset-to-onset gaps in beats, `notes - 1` of them, summing to
1959
+ * less than the statement's length: its reference motif's ratios times
1960
+ * {@link ReferenceMotif.unitBeats}. The first note sounds at `startBeat`
1961
+ * and the last lasts to `endBeat`. Null for a root whose onsets a generator
1962
+ * draws from `plan.rhythm`; always null for a derivation, whose rhythm is
1963
+ * its source's under the named transformation.
1964
+ */
1965
+ rhythm: number[] | null;
1966
+ /** Index into `plan.motifs` of the statement this one derives from; null for a root. Always less than this statement's own index. */
1967
+ from: number | null;
1968
+ /**
1969
+ * The named transformation from `from`, or null for a root, or for a
1970
+ * derivation with no named transformation (a variation). Its `semitones`
1971
+ * and `degrees` are the preferred pitch level: a generator may place the
1972
+ * derivation at another level to keep it inside the register and the harmony.
1973
+ */
1974
+ relation: MotifRelationSummary | null;
1975
+ };
1976
+ /**
1977
+ * The rhythmic target a generator's onset placement aims for.
1978
+ *
1979
+ * @category Composition
1980
+ */
1981
+ type PlannedRhythm = {
1982
+ /** Targeted distribution of onsets across metric levels; see {@link RhythmAnalysis.onsetLevels}. */
1983
+ onsetLevels: number[];
1984
+ /** Targeted distribution of inter-onset intervals; see {@link RhythmAnalysis.interOnsetShares}. */
1985
+ interOnsetShares: number[];
1986
+ /** Targeted syncopation, in [0, 1]; see {@link RhythmAnalysis.syncopation}. */
1987
+ syncopation: number;
1988
+ };
1989
+
1990
+ /**
1991
+ * Melody generation from a {@link CompositionPlan}.
1992
+ *
1993
+ * The plan is a hard constraint where the generator is free: every root, every
1994
+ * span no motif covers and every closing note keeps its phrase's register and
1995
+ * offers only the pitches its position class admits — a chord tone on a strong
1996
+ * pulse, a scale tone on a weak one or on a strong one where no chord is
1997
+ * planned, anything in the register off the pulses.
1998
+ * A derived statement is its source replayed through the named relation at the
1999
+ * pitch level that suits its phrase best; there the transformation outranks
2000
+ * the harmony, and the register outranks both. A root takes its plan's onset
2001
+ * gaps, or onsets drawn toward the plan's onset levels and gap shares, and pitches from a
2002
+ * chain search toward the phrase's target curve; each phrase closes on a note
2003
+ * held from its final bar to its end, bent onto its cadence.
2004
+ *
2005
+ * Every draw is addressed by phrase index and absolute beat, and a phrase
2006
+ * reads only its own plan entries and the statements its derivations lead
2007
+ * back to, so changing one phrase's plan leaves every phrase that does not
2008
+ * derive from it sounding as it did.
2009
+ */
2010
+
2011
+ /**
2012
+ * Options controlling {@link generateMelody}.
2013
+ *
2014
+ * @category Composition
2015
+ */
2016
+ type MelodyOptions = {
2017
+ /**
2018
+ * The generation context. Its `seed` and `algorithmVersion` take precedence
2019
+ * over the plan's; whatever it leaves out is read from the plan. A supplied
2020
+ * `rng` is rejected: every onset and tie-break is drawn at an address of
2021
+ * phrase and beat under a seed, which a caller-held source cannot provide.
2022
+ *
2023
+ * @defaultValue the plan's seed and algorithm version
2024
+ */
2025
+ ctx?: GenerationContextInput;
2026
+ /** Upper bound on the onset grid and on the pitch search. */
2027
+ budget?: number;
2028
+ };
2029
+ /**
2030
+ * Write a melody that follows a composition plan.
2031
+ *
2032
+ * Each phrase is written inside its planned register, and every note the
2033
+ * generator chooses freely takes a pitch its position class admits: a chord
2034
+ * tone on a strong pulse, a scale tone on a weak one, any pitch off the pulses.
2035
+ * A root motif takes the onset gaps its plan carries from its start, its last
2036
+ * note lasting to its end, or onsets drawn one after another on the sixteenth
2037
+ * grid toward the plan's onset levels and gap shares; its pitches come from a chain
2038
+ * search that moves by step, recovers from leaps and follows the phrase's
2039
+ * target shape. A derived motif replays its planned relation on the statement
2040
+ * it derives from, starting on its planned beat, at the pitch level inside the
2041
+ * register that best fits the harmony, the target curve and the planned level;
2042
+ * a harmony misfit it keeps is left, and only notes no level brings inside the
2043
+ * register are replaced. A variation keeps its source's rhythm and outer
2044
+ * pitches. The spans no motif covers get drawn onsets at the phrase's density
2045
+ * and searched pitches. In each phrase's final bar, the note sounding at the
2046
+ * downbeat (or the first onset after it) is held to the phrase's end, later
2047
+ * onsets are dropped, and that note is bent onto the tones the phrase's
2048
+ * cadence asks for; a note sounding across the downbeat is cut there, and the
2049
+ * downbeat becomes the held onset, re-chosen from the pitches the downbeat
2050
+ * admits unless a cadence or a derived statement decides it. Onsets fall on the sixteenth grid only, so
2051
+ * triplets never appear.
2052
+ *
2053
+ * Harmony is read from the plan alone, through {@link planTimeline}.
2054
+ *
2055
+ * @param plan The plan to follow; validated first.
2056
+ * @param opts Context and budget.
2057
+ * @returns The melody, in time order.
2058
+ * @throws {InvalidInputError} If the plan, the options or the context are
2059
+ * malformed, or the context supplies an `rng`.
2060
+ * @throws {NoSolutionError} If a phrase's register admits no line, no pitch a
2061
+ * position asks for, no pitch that ends its cadence, or a span more onsets
2062
+ * than its grid holds; `at` is the phrase's start beat.
2063
+ * @throws {BudgetExceededError} If the onset grid or the pitch search would
2064
+ * exceed the budget.
2065
+ * @example
2066
+ * ```ts
2067
+ * import { generateMelody, resolveKey } from '@libraz/libcantus';
2068
+ * import type { CompositionPlan } from '@libraz/libcantus';
2069
+ * const plan: CompositionPlan = {
2070
+ * planVersion: 1, seed: 7, algorithmVersion: 1,
2071
+ * keys: [resolveKey('C major')], meters: [{ startBeat: 0, ts: { numerator: 4, denominator: 4 } }],
2072
+ * span: { startBeat: 0, endBeat: 8, bars: 2 },
2073
+ * sections: [{ label: 'A', startBeat: 0, endBeat: 8 }],
2074
+ * phrases: [{
2075
+ * startBeat: 0, endBeat: 8, section: 0, cadence: 'authentic', shape: 'arch', peakPosition: 0.6,
2076
+ * register: { low: 60, high: 72, mean: 66 }, onsetDensity: 4, motifs: [0],
2077
+ * }],
2078
+ * harmony: [{ startBeat: 0, endBeat: 4, key: 0, roman: 'V' }, { startBeat: 4, endBeat: 8, key: 0, roman: 'I' }],
2079
+ * motifs: [{ phrase: 0, startBeat: 0, endBeat: 4, notes: 4, rhythm: [1, 1, 1], from: null, relation: null }],
2080
+ * rhythm: { onsetLevels: [0, 0, 0, 0, 0, 1], interOnsetShares: new Array(17).fill(0).fill(1, 8, 9), syncopation: 0 },
2081
+ * };
2082
+ * generateMelody(plan); // the same notes on every call
2083
+ * ```
2084
+ * @category Composition
2085
+ */
2086
+ declare function generateMelody(plan: CompositionPlan, opts?: MelodyOptions): NoteEvent[];
2087
+
2088
+ /**
2089
+ * A transformation applicable to a motif cell.
2090
+ *
2091
+ * @category Composition
2092
+ */
2093
+ declare const MOTIF_TRANSFORMS: readonly ["transposeDiatonic", "transposeChromatic", "invert", "retrograde", "augment", "diminish", "sequence"];
2094
+ /**
2095
+ * The name of a transformation {@link transformMotif} can apply to a cell.
2096
+ *
2097
+ * Derived from the table the transforms are dispatched from, so a transform
2098
+ * added to one is named by the other on the same commit.
2099
+ *
2100
+ * @category Composition
2101
+ */
2102
+ type MotifTransform = (typeof MOTIF_TRANSFORMS)[number];
2103
+ /**
2104
+ * A single note within a motif cell.
2105
+ *
2106
+ * @category Composition
2107
+ */
2108
+ type MotifNote = {
2109
+ pitch: number;
2110
+ startBeat: number;
2111
+ durationBeat: number;
2112
+ };
2113
+ /**
2114
+ * A short melodic cell.
2115
+ *
2116
+ * @category Composition
2117
+ */
2118
+ type MotifCell = {
2119
+ notes: MotifNote[];
2120
+ };
2121
+ /**
2122
+ * Melodic contour shape for {@link generateMotif}.
2123
+ *
2124
+ * @category Composition
2125
+ */
2126
+ type MotifContour = 'arch' | 'ascending' | 'descending' | 'wave';
2127
+ /**
2128
+ * Options controlling {@link generateMotif}.
2129
+ *
2130
+ * @category Composition
2131
+ */
2132
+ type MotifOptions = {
2133
+ /** The key the line is written in; a key name such as `'C major'` is read as that key. */
2134
+ key: KeyLike;
2135
+ /**
2136
+ * Chord the downbeats are pulled to, if any; it may be written as a chord
2137
+ * symbol as well as given as chord data.
2138
+ */
2139
+ chord?: ChordLike | null;
2140
+ /** Length of the motif in bars of `ts`. */
2141
+ bars: number;
2142
+ /**
2143
+ * Meter the bars are counted in. It sets the bar length, so a motif shares a
2144
+ * bar grid with the other generators instead of assuming four beats.
2145
+ *
2146
+ * @defaultValue 4/4
2147
+ */
2148
+ ts?: MeterLike;
2149
+ /**
2150
+ * Melodic contour shape the line follows.
2151
+ *
2152
+ * @defaultValue `'arch'`
2153
+ */
2154
+ contour?: MotifContour;
2155
+ /**
2156
+ * Probability in [0, 1] that a note is nudged by a single diatonic step. The
2157
+ * nudge direction is balanced (up or down with equal odds), so it adds
2158
+ * variety without biasing the line off its contour. Default 0, which
2159
+ * reproduces the requested contour exactly (no drift, tails return to tonic).
2160
+ *
2161
+ * Sugar for `ctx: { complexity: { ornament } }` — a nudge off the contour is
2162
+ * decoration rather than rhythm; the context wins where both are given. Being
2163
+ * the same dial, it takes the same values: one outside [0, 1] is rejected here
2164
+ * exactly as it is there, rather than being folded to the nearest end.
2165
+ *
2166
+ * @defaultValue 0
2167
+ * @throws If it is not a finite number in [0, 1].
2168
+ */
2169
+ jitter?: number;
2170
+ /**
2171
+ * The generation context. Its `complexity.ornament` is this generator's
2172
+ * jitter, and its `seed` fixes which notes are nudged.
2173
+ *
2174
+ * @defaultValue `{ seed: 0 }`
2175
+ */
2176
+ ctx?: GenerationContextInput;
2177
+ };
2178
+ /**
2179
+ * Generate a short seed motif over `bars`.
2180
+ *
2181
+ * The melody follows the requested contour in diatonic steps from the tonic,
2182
+ * snapped to the key. When a chord is supplied, notes landing on bar downbeats
2183
+ * are pulled to the nearest chord tone. An optional `jitter` adds balanced
2184
+ * per-note variation without biasing the contour; it is off by default, so the
2185
+ * contour is reproduced exactly. Output is deterministic for a given seed.
2186
+ *
2187
+ * @param opts Key, optional chord, length, contour, jitter, and context.
2188
+ * @returns The generated motif cell.
2189
+ *
2190
+ * @example
2191
+ * ```ts
2192
+ * import { generateMotif, majorKey } from '@libraz/libcantus';
2193
+ * const cell = generateMotif({ key: majorKey(0), bars: 2, contour: 'arch' });
2194
+ * // cell.notes is a deterministic MotifCell (seed defaults to 0)
2195
+ * ```
2196
+ *
2197
+ * @category Composition
2198
+ */
2199
+ declare function generateMotif(opts: MotifOptions): MotifCell;
2200
+ /**
2201
+ * Turn a motif cell into note events.
2202
+ *
2203
+ * A {@link MotifNote} already carries the {@link NoteEvent} fields, but a cell
2204
+ * wraps them in an object; this unwraps it, so a motif can be humanized,
2205
+ * grooved, or written out like any other line.
2206
+ *
2207
+ * @param cell The motif to convert.
2208
+ * @returns The cell's notes, copied, in the order they are stored.
2209
+ * @example
2210
+ * ```ts
2211
+ * import { generateMotif, humanize, majorKey, motifToNoteEvents } from '@libraz/libcantus';
2212
+ * humanize(motifToNoteEvents(generateMotif({ key: majorKey(0), bars: 2 })));
2213
+ * ```
2214
+ * @category Composition
2215
+ */
2216
+ declare function motifToNoteEvents(cell: MotifCell): NoteEvent[];
2217
+ /**
2218
+ * Apply a transformation to a motif cell.
2219
+ *
2220
+ * Every transform hands the cell back in onset order, so the note a later
2221
+ * transform reads as the first one is the note that sounds first.
2222
+ *
2223
+ * `invert` reflects pitches about the earliest note (chromatic, self-inverse);
2224
+ * `retrograde` mirrors onsets about the cell span, preserving rests (self-inverse);
2225
+ * `augment`/`diminish` scale time by `amount ?? 2` and its reciprocal;
2226
+ * `transposeChromatic` adds `amount` semitones; `transposeDiatonic` shifts by
2227
+ * `amount` scale degrees when a `key` is given, or — with no `key` — falls back
2228
+ * to a chromatic shift of `amount` semitones; `sequence` appends a shifted copy
2229
+ * (by `amount` diatonic degrees with a `key`, or by `amount` semitones without
2230
+ * one, since it delegates to `transposeDiatonic`).
2231
+ *
2232
+ * @param cell The cell to transform.
2233
+ * @param t The transformation.
2234
+ * @param amount Optional parameter (semitones, degrees, or time factor).
2235
+ * @param key Key context for the diatonic transforms, as a key name such as
2236
+ * `'C major'` or as a key/scale; without it, `transposeDiatonic` and
2237
+ * `sequence` shift chromatically by semitones.
2238
+ * @returns The transformed cell, its notes in time order whatever order the
2239
+ * source cell was written in, so it can be read as a line.
2240
+ * @throws If a transformed pitch would fall outside the MIDI range 0..127.
2241
+ *
2242
+ * @example
2243
+ * ```ts
2244
+ * import { generateMotif, transformMotif, majorKey } from '@libraz/libcantus';
2245
+ * const cell = generateMotif({ key: majorKey(0), bars: 1 });
2246
+ * const inverted = transformMotif(cell, 'invert');
2247
+ * ```
2248
+ *
2249
+ * @category Composition
2250
+ */
2251
+ declare function transformMotif(cell: MotifCell, t: MotifTransform, amount?: number, key?: KeyLike): MotifCell;
2252
+ /**
2253
+ * Lay a motif across `bars` and snap it to a chord timeline.
2254
+ *
2255
+ * The cell is tiled back-to-back to fill the requested span. Notes that carry
2256
+ * structural weight — the head of each tile and every bar line — are pulled to
2257
+ * the nearest chord tone of the segment sounding at that onset, so the
2258
+ * developed line spells the underlying harmony. The notes between them are kept
2259
+ * in the key as passing and neighbour tones, and two pitches that differ in the
2260
+ * cell still differ in the development, so the development is still recognizably
2261
+ * the motif rather than a chord arpeggiated over the cell's rhythm.
2262
+ *
2263
+ * @param cell The source motif.
2264
+ * @param timeline Chord segments to snap against.
2265
+ * @param key Key context, as a key name such as `'C major'` or as a key/scale;
2266
+ * the notes off the structural positions are kept in it.
2267
+ * @param bars Number of bars to fill.
2268
+ * @param ts Meter the bars are counted in. Asked for rather than defaulted: a
2269
+ * development laid on the wrong bar length drifts off the part it plays
2270
+ * under, and a caller who leaves it out has no way to hear that.
2271
+ * @returns The developed, harmony-aware cell, its notes in time order.
2272
+ *
2273
+ * @example
2274
+ * ```ts
2275
+ * import { chordTimelineFromChords, developMotif, generateMotif, majorKey } from '@libraz/libcantus';
2276
+ * const key = majorKey(0);
2277
+ * const timeline = chordTimelineFromChords([{ rootPc: 0, quality: 'maj', startBeat: 0 }], 8);
2278
+ * const developed = developMotif(generateMotif({ key, bars: 1 }), timeline, key, 2, '4/4');
2279
+ * developed.notes.map((n) => n.pitch); // [60, 62, 60, 60, 62, 60] — the C-D-C cell, twice
2280
+ * ```
2281
+ *
2282
+ * @category Composition
2283
+ */
2284
+ declare function developMotif(cell: MotifCell, timeline: ChordTimeline, key: KeyLike, bars: number, ts: MeterLike): MotifCell;
2285
+
2286
+ /**
2287
+ * Ornaments applied to material that already exists.
2288
+ *
2289
+ * Decoration is not a property of generation: this layer takes notes and gives
2290
+ * notes back, the way {@link humanize} does, so a line from any source — a
2291
+ * generator, a MIDI import, a caller's own array — can be decorated without
2292
+ * being generated again by whichever generator happens to write ghost notes.
2293
+ *
2294
+ * The decoration is carried as an {@link Articulation}, not baked into extra
2295
+ * onsets: a flam is one note marked `'flam'`, so the grace stroke stays the
2296
+ * reader's to voice and nothing downstream has to guess which of two onsets was
2297
+ * the ornament.
2298
+ */
2299
+
2300
+ /**
2301
+ * Every ornament idiom, in declaration order.
2302
+ *
2303
+ * @category Composition
2304
+ */
2305
+ declare const ORNAMENT_STYLES: readonly ["ghost", "flam", "drag", "slide", "accent"];
2306
+ /**
2307
+ * The kind of ornament to apply.
2308
+ *
2309
+ * - `'ghost'`: soften weak-position notes into ghosted strokes.
2310
+ * - `'flam'`: mark accented notes as flammed — the strong positions `'accent'`
2311
+ * also takes, voiced as a grace stroke instead of a velocity lift.
2312
+ * - `'drag'`: mark notes leading into a strong position as dragged. A weak-position
2313
+ * note qualifies only when the next onset in the material falls on a strong one.
2314
+ * - `'slide'`: mark a note reached by a step or a leap as slid into. A repeated
2315
+ * pitch is not: a slide is the move between two pitches, and there is none.
2316
+ * - `'accent'`: mark strong-position notes as accented, and lift their velocity.
2317
+ *
2318
+ * @category Composition
2319
+ */
2320
+ type OrnamentStyle = (typeof ORNAMENT_STYLES)[number];
2321
+ /**
2322
+ * Options controlling {@link ornament}.
2323
+ *
2324
+ * @category Composition
2325
+ */
2326
+ type OrnamentOptions = {
2327
+ /**
2328
+ * The ornament to apply.
2329
+ *
2330
+ * @defaultValue `'ghost'`
2331
+ */
2332
+ style?: OrnamentStyle;
2333
+ /**
2334
+ * How much of the eligible material is decorated, in [0, 1]. Raising it only
2335
+ * ornaments more notes; the notes already ornamented keep the ornament they
2336
+ * had. Defaults to `complexity.ornament` from the context, or 0.5.
2337
+ */
2338
+ amount?: number;
2339
+ /**
2340
+ * Time signature, in any form that names one, used to tell strong positions
2341
+ * from weak ones. A meter map is read bar by bar, so a note after a change
2342
+ * is weighed in the signature in force where it sounds.
2343
+ *
2344
+ * @defaultValue 4/4
2345
+ */
2346
+ ts?: MeterLike;
2347
+ /**
2348
+ * The generation context. Its `complexity.ornament` sets the amount, its
2349
+ * `complexity.difficulty` — with a tempo — keeps ornaments off passages too
2350
+ * fast to play them in, and its `seed` fixes which notes are decorated.
2351
+ *
2352
+ * @defaultValue `{ seed: 0 }`
2353
+ */
2354
+ ctx?: GenerationContextInput;
2355
+ };
2356
+ /**
2357
+ * Decorate existing notes with an ornament.
2358
+ *
2359
+ * Which notes are eligible follows from the style and the meter — ghosts fall on
2360
+ * weak positions, drags on the weak position before a strong one, flams and
2361
+ * accents on strong ones, slides on notes the line moves to, by a step or by a
2362
+ * leap — and `amount`
2363
+ * decides how many of those eligible notes are taken. The choice is addressed by
2364
+ * each note's own position, so raising `amount` adds ornaments without moving the
2365
+ * ones already there, and no onset is ever added or shifted: a decorated note is
2366
+ * the same note carrying an {@link Articulation}. A note that already carries one
2367
+ * is left alone, so ornament passes can be layered.
2368
+ *
2369
+ * With a difficulty ceiling and a tempo in the context, a passage whose strokes
2370
+ * come too fast for that ceiling is left plain — the ornament is exactly the
2371
+ * kind of candidate a ceiling exists to reject.
2372
+ *
2373
+ * @param notes The material to decorate.
2374
+ * @param opts Style, amount, meter, and context.
2375
+ * @returns Copies of the sounding notes, in input order, with ornaments applied.
2376
+ * @example
2377
+ * ```ts
2378
+ * import { generateBassLine, majorKey, makeChord, ornament } from '@libraz/libcantus';
2379
+ * const line = generateBassLine({
2380
+ * segments: [{ startBeat: 0, endBeat: 4, chord: makeChord(0, 'maj') }],
2381
+ * key: majorKey(0),
2382
+ * style: 'pop',
2383
+ * });
2384
+ * ornament(line, { style: 'ghost', amount: 0.4, ctx: 3 });
2385
+ * ```
2386
+ * Notes with a zero or negative duration never sound and are dropped, so the
2387
+ * result can be shorter than the input.
2388
+ *
2389
+ * @category Composition
2390
+ */
2391
+ declare function ornament(notes: readonly NoteEvent[], opts?: OrnamentOptions): NoteEvent[];
2392
+
2393
+ /**
2394
+ * Deriving a {@link CompositionPlan} from a {@link ReferenceProfile}.
2395
+ *
2396
+ * Each structural dimension of the reference is either carried into the plan
2397
+ * or replaced, weighted per dimension by {@link PreserveWeights}. A discrete
2398
+ * item (a section label, a phrase length, a structural chord, a motif
2399
+ * derivation) is kept or replaced whole by a positional draw addressed by that
2400
+ * item's index, so changing one weight or one item never redraws another; a
2401
+ * replacement follows a fixed rule. A continuous item (harmonic rhythm,
2402
+ * register and contour, onset placement) is interpolated between the
2403
+ * reference's value and a neutral one.
2404
+ *
2405
+ * The reference's melodic surface — its motif intervals and phrase outlines —
2406
+ * never reaches the plan: a plan says how motifs derive from one another and
2407
+ * carries a root's onset gaps, not the pitches it sounds.
2408
+ */
2409
+
2410
+ /**
2411
+ * How much of each structural dimension of a reference a derived plan keeps,
2412
+ * each in [0, 1]; an omitted weight is 1.
2413
+ *
2414
+ * @category Composition
2415
+ */
2416
+ type PreserveWeights = {
2417
+ /** Section labels; a replaced section takes its neighbour's label. */
2418
+ form?: number;
2419
+ /** Phrase lengths; a replaced phrase is rounded to a power-of-two bar count. */
2420
+ phraseLengths?: number;
2421
+ /** Structural chords; a replaced chord is another numeral of the same function. */
2422
+ harmonicFunction?: number;
2423
+ /** Where the chords change, interpolated toward one change per bar line. */
2424
+ harmonicRhythm?: number;
2425
+ /** Motif derivations; a replaced derivation becomes a variation of the same source. */
2426
+ motifRelations?: number;
2427
+ /** Phrase contour, peak and register, interpolated toward a neutral arch. */
2428
+ registerShape?: number;
2429
+ /**
2430
+ * Each root's onset gaps, kept per root by a positional draw, and the
2431
+ * onset placement, interpolated toward a level-proportional distribution
2432
+ * without syncopation.
2433
+ */
2434
+ rhythm?: number;
2435
+ };
2436
+ /**
2437
+ * Options for {@link deriveCompositionPlan}.
2438
+ *
2439
+ * @category Composition
2440
+ */
2441
+ type CompositionPlanOptions = {
2442
+ /**
2443
+ * The home key of the plan. Every reference key moves by the interval from
2444
+ * the reference's home tonic to this one, keeping its own variant. Defaults
2445
+ * to the reference's home key; a key of another variant is rejected.
2446
+ */
2447
+ key?: KeyLike;
2448
+ /**
2449
+ * The melody range the plan's phrase registers are mapped onto. Defaults to
2450
+ * the reference's melody range, moved by the nearest shift to the new key.
2451
+ */
2452
+ register?: {
2453
+ low: number;
2454
+ high: number;
2455
+ };
2456
+ /** How much of each dimension of the reference to keep; see {@link PreserveWeights}. */
2457
+ preserve?: PreserveWeights;
2458
+ /**
2459
+ * The seed and algorithm version the plan records. A caller-supplied `rng`
2460
+ * is rejected: a plan has to carry its source as a seed to be reproducible.
2461
+ */
2462
+ ctx?: GenerationContextInput;
2463
+ /** Upper bound on the motif selection. */
2464
+ budget?: number;
2465
+ };
2466
+ /**
2467
+ * Derive a composition plan from a reference profile.
2468
+ *
2469
+ * The plan keeps the reference's meter and span. Its keys are the reference's,
2470
+ * moved to `opts.key` with each key's variant kept, and its phrase registers
2471
+ * are the reference's mapped onto `opts.register`. Each dimension named in
2472
+ * `opts.preserve` is kept, replaced or interpolated by its weight; a draw for
2473
+ * a discrete item is addressed by the dimension and the item's index, so the
2474
+ * same reference, options and seed always give the same plan. The resolved
2475
+ * seed and algorithm version are recorded in the plan.
2476
+ *
2477
+ * @param reference The reference profile to derive from.
2478
+ * @param opts The key, register, preserve weights, generation context and budget.
2479
+ * @returns A plan that passes {@link assertCompositionPlan}.
2480
+ * @throws {InvalidInputError} If the reference is not a valid profile or has
2481
+ * no melody onsets, an option is out of range, `opts.key` is of another
2482
+ * variant than the reference's home key, `opts.ctx` carries an `rng`, or the
2483
+ * default register moved to the new key leaves the MIDI range.
2484
+ * @throws {BudgetExceededError} If the motif selection would exceed the budget.
2485
+ * @category Composition
2486
+ */
2487
+ declare function deriveCompositionPlan(reference: ReferenceProfile, opts?: CompositionPlanOptions): CompositionPlan;
2488
+
2489
+ /**
2490
+ * Checking a candidate melody against the plan it was written for.
2491
+ *
2492
+ * The candidate is read against the plan itself, never re-analyzed: its
2493
+ * phrases are the plan's phrases, its harmony is the plan's through
2494
+ * `planTimeline`, and its derivations are replayed from the candidate's own
2495
+ * source statements. What comes back is never one score: a list of concrete
2496
+ * violations (which are errors and which are only warnings), and a fit reading
2497
+ * per dimension, each measured the way {@link compareReferences} measures two
2498
+ * profiles against each other. Whether the piece is any good is left to the ear.
2499
+ */
2500
+
2501
+ /**
2502
+ * One way a candidate melody departs from its plan.
2503
+ *
2504
+ * @category Composition
2505
+ */
2506
+ type CompositionViolation = {
2507
+ /** What kind of departure this is. */
2508
+ kind: 'span' | 'phraseBoundary' | 'cadence' | 'harmony' | 'motifDerivation' | 'motifDisplaced' | 'register' | 'peakPosition';
2509
+ /** Whether this rules the candidate out, or only flags it. */
2510
+ severity: 'error' | 'warning';
2511
+ /** Where in the candidate this was found. */
2512
+ atBeat: number;
2513
+ /** What the plan called for. */
2514
+ expected: string;
2515
+ /** What the candidate did instead. */
2516
+ actual: string;
2517
+ /** Why this counts as a departure. */
2518
+ rationale: string;
2519
+ };
2520
+ /**
2521
+ * How a candidate melody measures up against its plan: violations that judge
2522
+ * it, and a fit reading per structural dimension.
2523
+ *
2524
+ * There is no aggregate: the fields never fold into one score, the same way
2525
+ * {@link ReferenceComparison} does not.
2526
+ *
2527
+ * @category Composition
2528
+ */
2529
+ type CompositionEvaluation = {
2530
+ /** Concrete departures from the plan, error and warning alike. */
2531
+ violations: CompositionViolation[];
2532
+ /** Likeness of the candidate to the plan, one field per dimension, each phrase read over its planned span. */
2533
+ fit: {
2534
+ /** Likeness of the phrases' melodic outlines to their planned shapes. */
2535
+ contour: number | null;
2536
+ /** Likeness of the phrases' registers to the planned ones. */
2537
+ register: number | null;
2538
+ /** Likeness of where the melody's onsets fall. */
2539
+ onset: number | null;
2540
+ /** Likeness of the melody's inter-onset-interval distribution. */
2541
+ duration: number | null;
2542
+ /** Likeness of the melody's syncopation. */
2543
+ syncopation: number | null;
2544
+ /** Likeness of the melody's onsets per bar to the phrases' planned densities. */
2545
+ density: number | null;
2546
+ };
2547
+ };
2548
+ /** Options for {@link evaluateComposition}. */
2549
+ type EvaluateCompositionOptions = {
2550
+ /**
2551
+ * Upper bound on the work each analysis may do.
2552
+ *
2553
+ * @defaultValue {@link DEFAULT_GENERATION_BUDGET}
2554
+ */
2555
+ budget?: number;
2556
+ };
2557
+ /**
2558
+ * Check a candidate melody against the plan it was written for.
2559
+ *
2560
+ * The candidate is read against the plan itself — its phrases, its harmony
2561
+ * through {@link planTimeline}, its derivations — rather than re-analyzed into
2562
+ * a profile, so every violation and fit reading judges the melody against what
2563
+ * the plan actually calls for.
2564
+ *
2565
+ * Violations name concrete departures at a beat. `span`, `phraseBoundary`,
2566
+ * `cadence`, `register` and `motifDerivation` are errors. `harmony` is an
2567
+ * error, or a warning for a note inside a derived statement, where the
2568
+ * transformation takes precedence. A derived statement passes at any pitch
2569
+ * level its relation admits, with its durations free and its closing and
2570
+ * out-of-register notes excused; `motifDisplaced` warns when that level is not
2571
+ * the planned one or a note was excused. `peakPosition` is a warning. The fit
2572
+ * fields, one per dimension, read each planned phrase of the candidate the way
2573
+ * a reference profile reads its phrases and measure it as
2574
+ * {@link compareReferences} would — never folded into one score.
2575
+ *
2576
+ * @param melody The candidate melody.
2577
+ * @param plan The plan it was written for.
2578
+ * @param opts The work budget.
2579
+ * @returns The violations found and the fit reading.
2580
+ * @throws {InvalidInputError} If the plan or the melody cannot be read.
2581
+ * @throws {BudgetExceededError} If an analysis would exceed the budget.
2582
+ * @example
2583
+ * ```ts
2584
+ * import { evaluateComposition, planTimeline, resolveKey } from '@libraz/libcantus';
2585
+ * import type { CompositionPlan } from '@libraz/libcantus';
2586
+ * const plan: CompositionPlan = {
2587
+ * planVersion: 1, seed: 0, algorithmVersion: 1,
2588
+ * keys: [resolveKey('C major')],
2589
+ * meters: [{ startBeat: 0, ts: { numerator: 4, denominator: 4 } }],
2590
+ * span: { startBeat: 0, endBeat: 4, bars: 1 },
2591
+ * sections: [{ label: 'A', startBeat: 0, endBeat: 4 }],
2592
+ * phrases: [
2593
+ * {
2594
+ * startBeat: 0, endBeat: 4, section: 0, cadence: null, shape: 'ascending',
2595
+ * peakPosition: 0.5, register: { low: 60, high: 67, mean: 64 }, onsetDensity: 4, motifs: [],
2596
+ * },
2597
+ * ],
2598
+ * harmony: [{ startBeat: 0, endBeat: 4, key: 0, roman: 'I' }],
2599
+ * motifs: [],
2600
+ * rhythm: { onsetLevels: [0, 0, 0, 1, 0, 0], interOnsetShares: new Array(17).fill(0).fill(1, 8, 9), syncopation: 0 },
2601
+ * };
2602
+ * const melody = [
2603
+ * { pitch: 60, startBeat: 0, durationBeat: 1 },
2604
+ * { pitch: 64, startBeat: 1, durationBeat: 1 },
2605
+ * { pitch: 67, startBeat: 2, durationBeat: 1 },
2606
+ * { pitch: 60, startBeat: 3, durationBeat: 1 },
2607
+ * ];
2608
+ * evaluateComposition(melody, plan).violations; // []
2609
+ * ```
2610
+ * @category Composition
2611
+ */
2612
+ declare function evaluateComposition(melody: readonly NoteEvent[], plan: CompositionPlan, opts?: EvaluateCompositionOptions): CompositionEvaluation;
2613
+
2614
+ /**
2615
+ * Reharmonization: chord substitution, modal-interchange palettes, and negative
2616
+ * harmony. These transforms take an existing chord (or a key) and propose
2617
+ * alternative harmonies that preserve a chosen relationship — a shared function,
2618
+ * a common tone, or a reflection across the key axis.
2619
+ *
2620
+ * Roots are pitch classes (0..11); no spelled key signature is required. Every
2621
+ * proposed chord nevertheless carries the spelling hints of the key it was asked
2622
+ * for, so a flat-side key names its chromatic chords with flats (the tritone
2623
+ * substitute of G7 in C major is Db7, not C#7).
2624
+ */
2625
+
2626
+ /**
2627
+ * The kind of substitution relationship a candidate realizes.
2628
+ *
2629
+ * An applied dominant is not among them: which dominant applies is decided by
2630
+ * the harmony that follows, and {@link substituteChord} is given one chord and a
2631
+ * key. Build one with `secondaryDominantOf` where the target is known, or let
2632
+ * `harmonizeMelody` open its vocabulary with `reharmonize: 'secondaryDominant'`
2633
+ * where the progression is being chosen as a whole.
2634
+ *
2635
+ * @category Reharmonization
2636
+ */
2637
+ type SubstitutionType = 'tritone' | 'relative' | 'borrowed' | 'chromaticMediant';
2638
+ /**
2639
+ * A proposed chord substitution with its relationship, numeral, and function.
2640
+ *
2641
+ * @category Reharmonization
2642
+ */
2643
+ type Substitution = {
2644
+ chord: Chord;
2645
+ type: SubstitutionType;
2646
+ roman: string;
2647
+ function: HarmonicFunction;
2648
+ };
2649
+ /**
2650
+ * Options controlling which substitutions {@link substituteChord} returns.
2651
+ *
2652
+ * @category Reharmonization
2653
+ */
2654
+ type SubstituteOptions = {
2655
+ /**
2656
+ * Melody pitch classes that must remain chord tones. When given, only
2657
+ * substitutions whose pitch classes contain every listed pitch class are
2658
+ * kept, so the melody stays consonant against the new harmony.
2659
+ */
2660
+ melodyPcs?: number[];
2661
+ };
2662
+ /**
2663
+ * Propose substitutions for a chord within a key.
2664
+ *
2665
+ * Candidates are generated by several relationships and deduplicated against the
2666
+ * original chord and each other:
2667
+ *
2668
+ * - `tritone`: for a dominant-type chord, the dominant seventh a tritone away.
2669
+ * - `relative`: a diatonic triad a third away that shares two common tones.
2670
+ * - `borrowed`: a triad from the parallel mode with the same harmonic function.
2671
+ * - `chromaticMediant`: a major/minor triad a third away sharing one common
2672
+ * tone.
2673
+ *
2674
+ * These four are the whole vocabulary. An applied dominant is not proposed
2675
+ * because the chord it applies to is the one that follows, which a call about a
2676
+ * single chord cannot see; `secondaryDominantOf` builds one from a named target.
2677
+ *
2678
+ * Each result carries its Roman numeral and harmonic function in `key`. When
2679
+ * `opts.melodyPcs` is given, only substitutions whose pitch classes contain all
2680
+ * of those pitch classes are returned.
2681
+ *
2682
+ * Every substitution is spelled the way `key` writes it, as `rootSpelling` and
2683
+ * `bassSpelling` hints, so a flat-side key keeps flat names: in C major the
2684
+ * tritone substitute of G7 formats as `Db7` and its chromatic mediants as `Bb`
2685
+ * and `Eb`. Where the substitution's function and the bare pitch class disagree,
2686
+ * the function decides — a tritone substitute is a bII7 and so is written on the
2687
+ * flattened supertonic of the chord it resolves to, a borrowed chord takes the
2688
+ * spelling of the mode it is borrowed from, and a chromatic mediant is written
2689
+ * on the letter a third from the source root (E's mediants are G#, not Ab).
2690
+ *
2691
+ * @param chord The chord to reharmonize, as a chord symbol or as chord data.
2692
+ * @param key The prevailing key, as a key name or as a key/scale.
2693
+ * @param opts Optional melody-preservation constraint.
2694
+ * @returns The deduplicated substitution candidates.
2695
+ * @example
2696
+ * ```ts
2697
+ * import { substituteChord, makeChord, majorKey, formatChordSymbol } from '@libraz/libcantus';
2698
+ * const subs = substituteChord(makeChord(7, 'dom7'), majorKey(0));
2699
+ * subs
2700
+ * .filter((sub) => sub.type === 'tritone')
2701
+ * .map((sub) => formatChordSymbol(sub.chord)); // ['Db7'] — the bII7 of C major, not 'C#7'
2702
+ * ```
2703
+ * @category Reharmonization
2704
+ */
2705
+ declare function substituteChord(chord: ChordLike, key: SpelledKeyLike, opts?: SubstituteOptions): Substitution[];
2706
+ /**
2707
+ * A borrowed chord in the modal-interchange palette of a key.
2708
+ *
2709
+ * @category Reharmonization
2710
+ */
2711
+ type BorrowedChord = {
2712
+ chord: Chord;
2713
+ roman: string;
2714
+ source: BorrowedSource;
2715
+ };
2716
+ /**
2717
+ * The modal-interchange palette of a key.
2718
+ *
2719
+ * Lists the diatonic triads of the parallel key that are not diatonic to
2720
+ * `key` (the classic borrowed chords such as `iv`, `bVI`, and `bVII` in a major
2721
+ * key), plus the Neapolitan (a major triad on the flat second degree). Each
2722
+ * carries its Roman numeral and {@link borrowedSource} relative to `key`.
2723
+ *
2724
+ * Every chord is spelled as the mode it is borrowed from writes it, recorded as
2725
+ * a `rootSpelling` hint: C major borrows `Fm`, `Ab` and `Bb` from C minor and
2726
+ * takes `Db` as its Neapolitan, while a minor key borrows in the other direction
2727
+ * (A minor borrows `A`, `D` and `F#m` from A major, with `Bb` as its
2728
+ * Neapolitan). The major dominant of a minor key — `E` in A minor — is not among
2729
+ * them: raising the seventh degree is an alteration inside the key rather than a
2730
+ * chord taken from the parallel mode.
2731
+ *
2732
+ * @param key The prevailing key, as a key name or as a key/scale.
2733
+ * @returns The borrowed-chord palette.
2734
+ * @example
2735
+ * ```ts
2736
+ * import { modalInterchangePalette, majorKey, formatChordSymbol } from '@libraz/libcantus';
2737
+ * const palette = modalInterchangePalette(majorKey(0));
2738
+ * palette.map((borrowed) => formatChordSymbol(borrowed.chord));
2739
+ * // ['Cm', 'Ddim', 'Eb', 'Fm', 'Gm', 'Ab', 'Bb', 'Db'] — flat-side, not 'D#'/'G#'/'A#'
2740
+ * ```
2741
+ * @category Reharmonization
2742
+ */
2743
+ declare function modalInterchangePalette(key: SpelledKeyLike): BorrowedChord[];
2744
+ /**
2745
+ * Reflect a chord across the tonic–dominant axis of a key (negative harmony).
2746
+ *
2747
+ * Every pitch class `p` maps to `(2*T + 7 - p) mod 12`, where `T` is the key
2748
+ * tonic — the reflection that swaps the tonic with the dominant. The mirrored
2749
+ * pitch classes (including the bass, if set) are reassembled into a chord by
2750
+ * {@link detectChordBest}; when no chord is recognized, the mirrored root and
2751
+ * the original quality are used as a fallback.
2752
+ *
2753
+ * The result is spelled the way `key` writes it, as `rootSpelling` and
2754
+ * `bassSpelling` hints, so the reflection of a chord in a flat-side key keeps
2755
+ * flat names: in Eb major the mirror of Bb formats as `Abm`, not `G#m`.
2756
+ *
2757
+ * @param chord The chord to reflect, as a chord symbol or as chord data.
2758
+ * @param key The prevailing key, as a key name or as a key/scale.
2759
+ * @returns The negative-harmony counterpart of the chord.
2760
+ * @example
2761
+ * ```ts
2762
+ * import { negativeHarmonyMirror, makeChord, majorKey } from '@libraz/libcantus';
2763
+ * negativeHarmonyMirror(makeChord(7, 'maj'), majorKey(0));
2764
+ * // G major reflected across C's axis => F minor (rootPc 5, quality 'min')
2765
+ * ```
2766
+ * @category Reharmonization
2767
+ */
2768
+ declare function negativeHarmonyMirror(chord: ChordLike, key: SpelledKeyLike): Chord;
2769
+
2770
+ /**
2771
+ * Deterministic rhythm generation over a metric grid.
2772
+ *
2773
+ * Builds a fixed-resolution grid across one or more bars of a time signature
2774
+ * and decides, per grid slot, whether it becomes a note onset. Onset
2775
+ * probability follows the metric-accent hierarchy from the `meter` module, so
2776
+ * strong positions (downbeats, secondary pulses) are favored over weak
2777
+ * off-pulse subdivisions. Given a seed the output is fully reproducible.
2778
+ *
2779
+ * Positions and durations are measured in quarter-note beats, matching the
2780
+ * library-wide convention.
2781
+ */
2782
+
2783
+ /**
2784
+ * A single rhythmic note: an onset position and how long it sounds.
2785
+ *
2786
+ * @category Rhythm & Meter
2787
+ */
2788
+ type RhythmEvent = {
2789
+ /** Onset position in quarter-note beats, absolute from the start of the span. */
2790
+ position: number;
2791
+ /** Duration in quarter-note beats, extending to the next onset. */
2792
+ duration: number;
2793
+ };
2794
+ /**
2795
+ * Turn rhythm events into note events at a fixed pitch.
2796
+ *
2797
+ * {@link RhythmEvent} names its fields `position`/`duration` because a rhythm
2798
+ * has no pitch; every other generator in the library speaks {@link NoteEvent}.
2799
+ * This is the bridge, so a generated rhythm can be humanized, grooved, or
2800
+ * written out like any other line.
2801
+ *
2802
+ * @param events The rhythm events to convert.
2803
+ * @param pitch The MIDI pitch to give every note.
2804
+ * @param velocity Velocity for every note; defaults to a mezzo-forte 96.
2805
+ * @returns The note events, in the order given.
2806
+ * @throws If the pitch or the velocity is not a whole MIDI value in [0, 127], or an event is not
2807
+ * a record with a finite position and duration.
2808
+ * @example
2809
+ * ```ts
2810
+ * import { generateRhythm, humanize, rhythmToNoteEvents } from '@libraz/libcantus';
2811
+ * const rhythm = generateRhythm({ numerator: 4, denominator: 4 }, { bars: 2 });
2812
+ * humanize(rhythmToNoteEvents(rhythm, 38));
2813
+ * ```
2814
+ * @category Rhythm & Meter
2815
+ */
2816
+ declare function rhythmToNoteEvents(events: RhythmEvent[], pitch: number, velocity?: number): NoteEvent[];
2817
+ /**
2818
+ * Options controlling {@link generateRhythm}.
2819
+ *
2820
+ * @category Rhythm & Meter
2821
+ */
2822
+ type RhythmOptions = {
2823
+ /**
2824
+ * Number of bars to generate.
2825
+ *
2826
+ * @defaultValue 1
2827
+ */
2828
+ bars?: number;
2829
+ /**
2830
+ * Grid resolution as the number of equal grid steps per quarter-note beat.
2831
+ * The default of 2 yields an eighth-note grid; 4 yields a sixteenth-note
2832
+ * grid, 3 an eighth-note triplet grid, and so on.
2833
+ *
2834
+ * @defaultValue 2
2835
+ */
2836
+ subdivision?: number;
2837
+ /**
2838
+ * The generation context.
2839
+ *
2840
+ * Its `complexity.rhythmic` is this generator's overall onset density: it
2841
+ * scales the per-slot onset probability, so higher values fill more grid
2842
+ * slots. A value outside [0, 1] is rejected. Its `seed` fixes which slots are
2843
+ * taken, so the same seed always yields the same pattern.
2844
+ *
2845
+ * @defaultValue `{ seed: 0, complexity: { rhythmic: 0.5 } }`
2846
+ */
2847
+ ctx?: GenerationContextInput;
2848
+ };
2849
+ /**
2850
+ * Map a metric weight (0–3 from {@link metricWeight}) to a base onset
2851
+ * probability before density scaling. Strong positions are much more likely to
2852
+ * carry an onset than weak ones; the curve is intentionally small and explicit
2853
+ * so its behavior is easy to inspect and test.
2854
+ *
2855
+ * @param weight The metric weight, 0 (off-pulse) to 3 (downbeat).
2856
+ * @returns A base onset probability in [0, 1].
2857
+ * @category Rhythm & Meter
2858
+ */
2859
+ declare function onsetWeightCurve(weight: number): number;
2860
+ /**
2861
+ * Generate a deterministic rhythmic pattern over `bars` bars of a time
2862
+ * signature. A grid is built at the chosen subdivision; each slot becomes an
2863
+ * onset when the draw belonging to that slot falls under its metric weight
2864
+ * scaled by the density dial. Because the draw belongs to the slot rather than
2865
+ * to the order the slots were visited, raising the dial only adds onsets:
2866
+ * everything already sounding stays where it was. Every bar's downbeat is always
2867
+ * an onset, so a pattern of any length has a reliable pulse independent of the
2868
+ * seed. Each event's duration extends to the next onset, and the last event
2869
+ * extends to the end of the span.
2870
+ *
2871
+ * @param ts The time signature, in any form that names one.
2872
+ * @param opts Generation options.
2873
+ * @returns Onset events sorted by position, non-overlapping, covering the span.
2874
+ * @example
2875
+ * ```ts
2876
+ * import { generateRhythm } from '@libraz/libcantus';
2877
+ * generateRhythm('4/4', { ctx: { seed: 42, complexity: { rhythmic: 0.6 } } });
2878
+ * // onset events over one bar
2879
+ * ```
2880
+ * @category Rhythm & Meter
2881
+ */
2882
+ declare function generateRhythm(ts: MeterLike, opts?: RhythmOptions): RhythmEvent[];
2883
+ /**
2884
+ * Onset density of a generated pattern: the mean number of onsets per bar.
2885
+ *
2886
+ * @param events Events from {@link generateRhythm}.
2887
+ * @param ts The time signature, in any form that names one.
2888
+ * @returns The onset count divided by the number of bars the events span.
2889
+ * @category Rhythm & Meter
2890
+ */
2891
+ declare function rhythmDensity(events: RhythmEvent[], ts: MeterLike): number;
2892
+
2893
+ export { BAR_STEPS as B, COMPOSITION_PLAN_VERSION as C, DRUM_NOTES as D, GENRES as G, ORNAMENT_STYLES as T, PROVENANCE_BASES as W, BASS_STYLES as a, generateRhythm as aA, gridMetricWeight as aB, halfTime as aC, humanize as aD, mergeVocabulary as aE, modalInterchangePalette as aF, motifToNoteEvents as aG, negativeHarmonyMirror as aH, onsetWeightCurve as aI, ornament as aJ, ornamentBy as aK, pickProgressionPreset as aL, pickVocabulary as aM, progressions as aN, progressionsByStyle as aO, resolveContext as aP, rhythmDensity as aQ, rhythmToNoteEvents as aR, selectVocabulary as aS, substituteChord as aT, syncopate as aU, thin as aV, transformMotif as aW, vocabularyOfKind as aX, withinCeiling as aY, STEP_BEATS as ab, applyGrooveTemplate as aj, assertVocabulary as ak, deform as al, deriveCompositionPlan as am, developMotif as an, double as ao, doubleTime as ap, drumVoiceOf as aq, evaluateComposition as ar, extractGrooveTemplate as as, fitsQuery as at, generateBassLine as au, generateCounterMelody as av, generateDrums as aw, generateMelody as ax, generateMotif as ay, generateProgression as az, BEAT_STEPS as b, BORROWED_DEGREES as c };
2894
+ export type { PlannedSection as $, GrooveSlot as A, EuclideanKick as E, GrooveStyle as F, GrooveTemplate as H, HarmonizeOptions as I, HarmonizePlacement as J, HarmonizeResult as K, HumanizeOptions as L, MelodyNote as M, MelodyOptions as N, MotifCell as O, MotifContour as P, MotifNote as Q, MotifOptions as R, MotifTransform as S, OrnamentOptions as U, OrnamentStyle as V, PlannedChord as X, PlannedMotif as Y, PlannedPhrase as Z, PlannedRhythm as _, PreserveWeights as a0, ProgFunction as a1, ProgStyle as a2, ProgressionDegree as a3, ProgressionOptions as a4, ProgressionPreset as a5, Provenance as a6, ProvenanceBasis as a7, ResolvedContext as a8, RhythmEvent as a9, RhythmOptions as aa, Section as ac, SubstituteOptions as ad, Substitution as ae, SubstitutionType as af, SyncopateOptions as ag, Vocabulary as ah, VocabularyQuery as ai, BassLineOptions as d, BassSegment as e, BassStyle as f, BorrowedChord as g, Complexity as h, CompositionEvaluation as i, CompositionPlan as j, CompositionPlanOptions as k, CompositionViolation as l, CounterMelodyOptions as m, DeformOptions as n, Draw as o, DrumHit as p, DrumRole as q, DrumStyle as r, DrumVoice as s, DrumsOptions as t, EvaluateCompositionOptions as u, GenerationContext as v, GenerationContextInput as w, Genre as x, GridEvent as y, GrooveFeel as z };