@libraz/libcantus 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +63 -0
- package/README.md +7 -1
- package/README_ja.md +17 -11
- package/dist/analyze/index.cjs +31 -7
- package/dist/analyze/index.cjs.map +1 -1
- package/dist/analyze/index.d.cts +161 -13
- package/dist/analyze/index.d.ts +161 -13
- package/dist/analyze/index.js +37 -13
- package/dist/{chunk-NB25P3EH.js → chunk-2G5MCGYU.js} +33 -11
- package/dist/chunk-2G5MCGYU.js.map +1 -0
- package/dist/{chunk-NM7UAMC3.cjs → chunk-3FDBMIPR.cjs} +64 -64
- package/dist/chunk-3FDBMIPR.cjs.map +1 -0
- package/dist/{chunk-HPVSH7SF.cjs → chunk-3MDOEFIQ.cjs} +618 -954
- package/dist/chunk-3MDOEFIQ.cjs.map +1 -0
- package/dist/{chunk-FBH75DAY.js → chunk-5MWRBYAT.js} +560 -159
- package/dist/chunk-5MWRBYAT.js.map +1 -0
- package/dist/{chunk-J7FHVZII.cjs → chunk-6TTBEON3.cjs} +3074 -740
- package/dist/chunk-6TTBEON3.cjs.map +1 -0
- package/dist/{chunk-UMWZ4ZET.js → chunk-7NQ6AL3H.js} +4 -4
- package/dist/chunk-7NQ6AL3H.js.map +1 -0
- package/dist/{chunk-HWHGOVO6.cjs → chunk-E3QO3UET.cjs} +31 -23
- package/dist/chunk-E3QO3UET.cjs.map +1 -0
- package/dist/{chunk-H2KJHBW4.js → chunk-FJFULJZE.js} +2375 -191
- package/dist/chunk-FJFULJZE.js.map +1 -0
- package/dist/{chunk-Q6LFSAKV.js → chunk-FK3DGAIZ.js} +2657 -323
- package/dist/chunk-FK3DGAIZ.js.map +1 -0
- package/dist/chunk-GEDTJHAC.cjs.map +1 -1
- package/dist/{chunk-RFIBF2RR.js → chunk-H7FVMBUC.js} +138 -65
- package/dist/chunk-H7FVMBUC.js.map +1 -0
- package/dist/{chunk-DSMJRXCZ.cjs → chunk-HYSVSFNI.cjs} +931 -530
- package/dist/chunk-HYSVSFNI.cjs.map +1 -0
- package/dist/{chunk-35NBV2FT.cjs → chunk-KMYGRFZ6.cjs} +47 -24
- package/dist/chunk-KMYGRFZ6.cjs.map +1 -0
- package/dist/chunk-LQZQDBCD.cjs +5513 -0
- package/dist/chunk-LQZQDBCD.cjs.map +1 -0
- package/dist/{chunk-PM4XJE2Y.cjs → chunk-P3CPXAJ5.cjs} +76 -54
- package/dist/chunk-P3CPXAJ5.cjs.map +1 -0
- package/dist/{chunk-S5BKZZGM.cjs → chunk-S3QELJUE.cjs} +72 -56
- package/dist/chunk-S3QELJUE.cjs.map +1 -0
- package/dist/{chunk-PUKJP2Z5.js → chunk-TXFWSU5D.js} +31 -8
- package/dist/chunk-TXFWSU5D.js.map +1 -0
- package/dist/{chunk-76ZBTRG2.cjs → chunk-U4EQTDGN.cjs} +258 -218
- package/dist/chunk-U4EQTDGN.cjs.map +1 -0
- package/dist/chunk-UGLFDG7L.cjs.map +1 -1
- package/dist/{chunk-HYJJ2V2I.js → chunk-UTE5A36R.js} +483 -819
- package/dist/chunk-UTE5A36R.js.map +1 -0
- package/dist/{chunk-NFJ4P6ZZ.js → chunk-UZKQISRF.js} +17 -9
- package/dist/chunk-UZKQISRF.js.map +1 -0
- package/dist/{chunk-7KG3RTYS.js → chunk-VL5NXVCN.js} +281 -155
- package/dist/chunk-VL5NXVCN.js.map +1 -0
- package/dist/{chunk-CGBADIO5.cjs → chunk-WOMCXN2W.cjs} +328 -202
- package/dist/chunk-WOMCXN2W.cjs.map +1 -0
- package/dist/{chunk-3R3QVKY5.cjs → chunk-YDGMWH43.cjs} +397 -324
- package/dist/chunk-YDGMWH43.cjs.map +1 -0
- package/dist/{chunk-AGOVW7U6.js → chunk-YYVXRV3V.js} +72 -56
- package/dist/chunk-YYVXRV3V.js.map +1 -0
- package/dist/{chunk-M5RYMAFI.js → chunk-ZLNSH4UL.js} +71 -31
- package/dist/chunk-ZLNSH4UL.js.map +1 -0
- package/dist/{coerce-DRERzdve.d.cts → coerce-CUhHc3Tu.d.ts} +16 -8
- package/dist/{coerce-DP0vYu-x.d.ts → coerce-Ytt2Eiq9.d.cts} +16 -8
- package/dist/core/index.cjs +5 -5
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +9 -8
- package/dist/core/index.d.ts +9 -8
- package/dist/core/index.js +4 -4
- package/dist/generate/index.cjs +20 -8
- package/dist/generate/index.cjs.map +1 -1
- package/dist/generate/index.d.cts +105 -17
- package/dist/generate/index.d.ts +105 -17
- package/dist/generate/index.js +19 -7
- package/dist/{index-CL4b4gUQ.d.ts → index-5VJgKz_Q.d.cts} +6 -2
- package/dist/{index-B9QLziDe.d.cts → index-BLuDesVG.d.ts} +20 -13
- package/dist/{index-BHIUyjhZ.d.ts → index-BV6APVa6.d.cts} +20 -13
- package/dist/{index-BMweUlm5.d.cts → index-Bf0Sv8a9.d.ts} +6 -2
- package/dist/{index-Dw2DP7vm.d.ts → index-BkT21EMv.d.cts} +3 -2
- package/dist/{index-BL5N2Oyz.d.cts → index-C7KCaTRz.d.ts} +3 -2
- package/dist/{index-Cy15oTvh.d.ts → index-C9MYbuKS.d.cts} +7 -3
- package/dist/{index-Cy15oTvh.d.cts → index-C9MYbuKS.d.ts} +7 -3
- package/dist/{index-BNSM-DSk.d.cts → index-DVInzCDS.d.cts} +533 -28
- package/dist/{index-9eoQs2C1.d.ts → index-Dg-SAfhz.d.ts} +6 -4
- package/dist/{index-BJgP97N1.d.ts → index-jgeug9EA.d.ts} +533 -28
- package/dist/{index-cHvbYgJI.d.cts → index-pQihL4z7.d.cts} +6 -4
- package/dist/index.cjs +49 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -13
- package/dist/index.d.ts +13 -13
- package/dist/index.js +55 -19
- package/dist/{masks-Cc7-MzzY.d.ts → masks-BnzXnBj0.d.cts} +3 -2
- package/dist/{masks-pADfTOiD.d.cts → masks-tycmkrgs.d.ts} +3 -2
- package/dist/model/index.cjs +12 -12
- package/dist/model/index.cjs.map +1 -1
- package/dist/model/index.d.cts +259 -48
- package/dist/model/index.d.ts +259 -48
- package/dist/model/index.js +11 -11
- package/dist/{positional-DJgs6ltD.d.ts → positional-CscpxtlE.d.cts} +3 -2
- package/dist/{positional-DMZer-FM.d.cts → positional-DLnfUgqG.d.ts} +3 -2
- package/dist/{index-BRMbPkHE.d.ts → profile-B4WqcM4H.d.ts} +85 -610
- package/dist/{index-DGCNKAUr.d.cts → profile-BJd1XkPB.d.cts} +85 -610
- package/dist/theory/index.cjs +5 -5
- package/dist/theory/index.cjs.map +1 -1
- package/dist/theory/index.d.cts +18 -14
- package/dist/theory/index.d.ts +18 -14
- package/dist/theory/index.js +4 -4
- package/dist/{index-CJBBiAmU.d.ts → types-7mGFwvMm.d.ts} +1210 -31
- package/dist/{index-BBWNZS0f.d.cts → types-_ofpb2be.d.cts} +1210 -31
- package/package.json +13 -13
- package/dist/chunk-35NBV2FT.cjs.map +0 -1
- package/dist/chunk-3R3QVKY5.cjs.map +0 -1
- package/dist/chunk-76ZBTRG2.cjs.map +0 -1
- package/dist/chunk-7KG3RTYS.js.map +0 -1
- package/dist/chunk-AGOVW7U6.js.map +0 -1
- package/dist/chunk-CGBADIO5.cjs.map +0 -1
- package/dist/chunk-DSMJRXCZ.cjs.map +0 -1
- package/dist/chunk-FBH75DAY.js.map +0 -1
- package/dist/chunk-H2KJHBW4.js.map +0 -1
- package/dist/chunk-HPVSH7SF.cjs.map +0 -1
- package/dist/chunk-HWHGOVO6.cjs.map +0 -1
- package/dist/chunk-HYJJ2V2I.js.map +0 -1
- package/dist/chunk-J7FHVZII.cjs.map +0 -1
- package/dist/chunk-M5RYMAFI.js.map +0 -1
- package/dist/chunk-NB25P3EH.js.map +0 -1
- package/dist/chunk-NFJ4P6ZZ.js.map +0 -1
- package/dist/chunk-NM7UAMC3.cjs.map +0 -1
- package/dist/chunk-PM4XJE2Y.cjs.map +0 -1
- package/dist/chunk-PUKJP2Z5.js.map +0 -1
- package/dist/chunk-Q6LFSAKV.js.map +0 -1
- package/dist/chunk-RFIBF2RR.js.map +0 -1
- package/dist/chunk-S5BKZZGM.cjs.map +0 -1
- package/dist/chunk-SGLEQVJH.cjs +0 -3329
- package/dist/chunk-SGLEQVJH.cjs.map +0 -1
- package/dist/chunk-UMWZ4ZET.js.map +0 -1
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
assertPositiveInt,
|
|
10
10
|
assertRange,
|
|
11
11
|
describeRejected
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-YYVXRV3V.js";
|
|
13
13
|
|
|
14
14
|
// src/core/duration/index.ts
|
|
15
15
|
var NOTE_VALUES = Object.freeze([
|
|
@@ -232,7 +232,6 @@ function segmentBy(ascending, value) {
|
|
|
232
232
|
}
|
|
233
233
|
|
|
234
234
|
// src/core/tempo/index.ts
|
|
235
|
-
var SECONDS_PER_MINUTE2 = 60;
|
|
236
235
|
var MAX_BPM = 1e3;
|
|
237
236
|
var MIN_BPM = 0.1;
|
|
238
237
|
var MAX_TEMPO_CHANGES = 1e5;
|
|
@@ -285,7 +284,7 @@ function integrateSeconds(map, fromBeat, toBeat) {
|
|
|
285
284
|
const low = Math.max(fromBeat, segmentStart);
|
|
286
285
|
const high = Math.min(toBeat, segmentEnd);
|
|
287
286
|
if (high > low) {
|
|
288
|
-
seconds += (high - low) *
|
|
287
|
+
seconds += (high - low) * SECONDS_PER_MINUTE / event.bpm;
|
|
289
288
|
}
|
|
290
289
|
if (toBeat <= segmentEnd) {
|
|
291
290
|
break;
|
|
@@ -326,6 +325,7 @@ function beatsToTicks(beat, ppq) {
|
|
|
326
325
|
assertFiniteNumber(beat, "beat");
|
|
327
326
|
assertPositiveInt(ppq, "ppq");
|
|
328
327
|
const ticks = Math.round(beat * ppq);
|
|
328
|
+
assertInteger(ticks, "ticks result");
|
|
329
329
|
return ticks === 0 ? 0 : ticks;
|
|
330
330
|
}
|
|
331
331
|
function ticksToBeats(ticks, ppq) {
|
|
@@ -454,4 +454,4 @@ export {
|
|
|
454
454
|
JUST_RATIOS,
|
|
455
455
|
justDeviationCents
|
|
456
456
|
};
|
|
457
|
-
//# sourceMappingURL=chunk-
|
|
457
|
+
//# sourceMappingURL=chunk-7NQ6AL3H.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/duration/index.ts","../src/core/tempo/internal.ts","../src/core/tempo/index.ts","../src/core/tuning/index.ts"],"sourcesContent":["/**\n * Note values: the written durations a score shows — a base value, its\n * augmentation dots, and an optional tuplet ratio — and the conversion between\n * them and the quarter-note beats the rest of the library measures in.\n *\n * The base values are named the American way (whole, half, quarter, eighth),\n * matching the library's \"quarter-note beat\" convention and the vocabulary of\n * the MIDI and DAW world this engine reads events from.\n */\n\nimport { InvalidInputError, NoSolutionError } from '../errors/index.js';\nimport {\n assertFiniteNumber,\n assertGenerationBudget,\n assertInteger,\n assertOneOf,\n assertOptions,\n assertPositiveInt,\n describeRejected,\n} from '../validation/index.js';\n\n/**\n * A written base note value, from the whole note down to the sixty-fourth.\n *\n * Longer values (the breve and beyond) are written as tied notes; see\n * {@link beatsToTiedDurations}.\n *\n * @category Rhythm & Meter\n */\nexport type NoteValue =\n | 'whole'\n | 'half'\n | 'quarter'\n | 'eighth'\n | 'sixteenth'\n | 'thirtySecond'\n | 'sixtyFourth';\n\n/**\n * Every base note value, longest first.\n *\n * @category Rhythm & Meter\n */\nexport const NOTE_VALUES: readonly NoteValue[] = Object.freeze([\n 'whole',\n 'half',\n 'quarter',\n 'eighth',\n 'sixteenth',\n 'thirtySecond',\n 'sixtyFourth',\n] as const);\n\n/**\n * A tuplet ratio: `actual` written notes played in the time of `normal` ones —\n * `{ actual: 3, normal: 2 }` for a triplet, `{ actual: 5, normal: 4 }` for a\n * quintuplet.\n *\n * @category Rhythm & Meter\n */\nexport type Tuplet = {\n /** How many notes are written. */\n actual: number;\n /** How many of the same base value they occupy. */\n normal: number;\n};\n\n/**\n * A written duration: a base value, optional augmentation dots, and an optional\n * tuplet ratio. Its length is `base * (2 - 2^-dots) * normal / actual`.\n *\n * @category Rhythm & Meter\n */\nexport type DurationData = {\n base: NoteValue;\n /** Augmentation dots, 0 when absent; up to four are accepted. */\n dots?: number;\n tuplet?: Tuplet;\n};\n\n/**\n * A duration as {@link beatsToDuration} spells it, with the dot count always\n * stated.\n *\n * @category Rhythm & Meter\n */\nexport type SpelledDuration = {\n base: NoteValue;\n dots: number;\n tuplet?: Tuplet;\n};\n\n/** Length of each base value in quarter notes. */\nexport const NOTE_VALUE_QUARTERS: Readonly<Record<NoteValue, number>> = Object.freeze({\n whole: 4,\n half: 2,\n quarter: 1,\n eighth: 0.5,\n sixteenth: 0.25,\n thirtySecond: 0.125,\n sixtyFourth: 0.0625,\n});\n\n/**\n * Match tolerance in quarter-note beats. Wide enough to read a seven-digit\n * decimal such as 0.3333333 as a triplet, and still far below one tick at\n * PPQ 960 (≈ 0.00104 beats), so no two spellings a sequencer can distinguish\n * collapse into one.\n */\nexport const EPS = 1e-6;\n\n/** Most dots {@link beatsToDuration} will spell; more is never the reading. */\nexport const MAX_SPELLED_DOTS = 2;\n\n/** Most dots {@link durationToBeats} will read; triple dots occur, four is the ceiling. */\nexport const MAX_DOTS = 4;\n\n/** Upper bound on either side of a tuplet ratio. */\nexport const MAX_TUPLET = 64;\n\n/**\n * The tuplet families {@link beatsToDuration} spells, in preference order, with\n * the plain (non-tuplet) reading first. Quintuplets and septuplets are taken in\n * the time of four, the reading that fills one beat of their base value.\n */\nexport const SPELLED_TUPLETS: readonly (Tuplet | undefined)[] = Object.freeze([\n undefined,\n { actual: 3, normal: 2 },\n { actual: 5, normal: 4 },\n { actual: 7, normal: 4 },\n]);\n\n/** Length in quarter notes of a base value with dots and an optional tuplet. */\nfunction quartersOfParts(base: NoteValue, dots: number, tuplet: Tuplet | undefined): number {\n const dotted = NOTE_VALUE_QUARTERS[base] * (2 - 2 ** -dots);\n return tuplet === undefined ? dotted : (dotted * tuplet.normal) / tuplet.actual;\n}\n\n/** Validate a duration, accepting the bare base value as shorthand. */\nfunction assertDuration(value: NoteValue | DurationData, name: string): DurationData {\n if (typeof value === 'string') {\n return { base: assertOneOf(value, NOTE_VALUES, name), dots: 0 };\n }\n if (typeof value !== 'object' || value === null) {\n throw new InvalidInputError(\n `${name} must be a note value or a duration; received ${describeRejected(value)}`,\n );\n }\n const base = assertOneOf(value.base, NOTE_VALUES, `${name}.base`);\n const dots =\n value.dots === undefined ? 0 : assertInteger(value.dots, `${name}.dots`, 0, MAX_DOTS);\n if (value.tuplet === undefined) {\n return { base, dots };\n }\n // A duration restored from a file can carry a null where the tuplet is, and\n // reading a field off it would report the library's own TypeError rather than\n // the malformed input it is.\n if (typeof value.tuplet !== 'object' || value.tuplet === null) {\n throw new InvalidInputError(\n `${name}.tuplet must be a tuplet; received ${describeRejected(value.tuplet)}`,\n );\n }\n const tuplet = {\n actual: assertPositiveInt(value.tuplet.actual, `${name}.tuplet.actual`, MAX_TUPLET),\n normal: assertPositiveInt(value.tuplet.normal, `${name}.tuplet.normal`, MAX_TUPLET),\n };\n return { base, dots, tuplet };\n}\n\n/** Length of a validated duration in quarter notes. */\nfunction quartersOf(duration: DurationData): number {\n return quartersOfParts(duration.base, duration.dots ?? 0, duration.tuplet);\n}\n\n/** Length of the beat unit in quarter notes; a quarter note unless overridden. */\nfunction beatQuarters(options: { beatUnit?: NoteValue | DurationData }): number {\n if (options.beatUnit === undefined) {\n return NOTE_VALUE_QUARTERS.quarter;\n }\n return quartersOf(assertDuration(options.beatUnit, 'beatUnit'));\n}\n\n/** The conventional spelling of a length in quarter notes, if it has one. */\nfunction spellQuarters(quarters: number): SpelledDuration | undefined {\n for (const tuplet of SPELLED_TUPLETS) {\n for (let dots = 0; dots <= MAX_SPELLED_DOTS; dots += 1) {\n for (const base of NOTE_VALUES) {\n if (Math.abs(quartersOfParts(base, dots, tuplet) - quarters) <= EPS) {\n return tuplet === undefined\n ? { base, dots }\n : { base, dots, tuplet: { actual: tuplet.actual, normal: tuplet.normal } };\n }\n }\n }\n }\n return undefined;\n}\n\n/** The undotted values a tie chain is built from, longest first. */\nconst PLAIN_VALUES: readonly { base: NoteValue; quarters: number }[] = Object.freeze(\n NOTE_VALUES.map((base) => ({ base, quarters: NOTE_VALUE_QUARTERS[base] })),\n);\n\n/** Require a positive, finite beat count. */\nfunction assertPositiveBeats(beats: number, name: string): number {\n assertFiniteNumber(beats, name);\n if (beats <= 0) {\n throw new InvalidInputError(`${name} must be positive; received ${beats}`);\n }\n return beats;\n}\n\n/**\n * Length of a written duration in beats.\n *\n * @param duration The duration, or a bare base value as shorthand for an\n * undotted one.\n * @param options `beatUnit` sets what one beat is; a quarter note by default,\n * so a dotted quarter reads as 1.5. Pass `{ base: 'quarter', dots: 1 }` to\n * count in the felt beats of a compound meter.\n * @returns The length in beats.\n * @throws If the base value is unknown, the dot count is not an integer in\n * 0..4, or a tuplet side is not a positive integer.\n * @example\n * ```ts\n * import { durationToBeats } from '@libraz/libcantus';\n * durationToBeats('quarter'); // 1\n * durationToBeats({ base: 'quarter', dots: 1 }); // 1.5\n * durationToBeats({ base: 'eighth', tuplet: { actual: 3, normal: 2 } }) * 3; // 1 — three\n * // eighth-note triplets fill the beat two eighths would\n * ```\n * @category Rhythm & Meter\n */\nexport function durationToBeats(\n duration: NoteValue | DurationData,\n options: { beatUnit?: NoteValue | DurationData } = {},\n): number {\n const quarters = quartersOf(assertDuration(duration, 'duration'));\n return quarters / beatQuarters(assertOptions(options, 'options'));\n}\n\n/**\n * Spell a length in beats as the note value a score would show.\n *\n * The spelling is the conventional one, not merely an arithmetically valid one:\n * 1.5 beats is a dotted quarter rather than a quarter tied to an eighth, and a\n * third of a beat is an eighth triplet rather than a twenty-fourth note. Plain\n * values are preferred to dotted ones and both to tuplets, and within the\n * tuplets triplets come before quintuplets and septuplets.\n *\n * Lengths are matched within 1e-6 quarter notes, so a rounded decimal such as\n * 0.3333333 still reads as a triplet. The tolerance is measured in quarter\n * notes whatever `beatUnit` names, so a longer beat unit narrows it in\n * proportion: under `{ beatUnit: 'whole' }` it is 2.5e-7 of a beat.\n *\n * @param beats The length in beats.\n * @param options `beatUnit` sets what one beat is; a quarter note by default.\n * @returns The base value, its dot count, and its tuplet when it has one.\n * @throws If `beats` is not positive, or — as a `NoSolutionError` — if no single\n * note value spells it, as for 5 beats in 4/4. Use\n * {@link beatsToTiedDurations} for those.\n * @example\n * ```ts\n * import { beatsToDuration } from '@libraz/libcantus';\n * beatsToDuration(1.5); // { base: 'quarter', dots: 1 }\n * beatsToDuration(1 / 3); // { base: 'eighth', dots: 0, tuplet: { actual: 3, normal: 2 } }\n * ```\n * @category Rhythm & Meter\n */\nexport function beatsToDuration(\n beats: number,\n options: { beatUnit?: NoteValue | DurationData } = {},\n): SpelledDuration {\n assertPositiveBeats(beats, 'beats');\n const spelled = spellQuarters(beats * beatQuarters(assertOptions(options, 'options')));\n if (spelled === undefined) {\n throw new NoSolutionError(`no single note value spells ${beats} beats`);\n }\n return spelled;\n}\n\n/**\n * Spell a length in beats as a chain of tied note values.\n *\n * A length with a single spelling comes back as a one-element chain. Anything\n * else is broken into undotted values, longest first, and a value immediately\n * followed by its own half is then written as a dot instead: 5 beats reads as a\n * whole note tied to a quarter, and 1.9375 beats as a double-dotted quarter tied\n * to a dotted thirty-second. The dot is only written where it leaves the chain\n * in longest-first order, so 10 beats reads as two whole notes tied to a half\n * rather than as a whole note tied to a longer dotted whole. The chain knows\n * nothing of barlines or beat grouping — an engraver splits further at those —\n * and it uses no tuplets, so a length off the plain grid and with no single\n * spelling has no chain either.\n *\n * @param beats The length in beats.\n * @param options `beatUnit` sets what one beat is; a quarter note by default.\n * @returns The tied durations, longest first, summing to `beats`.\n * @throws If `beats` is not positive, if the chain would exceed the generation\n * budget, or — as a `NoSolutionError` — if no chain of plain and dotted values\n * sums to it.\n * @example\n * ```ts\n * import { beatsToTiedDurations } from '@libraz/libcantus';\n * beatsToTiedDurations(5); // [{ base: 'whole', dots: 0 }, { base: 'quarter', dots: 0 }]\n * ```\n * @category Rhythm & Meter\n */\nexport function beatsToTiedDurations(\n beats: number,\n options: { beatUnit?: NoteValue | DurationData } = {},\n): SpelledDuration[] {\n assertPositiveBeats(beats, 'beats');\n const quarters = beats * beatQuarters(assertOptions(options, 'options'));\n const single = spellQuarters(quarters);\n if (single !== undefined) {\n return [single];\n }\n assertGenerationBudget(\n Math.ceil(quarters / NOTE_VALUE_QUARTERS.whole) + PLAIN_VALUES.length,\n 'tie chain length',\n );\n const chain: SpelledDuration[] = [];\n let remaining = quarters;\n let previousQuarters = 0;\n while (remaining > EPS) {\n const next = PLAIN_VALUES.find((candidate) => candidate.quarters <= remaining + EPS);\n if (next === undefined) {\n throw new NoSolutionError(`no chain of tied note values sums to ${beats} beats`);\n }\n const last = chain[chain.length - 1];\n const before = chain[chain.length - 2];\n // A value followed by exactly its own half is one dotted note, not a tie —\n // but the dot lengthens a value already written, so it is only taken where\n // the result still fits under the value it is tied after. Dotting the\n // second whole note of 10 beats would make it outlast the first.\n const dotted =\n last === undefined || last.dots >= MAX_SPELLED_DOTS\n ? undefined\n : quartersOfParts(last.base, last.dots + 1, undefined);\n const staysInOrder =\n dotted !== undefined && (before === undefined || dotted <= quartersOf(before) + EPS);\n if (\n last !== undefined &&\n staysInOrder &&\n Math.abs(next.quarters * 2 - previousQuarters) <= EPS\n ) {\n last.dots += 1;\n } else {\n chain.push({ base: next.base, dots: 0 });\n }\n previousQuarters = next.quarters;\n remaining -= next.quarters;\n }\n return chain;\n}\n","/**\n * The index a tempo map is read through, and the mark that says it is valid.\n *\n * A map is handed to a conversion once per note, so a pass over a piece asks\n * the same array the same questions tens of thousands of times: is it valid,\n * and which segment holds this beat. Answered from the array each time, both\n * cost the whole map per note — an imported accelerando marks a tempo every\n * tick, and the two counts multiply. They are answered from a snapshot instead,\n * which is the shape the meter map already reads through.\n */\n\nimport type { TempoMap } from './index.js';\n\n/** One tempo map as it read when the index was built. */\nexport type TempoIndex = {\n /** Onsets in map order. */\n startBeats: number[];\n /** Tempo of each entry. */\n bpms: number[];\n /**\n * Seconds elapsed from the map's origin to each entry's own onset — the\n * prefix sum of the segments before it, summed in map order.\n *\n * The same additions the origin-to-beat integral makes, made once for the\n * map rather than once per note: asking when the last note of an imported\n * accelerando sounds otherwise re-adds every tempo change in the piece.\n */\n secondsBefore: number[];\n /** Whether the map had passed validation when the index was built. */\n validated: boolean;\n};\n\nexport const SECONDS_PER_MINUTE = 60;\n\n/**\n * Indexes held against the identity of the map they describe.\n *\n * A caller keeps its own array and may write to it after the library has read\n * it, so an index is only trusted while every entry still reads as it did when\n * the index was built. Anything else rebuilds, and a map that had passed\n * validation is validated again.\n */\nconst INDEX_CACHE = new WeakMap<TempoMap, TempoIndex>();\n\n/** Whether the index still describes the map it was built from. */\nfunction describesMap(index: TempoIndex, map: TempoMap): boolean {\n if (index.startBeats.length !== map.length) {\n return false;\n }\n for (let i = 0; i < map.length; i += 1) {\n const event = map[i];\n if (\n event === undefined ||\n event === null ||\n event.startBeat !== index.startBeats[i] ||\n event.bpm !== index.bpms[i]\n ) {\n return false;\n }\n }\n return true;\n}\n\n/** Build and cache the index of a map, recording whether it is validated. */\nfunction buildTempoIndex(map: TempoMap, validated: boolean): TempoIndex {\n const startBeats: number[] = [];\n const bpms: number[] = [];\n const secondsBefore: number[] = [];\n let elapsed = 0;\n for (let i = 0; i < map.length; i += 1) {\n const event = map[i];\n if (event === undefined) {\n continue;\n }\n const previousBeat = startBeats[i - 1];\n const previousBpm = bpms[i - 1];\n if (previousBeat !== undefined && previousBpm !== undefined) {\n elapsed += ((event.startBeat - previousBeat) * SECONDS_PER_MINUTE) / previousBpm;\n }\n startBeats.push(event.startBeat);\n bpms.push(event.bpm);\n secondsBefore.push(elapsed);\n }\n const index: TempoIndex = { startBeats, bpms, secondsBefore, validated };\n INDEX_CACHE.set(map, index);\n return index;\n}\n\n/** The index of `map`, rebuilt when the caller has written to the array since. */\nexport function tempoIndexOf(map: TempoMap): TempoIndex {\n const cached = INDEX_CACHE.get(map);\n return cached !== undefined && describesMap(cached, map) ? cached : buildTempoIndex(map, false);\n}\n\n/**\n * Whether the map has already passed validation and is unchanged since.\n *\n * What this still pays on every call is a comparison per entry: an array the\n * caller keeps says nothing about whether it has been written to since, so the\n * only way to know a validated map is still the one that was validated is to\n * read it. What it saves is the validation itself — the range checks, the\n * ordering, and the error messages built to describe them.\n */\nexport function isValidatedTempoMap(map: TempoMap): boolean {\n const cached = INDEX_CACHE.get(map);\n return cached?.validated === true && describesMap(cached, map);\n}\n\n/** Record that a map passed validation, and snapshot it. */\nexport function rememberValidatedTempoMap(map: TempoMap): void {\n buildTempoIndex(map, true);\n}\n\n/**\n * Index of the segment in force at `beat`, by binary search.\n *\n * The opening tempo reaches back before the beat it is marked on, so a beat\n * before the first entry answers with entry 0: a pickup is played at the tempo\n * of the piece it leads into, and the map names no other one to play it at.\n *\n * @param map A validated tempo map.\n * @param beat The beat to place.\n * @returns The index of the entry whose tempo holds at `beat`.\n */\nexport function tempoSegmentAt(map: TempoMap, beat: number): number {\n return segmentBy(tempoIndexOf(map).startBeats, beat);\n}\n\n/**\n * Seconds from the map's origin to `beat`, read off the prefix sums.\n *\n * The same additions the segment-by-segment integral makes, in the same order:\n * every whole segment before `beat` was summed into the index in map order, and\n * the part of the segment holding `beat` is added last. A beat before the origin\n * comes back negative, at the opening tempo.\n *\n * @param map A validated tempo map.\n * @param beat The beat to place in time.\n * @returns Elapsed seconds, 0 at the map's first event.\n */\nexport function elapsedSecondsAt(map: TempoMap, beat: number): number {\n return elapsedSecondsIn(tempoIndexOf(map), beat);\n}\n\n/** Seconds from the origin to `beat`, against an index already in hand. */\nexport function elapsedSecondsIn(index: TempoIndex, beat: number): number {\n const at = segmentBy(index.startBeats, beat);\n const start = index.startBeats[at] ?? 0;\n const bpm = index.bpms[at] ?? 1;\n return (index.secondsBefore[at] ?? 0) + ((beat - start) * SECONDS_PER_MINUTE) / bpm;\n}\n\n/**\n * Beat reached after `seconds` from the map's origin — the inverse of\n * {@link elapsedSecondsAt}, read off the same prefix sums.\n *\n * @param map A validated tempo map.\n * @param seconds Elapsed seconds; negative for a position before the origin.\n * @returns The position in quarter-note beats.\n */\nexport function beatAtElapsedSeconds(map: TempoMap, seconds: number): number {\n return beatAtElapsedIn(tempoIndexOf(map), seconds);\n}\n\n/** The beat reached after `seconds`, against an index already in hand. */\nexport function beatAtElapsedIn(index: TempoIndex, seconds: number): number {\n const at = segmentBy(index.secondsBefore, seconds);\n const start = index.startBeats[at] ?? 0;\n const bpm = index.bpms[at] ?? 1;\n return start + ((seconds - (index.secondsBefore[at] ?? 0)) * bpm) / SECONDS_PER_MINUTE;\n}\n\n/**\n * The last index of an ascending run whose value is at or below `value`, and 0\n * for a value below the run's first: the opening segment governs what precedes\n * it, so there is no index before it to answer with.\n */\nfunction segmentBy(ascending: readonly number[], value: number): number {\n let low = 0;\n let high = ascending.length - 1;\n while (low < high) {\n const mid = (low + high + 1) >> 1;\n const at = ascending[mid];\n if (at !== undefined && at <= value) {\n low = mid;\n } else {\n high = mid - 1;\n }\n }\n return Math.max(0, low);\n}\n","/**\n * Tempo and time conversion: beats to wall-clock seconds across tempo changes,\n * and beats to MIDI ticks.\n *\n * Positions are measured in quarter-note beats, matching the rest of the\n * library's beat convention. A {@link TempoMap} is piecewise constant: each\n * entry sets the tempo from its beat onwards, so the elapsed time over a span is\n * the sum of the segments it crosses rather than the tempo at either end.\n */\n\nimport { InvalidInputError } from '../errors/index.js';\nimport {\n assertFiniteNumber,\n assertGenerationBudget,\n assertInteger,\n assertPositiveInt,\n assertRange,\n describeRejected,\n} from '../validation/index.js';\nimport {\n beatAtElapsedIn,\n beatAtElapsedSeconds,\n elapsedSecondsAt,\n elapsedSecondsIn,\n isValidatedTempoMap,\n rememberValidatedTempoMap,\n SECONDS_PER_MINUTE,\n tempoIndexOf,\n tempoSegmentAt,\n} from './internal.js';\n\n/**\n * A tempo change: the beat it takes effect on, and the tempo it sets.\n *\n * The tempo holds until the next entry, so a map of one entry is a constant\n * tempo for the whole timeline.\n *\n * @category Rhythm & Meter\n */\nexport type TempoEvent = {\n /** Onset in quarter-note beats, absolute from the start of the timeline. */\n readonly startBeat: number;\n /** Quarter-note beats per minute from `startBeat` onwards. */\n readonly bpm: number;\n};\n\n/**\n * A tempo track: {@link TempoEvent}s sorted by `startBeat`, strictly ascending.\n *\n * The first entry is the time origin — {@link beatsToSeconds} returns 0 for its\n * `startBeat` — and its tempo also governs the beats before it, which is where\n * a pickup sounds. A map cannot say anything else about that stretch, and a\n * piece is played into its first downbeat at the tempo it starts in, so elapsed\n * time there is negative rather than an error.\n *\n * @category Rhythm & Meter\n */\nexport type TempoMap = readonly TempoEvent[];\n\n/**\n * Upper bound on a tempo, matching the bound the generators accept. A faster\n * marking is a notation of a slower pulse, not a distinct tempo.\n */\nexport const MAX_BPM = 1000;\n\n/**\n * Lower bound on a tempo. One beat lasts ten minutes here; anything slower is a\n * corrupt or mis-scaled value rather than a marking, and letting it through\n * would make the conversions overflow to infinity while still reporting a\n * validated tempo.\n */\nexport const MIN_BPM = 0.1;\n\n/**\n * Upper bound on the number of changes one tempo map may declare.\n *\n * A map is read on every conversion asked of it, so an unbounded map is an\n * unbounded per-note cost the way an unbounded event array is an unbounded\n * pass. The bound is the one the meter map takes, and for the same reason: far\n * above any notated piece — a change on every bar of a hundred thousand bars —\n * and it rejects the map rather than the work built on it. A recorded\n * accelerando reaches it, which is exactly the import the bound is for.\n */\nexport const MAX_TEMPO_CHANGES = 100_000;\n\n/**\n * Validate a tempo map: non-empty, strictly ascending, finite onsets, and\n * tempos inside the range the conversions stay finite over.\n *\n * An onset is not bounded below, for the reason the note events are not: beat 0\n * is the first downbeat, so a piece that opens with a pickup marks its tempo\n * before it.\n *\n * An unsorted map is rejected rather than sorted: reordering it would silently\n * accept a data error, and two entries on the same beat name no segment at all.\n */\nfunction assertTempoMap(map: TempoMap, name = 'tempo map'): TempoMap {\n if (!Array.isArray(map) || map.length === 0) {\n throw new InvalidInputError(`${name} must hold at least one tempo event`);\n }\n assertGenerationBudget(map.length, `${name} count`, MAX_TEMPO_CHANGES);\n // A map is re-validated on every conversion asked of it, so a pass over a\n // piece pays for the whole map per note unless a map it has already read is\n // recognized as one. The meter map is read the same way.\n if (isValidatedTempoMap(map)) {\n return map;\n }\n for (let index = 0; index < map.length; index += 1) {\n const event = map[index];\n // A hole in a sparse array, an explicit null, and a number are all rejected\n // here rather than at the first field read, which would surface as the\n // library's own TypeError instead of as the malformed input it is. The\n // meter map is read the same way.\n if (typeof event !== 'object' || event === null) {\n throw new InvalidInputError(\n `${name}[${index}] must be a tempo event; received ${describeRejected(event)}`,\n );\n }\n assertFiniteNumber(event.startBeat, `${name}[${index}].startBeat`);\n assertRange(event.bpm, MIN_BPM, MAX_BPM, `${name}[${index}].bpm`);\n const previous = map[index - 1];\n if (previous !== undefined && event.startBeat <= previous.startBeat) {\n throw new InvalidInputError(\n `${name} must be sorted by startBeat with no repeats; ` +\n `[${index}].startBeat ${event.startBeat} does not follow ${previous.startBeat}`,\n );\n }\n }\n rememberValidatedTempoMap(map);\n return map;\n}\n\n/** The map's first event, which is its time origin. */\nfunction firstEvent(map: TempoMap): TempoEvent {\n const first = map[0];\n if (first === undefined) {\n throw new InvalidInputError('tempo map must hold at least one tempo event');\n }\n return first;\n}\n\n/**\n * Elapsed seconds over `[fromBeat, toBeat]`, summed segment by segment. Both\n * bounds are assumed validated; a span running backwards reports negative time,\n * which is what keeps the integral additive across the origin.\n *\n * The sum starts at the segment the span starts in rather than at the map's\n * first, so a note late in a piece is not charged for every tempo change before\n * it. What it costs is the segments the span actually crosses, which is what\n * the span is made of.\n */\nfunction integrateSeconds(map: TempoMap, fromBeat: number, toBeat: number): number {\n if (toBeat < fromBeat) {\n return -integrateSeconds(map, toBeat, fromBeat);\n }\n let seconds = 0;\n for (let index = tempoSegmentAt(map, fromBeat); index < map.length; index += 1) {\n const event = map[index];\n if (event === undefined) {\n continue;\n }\n // The opening tempo reaches back before the beat it is marked on: a pickup\n // is played at the tempo of the piece it leads into, and the map names no\n // other one to play it at.\n const segmentStart = index === 0 ? Number.NEGATIVE_INFINITY : event.startBeat;\n const segmentEnd = map[index + 1]?.startBeat ?? Number.POSITIVE_INFINITY;\n const low = Math.max(fromBeat, segmentStart);\n const high = Math.min(toBeat, segmentEnd);\n if (high > low) {\n seconds += ((high - low) * SECONDS_PER_MINUTE) / event.bpm;\n }\n if (toBeat <= segmentEnd) {\n break;\n }\n }\n return seconds;\n}\n\n/**\n * Wall-clock seconds from the start of a tempo map to a beat.\n *\n * The result integrates every tempo segment the span crosses; it is not the\n * tempo in effect at `beat` applied to the whole span.\n *\n * A beat before the map's first event reports negative elapsed time, at the\n * opening tempo: a pickup sounds before the downbeat, and asking when it sounds\n * is a fair question.\n *\n * @param beat Position in quarter-note beats.\n * @param map The tempo map; its first event is the time origin.\n * @returns Elapsed seconds, 0 at the map's first event and negative before it.\n * @throws If the map is empty, unsorted, or carries a tempo outside 0.1..1000\n * quarter-note beats per minute.\n * @example\n * ```ts\n * import { beatsToSeconds } from '@libraz/libcantus';\n * const map = [{ startBeat: 0, bpm: 120 }, { startBeat: 4, bpm: 60 }];\n * beatsToSeconds(8, map); // 6 = 4 beats at 120 + 4 beats at 60\n * ```\n * @category Rhythm & Meter\n */\nexport function beatsToSeconds(beat: number, map: TempoMap): number {\n assertFiniteNumber(beat, 'beat');\n assertTempoMap(map);\n // The origin-to-beat integral crosses every segment before `beat`, so a pass\n // that asks it of every note re-adds the whole map per note. The sum of the\n // whole segments is the map's own, made once and read here.\n return elapsedSecondsAt(map, beat);\n}\n\n/**\n * The beat reached after a number of seconds — the inverse of\n * {@link beatsToSeconds}.\n *\n * @param seconds Elapsed seconds from the map's first event; negative for a\n * position before it, such as a pickup.\n * @param map The tempo map.\n * @returns The position in quarter-note beats.\n * @throws If the map is malformed or `seconds` is not finite.\n * @example\n * ```ts\n * import { secondsToBeats } from '@libraz/libcantus';\n * const map = [{ startBeat: 0, bpm: 120 }, { startBeat: 4, bpm: 60 }];\n * secondsToBeats(6, map); // 8\n * ```\n * @category Rhythm & Meter\n */\nexport function secondsToBeats(seconds: number, map: TempoMap): number {\n assertFiniteNumber(seconds, 'seconds');\n assertTempoMap(map);\n // Before the origin only the opening tempo is in force, which is the segment\n // {@link beatsToSeconds} integrates backwards over; the prefix sums place a\n // negative elapsed time there without a case of its own.\n return beatAtElapsedSeconds(map, seconds);\n}\n\n/**\n * Duration in seconds of a span of beats.\n *\n * Equal to the difference of two {@link beatsToSeconds} calls — the integral is\n * additive, so that reading is exact — but integrated over the span directly, so\n * a short note late in a long piece does not lose precision to the subtraction\n * of two large elapsed times.\n *\n * @param startBeat Where the span begins, in quarter-note beats; a pickup\n * starts before the map's first event and is measured like any other span.\n * @param lengthBeats How long the span lasts, in quarter-note beats.\n * @param map The tempo map.\n * @returns The span's duration in seconds, never negative.\n * @throws If the map is malformed or the length is negative.\n * @example\n * ```ts\n * import { durationToSeconds } from '@libraz/libcantus';\n * const map = [{ startBeat: 0, bpm: 120 }, { startBeat: 4, bpm: 60 }];\n * durationToSeconds(2, 4, map); // 3 = 2 beats at 120 + 2 beats at 60\n * ```\n * @category Rhythm & Meter\n */\nexport function durationToSeconds(startBeat: number, lengthBeats: number, map: TempoMap): number {\n assertFiniteNumber(startBeat, 'startBeat');\n assertRange(lengthBeats, 0, Number.MAX_SAFE_INTEGER, 'lengthBeats');\n assertTempoMap(map);\n return integrateSeconds(map, startBeat, startBeat + lengthBeats);\n}\n\n/**\n * The tempo in effect at a beat.\n *\n * A beat before the first event reads the opening tempo, which is the tempo a\n * pickup is played at.\n *\n * @param beat Position in quarter-note beats.\n * @param map The tempo map.\n * @returns Quarter-note beats per minute.\n * @throws If the map is malformed.\n * @example\n * ```ts\n * import { tempoAt } from '@libraz/libcantus';\n * tempoAt(5, [{ startBeat: 0, bpm: 120 }, { startBeat: 4, bpm: 60 }]); // 60\n * ```\n * @category Rhythm & Meter\n */\nexport function tempoAt(beat: number, map: TempoMap): number {\n assertFiniteNumber(beat, 'beat');\n assertTempoMap(map);\n return map[tempoSegmentAt(map, beat)]?.bpm ?? firstEvent(map).bpm;\n}\n\n/** A reader that converts many positions against one tempo map. */\nexport type TempoReader = {\n /** Elapsed seconds from the map's origin to a beat. */\n secondsAt(beat: number): number;\n /** The beat reached after a number of seconds from the origin. */\n beatAt(seconds: number): number;\n};\n\n/**\n * Hold a tempo map for the length of one pass, and convert against it.\n *\n * A conversion validates the map it is handed and re-reads it to know the\n * caller has not written to it since, so a pass that converts every note of a\n * piece pays for the whole map per note — and an imported accelerando marks a\n * tempo every tick. A pass that reads the map once instead pays for it once.\n *\n * The map is read when the reader is made, so the reader answers for the map as\n * it was then: a pass hands out no reader it does not own the map of.\n *\n * Not part of the public surface: it hands out a view of a validated map, which\n * only the pass that validated it can say is still current.\n *\n * @param map The tempo map, validated here.\n * @returns The conversions, reading one snapshot of the map.\n */\nexport function tempoReader(map: TempoMap): TempoReader {\n assertTempoMap(map);\n const index = tempoIndexOf(map);\n return {\n secondsAt: (beat) => elapsedSecondsIn(index, assertFiniteNumber(beat, 'beat')),\n beatAt: (seconds) => beatAtElapsedIn(index, assertFiniteNumber(seconds, 'seconds')),\n };\n}\n\n/**\n * Convert quarter-note beats to MIDI ticks.\n *\n * Ticks are whole units of a sequencer's grid, so the result is rounded to the\n * nearest tick; a beat that is not on the grid is not representable and comes\n * back quantized.\n *\n * A position before the first downbeat is a negative tick count, which is how a\n * pickup crosses the MIDI boundary and comes back. A position that rounds to\n * the downbeat from below comes back as positive zero: `-0` and `0` are the\n * same tick, and only one of them keys as it under `Object.is`.\n *\n * @param beat Position or length in quarter-note beats.\n * @param ppq Pulses (ticks) per quarter note, e.g. 96, 480, or 960.\n * @returns The whole tick count.\n * @throws If `beat` is not finite, `ppq` is not a positive integer, or the\n * tick count is past the safe integers.\n * @example\n * ```ts\n * import { beatsToTicks } from '@libraz/libcantus';\n * beatsToTicks(1.5, 480); // 720\n * ```\n * @category Rhythm & Meter\n */\nexport function beatsToTicks(beat: number, ppq: number): number {\n assertFiniteNumber(beat, 'beat');\n assertPositiveInt(ppq, 'ppq');\n const ticks = Math.round(beat * ppq);\n // A count past the safe integers is not a whole tick, and ticksToBeats refuses it.\n assertInteger(ticks, 'ticks result');\n return ticks === 0 ? 0 : ticks;\n}\n\n/**\n * Convert MIDI ticks to quarter-note beats.\n *\n * @param ticks Whole tick count, negative before the first downbeat.\n * @param ppq Pulses (ticks) per quarter note, e.g. 96, 480, or 960.\n * @returns The position or length in quarter-note beats.\n * @throws If `ticks` is not an integer or `ppq` is not a positive integer.\n * @example\n * ```ts\n * import { ticksToBeats } from '@libraz/libcantus';\n * ticksToBeats(720, 480); // 1.5\n * ```\n * @category Rhythm & Meter\n */\nexport function ticksToBeats(ticks: number, ppq: number): number {\n assertInteger(ticks, 'ticks');\n assertPositiveInt(ppq, 'ppq');\n return ticks / ppq;\n}\n","/**\n * Tuning and microtonality: frequency conversion, cents, arbitrary equal\n * temperaments (EDO), and just-intonation ratios.\n *\n * The rest of the library reasons in twelve-tone pitch classes, which is a\n * deliberate scope choice for tonal theory. This module is the escape hatch for\n * anyone who needs actual frequencies, cents, non-12 equal temperaments, or the\n * acoustic (just) tuning behind the tempered intervals.\n */\n\nimport { InvalidInputError } from '../errors/index.js';\nimport {\n assertFiniteNumber,\n assertInteger,\n assertPositiveInt,\n assertRange,\n describeRejected,\n} from '../validation/index.js';\n\n/**\n * An equal-tempered tuning: a reference pitch and a number of equal divisions of\n * the octave. With `divisions === 12` a step index is an ordinary MIDI number.\n *\n * @category Pitch & Intervals\n */\nexport type TuningTable = {\n /** Step index (MIDI number when `divisions` is 12) whose frequency is `refFreq`. */\n readonly refStep: number;\n /** Frequency in Hz of `refStep`. */\n readonly refFreq: number;\n /** Equal divisions of the octave (12 standard; e.g. 19 or 31 for microtonal). */\n readonly divisions: number;\n};\n\n/**\n * Standard twelve-tone equal temperament, A4 (MIDI 69) = 440 Hz.\n *\n * @category Pitch & Intervals\n */\nexport const TWELVE_TET: TuningTable = Object.freeze({ refStep: 69, refFreq: 440, divisions: 12 });\n\nfunction assertTuning(tuning: TuningTable): TuningTable {\n // The shape is checked before any field is read: a value from JSON or a\n // plugin host may be null or a number, and reading a reference step off it\n // would report the library's own TypeError instead of the caller's bad input.\n if (typeof tuning !== 'object' || tuning === null) {\n throw new InvalidInputError(\n `tuning must be a tuning table; received ${describeRejected(tuning)}`,\n );\n }\n assertFiniteNumber(tuning.refStep, 'tuning.refStep');\n assertRange(tuning.refFreq, Number.MIN_VALUE, Number.MAX_VALUE, 'tuning.refFreq');\n assertPositiveInt(tuning.divisions, 'tuning.divisions');\n return tuning;\n}\n\n/**\n * Build an equal temperament with `n` divisions of the octave.\n *\n * @param n Divisions of the octave (e.g. 19, 24, 31).\n * @param refFreq Reference frequency in Hz (default 440).\n * @param refStep Step index of the reference (default 69).\n * @returns The tuning.\n * @example\n * ```ts\n * import { edo, frequencyOf } from '@libraz/libcantus';\n * const et19 = edo(19); // { refStep: 69, refFreq: 440, divisions: 19 }\n * frequencyOf(70, et19); // one 19-EDO step above A4\n * ```\n * @category Pitch & Intervals\n */\nexport function edo(n: number, refFreq = 440, refStep = 69): TuningTable {\n assertPositiveInt(n, 'EDO divisions');\n assertRange(refFreq, Number.MIN_VALUE, Number.MAX_VALUE, 'reference frequency');\n assertFiniteNumber(refStep, 'reference step');\n return { refStep, refFreq, divisions: n };\n}\n\n/**\n * Frequency in Hz of a step index under a tuning.\n *\n * @param step Step index (a MIDI number under 12-EDO).\n * @param tuning The tuning (default 12-TET).\n * @returns The frequency in Hz.\n * @example\n * ```ts\n * import { frequencyOf } from '@libraz/libcantus';\n * frequencyOf(69); // 440 (A4 in 12-TET)\n * frequencyOf(60); // middle C in Hz\n * ```\n * @category Pitch & Intervals\n */\nexport function frequencyOf(step: number, tuning: TuningTable = TWELVE_TET): number {\n assertFiniteNumber(step, 'step');\n assertTuning(tuning);\n const result = tuning.refFreq * 2 ** ((step - tuning.refStep) / tuning.divisions);\n return assertRange(result, Number.MIN_VALUE, Number.MAX_VALUE, 'frequency result');\n}\n\n/**\n * Nearest step index to a frequency under a tuning (the inverse of\n * {@link frequencyOf}, rounded).\n *\n * @param freq Frequency in Hz.\n * @param tuning The tuning (default 12-TET).\n * @returns The nearest step index.\n * @category Pitch & Intervals\n */\nexport function nearestStep(freq: number, tuning: TuningTable = TWELVE_TET): number {\n assertRange(freq, Number.MIN_VALUE, Number.MAX_VALUE, 'frequency');\n assertTuning(tuning);\n return Math.round(tuning.refStep + tuning.divisions * Math.log2(freq / tuning.refFreq));\n}\n\n/**\n * Step index of a frequency under a tuning, unrounded.\n *\n * The exact inverse of {@link frequencyOf}. {@link nearestStep} rounds it,\n * which discards how far off the pitch actually is — the figure a tuner\n * display, a pitch-bend amount, or an intonation check is built on.\n *\n * @param freq Frequency in Hz.\n * @param tuning The tuning (default 12-TET).\n * @returns The fractional step index.\n * @example\n * ```ts\n * import { stepOf } from '@libraz/libcantus';\n * stepOf(442); // slightly above 69, the step for A440\n * ```\n * @category Pitch & Intervals\n */\nexport function stepOf(freq: number, tuning: TuningTable = TWELVE_TET): number {\n assertRange(freq, Number.MIN_VALUE, Number.MAX_VALUE, 'frequency');\n assertTuning(tuning);\n return tuning.refStep + tuning.divisions * Math.log2(freq / tuning.refFreq);\n}\n\n/**\n * How far a frequency sits from its nearest step, in cents.\n *\n * Positive means sharp of the step, negative flat.\n *\n * @param freq Frequency in Hz.\n * @param tuning The tuning (default 12-TET).\n * @returns The signed deviation in cents.\n * @example\n * ```ts\n * import { centsFromNearestStep } from '@libraz/libcantus';\n * Math.round(centsFromNearestStep(442)); // 8\n * ```\n * @category Pitch & Intervals\n */\nexport function centsFromNearestStep(freq: number, tuning: TuningTable = TWELVE_TET): number {\n const exact = stepOf(freq, tuning);\n return centsOfSteps(exact - Math.round(exact), tuning);\n}\n\n/**\n * Steps spanned by an interval in cents, unrounded — the inverse of\n * {@link centsOfSteps}.\n *\n * @param cents The interval in cents.\n * @param tuning The tuning (default 12-TET).\n * @returns The fractional step count.\n * @category Pitch & Intervals\n */\nexport function stepsOfCents(cents: number, tuning: TuningTable = TWELVE_TET): number {\n assertFiniteNumber(cents, 'cents');\n assertTuning(tuning);\n return assertFiniteNumber((cents * tuning.divisions) / 1200, 'steps result');\n}\n\n/**\n * The frequency ratio an interval in cents spans — the inverse of\n * {@link ratioToCents}.\n *\n * Multiply a frequency by this to move it by that many cents, which is how a\n * cents offset (a pitch-bend spec, a tuning table entry) is applied.\n *\n * @param cents The interval in cents.\n * @returns The frequency ratio.\n * @example\n * ```ts\n * import { centsToRatio } from '@libraz/libcantus';\n * 440 * centsToRatio(14); // A440 raised by 14 cents\n * ```\n * @category Pitch & Intervals\n */\nexport function centsToRatio(cents: number): number {\n assertFiniteNumber(cents, 'cents');\n const result = 2 ** (cents / 1200);\n return assertRange(result, Number.MIN_VALUE, Number.MAX_VALUE, 'ratio result');\n}\n\n/**\n * Interval in cents between two frequencies.\n *\n * @param a Lower/first frequency in Hz.\n * @param b Upper/second frequency in Hz.\n * @returns Cents from `a` to `b` (negative if `b` is lower).\n * @category Pitch & Intervals\n */\nexport function centsBetweenFreq(a: number, b: number): number {\n assertRange(a, Number.MIN_VALUE, Number.MAX_VALUE, 'first frequency');\n assertRange(b, Number.MIN_VALUE, Number.MAX_VALUE, 'second frequency');\n return 1200 * (Math.log2(b) - Math.log2(a));\n}\n\n/**\n * Cents spanned by a number of equal-temperament steps.\n *\n * @param steps Number of steps.\n * @param tuning The tuning (default 12-TET).\n * @returns The cents.\n * @category Pitch & Intervals\n */\nexport function centsOfSteps(steps: number, tuning: TuningTable = TWELVE_TET): number {\n assertFiniteNumber(steps, 'steps');\n assertTuning(tuning);\n return assertFiniteNumber((steps * 1200) / tuning.divisions, 'cents result');\n}\n\n/**\n * Cents of a frequency ratio, e.g. `ratioToCents(3, 2)` ≈ 701.955 for the just\n * perfect fifth.\n *\n * @param numerator Ratio numerator.\n * @param denominator Ratio denominator.\n * @returns The interval in cents.\n * @category Pitch & Intervals\n */\nexport function ratioToCents(numerator: number, denominator: number): number {\n assertRange(numerator, Number.MIN_VALUE, Number.MAX_VALUE, 'ratio numerator');\n assertRange(denominator, Number.MIN_VALUE, Number.MAX_VALUE, 'ratio denominator');\n return 1200 * (Math.log2(numerator) - Math.log2(denominator));\n}\n\n/** One entry of {@link JUST_RATIOS}: a numerator and a denominator, frozen. */\nfunction justRatio(numerator: number, denominator: number): readonly [number, number] {\n return Object.freeze([numerator, denominator] as [number, number]);\n}\n\n/**\n * Five-limit just-intonation ratios for the twelve interval classes above a\n * unison, indexed by semitone class (0..12).\n *\n * @category Pitch & Intervals\n */\nexport const JUST_RATIOS: Readonly<\n Record<0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12, readonly [number, number]>\n> = Object.freeze({\n 0: justRatio(1, 1),\n 1: justRatio(16, 15),\n 2: justRatio(9, 8),\n 3: justRatio(6, 5),\n 4: justRatio(5, 4),\n 5: justRatio(4, 3),\n 6: justRatio(45, 32),\n 7: justRatio(3, 2),\n 8: justRatio(8, 5),\n 9: justRatio(5, 3),\n 10: justRatio(9, 5),\n 11: justRatio(15, 8),\n 12: justRatio(2, 1),\n});\n\n/** Whether a semitone class is one of the classes {@link JUST_RATIOS} lists. */\nfunction isJustSemitoneClass(value: number): value is keyof typeof JUST_RATIOS {\n return value in JUST_RATIOS;\n}\n\n/**\n * Cents by which a five-limit just interval departs from its 12-TET tempering\n * (positive means the just interval is wider).\n *\n * @param semitoneClass Semitone class in [0, 12].\n * @returns The deviation in cents.\n * @throws If `semitoneClass` is not an integer in [0, 12].\n * @category Pitch & Intervals\n */\nexport function justDeviationCents(semitoneClass: number): number {\n assertInteger(semitoneClass, 'semitone class', 0, 12);\n if (!isJustSemitoneClass(semitoneClass)) {\n throw new InvalidInputError(`semitone class has no just ratio: ${semitoneClass}`);\n }\n const ratio = JUST_RATIOS[semitoneClass];\n return ratioToCents(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@@ -4,21 +4,23 @@
|
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
|
|
7
|
-
var _chunk3R3QVKY5cjs = require('./chunk-3R3QVKY5.cjs');
|
|
8
7
|
|
|
9
8
|
|
|
9
|
+
var _chunkYDGMWH43cjs = require('./chunk-YDGMWH43.cjs');
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
var _chunkS3QELJUEcjs = require('./chunk-S3QELJUE.cjs');
|
|
17
19
|
|
|
18
20
|
// src/analyze/spelling/index.ts
|
|
19
21
|
var CHORD_MISMATCH = 64;
|
|
20
22
|
var SCALE_TONE_MISMATCH = 32;
|
|
21
|
-
var LETTER_STEP_DEVIATION =
|
|
23
|
+
var LETTER_STEP_DEVIATION = 8;
|
|
22
24
|
var MAX_COUNTED_DEVIATION = 2;
|
|
23
25
|
var AGAINST_DIRECTION = 3;
|
|
24
26
|
var KEY_MISMATCH = 4;
|
|
@@ -53,17 +55,17 @@ var CONVENTIONAL_LETTER_STEPS = [
|
|
|
53
55
|
// major seventh
|
|
54
56
|
];
|
|
55
57
|
function alterationFor(letter, pc) {
|
|
56
|
-
const distance =
|
|
58
|
+
const distance = _chunkS3QELJUEcjs.pitchClassOf.call(void 0, pc - _chunkS3QELJUEcjs.naturalPitchClassOf.call(void 0, letter));
|
|
57
59
|
return distance > 6 ? distance - 12 : distance;
|
|
58
60
|
}
|
|
59
61
|
function octaveFor(pitch, letter, alter) {
|
|
60
|
-
return (pitch -
|
|
62
|
+
return (pitch - _chunkS3QELJUEcjs.naturalPitchClassOf.call(void 0, letter) - alter) / 12 - 1;
|
|
61
63
|
}
|
|
62
64
|
function sameSpelling(a, b) {
|
|
63
65
|
return a.letter === b.letter && a.alter === b.alter;
|
|
64
66
|
}
|
|
65
67
|
function candidatesFor(pitch, preferred) {
|
|
66
|
-
const pc =
|
|
68
|
+
const pc = _chunkS3QELJUEcjs.pitchClassOf.call(void 0, pitch);
|
|
67
69
|
const rest = [];
|
|
68
70
|
for (let letter = 0; letter < 7; letter += 1) {
|
|
69
71
|
const alter = alterationFor(letter, pc);
|
|
@@ -83,28 +85,33 @@ function candidatesFor(pitch, preferred) {
|
|
|
83
85
|
];
|
|
84
86
|
}
|
|
85
87
|
function chordSpellingOf(pc, chord, tonic, key) {
|
|
86
|
-
for (const tone of
|
|
87
|
-
if (
|
|
88
|
+
for (const tone of _chunkYDGMWH43cjs.spellChord.call(void 0, chord, tonic, key)) {
|
|
89
|
+
if (_chunkS3QELJUEcjs.pitchClassOf.call(void 0, _chunkS3QELJUEcjs.naturalPitchClassOf.call(void 0, tone.letter) + tone.alter) === pc) {
|
|
88
90
|
return tone;
|
|
89
91
|
}
|
|
90
92
|
}
|
|
91
93
|
const bass = chord.bassPc;
|
|
92
|
-
if (bass === void 0 ||
|
|
94
|
+
if (bass === void 0 || _chunkS3QELJUEcjs.pitchClassOf.call(void 0, bass) !== pc) {
|
|
93
95
|
return void 0;
|
|
94
96
|
}
|
|
95
97
|
const hint = chord.bassSpelling;
|
|
96
|
-
return hint !== void 0 &&
|
|
98
|
+
return hint !== void 0 && _chunkS3QELJUEcjs.pitchClassOf.call(void 0, _chunkS3QELJUEcjs.naturalPitchClassOf.call(void 0, hint.letter) + hint.alter) === pc ? { letter: _chunkS3QELJUEcjs.diatonicLetterOf.call(void 0, hint.letter), alter: hint.alter } : _chunkYDGMWH43cjs.spellPitchClass.call(void 0, pc, tonic, key);
|
|
99
|
+
}
|
|
100
|
+
function keyToneSpelling(pc, tonic, key) {
|
|
101
|
+
const own = _chunkYDGMWH43cjs.isScaleTone.call(void 0, pc, key) || _chunkYDGMWH43cjs.cadencesThroughRaisedSeventh.call(void 0, key) && _chunkYDGMWH43cjs.isScaleTone.call(void 0, pc, { rootPc: key.rootPc, modeMask12: _chunkYDGMWH43cjs.MELODIC_MINOR_MASK });
|
|
102
|
+
return own ? _chunkYDGMWH43cjs.spellPitchClass.call(void 0, pc, tonic, key) : void 0;
|
|
97
103
|
}
|
|
98
104
|
function stateFor(pitch, chord, tonic, key) {
|
|
99
|
-
const pc =
|
|
105
|
+
const pc = _chunkS3QELJUEcjs.pitchClassOf.call(void 0, pitch);
|
|
100
106
|
const fromChord = chord === null ? void 0 : chordSpellingOf(pc, chord, tonic, key);
|
|
101
|
-
const
|
|
102
|
-
const reference = _nullishCoalesce(fromChord, () => (
|
|
103
|
-
const mismatch = fromChord !== void 0 ? CHORD_MISMATCH :
|
|
107
|
+
const keyTone = keyToneSpelling(pc, tonic, key);
|
|
108
|
+
const reference = _nullishCoalesce(_nullishCoalesce(fromChord, () => ( keyTone)), () => ( _chunkYDGMWH43cjs.spellPitchClass.call(void 0, pc, tonic, key)));
|
|
109
|
+
const mismatch = fromChord !== void 0 ? CHORD_MISMATCH : keyTone !== void 0 ? SCALE_TONE_MISMATCH : KEY_MISMATCH;
|
|
104
110
|
const candidates = candidatesFor(pitch, reference);
|
|
105
111
|
return {
|
|
106
112
|
pitch,
|
|
107
|
-
chromatic:
|
|
113
|
+
chromatic: keyTone === void 0,
|
|
114
|
+
keyTone,
|
|
108
115
|
candidates,
|
|
109
116
|
emissions: candidates.map(
|
|
110
117
|
(candidate) => (sameSpelling(candidate, reference) ? 0 : mismatch) + ACCIDENTAL * Math.abs(candidate.alter)
|
|
@@ -138,24 +145,25 @@ function directionCost(note, chromatic, semitones) {
|
|
|
138
145
|
}
|
|
139
146
|
function transitionCost(from, source, to, target) {
|
|
140
147
|
const semitones = to.pitch - from.pitch;
|
|
141
|
-
|
|
148
|
+
const keyInterval = from.keyTone !== void 0 && to.keyTone !== void 0 && sameSpelling(source, from.keyTone) && sameSpelling(target, to.keyTone);
|
|
149
|
+
return (keyInterval ? 0 : letterStepCost(source, target, semitones)) + directionCost(target, to.chromatic, semitones) + directionCost(source, from.chromatic, semitones);
|
|
142
150
|
}
|
|
143
151
|
function spellLine(notes, timeline, key, opts = {}) {
|
|
144
|
-
|
|
145
|
-
const resolved =
|
|
152
|
+
_chunkS3QELJUEcjs.assertOptions.call(void 0, opts, "opts");
|
|
153
|
+
const resolved = _chunkYDGMWH43cjs.resolveKey.call(void 0, key);
|
|
146
154
|
const scale = resolved.scale;
|
|
147
|
-
const given = opts.tonic === void 0 ? void 0 :
|
|
148
|
-
|
|
155
|
+
const given = opts.tonic === void 0 ? void 0 : _chunkS3QELJUEcjs.toNoteData.call(void 0, opts.tonic);
|
|
156
|
+
_chunkS3QELJUEcjs.assertNoteEvents.call(void 0, notes, "line notes", {
|
|
149
157
|
allowNonPositiveDuration: true,
|
|
150
158
|
budget: opts.budget
|
|
151
159
|
});
|
|
152
|
-
|
|
160
|
+
_chunkS3QELJUEcjs.assertGenerationBudget.call(void 0,
|
|
153
161
|
notes.length * SPELLINGS_PER_PITCH * SPELLINGS_PER_PITCH,
|
|
154
162
|
"line spelling states",
|
|
155
163
|
opts.budget
|
|
156
164
|
);
|
|
157
165
|
if (given !== void 0) {
|
|
158
|
-
|
|
166
|
+
_chunkYDGMWH43cjs.assertTonicOf.call(void 0, given, scale, "spellLine");
|
|
159
167
|
}
|
|
160
168
|
if (notes.length === 0) {
|
|
161
169
|
return [];
|
|
@@ -210,4 +218,4 @@ function spellLine(notes, timeline, key, opts = {}) {
|
|
|
210
218
|
|
|
211
219
|
|
|
212
220
|
exports.spellLine = spellLine;
|
|
213
|
-
//# sourceMappingURL=chunk-
|
|
221
|
+
//# sourceMappingURL=chunk-E3QO3UET.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/libcantus/libcantus/ts/dist/chunk-E3QO3UET.cjs","../src/analyze/spelling/index.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACoDO,IAAM,eAAA,EAAiB,EAAA;AAGvB,IAAM,o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,KAAK,CAAA,4BAAA,CAAI,MAAM,GAAA,UAAK,GAAA;AAAA,EACpC;AACA,EAAA,OAAO,MAAA,CAAO,GAAA,CAAI,CAAC,KAAA,EAAO,KAAA,EAAA,oBAAU,KAAA,CAAM,UAAA,kBAAW,MAAA,CAAO,KAAK,CAAA,UAAK,GAAC,CAAA,UAAK,KAAA,CAAM,WAAS,CAAA;AAC7F;ADvRA;AACA;AACE;AACF,8BAAC","file":"/home/runner/work/libcantus/libcantus/ts/dist/chunk-E3QO3UET.cjs","sourcesContent":[null,"/**\n * Line spelling: name every note of a melodic line in one pass.\n *\n * {@link spellPitch} decides one note from the key, the root of the chord under\n * it and its two immediate neighbours. That is enough for a single note, but a\n * line spelled note by note can zig-zag between the two readings of one idea —\n * a rising whole-tone figure comes out F# Ab Bb, with a diminished third in the\n * middle of it.\n *\n * This module solves the whole line at once. The theory layer's own judgment\n * becomes the cost of emitting a spelling, the melodic rules become the cost of\n * moving from one spelling to the next, and a dynamic program takes the\n * cheapest path across the line. Nothing here re-decides what\n * {@link spellPitchClass} and {@link spellChord} already decide: it only weighs\n * their answers against the shape of the line they sit in.\n */\n\nimport type { Note, NoteLike } from '../../core/pitch/index.js';\nimport {\n diatonicLetterOf as mod7,\n pitchClassOf as mod12,\n naturalPitchClassOf as naturalPc,\n toNoteData,\n} from '../../core/pitch/index.js';\nimport type { KeyScale, NoteEvent } from '../../core/types.js';\nimport {\n assertGenerationBudget,\n assertNoteEvents,\n assertOptions,\n} from '../../core/validation/index.js';\nimport type { Chord } from '../../theory/chord/index.js';\nimport {\n isScaleTone,\n MELODIC_MINOR_MASK,\n resolveKey,\n type SpelledKeyLike,\n} from '../../theory/scale/index.js';\nimport { assertTonicOf, spellChord, spellPitchClass } from '../../theory/spelling/index.js';\nimport { cadencesThroughRaisedSeventh } from '../../theory/tendency/index.js';\nimport type { ChordTimeline } from '../timeline/index.js';\n\n/**\n * The four rules, and what happens where they pull against each other.\n *\n * The costs below are spread far enough apart that a rule can never be\n * outvoted by any number of the rules under it, which fixes the precedence:\n *\n * 1. **The sounding chord.** A note the chord names takes the chord's own\n * spelling of that tone. This is the one place the line departs from\n * {@link spellPitchClass}, which never respells a tone of the key: over a\n * Db7 the seventh has to read Cb even in C major, where B is a scale tone,\n * because a dominant seventh spelled as a sixth is not the chord that was\n * played.\n * 2. **The key's own tones.** Anything else the key itself spells — a scale\n * tone, the tonic, and in a minor key the raised sixth and seventh it\n * cadences through — keeps that spelling, and an interval between two of\n * them is written as the key writes it, so the augmented second of the\n * harmonic minor is no shape error. No amount of melodic pressure moves it.\n * 3. **The shape of the line, then its direction.** A chromatic note is spelled\n * so the letters of the intervals around it match the intervals actually\n * sounding, and a stepwise line then prefers sharps rising and flats\n * falling. Shape outranks direction because a rising line spelled with\n * sharps is still wrong if it spells a whole tone as a diminished third.\n * 4. **The key's chromatic convention, then the fewest accidentals.** What the\n * key alone would have said, as the tiebreak it is: the direction rule beats\n * it, which is why a chromatic ascent in C major spells C# D# G# A# rather\n * than the flats the key prefers, but one-sided evidence — a chromatic note\n * with only one stepwise neighbour — does not.\n */\n\n/** Emission cost for a spelling the chord sounding under the note does not name. */\nexport const CHORD_MISMATCH = 64;\n\n/** Emission cost for respelling a tone the key already names. */\nexport const SCALE_TONE_MISMATCH = 32;\n\n/** Transition cost per diatonic step an interval's letters miss its written size by. */\nexport const LETTER_STEP_DEVIATION = 8;\n\n/**\n * How many steps of deviation are counted before the cost stops growing.\n *\n * Two letters out is already an interval no reading supports, and capping there\n * keeps the whole melodic term below {@link SCALE_TONE_MISMATCH}, so a badly\n * shaped line can never argue a scale tone out of its key spelling.\n */\nexport const MAX_COUNTED_DEVIATION = 2;\n\n/** Transition cost for an accidental leaning against the direction of a stepwise line. */\nexport const AGAINST_DIRECTION = 3;\n\n/** Emission cost for a chromatic spelling the key alone would not choose. */\nexport const KEY_MISMATCH = 4;\n\n/** Emission cost per semitone of alteration: what minimises accidentals overall. */\nexport const ACCIDENTAL = 1;\n\n/** Widest melodic interval still counted as a step, where the direction rule applies. */\nexport const MAX_STEP = 2;\n\n/** Widest alteration a spelling may carry: a double accidental. */\nexport const MAX_ALTER = 2;\n\n/**\n * Spellings each pitch class has within a double accidental.\n *\n * Always exactly three — a natural or its accidental, one letter above, one\n * letter below (C is C, B# and Dbb) — which is what bounds the work the dynamic\n * program is allowed to do.\n */\nexport const SPELLINGS_PER_PITCH = 3;\n\n/**\n * The diatonic letter distances a melodic interval of a given size is\n * conventionally written with, indexed by its semitone class.\n *\n * Most sizes read only one way: a whole tone is a second, a minor third is a\n * third, so spelling one as anything else costs. Two sizes read two ways and\n * both are free — a semitone is either a chromatic inflection of one letter\n * (F to F#) or a diatonic step (E to F), and the tritone is either an augmented\n * fourth or a diminished fifth. Direction chooses between those.\n */\nexport const CONVENTIONAL_LETTER_STEPS: readonly (readonly number[])[] = [\n [0], // unison\n [0, 1], // chromatic semitone or diatonic semitone\n [1], // second\n [2], // minor third\n [2], // major third\n [3], // fourth\n [3, 4], // augmented fourth or diminished fifth\n [4], // fifth\n [5], // minor sixth\n [5], // major sixth\n [6], // minor seventh\n [6], // major seventh\n];\n\n/**\n * Options for {@link spellLine}.\n *\n * @category Arrangement & Analysis\n */\nexport type SpellLineOptions = {\n /**\n * Tonic spelling to anchor the key, for a caller that already knows how the\n * piece is written. It must sound the key's own root pitch class; anything\n * else is rejected rather than spelled. Defaults to the conventional\n * spelling the key itself is written with. Accepted as a note name, a MIDI\n * number, note data, or a `Note`.\n */\n tonic?: NoteLike;\n /** Upper bound on the work the line may cost; defaults to the generation budget. */\n budget?: number;\n};\n\n/** Shortest signed alteration (in [-6, 6]) taking a letter's natural pc to `pc`. */\nfunction alterationFor(letter: number, pc: number): number {\n const distance = mod12(pc - naturalPc(letter));\n return distance > 6 ? distance - 12 : distance;\n}\n\n/** The octave that reproduces `pitch` from a letter and its alteration. */\nfunction octaveFor(pitch: number, letter: number, alter: number): number {\n return (pitch - naturalPc(letter) - alter) / 12 - 1;\n}\n\n/** Whether two spellings name the same letter with the same alteration. */\nfunction sameSpelling(a: Note, b: Note): boolean {\n return a.letter === b.letter && a.alter === b.alter;\n}\n\n/**\n * Every spelling of `pitch` within a double accidental, `preferred` first.\n *\n * The order is what settles a tie: two readings that cost the same are equally\n * defensible, and the one the theory layer would have chosen alone is then the\n * one that stands.\n */\nfunction candidatesFor(pitch: number, preferred: Note): Note[] {\n const pc = mod12(pitch);\n const rest: Note[] = [];\n for (let letter = 0; letter < 7; letter += 1) {\n const alter = alterationFor(letter, pc);\n if (Math.abs(alter) > MAX_ALTER || letter === preferred.letter) {\n continue;\n }\n rest.push({ letter, alter, octave: octaveFor(pitch, letter, alter) });\n }\n rest.sort((a, b) => Math.abs(a.alter) - Math.abs(b.alter) || a.letter - b.letter);\n return [\n {\n letter: preferred.letter,\n alter: preferred.alter,\n octave: octaveFor(pitch, preferred.letter, preferred.alter),\n },\n ...rest,\n ];\n}\n\n/**\n * The chord's own spelling of a pitch class, or undefined when the chord does\n * not sound it.\n *\n * The tones come from {@link spellChord}, so a chord carrying its own spellings\n * — a parsed symbol, an augmented sixth — is read by them; a slash bass outside\n * the chord's tones is spelled from its hint when it has one.\n */\nfunction chordSpellingOf(pc: number, chord: Chord, tonic: Note, key: KeyScale): Note | undefined {\n for (const tone of spellChord(chord, tonic, key)) {\n if (mod12(naturalPc(tone.letter) + tone.alter) === pc) {\n return tone;\n }\n }\n const bass = chord.bassPc;\n if (bass === undefined || mod12(bass) !== pc) {\n return undefined;\n }\n const hint = chord.bassSpelling;\n return hint !== undefined && mod12(naturalPc(hint.letter) + hint.alter) === pc\n ? { letter: mod7(hint.letter), alter: hint.alter }\n : spellPitchClass(pc, tonic, key);\n}\n\n/**\n * The key's spelling of a pitch class it counts as its own, or undefined for a\n * chromatic one.\n *\n * Its own tones are the scale's, and in a minor key also the raised sixth and\n * seventh of its melodic and harmonic forms: the leading tone of A minor is the\n * G# on the seventh letter, never an Ab, whichever way the line moves around it.\n */\nfunction keyToneSpelling(pc: number, tonic: Note, key: KeyScale): Note | undefined {\n const own =\n isScaleTone(pc, key) ||\n (cadencesThroughRaisedSeventh(key) &&\n isScaleTone(pc, { rootPc: key.rootPc, modeMask12: MELODIC_MINOR_MASK }));\n return own ? spellPitchClass(pc, tonic, key) : undefined;\n}\n\n/** One note of the line, with the spellings open to it and what each costs. */\ntype LineState = {\n pitch: number;\n /** True when the key does not already spell this pitch, so direction may decide. */\n chromatic: boolean;\n /** The key's spelling of the pitch when it is one of the key's own tones. */\n keyTone: Note | undefined;\n candidates: Note[];\n emissions: number[];\n /** The spelling the note-by-note path would have chosen, used as the fallback. */\n reference: Note;\n};\n\n/**\n * Weigh every spelling open to one note against what the chord and the key say\n * about it.\n *\n * The reference spelling is the theory layer's own answer — the chord's, when\n * the chord names the note, and the key's otherwise — and the cost of departing\n * from it is what ranks the three rules that do not depend on the neighbours.\n */\nfunction stateFor(pitch: number, chord: Chord | null, tonic: Note, key: KeyScale): LineState {\n const pc = mod12(pitch);\n const fromChord = chord === null ? undefined : chordSpellingOf(pc, chord, tonic, key);\n const keyTone = keyToneSpelling(pc, tonic, key);\n const reference = fromChord ?? keyTone ?? spellPitchClass(pc, tonic, key);\n const mismatch =\n fromChord !== undefined\n ? CHORD_MISMATCH\n : keyTone !== undefined\n ? SCALE_TONE_MISMATCH\n : KEY_MISMATCH;\n const candidates = candidatesFor(pitch, reference);\n return {\n pitch,\n chromatic: keyTone === undefined,\n keyTone,\n candidates,\n emissions: candidates.map(\n (candidate) =>\n (sameSpelling(candidate, reference) ? 0 : mismatch) +\n ACCIDENTAL * Math.abs(candidate.alter),\n ),\n reference,\n };\n}\n\n/** A spelling's position on the diatonic ladder, octave included. */\nfunction diatonicIndex(note: Note): number {\n return note.letter + 7 * (note.octave ?? 0);\n}\n\n/**\n * What the letters of a melodic interval cost when they do not match the\n * interval that actually sounds.\n *\n * Both notes are already spelled, so the sounding interval and the written one\n * are both known: a whole tone written F# to Ab is two letters apart where a\n * second is one, and pays for the difference.\n */\nfunction letterStepCost(from: Note, to: Note, semitones: number): number {\n const written = diatonicIndex(to) - diatonicIndex(from);\n const size = Math.abs(semitones);\n const octaves = Math.floor(size / 12);\n const direction = semitones < 0 ? -1 : 1;\n let deviation = Number.POSITIVE_INFINITY;\n for (const steps of CONVENTIONAL_LETTER_STEPS[size % 12] ?? []) {\n deviation = Math.min(deviation, Math.abs(written - direction * (octaves * 7 + steps)));\n }\n if (!Number.isFinite(deviation)) {\n return 0;\n }\n return LETTER_STEP_DEVIATION * Math.min(deviation, MAX_COUNTED_DEVIATION);\n}\n\n/**\n * What an accidental costs for leaning the wrong way in a stepwise line: a\n * rising line is written with sharps and a falling one with flats.\n *\n * Only steps are judged. The rule describes chromatic motion, and a leap onto a\n * flat says nothing about the flat — the key and the chord have the whole story\n * there.\n */\nfunction directionCost(note: Note, chromatic: boolean, semitones: number): number {\n if (!chromatic || semitones === 0 || Math.abs(semitones) > MAX_STEP) {\n return 0;\n }\n const rising = semitones > 0;\n return (rising && note.alter < 0) || (!rising && note.alter > 0) ? AGAINST_DIRECTION : 0;\n}\n\n/**\n * The cost of following one spelling with another.\n *\n * Direction is charged to both notes: a chromatic note is judged by the step it\n * arrives on and by the step it leaves on, so a note inside a run collects the\n * rule twice and a note at the end of one collects it once. Two of the key's own\n * tones spelled as the key spells them are written as the key writes them, so\n * their letters cost nothing.\n */\nfunction transitionCost(from: LineState, source: Note, to: LineState, target: Note): number {\n const semitones = to.pitch - from.pitch;\n const keyInterval =\n from.keyTone !== undefined &&\n to.keyTone !== undefined &&\n sameSpelling(source, from.keyTone) &&\n sameSpelling(target, to.keyTone);\n return (\n (keyInterval ? 0 : letterStepCost(source, target, semitones)) +\n directionCost(target, to.chromatic, semitones) +\n directionCost(source, from.chromatic, semitones)\n );\n}\n\n/**\n * Spell a whole melodic line at once, so its notes agree with each other.\n *\n * Every note is spelled together with the rest of the line rather than one at a\n * time: each pitch offers the three spellings a double accidental allows, the\n * chord and the key price them, the intervals between neighbours price the\n * pairs, and the cheapest reading of the whole line wins. Ties fall to the\n * spelling {@link spellPitchClass} would have chosen alone, so the answer never\n * drifts from the theory layer without a reason.\n *\n * Four rules decide, in this order:\n *\n * 1. A note the sounding chord names takes that chord's spelling of it, even\n * when the key spells the pitch otherwise — the seventh of a Db7 reads Cb in\n * C major, not B.\n * 2. Anything else the key spells as its own — a scale tone, or the raised\n * sixth and seventh of a minor key — keeps its key spelling, so the leading\n * tone of A minor reads G# even where the line falls through it.\n * 3. A chromatic note is spelled so the written intervals around it match the\n * sounding ones, and then so a rising step carries a sharp and a falling\n * step a flat.\n * 4. Failing all of that, the key's own chromatic spelling stands, and the\n * fewest accidentals win.\n *\n * Without a timeline — pass `null` — rules 2 to 4 still apply in full, so a\n * diatonic line and a chromatic run come out the same. What is lost is rule 1:\n * a chromatic chord can no longer name its own tones, so the tones of a\n * borrowed or altered chord fall back to the key's convention (that Cb becomes\n * B), and an enharmonically ambiguous tone under a chord that would have fixed\n * it is decided by the line's direction instead.\n *\n * @param notes The line, monophonic and in time order. Notes sharing an onset\n * are read as consecutive, so split polyphonic material into voices first.\n * @param timeline The chords sounding under the line, or null when only the key\n * is known. Each note is judged against the chord at its own onset.\n * @param key The key the line is written in, as a key name, a key/scale, or a\n * `Key`.\n * @param opts Optional tonic spelling and work budget.\n * @returns One spelled note per input note, in input order, each carrying the\n * octave that reproduces its pitch.\n * @throws If `opts.tonic` does not sound the key's root pitch class, if a note\n * event is malformed, or if the line is longer than the budget allows.\n * @example\n * ```ts\n * import { chordTimelineFromChords, majorKey, noteNames, spellLine } from '@libraz/libcantus';\n * // A chromatic ascent spells with sharps, whatever the key would say alone.\n * const rising = [60, 61, 62, 63, 64].map((pitch, index) => ({\n * pitch,\n * startBeat: index,\n * durationBeat: 1,\n * }));\n * noteNames(spellLine(rising, null, majorKey(0)));\n * // ['C4', 'C#4', 'D4', 'D#4', 'E4']\n * // Under a Db7 the same B sounds as the chord's seventh.\n * const timeline = chordTimelineFromChords([{ rootPc: 1, quality: 'dom7', startBeat: 0 }], 4);\n * noteNames(spellLine([{ pitch: 71, startBeat: 0, durationBeat: 1 }], timeline, majorKey(0)));\n * // ['Cb5']\n * ```\n * @category Arrangement & Analysis\n */\nexport function spellLine(\n notes: readonly NoteEvent[],\n timeline: ChordTimeline | null,\n key: SpelledKeyLike,\n opts: SpellLineOptions = {},\n): Note[] {\n assertOptions(opts, 'opts');\n // Read whole rather than reduced: a line in Ab minor is written on flats, and\n // a key handed in spelled that way would otherwise have its spelling derived\n // back from the pitch classes and come out in G# minor.\n const resolved = resolveKey(key);\n const scale = resolved.scale;\n const given = opts.tonic === undefined ? undefined : toNoteData(opts.tonic);\n assertNoteEvents(notes, 'line notes', {\n allowNonPositiveDuration: true,\n budget: opts.budget,\n });\n // The dynamic program compares every spelling of a note with every spelling\n // of the one before it, so the work is bounded before any of it is done.\n assertGenerationBudget(\n notes.length * SPELLINGS_PER_PITCH * SPELLINGS_PER_PITCH,\n 'line spelling states',\n opts.budget,\n );\n if (given !== undefined) {\n assertTonicOf(given, scale, 'spellLine');\n }\n if (notes.length === 0) {\n return [];\n }\n const tonic = given ?? resolved.tonic;\n const states = notes.map((note) =>\n stateFor(note.pitch, timeline?.at(note.startBeat) ?? null, tonic, scale),\n );\n\n // Viterbi across the line: `costs` holds the cheapest path reaching each\n // spelling of the current note, and `back` remembers which spelling of the\n // previous note that path came through.\n let costs: number[] = [];\n let previous: LineState | undefined;\n const back: number[][] = [];\n for (const current of states) {\n if (previous === undefined) {\n costs = [...current.emissions];\n back.push(current.candidates.map(() => 0));\n previous = current;\n continue;\n }\n const reached: number[] = [];\n const chosen: number[] = [];\n for (const [target, candidate] of current.candidates.entries()) {\n let best = Number.POSITIVE_INFINITY;\n let bestSource = 0;\n for (const [source, sourceNote] of previous.candidates.entries()) {\n const total =\n (costs[source] ?? Number.POSITIVE_INFINITY) +\n transitionCost(previous, sourceNote, current, candidate);\n if (total < best) {\n best = total;\n bestSource = source;\n }\n }\n reached.push(best + (current.emissions[target] ?? 0));\n chosen.push(bestSource);\n }\n costs = reached;\n back.push(chosen);\n previous = current;\n }\n\n let cursor = 0;\n for (const [index, cost] of costs.entries()) {\n if (cost < (costs[cursor] ?? Number.POSITIVE_INFINITY)) {\n cursor = index;\n }\n }\n const picked: number[] = new Array(states.length).fill(0);\n for (let index = states.length - 1; index >= 0; index -= 1) {\n picked[index] = cursor;\n cursor = back[index]?.[cursor] ?? 0;\n }\n return states.map((state, index) => state.candidates[picked[index] ?? 0] ?? state.reference);\n}\n"]}
|