barmark 0.26.1 → 0.27.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/CHANGELOG.md CHANGED
@@ -9,6 +9,33 @@ Releases follow the process in [RELEASING.md](RELEASING.md).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.27.0] - 2026-11-30
13
+
14
+ ### Added
15
+
16
+ - **`keyFromChart` and `keyFromChords`: the key read from the chords.**
17
+ `keyFromChart(parse)` reads a chart's key from its chords in play
18
+ order; `keyFromChords(spans)` does the same for timed chords from
19
+ anywhere, a chord detector's output for one. Both give the keys the
20
+ music moves through and a `margin` that says how sure the read is
21
+ (`KEY_SURE`, 0.1, is where stem-bench found it right 97 times in 100).
22
+ It is Stem Shovel's rule, held to the app's own code case for case:
23
+ stem-bench's Study 53 measured it at 47 of 49 songs' opening keys,
24
+ against 41 for pitch-class profiles on the audio. Its known weaknesses
25
+ (a tie between a key and its relative, chords with no third, an intro
26
+ in another key) are in the README. No chart means anything different.
27
+ - **A section heading says how far its bars' numbers stand on the page**
28
+ (Kevin, 2026-11-30; grammar A.7 and decisions log): a heading in `lines`
29
+ carries `pageShift`, what to add to the `firstWritten` of the bar lines
30
+ drawn under it for their numbers on the page, every drawn bar counted
31
+ once from the top. A replay heading that a pass plays counts as its
32
+ section written again in its place, so the numbers after it go on from
33
+ there instead of repeating: in a chart whose Verse (bars 10 and 11) is
34
+ replayed after bar 23, the replay draws 24 and 25, and the sections
35
+ after it count those two too. `written` and `firstWritten` keep their
36
+ meaning, the bar as written; a repeat still counts its bars once. Absent
37
+ when 0, so a chart with no replay that plays parses exactly as before.
38
+
12
39
  ## [0.26.1] - 2026-11-30
13
40
 
14
41
  ### Fixed
@@ -1034,7 +1061,8 @@ The first working release: the reference parser and printer for the
1034
1061
 
1035
1062
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
1036
1063
 
1037
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.26.1...HEAD
1064
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.27.0...HEAD
1065
+ [0.27.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.26.1...barmark-v0.27.0
1038
1066
  [0.26.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.26.0...barmark-v0.26.1
1039
1067
  [0.26.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.25.1...barmark-v0.26.0
1040
1068
  [0.25.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.25.0...barmark-v0.25.1
package/README.md CHANGED
@@ -199,6 +199,12 @@ an object. It has two kinds of field:
199
199
  a part's share of the lines in a very long chart of many parts (the
200
200
  grammar's A.7 row lists every case). A pickup's line has
201
201
  `firstWritten: 0`, which is falsy: test it with `!== undefined`.
202
+ A section heading carries `pageShift` when a replay that plays comes
203
+ before it, or is it: add it to the `firstWritten` of the bar lines drawn
204
+ under that heading (for a replay, its section's) to number the bars down
205
+ the page, a replayed section counted as written again there. It is absent
206
+ when 0, and on a heading with no bar line drawn under it, so a chart
207
+ with no replay that plays has none.
202
208
  - **The chart as played**, worked out from the written lines:
203
209
  - `events` is play order with fermatas and an open repeat kept as
204
210
  events.
@@ -236,6 +242,79 @@ package's minor versions: 0.17.0, for example, added the `break` and
236
242
  music itself changes. An open repeat (`x ...`) plays its bars once in
237
243
  `bars`, so its later passes have no index of their own.
238
244
 
245
+ ### The key from the chords
246
+
247
+ `keyFromChart` reads a chart's key from its chords, and `keyFromChords`
248
+ does the same for timed chords from anywhere, a chord detector's output
249
+ for one:
250
+
251
+ ```ts
252
+ import { KEY_SURE, keyFromChart, keyFromChords, parseChart, parseHarte } from "barmark";
253
+
254
+ const read = keyFromChart(parseChart("tempo: 96\n| G | G | C | D |\n"));
255
+ read.keys; // [{ bar: 1, key: { tonic: "G", mode: "major" } }]
256
+ read.margin; // 0.25: at or over KEY_SURE (0.1), a clear read
257
+
258
+ // A detector's chords, as Harte labels with times in seconds:
259
+ const runs = [["A:min7", 0, 12], ["D:min", 12, 18], ["E:7", 18, 24], ["A:min", 24, 36]] as const;
260
+ const spans = runs.flatMap(([label, start, end]) => {
261
+ const chord = parseHarte(label);
262
+ return chord && chord !== "N" && chord !== "X" ? [{ chord, start, end }] : [];
263
+ });
264
+ keyFromChords(spans).keys; // [{ start: 0, key: { tonic: "A", mode: "minor" } }]
265
+ ```
266
+
267
+ Each ten-second window scores the 24 major and minor keys by the chord
268
+ time whose triad lies in the key's scale (a minor key also takes its
269
+ major V, and the tonic triad counts half as much again); the best path
270
+ through the windows, with a cost for each change of key, gives the keys
271
+ the music moves through. `keys` has one entry for music that stays put
272
+ and one more for each change that lasts; it is empty when there are no
273
+ chords. Neither function throws.
274
+
275
+ This is Stem Shovel's rule, and `keyFromChords` is held to the app's own
276
+ code case for case. [stem-bench](https://github.com/kevinpeckham/stem-bench)
277
+ measured that rule on a chord model's reading of recordings (Study 53,
278
+ 2026-11-30): the opening key right on 47 of 49 songs and 44 of 48
279
+ art-song recordings, against 41 and 28 for pitch-class profiles on the
280
+ audio, which name the fifth's key when a voice rests on the fifth. A
281
+ language model asked about the same chords did no better.
282
+
283
+ **`margin` says how sure the read is**: how far the least certain key
284
+ stands clear of the next best on the same chords, as a share of the
285
+ chord time. At `KEY_SURE` (0.1) or more the bench found the rule right
286
+ 97 times in 100. Under it, show the key as a suggestion. What the rule
287
+ gets wrong is kept as the app has it, so the bench's numbers hold:
288
+
289
+ - **A tie goes to the first key in the order C major, C minor, C♯ major
290
+ and so on.** I, IV, V and vi held alike fit a key and its relative
291
+ equally, at margin 0.
292
+ - **Chords with no third place no key.** A chart written in power chords
293
+ or suspended chords fits several keys alike: expect a margin near 0.
294
+ - **A first window in another key is reported as the opening key**: an
295
+ intro on the parallel major of a minor song, say.
296
+ - **Most of its misses on recordings are the parallel key** (major for
297
+ minor on the same tonic).
298
+
299
+ `keyFromChart` times the chart's play order in seconds by its tempo (120
300
+ where it gives none; a rit. or accel. is not followed), so its windows
301
+ are the ten seconds that were measured. A repeat counts each time it is
302
+ played, a hold keeps the chord before it sounding, and `N.C.`, silence,
303
+ an unknown slot and a note set count for nothing. In a chart of several
304
+ parts the harmony is the first part's that writes a chord symbol, read
305
+ throughout. The chart's own `key:` line is not consulted, so the two can
306
+ be compared. A key starts at `bar`, the `PlayedBar.index` of the bar its
307
+ window starts in. The window, the cost of a change and the tonic's bonus
308
+ are options (`KeyOptions`), and for `keyFromChords` the music's length,
309
+ past which chords are not read.
310
+
311
+ A chord is counted by the triad its notes make, not by how its name is
312
+ spelled, so a power chord is its root and fifth. Both functions take time
313
+ linear in the chords they are given: music long enough for more than
314
+ 65,536 windows, or chords that overlap for hours, are read in
315
+ proportionally longer windows, and a chart is read as far as its first
316
+ quarter of a million played slots.
317
+
239
318
  ## Develop
240
319
 
241
320
  ```
@@ -66,4 +66,9 @@ sing?: Sing): {
66
66
  * a part's share of lines. `withFirstWritten` makes the bar lines' field.
67
67
  */
68
68
  firsts: Map<number, number>;
69
+ /**
70
+ * Each heading's section as `firsts` counts it, by the heading's line: how
71
+ * many bars were written before it, and before the next heading.
72
+ */
73
+ spans: Map<number, number[]>;
69
74
  };
@@ -260,8 +260,14 @@ sing) {
260
260
  if (written >= first)
261
261
  firsts.set(l.line, first);
262
262
  };
263
- for (const l of sections.flatMap((s) => s.lines))
264
- readLine(l);
263
+ const spans = new Map();
264
+ for (const s of sections) {
265
+ const from = written;
266
+ for (const l of s.lines)
267
+ readLine(l);
268
+ if (s.heading)
269
+ spans.set(s.heading.line, [from, written]);
270
+ }
265
271
  const unused = pending.mark;
266
272
  if (unused)
267
273
  error(unused.line, "a rehearsal mark marks the bar after it; none follows", `@${unused.label}`);
@@ -683,5 +689,5 @@ sing) {
683
689
  });
684
690
  if (pedal)
685
691
  append(diagnostics, pedalWarnings(flattenBars(events)));
686
- return { events, sections: sectionsOut, diagnostics, stopped: capped, firsts };
692
+ return { events, sections: sectionsOut, diagnostics, stopped: capped, firsts, spans };
687
693
  }
@@ -6,6 +6,7 @@ export { beatsOf, DIRECTIVE_NAMES, parseDirectiveLine, parseMeter } from "./dire
6
6
  export { readDocument } from "./document.js";
7
7
  export { expand, flattenBars, MAX_EXPANDED_BARS } from "./expand.js";
8
8
  export { CLEF_NAMES, type ClefName, INSTRUMENTS, type InstrumentInfo, type InstrumentName, instrumentInfo, type WrittenInterval, } from "./instruments.js";
9
+ export { type ChartKeyRead, type ChordSpan, KEY_SURE, type KeyChord, type KeyOptions, type KeyRead, keyFromChart, keyFromChords, } from "./keyFromChords.js";
9
10
  export { conventionalKey, keyFromText, printKey, spellPitch } from "./keys.js";
10
11
  export { MAX_LINES } from "./lines.js";
11
12
  export { extractPart, parseChart } from "./parse.js";
@@ -6,6 +6,7 @@ export { beatsOf, DIRECTIVE_NAMES, parseDirectiveLine, parseMeter } from "./dire
6
6
  export { readDocument } from "./document.js";
7
7
  export { expand, flattenBars, MAX_EXPANDED_BARS } from "./expand.js";
8
8
  export { CLEF_NAMES, INSTRUMENTS, instrumentInfo, } from "./instruments.js";
9
+ export { KEY_SURE, keyFromChart, keyFromChords, } from "./keyFromChords.js";
9
10
  export { conventionalKey, keyFromText, printKey, spellPitch } from "./keys.js";
10
11
  export { MAX_LINES } from "./lines.js";
11
12
  export { extractPart, parseChart } from "./parse.js";
@@ -0,0 +1,70 @@
1
+ import type { Interval } from "../chords/types.js";
2
+ import type { ChartParse, Key } from "./types.js";
3
+ /** What the rule needs of a chord: a `ChordRecord`, or what `parseHarte` reads. A null root (a note set) counts for nothing. */
4
+ export type KeyChord = {
5
+ root: string | null;
6
+ intervals: Interval[];
7
+ };
8
+ /** A chord sounding from `start` to `end`, in one unit throughout (seconds, beats). */
9
+ export type ChordSpan = {
10
+ chord: KeyChord;
11
+ start: number;
12
+ end: number;
13
+ };
14
+ export type KeyOptions = {
15
+ /** The length of a window, in the spans' unit. Default 10: the ten seconds Study 53 measured. */
16
+ window?: number;
17
+ /** What a change of key costs, in windows' worth of chords that fit only the new key. Default 1. */
18
+ changeCost?: number;
19
+ /** What the tonic triad's time counts for, on top of lying in the scale. Default 0.5. */
20
+ tonicBonus?: number;
21
+ /** Where the music ends (a recording's length): windows run to it, and chords past it are not read. Default: the last span's end. */
22
+ duration?: number;
23
+ };
24
+ /** The keys through the music, a change each (one when it stays put; none when there are no chords). */
25
+ export type KeyRead = {
26
+ keys: {
27
+ start: number;
28
+ key: Key;
29
+ }[];
30
+ /**
31
+ * How far the least certain of those keys stands clear of the next key
32
+ * on the same chords, as a share of the chord time: 0 is a tie (a key
33
+ * and its relative on I, IV, V and vi held alike), 0.2 a clear read.
34
+ */
35
+ margin: number;
36
+ };
37
+ /** `keyFromChart`'s read: each key from the played bar (`PlayedBar.index`) its window starts in. */
38
+ export type ChartKeyRead = {
39
+ keys: {
40
+ bar: number;
41
+ key: Key;
42
+ }[];
43
+ margin: number;
44
+ };
45
+ /** The margin from which Study 53 found the rule right 97 times in 100; under it, treat the read as unsure. */
46
+ export declare const KEY_SURE = 0.1;
47
+ /**
48
+ * The key from timed chords. Each window scores the 24 keys by the chord
49
+ * time that fits them, and the best path through the windows, with a cost
50
+ * for every change, gives the few keys the music really moves through.
51
+ * Chords decide what pitch-class counts cannot: a voice that holds the
52
+ * fifth makes the fifth the loudest note, but A major is still not a chord
53
+ * of B major. Never throws: what is not a stretch of time holding a chord
54
+ * is skipped, and an option that is not a number it can use is its default.
55
+ * Its time is linear in the chords, however long they sound or overlap.
56
+ */
57
+ export declare function keyFromChords(spans: ChordSpan[], options?: KeyOptions): KeyRead;
58
+ /**
59
+ * The key from a chart's chords in play order, timed in seconds by the
60
+ * chart's tempo (120 where it gives none; a rit. or accel. is not followed),
61
+ * so a window is the ten seconds the bench measured. A bar's slots share it
62
+ * as the grammar divides it (2.1, 2.2), a hold keeps the chord before it
63
+ * sounding, and `N.C.`, silence, an unknown slot and a note set count for
64
+ * nothing. A repeat counts each time it is played. In a chart of several
65
+ * parts the harmony is the first part's that writes a chord symbol, read
66
+ * throughout. The chart's own `key:` is not consulted. `options.window` is
67
+ * in seconds. A chart of more than a quarter of a million played slots is
68
+ * read that far.
69
+ */
70
+ export declare function keyFromChart(parse: ChartParse, options?: Omit<KeyOptions, "duration">): ChartKeyRead;
@@ -0,0 +1,350 @@
1
+ /**
2
+ * The key read from chords: Stem Shovel's rule (its `keyFromChords`), the
3
+ * app's arithmetic in the app's order. stem-bench's Study 53 measured it on
4
+ * a chord model's runs with ten-second windows: the opening key right on 47
5
+ * of 49 songs, against 41 for pitch-class profiles on the audio.
6
+ *
7
+ * What it gets wrong, kept as the app has it so the bench's numbers hold
8
+ * (README, "The key from the chords"): a tie goes to the first key in the
9
+ * order C major, C minor, C♯ major …; a first window in another key is
10
+ * reported as the opening key; most of its misses are the parallel key.
11
+ * `margin` is how a caller tells a clear read from a tie.
12
+ */
13
+ import { noteSemitone } from "../chords/intervals.js";
14
+ import { beatsOf } from "./directives.js";
15
+ import { conventionalKey, SHARPS } from "./keys.js";
16
+ import { slotTimes } from "./shares.js";
17
+ /** The margin from which Study 53 found the rule right 97 times in 100; under it, treat the read as unsure. */
18
+ export const KEY_SURE = 0.1;
19
+ const WINDOW = 10;
20
+ const CHANGE_COST = 1;
21
+ const TONIC_BONUS = 0.5;
22
+ /** The most windows read; longer music is read in proportionally longer ones. */
23
+ const MAX_WINDOWS = 65_536;
24
+ /** The most window-by-chord steps taken beyond four a chord; chords that overlap for longer are read in longer windows. */
25
+ const MAX_STEPS = 2_000_000;
26
+ /** The latest time read, and the largest bonus and cost: beyond them the sums would no longer be numbers. */
27
+ const MAX_TIME = 1e15;
28
+ const MAX_WEIGHT = 1e6;
29
+ /** The most slots `keyFromChart` reads, in play order: a chart's first quarter of a million. */
30
+ const MAX_CHART_SLOTS = 250_000;
31
+ const TRIADS = {
32
+ maj: [0, 4, 7],
33
+ min: [0, 3, 7],
34
+ dim: [0, 3, 6],
35
+ aug: [0, 4, 8],
36
+ // No third to place it (a suspended chord, a power chord): its root and fifth.
37
+ open: [0, 7],
38
+ };
39
+ const MAJOR_SCALE = [0, 2, 4, 5, 7, 9, 11];
40
+ const MINOR_SCALE = [0, 2, 3, 5, 7, 8, 10];
41
+ const positive = (value, fallback) => value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback;
42
+ const notNegative = (value, fallback) => value !== undefined && Number.isFinite(value) && value >= 0 ? value : fallback;
43
+ /** The triad a chord is counted as: sevenths, sixths and extensions by the triad under them. */
44
+ function triadOf(intervals) {
45
+ const has = (degree, alter) => intervals.some((i) => i?.degree === degree && i?.alter === alter);
46
+ if (has(3, -1))
47
+ return has(5, -1) && !has(5, 0) ? "dim" : "min";
48
+ if (has(3, 0))
49
+ return has(5, 1) && !has(5, 0) ? "aug" : "maj";
50
+ return "open";
51
+ }
52
+ let scales = null;
53
+ /** The 24 keys in the rule's order (C major, C minor, C♯ major …), each with its scale's pitch classes; built on first use, so a bundle that never reads a key carries none of this. */
54
+ function allKeys() {
55
+ scales ??= Array.from({ length: 24 }, (_, index) => {
56
+ const tonic = index >> 1;
57
+ const minor = index % 2 === 1;
58
+ const scale = new Set((minor ? MINOR_SCALE : MAJOR_SCALE).map((step) => (step + tonic) % 12));
59
+ return { tonic, minor, scale };
60
+ });
61
+ return scales;
62
+ }
63
+ /**
64
+ * A chord's worth to each of the 24 keys: 1 when its triad lies in the
65
+ * key's scale (a minor key takes its major V too), and the tonic triad
66
+ * `bonus` more.
67
+ */
68
+ function worthOf(root, kind, bonus) {
69
+ const tones = TRIADS[kind].map((interval) => (root + interval) % 12);
70
+ return allKeys().map(({ tonic, minor, scale }) => {
71
+ const majorFive = minor && kind === "maj" && root === (tonic + 7) % 12;
72
+ const fits = majorFive || tones.every((tone) => scale.has(tone));
73
+ const isTonic = root === tonic && kind === (minor ? "min" : "maj");
74
+ return (fits ? 1 : 0) + (isTonic ? bonus : 0);
75
+ });
76
+ }
77
+ const keyOf = (index) => conventionalKey({ tonic: SHARPS[index >> 1] ?? "C", mode: index % 2 === 0 ? "major" : "minor" });
78
+ /** A span's chord when it is one the rule can read: a root that is text, and intervals. */
79
+ function chordOf(span) {
80
+ const chord = span?.chord;
81
+ if (!chord || typeof chord.root !== "string" || !Array.isArray(chord.intervals))
82
+ return null;
83
+ return { root: chord.root, intervals: chord.intervals };
84
+ }
85
+ /**
86
+ * The spans that are a stretch of time holding a chord with a root, clipped
87
+ * to start at 0 and to end by `limit`. Data that is not what the types say
88
+ * (a detector's JSON, unchecked) is skipped like any other unusable span.
89
+ */
90
+ function usable(spans, limit) {
91
+ const out = [];
92
+ for (const span of Array.isArray(spans) ? spans : []) {
93
+ const chord = chordOf(span);
94
+ if (!chord || !Number.isFinite(span.start) || !Number.isFinite(span.end))
95
+ continue;
96
+ const from = Math.max(span.start, 0);
97
+ const to = Math.min(span.end, limit);
98
+ const pitch = pitchOf(chord.root);
99
+ if (pitch === null || !(to > from))
100
+ continue;
101
+ out.push({ root: pitch, kind: triadOf(chord.intervals), from, to });
102
+ }
103
+ return out;
104
+ }
105
+ /** A root's pitch class; null for what is not a note name (a caller's own chord may hold anything). */
106
+ function pitchOf(root) {
107
+ try {
108
+ return noteSemitone(root);
109
+ }
110
+ catch {
111
+ return null;
112
+ }
113
+ }
114
+ /** Where each window starts: every `window` from 0, the last never shorter than half of one. */
115
+ function windowStarts(duration, window) {
116
+ const out = [0];
117
+ for (let t = window; t < duration - window / 2; t += window)
118
+ out.push(t);
119
+ return out;
120
+ }
121
+ const at = (values, i) => values?.[i] ?? 0;
122
+ /** Adds the part of a chord that sounds in window `w` to the window's tally. */
123
+ function hold(tally, w, chord, worth) {
124
+ const end = tally.starts[w + 1] ?? tally.duration;
125
+ const held = Math.min(chord.to, end) - Math.max(chord.from, at(tally.starts, w));
126
+ const row = tally.rows[w];
127
+ if (held <= 0 || !row)
128
+ return;
129
+ tally.chordTime[w] = at(tally.chordTime, w) + held;
130
+ for (let k = 0; k < 24; k++)
131
+ row[k] = at(row, k) + at(worth, k) * held;
132
+ }
133
+ function tallyOf(chords, window, duration, bonus) {
134
+ const starts = windowStarts(duration, window);
135
+ const tally = {
136
+ starts,
137
+ duration,
138
+ rows: starts.map(() => Array.from({ length: 24 }, () => 0)),
139
+ chordTime: starts.map(() => 0),
140
+ };
141
+ const worths = new Map();
142
+ for (const chord of chords) {
143
+ const name = `${chord.root} ${chord.kind}`;
144
+ const worth = worths.get(name) ?? worthOf(chord.root, chord.kind, bonus);
145
+ worths.set(name, worth);
146
+ // Only the windows the chord sounds in.
147
+ let w = Math.min(Math.floor(chord.from / window), starts.length - 1);
148
+ while (w > 0 && at(starts, w) > chord.from)
149
+ w--;
150
+ for (; w < starts.length && at(starts, w) < chord.to; w++)
151
+ hold(tally, w, chord, worth);
152
+ }
153
+ return tally;
154
+ }
155
+ /**
156
+ * The key from timed chords. Each window scores the 24 keys by the chord
157
+ * time that fits them, and the best path through the windows, with a cost
158
+ * for every change, gives the few keys the music really moves through.
159
+ * Chords decide what pitch-class counts cannot: a voice that holds the
160
+ * fifth makes the fifth the loudest note, but A major is still not a chord
161
+ * of B major. Never throws: what is not a stretch of time holding a chord
162
+ * is skipped, and an option that is not a number it can use is its default.
163
+ * Its time is linear in the chords, however long they sound or overlap.
164
+ */
165
+ export function keyFromChords(spans, options) {
166
+ const given = options ?? {};
167
+ const ends = Math.min(positive(given.duration, MAX_TIME), MAX_TIME);
168
+ const chords = usable(spans, ends);
169
+ const last = chords.reduce((latest, c) => Math.max(latest, c.to), 0);
170
+ const duration = given.duration === undefined || ends === MAX_TIME ? last : ends;
171
+ const window = windowFor(chords, duration, positive(given.window, WINDOW));
172
+ const bonus = Math.min(notNegative(given.tonicBonus, TONIC_BONUS), MAX_WEIGHT);
173
+ const tally = tallyOf(chords, window, duration, bonus);
174
+ if (tally.chordTime.reduce((a, b) => a + b, 0) <= 0)
175
+ return { keys: [], margin: 0 };
176
+ // A window's row as a share of a full window, so a window that is mostly silence says little.
177
+ const { starts } = tally;
178
+ const length = starts.length > 1 ? at(starts, 1) - at(starts, 0) : Math.max(duration, 1);
179
+ const path = bestPath(tally.rows.map((row) => row.map((time) => time / length)), Math.min(notNegative(given.changeCost, CHANGE_COST), MAX_WEIGHT));
180
+ const keys = [];
181
+ let margin = Number.POSITIVE_INFINITY;
182
+ for (let w = 0; w < path.length;) {
183
+ const key = at(path, w);
184
+ let next = w + 1;
185
+ while (next < path.length && path[next] === key)
186
+ next++;
187
+ keys.push({ start: at(starts, w), key: keyOf(key) });
188
+ margin = Math.min(margin, marginOf(tally, w, next, key));
189
+ w = next;
190
+ }
191
+ return { keys, margin: Number.isFinite(margin) ? Math.max(0, margin) : 0 };
192
+ }
193
+ /**
194
+ * The window read with: the one asked for, or a longer one when the music
195
+ * would make more than `MAX_WINDOWS` of them, or when chords overlap for so
196
+ * long that reading them window by window would take more than `MAX_STEPS`.
197
+ */
198
+ function windowFor(chords, duration, asked) {
199
+ const window = Math.max(asked, duration / MAX_WINDOWS);
200
+ const steps = chords.reduce((n, c) => n + (c.to - c.from) / window + 1, 0);
201
+ const budget = MAX_STEPS + 4 * chords.length;
202
+ return steps > budget ? window * (steps / budget) : window;
203
+ }
204
+ /** The first of the highest values: a tie goes to the lowest-numbered key. */
205
+ function topOf(values) {
206
+ let top = 0;
207
+ for (let k = 0; k < values.length; k++)
208
+ if (at(values, k) > at(values, top))
209
+ top = k;
210
+ return top;
211
+ }
212
+ /** The best-scoring key per window when every change of key costs `cost` (Viterbi over the 24 keys). */
213
+ function bestPath(rows, cost) {
214
+ let best = Array.from({ length: 24 }, () => 0);
215
+ const from = [];
216
+ rows.forEach((row, t) => {
217
+ const top = topOf(best);
218
+ const reach = at(best, top) - cost;
219
+ const next = [];
220
+ const back = [];
221
+ for (let k = 0; k < 24; k++) {
222
+ const stays = t === 0 || at(best, k) >= reach;
223
+ const carried = stays ? at(best, k) : reach;
224
+ next.push((t === 0 ? 0 : carried) + at(row, k));
225
+ back.push(stays ? k : top);
226
+ }
227
+ from.push(back);
228
+ best = next;
229
+ });
230
+ let key = topOf(best);
231
+ const path = rows.map(() => 0);
232
+ for (let t = rows.length - 1; t >= 0; t--) {
233
+ path[t] = key;
234
+ key = at(from[t], key);
235
+ }
236
+ return path;
237
+ }
238
+ /** Over windows `from` to `to`: how far `key` leads the best other key, as a share of the chord time there. */
239
+ function marginOf(tally, from, to, key) {
240
+ const sums = Array.from({ length: 24 }, () => 0);
241
+ let time = 0;
242
+ for (let w = from; w < to; w++) {
243
+ time += at(tally.chordTime, w);
244
+ for (let k = 0; k < 24; k++)
245
+ sums[k] = at(sums, k) + at(tally.rows[w], k);
246
+ }
247
+ if (time <= 0)
248
+ return 0;
249
+ const other = sums.reduce((best, sum, k) => (k === key ? best : Math.max(best, sum)), -Infinity);
250
+ return (at(sums, key) - other) / time;
251
+ }
252
+ const simple = (slots) => slots.flatMap((slot) => (slot.kind === "group" ? slot.members : [slot]));
253
+ const namesChord = (slots) => simple(slots).some((slot) => slot.kind === "chord" && slot.chord.root !== null);
254
+ /**
255
+ * Which part a chart's harmony is read from, the same one in every bar: the
256
+ * first that writes a chord symbol anywhere; -1 for the bars' own slots (a
257
+ * chart of one part, or one where no part names a chord). A repeat shares
258
+ * its slots, so each written bar is looked at once.
259
+ */
260
+ function harmonyPart(bars) {
261
+ const seen = new WeakSet();
262
+ let found = Number.POSITIVE_INFINITY;
263
+ for (const bar of bars) {
264
+ (bar.parts ?? []).forEach((part, p) => {
265
+ if (p >= found || !part || seen.has(part.slots))
266
+ return;
267
+ seen.add(part.slots);
268
+ if (namesChord(part.slots))
269
+ found = p;
270
+ });
271
+ if (found === 0)
272
+ break;
273
+ }
274
+ return Number.isFinite(found) ? found : -1;
275
+ }
276
+ /** A bar's slots in the part the harmony is read from; none where that part is tacet. */
277
+ const harmonyOf = (bar, part) => part < 0 ? bar.slots : (bar.parts?.[part]?.slots ?? []);
278
+ /** The tempo a chart with no `tempo:` is timed at. */
279
+ const CHART_TEMPO = 120;
280
+ const quarters = (meter) => (meter.n / meter.d) * 4;
281
+ /** A played bar's length in seconds at its steady tempo, which counts the beat of the `time:` meter in force (grammar 2.4). */
282
+ function barSeconds(bar) {
283
+ const counted = bar.time ?? bar.meter;
284
+ const beat = quarters(counted) / beatsOf(counted);
285
+ return (quarters(bar.meter) * 60) / (positive(bar.tempo ?? undefined, CHART_TEMPO) * beat);
286
+ }
287
+ /**
288
+ * Reads the bars' harmony in play order until `MAX_CHART_SLOTS` slots are
289
+ * read. A chord that goes on sounding (a hold, a `%`, the same bar played
290
+ * again) is one span, so a long repeat is one stretch of time.
291
+ */
292
+ function chartChords(bars) {
293
+ const part = harmonyPart(bars);
294
+ const spans = [];
295
+ const barStarts = [];
296
+ let at = 0;
297
+ let read = 0;
298
+ let sounding = null;
299
+ for (const bar of bars) {
300
+ if (read >= MAX_CHART_SLOTS)
301
+ break;
302
+ barStarts.push(at);
303
+ const seconds = barSeconds(bar);
304
+ const whole = bar.meter.n / bar.meter.d;
305
+ for (const timed of slotTimes(harmonyOf(bar, part), bar.meter)) {
306
+ read++;
307
+ sounding = soundingAfter(timed.slot, sounding);
308
+ if (!sounding)
309
+ continue;
310
+ const start = at + (timed.at / whole) * seconds;
311
+ const end = start + (timed.length / whole) * seconds;
312
+ const before = spans.at(-1);
313
+ if (before && before.chord === sounding && before.end === start)
314
+ before.end = end;
315
+ else
316
+ spans.push({ chord: sounding, start, end });
317
+ }
318
+ at += seconds;
319
+ }
320
+ return { spans, barStarts, duration: at };
321
+ }
322
+ /** The chord sounding once a slot has been reached: its own, the one before it for a hold, none otherwise. */
323
+ function soundingAfter(slot, before) {
324
+ if (slot.kind === "hold")
325
+ return before;
326
+ return slot.kind === "chord" && slot.chord.root !== null ? slot.chord : null;
327
+ }
328
+ /**
329
+ * The key from a chart's chords in play order, timed in seconds by the
330
+ * chart's tempo (120 where it gives none; a rit. or accel. is not followed),
331
+ * so a window is the ten seconds the bench measured. A bar's slots share it
332
+ * as the grammar divides it (2.1, 2.2), a hold keeps the chord before it
333
+ * sounding, and `N.C.`, silence, an unknown slot and a note set count for
334
+ * nothing. A repeat counts each time it is played. In a chart of several
335
+ * parts the harmony is the first part's that writes a chord symbol, read
336
+ * throughout. The chart's own `key:` is not consulted. `options.window` is
337
+ * in seconds. A chart of more than a quarter of a million played slots is
338
+ * read that far.
339
+ */
340
+ export function keyFromChart(parse, options) {
341
+ const { spans, barStarts, duration } = chartChords(parse.bars);
342
+ const read = keyFromChords(spans, { ...options, ...(duration > 0 && { duration }) });
343
+ let b = 0;
344
+ const keys = read.keys.map(({ start, key }) => {
345
+ while (b + 1 < barStarts.length && (barStarts[b + 1] ?? 0) <= start)
346
+ b++;
347
+ return { bar: parse.bars[b]?.index ?? 1, key };
348
+ });
349
+ return { keys, margin: read.margin };
350
+ }
@@ -0,0 +1,14 @@
1
+ import type { Line, SectionOccurrence } from "./types.js";
2
+ /**
3
+ * The lines with each section heading's `pageShift` (grammar A.7): what
4
+ * numbers the bars drawn under it on the page, every drawn bar once from
5
+ * the top. A replay heading a pass plays stands for its section written
6
+ * again in its place: its shift numbers the redrawn bars on from the
7
+ * count, and every heading after it counts them. `spans` is the parser's
8
+ * own numbering: by each heading's line, how many bars were written
9
+ * before its section, and before the next heading.
10
+ */
11
+ export declare function withPageShift(lines: Line[], played: {
12
+ sections: SectionOccurrence[];
13
+ spans: Map<number, number[]>;
14
+ }): Line[];
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The lines with each section heading's `pageShift` (grammar A.7): what
3
+ * numbers the bars drawn under it on the page, every drawn bar once from
4
+ * the top. A replay heading a pass plays stands for its section written
5
+ * again in its place: its shift numbers the redrawn bars on from the
6
+ * count, and every heading after it counts them. `spans` is the parser's
7
+ * own numbering: by each heading's line, how many bars were written
8
+ * before its section, and before the next heading.
9
+ */
10
+ export function withPageShift(lines, played) {
11
+ const replays = playedReplays(played.sections);
12
+ const span = (line) => {
13
+ const [from = 0, to = from] = played.spans.get(line) ?? [];
14
+ return { from, bars: to - from };
15
+ };
16
+ let added = 0;
17
+ return lines.map((l) => {
18
+ if (l.kind !== "section")
19
+ return l;
20
+ const of = replays.get(l.line);
21
+ const own = span(l.line);
22
+ const replayed = of === undefined ? null : span(of);
23
+ const shift = added + (replayed ? own.from - replayed.from : 0);
24
+ added += replayed?.bars ?? 0;
25
+ return (replayed ?? own).bars && shift ? { ...l, pageShift: shift } : l;
26
+ });
27
+ }
28
+ /**
29
+ * The heading lines a pass plays as a replay, each with the heading of the
30
+ * section it replays: a heading's first occurrence decides, as a host that
31
+ * draws the chart finds it. A written section the return of a jump plays
32
+ * again is no replay where it is written.
33
+ */
34
+ function playedReplays(sections) {
35
+ const first = new Map();
36
+ for (const s of sections)
37
+ if (!first.has(s.line))
38
+ first.set(s.line, s.replayOf);
39
+ const out = new Map();
40
+ for (const [line, of] of first)
41
+ if (of !== null && of !== line)
42
+ out.set(line, of);
43
+ return out;
44
+ }
@@ -2,6 +2,7 @@ import { readDocument } from "./document.js";
2
2
  import { expand, flattenBars, workFor } from "./expand.js";
3
3
  import { withFirstWritten } from "./firstWritten.js";
4
4
  import { append, largest } from "./many.js";
5
+ import { withPageShift } from "./pageShift.js";
5
6
  import { projectPart, projectPartLines } from "./parts.js";
6
7
  import { pedalWarnings } from "./pedal.js";
7
8
  import { numberFromPickup } from "./pickup.js";
@@ -223,6 +224,7 @@ function playStreams(lines, parts, shown, voices) {
223
224
  diagnostics,
224
225
  stopped,
225
226
  firsts: lead?.firsts ?? new Map(),
227
+ spans: lead?.spans ?? new Map(),
226
228
  };
227
229
  }
228
230
  const lined = (parts) => parts.some((p) => p.lines?.length);
@@ -233,6 +235,8 @@ function sungChecks(voices, stopped) {
233
235
  return v.diagnostics;
234
236
  });
235
237
  }
238
+ /** The lines with their numbers: each bar line's written first (grammar 2.4), each heading's shift on the page (A.7). */
239
+ const numbered = (lines, written, played, pickup) => withPageShift(withFirstWritten(lines, written, played.firsts, pickup), played);
236
240
  /** Read a whole barmark chart: the document as written and the bars in play order. Never throws. */
237
241
  export function parseChart(text) {
238
242
  const doc = readDocument(text);
@@ -248,7 +252,7 @@ export function parseChart(text) {
248
252
  part,
249
253
  parts: withSings(doc.parts, voice.all),
250
254
  credits: doc.credits,
251
- lines: withFirstWritten(doc.lines, doc.lines, played.firsts, pickup),
255
+ lines: numbered(doc.lines, doc.lines, played, pickup),
252
256
  events: played.events,
253
257
  bars,
254
258
  pickup,
@@ -304,8 +308,8 @@ export function extractPart(text, label, lineName) {
304
308
  const pickup = numberFromPickup(bars);
305
309
  // The lyric rows are their owner's, or the chart's when no part sings (grammar 7.7).
306
310
  const rows = voices.some((v) => v.singer === voice.owner);
307
- const numbered = withFirstWritten(extract.lines, doc.lines, played.firsts, pickup);
308
- const lines = rows ? numbered : numbered.filter((l) => l.kind !== "lyrics");
311
+ const all = numbered(extract.lines, doc.lines, played, pickup);
312
+ const lines = rows ? all : all.filter((l) => l.kind !== "lyrics");
309
313
  const kept = new Set(lines.map((l) => l.line));
310
314
  // A stand-in may sit on another part's line; that part's problems are not this one's.
311
315
  for (const l of doc.lines)
@@ -189,6 +189,13 @@ export type Line = {
189
189
  name: string;
190
190
  repeat: Repeat;
191
191
  elided: boolean;
192
+ /**
193
+ * What to add to the `firstWritten` of the bar lines drawn under this
194
+ * heading for the numbers their bars have on the page, where a replay that
195
+ * some pass plays counts as its section written again in that place
196
+ * (grammar A.7). Present only when it is not 0.
197
+ */
198
+ pageShift?: number;
192
199
  } | {
193
200
  kind: "directive";
194
201
  line: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barmark",
3
- "version": "0.26.1",
3
+ "version": "0.27.0",
4
4
  "description": "Markdown-inspired plain-text notation for chord charts: a parser, a canonical printer and Harte-label conversion.",
5
5
  "type": "module",
6
6
  "exports": {