@libraz/libcantus-wasm 0.0.0-stage → 1.4.1

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