barmark 0.26.0 → 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,91 @@ 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
+
39
+ ## [0.26.1] - 2026-11-30
40
+
41
+ ### Fixed
42
+
43
+ - **Directive lines applied too many times stop the expansion.** Every
44
+ repetition of a section (a replay, `## A x N`, `|: … :| x N`, the
45
+ return after a jump) applies each of its directive lines again, and
46
+ applying one charged no work, so N repetitions of N `key:` lines took
47
+ time quadratic in N: 8,000 replays of 8,000 lines about 2 s, 100 kB
48
+ (10,000 replays of 7,100 lines) 1.3 to 2 s, 1 MB 62 to 108 s when the
49
+ section plays a bar and 309 to 507 s when its only bar line is `| |`;
50
+ and `## A x ...` replays of such a section met no limit at all (1.8 MB:
51
+ 98 s). Play now applies at most ten times its work budget in directive
52
+ lines: 1,000,000 for one stream, and its share for each of several (a
53
+ stream is a part, or one line of a part that writes lines; `extractPart`
54
+ of a two-line part shares it between them, and of a part without lines,
55
+ or of one named line, has it all). A chart past it stops with an error
56
+ on the directive line it reached
57
+ ("expansion stopped after 278 bars: its directive lines are applied too
58
+ many times (1,000,000)"), which, as at every other limit, is then the
59
+ only report of what it cut short: each of those shapes now takes under
60
+ 0.4 s. The budget is far above real charts, not only above slow ones:
61
+ the examples and fixtures apply at most 10 of 1,000,000, the owner's
62
+ songs at most 2, while a chart that applies just over 1,000,000 took
63
+ under 0.1 s (2,000 replays of 2,000 `key: D` lines, 24 kB, now stops
64
+ after 501 bars). A chart under the budget reads exactly as before.
65
+ - **The parser no longer throws on a long chart.** It passed some of its
66
+ lists to a call one argument per element (`events.push(...out)`, and
67
+ the same for diagnostics, repeats' lines and `Math.max`), and an engine
68
+ takes only so many, so `parseChart` threw a `RangeError` on charts as
69
+ small as a few kilobytes of a particular shape: `## A x 355` over 355
70
+ lines of `| @A | x ...` (4.6 kB) under Node, `## A x 800` (10.4 kB)
71
+ under Bun; and under Node a directive line of 150,000 settings
72
+ (900 kB), an unclosed `|:` before 150,000 lines (1 MB), or a section of
73
+ 99,000 fermatas on a small stack. Each list is now appended to one
74
+ element at a time, with the same result in the same order; a test
75
+ parses those charts under Node and Bun, and another keeps the pattern
76
+ out of the parser's source.
77
+ - **A pass of an open repeat counts toward the expansion's work.** A
78
+ counted pass (`x 3`, a section's pass) cost one unit of the work budget
79
+ and a pass of `x ...` cost nothing, so a bar line with its own `x ...`
80
+ that plays no bar and no fermata (`| @A | x ...`, `| Segno | x ...`)
81
+ could be repeated without limit: N replays of N such lines took time
82
+ and memory quadratic in N (36 kB: 1.5 s, 4 million events, 1.8 GB;
83
+ 72 kB: 5 to 7 s, 16 million, 6.8 GB; `## A x ...` replays at 768 kB:
84
+ 52 to 85 s). Each open pass now costs one unit, as a counted one does,
85
+ so such a chart stops with "expansion stopped after N bars: its repeats
86
+ play too many times", as repeats of fermatas do: each of those shapes
87
+ now takes under 0.3 s and 200 MB, and no chart makes more than 100,000
88
+ open events. A chart whose work stays within the budget reads exactly
89
+ as before.
90
+ - **A replay with `->` no longer walks its section's lines again.**
91
+ Whether `->` cuts a bar looked for the section's last written bar on
92
+ every replay, walking each of its lines, so N `->` replays of a section
93
+ of N lines of any kind took time quadratic in N (4,000 of 4,000 text
94
+ lines took 9 to 12 times as long as 1,000 of 1,000). The bar is now
95
+ found once per section, and nothing in the parse changes.
96
+
12
97
  ## [0.26.0] - 2026-11-29
13
98
 
14
99
  ### Added
@@ -976,7 +1061,9 @@ The first working release: the reference parser and printer for the
976
1061
 
977
1062
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
978
1063
 
979
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.26.0...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
1066
+ [0.26.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.26.0...barmark-v0.26.1
980
1067
  [0.26.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.25.1...barmark-v0.26.0
981
1068
  [0.25.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.25.0...barmark-v0.25.1
982
1069
  [0.25.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.24.0...barmark-v0.25.0
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
  ```
@@ -617,6 +617,7 @@ export function parseBarLine(text, line) {
617
617
  body = `${body.slice(0, -2)}|`;
618
618
  const written = barsWritten(body);
619
619
  const stray = strayEnding(body);
620
+ // bounded: a message and its token.
620
621
  if (stray)
621
622
  error(...stray);
622
623
  if (body.includes(":|") || body.includes("|:"))
@@ -118,6 +118,7 @@ export function planJump(lines, error) {
118
118
  const jump = first.get("jump");
119
119
  const plan = jump?.direction.kind === "jump" ? jump.direction : null;
120
120
  if (jump && plan)
121
+ // bounded: at most the four marks a jump can miss.
121
122
  problems.push(...missingMarks(jump, plan, first).map((m) => [jump, m]));
122
123
  const coda = first.get("coda");
123
124
  // Only the Coda an al Coda goes on; an unused one is an error of its own.
@@ -5,6 +5,7 @@ import { parseDirectiveLine } from "./directives.js";
5
5
  import { continueEndings } from "./endingLines.js";
6
6
  import { checkLines } from "./lines.js";
7
7
  import { attachLyrics, readLyricRow } from "./lyricRows.js";
8
+ import { append } from "./many.js";
8
9
  import { readPart } from "./partLine.js";
9
10
  import { groupSystems } from "./systems.js";
10
11
  const NEAR_DIRECTIVES = {
@@ -274,7 +275,7 @@ export function readDocument(text) {
274
275
  return partLine(read, t, line);
275
276
  const directive = parseDirectiveLine(t, line);
276
277
  if (directive) {
277
- diagnostics.push(...directive.diagnostics);
278
+ append(diagnostics, directive.diagnostics);
278
279
  return { kind: "directive", line, set: directive.set };
279
280
  }
280
281
  const old = oldFormat(t, line);
@@ -284,7 +285,7 @@ export function readDocument(text) {
284
285
  };
285
286
  const barLine = (t, line) => {
286
287
  const r = parseBarLine(t, line);
287
- diagnostics.push(...r.diagnostics);
288
+ append(diagnostics, r.diagnostics);
288
289
  return r.bars ?? { kind: "invalid", line, text: t, written: r.written };
289
290
  };
290
291
  /** A labelled line that can't be read: no space before its pipe, or a bad line name. */
@@ -322,7 +323,7 @@ export function readDocument(text) {
322
323
  /** `lyrics:` or `lyrics N:` then a bar line (grammar 7.7); one with an error stays text. */
323
324
  const lyricRow = (t, line) => {
324
325
  const read = readLyricRow(t, line);
325
- diagnostics.push(...read.diagnostics);
326
+ append(diagnostics, read.diagnostics);
326
327
  if (read.row || read.diagnostics.length)
327
328
  return read.row ?? { kind: "text", line, text: t };
328
329
  return null;
@@ -365,7 +366,8 @@ export function readDocument(text) {
365
366
  const grouped = groupParts(lines, read);
366
367
  const lyrics = attachLyrics(grouped.lines);
367
368
  const ended = continueEndings(lyrics.lines);
368
- diagnostics.push(...grouped.diagnostics, ...lyrics.diagnostics, ...ended.diagnostics);
369
+ for (const found of [grouped, lyrics, ended])
370
+ append(diagnostics, found.diagnostics);
369
371
  const { parts } = grouped;
370
372
  return {
371
373
  title,
@@ -30,6 +30,18 @@ export declare const MAX_EXPANDED_BARS = 10000;
30
30
  * times the lines never multiply.
31
31
  */
32
32
  export declare const workFor: (share: number) => number;
33
+ /**
34
+ * The directive lines one of `share` streams may apply: ten times its
35
+ * work. A stream is a part, or one line of a part that writes lines, so a
36
+ * chart's two-line part has two and each applies 500,000; `extractPart`
37
+ * plays a part of no lines, or one named line, as one stream. Every
38
+ * repetition of a section applies its directive lines again, so N
39
+ * repetitions of N lines would cost N squared with no bound but the
40
+ * file's size. An application costs about 30 ns, so a million bound it at
41
+ * tens of milliseconds; real charts apply a handful (the examples and
42
+ * fixtures at most 10, the owner's songs at most 2).
43
+ */
44
+ export declare const directivesFor: (share: number) => number;
33
45
  /** Every played bar in order, with an open repeat's pass included once. */
34
46
  export declare function flattenBars(events: ChartEvent[]): PlayedBar[];
35
47
  /**
@@ -54,4 +66,9 @@ sing?: Sing): {
54
66
  * a part's share of lines. `withFirstWritten` makes the bar lines' field.
55
67
  */
56
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[]>;
57
74
  };
@@ -1,5 +1,6 @@
1
1
  import { planJump } from "./direction.js";
2
2
  import { beatsOf } from "./directives.js";
3
+ import { append } from "./many.js";
3
4
  import { pedalWarnings } from "./pedal.js";
4
5
  import { pairRepeats } from "./repeats.js";
5
6
  import { perWritten, slotTimes } from "./shares.js";
@@ -13,6 +14,18 @@ const barsFor = (share) => Math.max(1, Math.floor(MAX_EXPANDED_BARS / share));
13
14
  * times the lines never multiply.
14
15
  */
15
16
  export const workFor = (share) => barsFor(share) * 10;
17
+ /**
18
+ * The directive lines one of `share` streams may apply: ten times its
19
+ * work. A stream is a part, or one line of a part that writes lines, so a
20
+ * chart's two-line part has two and each applies 500,000; `extractPart`
21
+ * plays a part of no lines, or one named line, as one stream. Every
22
+ * repetition of a section applies its directive lines again, so N
23
+ * repetitions of N lines would cost N squared with no bound but the
24
+ * file's size. An application costs about 30 ns, so a million bound it at
25
+ * tens of milliseconds; real charts apply a handful (the examples and
26
+ * fixtures at most 10, the owner's songs at most 2).
27
+ */
28
+ export const directivesFor = (share) => workFor(share) * 10;
16
29
  /**
17
30
  * The lines one of several parts reads: its share of the work, since the
18
31
  * parts times the lines would otherwise multiply; and the first it
@@ -143,6 +156,7 @@ sing) {
143
156
  const maxBars = barsFor(share);
144
157
  // Repeats of bodies that play no bars (fermatas only) are bounded too.
145
158
  const maxWork = workFor(share);
159
+ const maxApplied = directivesFor(share);
146
160
  const { readable, unread } = shareOf(lines, share, maxWork);
147
161
  // The return after a jump plays sections again: it reports only what the first pass did not.
148
162
  const reported = new Set();
@@ -246,8 +260,14 @@ sing) {
246
260
  if (written >= first)
247
261
  firsts.set(l.line, first);
248
262
  };
249
- for (const l of sections.flatMap((s) => s.lines))
250
- 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
+ }
251
271
  const unused = pending.mark;
252
272
  if (unused)
253
273
  error(unused.line, "a rehearsal mark marks the bar after it; none follows", `@${unused.label}`);
@@ -310,6 +330,7 @@ sing) {
310
330
  };
311
331
  let count = 0;
312
332
  let work = 0;
333
+ let applied = 0;
313
334
  let capped = false;
314
335
  let openDepth = 0;
315
336
  const nestedOpen = new Set();
@@ -318,20 +339,20 @@ sing) {
318
339
  let againSung = 0;
319
340
  /** Bars a replay's `->` cut after they played: `count` counts them, the output doesn't. */
320
341
  let cutBars = 0;
321
- /** Stop playing, saying why: the bar cap, the verses sung again, repeats that play too much, or a part's lines. */
342
+ /** Why play stopped, after the bars it played: each limit but the bar cap's. */
343
+ const reasons = {
344
+ verses: () => `the bars played again sing too many verses (${againSung.toLocaleString("en-US")})`,
345
+ lines: () => `each of ${share} parts reads at most ${maxWork} lines`,
346
+ work: () => "its repeats play too many times",
347
+ directives: () => `its directive lines are applied too many times (${maxApplied.toLocaleString("en-US")})`,
348
+ };
349
+ /** Stop playing, saying why: the bar cap, the verses sung again, repeats that play too much, directive lines applied too often, or a part's lines. */
322
350
  const stop = (line, why = "work") => {
323
351
  capped = true;
324
- const what = () => {
325
- if (why === "bars")
326
- return `expansion stopped at ${maxBars} bars`;
327
- const after = `expansion stopped after ${count - cutBars} bars`;
328
- if (why === "verses")
329
- return `${after}: the bars played again sing too many verses (${againSung.toLocaleString("en-US")})`;
330
- if (why === "lines")
331
- return `${after}: each of ${share} parts reads at most ${maxWork} lines`;
332
- return `${after}: its repeats play too many times`;
333
- };
334
- error(line, what(), "x");
352
+ const what = why === "bars"
353
+ ? `expansion stopped at ${maxBars} bars`
354
+ : `expansion stopped after ${count - cutBars} bars: ${reasons[why]()}`;
355
+ error(line, what, "x");
335
356
  };
336
357
  /** A part that stopped reading its lines before play stopped says so. */
337
358
  const readAll = (next) => {
@@ -465,9 +486,16 @@ sing) {
465
486
  count++;
466
487
  out.push({ kind: "bar", bar: played });
467
488
  };
468
- /** Play `body` `repeat` times into `out`; an open repeat plays one pass inside an open event. */
489
+ /**
490
+ * Play `body` `repeat` times into `out`; an open repeat plays one pass
491
+ * inside an open event. Its pass is work, as a counted pass is: a pass
492
+ * that plays nothing would otherwise repeat for free.
493
+ */
469
494
  const times = (repeat, line, out, body) => {
470
495
  if (repeat === "open") {
496
+ // Not once play has stopped: the stop is the only report of what it cut short.
497
+ if (!capped && ++work > maxWork)
498
+ return stop(line);
471
499
  if (openDepth > 0) {
472
500
  if (!nestedOpen.has(line))
473
501
  error(line, "an open repeat inside another open repeat", "x ...");
@@ -499,11 +527,17 @@ sing) {
499
527
  }
500
528
  Object.assign(where, { pass: outer.pass, passes: outer.passes });
501
529
  };
530
+ /** A directive line applied as play reaches it, once the budget has room for it. */
531
+ const applyLine = (l) => {
532
+ if (++applied > maxApplied)
533
+ return stop(l.line, "directives");
534
+ apply(l.set, l.line);
535
+ };
502
536
  const playLine = ({ line: l, repeat }, out) => {
503
537
  if (stopped())
504
538
  return;
505
539
  if (l.kind === "directive")
506
- apply(l.set, l.line);
540
+ return applyLine(l);
507
541
  if (l.kind !== "bars")
508
542
  return;
509
543
  times(repeat, l.line, out, (into) => {
@@ -564,11 +598,20 @@ sing) {
564
598
  times(h.repeat, h.line, out, (into) => playItems(itemsOf.get(s) ?? [], into));
565
599
  return { replayOf: null, elided: false };
566
600
  };
567
- /** Whether `out` ends with the last bar written in `s` (grammar 6: what `->` cuts). */
568
- const reachesEnd = (s, out) => {
601
+ /** The written number of the last bar written in each section, found once: every `->` replay asks. */
602
+ const lastWritten = new Map();
603
+ const lastIn = (s) => {
604
+ if (lastWritten.has(s))
605
+ return lastWritten.get(s);
569
606
  const bars = s.lines.flatMap((l) => (l.kind === "bars" ? (resolved.get(l) ?? []) : []));
570
607
  const last = bars.findLast((p) => p.kind === "bar");
571
- return last?.kind === "bar" && flattenBars(out).at(-1)?.written === last.written;
608
+ lastWritten.set(s, last?.kind === "bar" ? last.written : undefined);
609
+ return lastWritten.get(s);
610
+ };
611
+ /** Whether `out` ends with the last bar written in `s` (grammar 6: what `->` cuts). */
612
+ const reachesEnd = (s, out) => {
613
+ const last = lastIn(s);
614
+ return last !== undefined && flattenBars(out).at(-1)?.written === last;
572
615
  };
573
616
  /** A replay's bars into `out`, then its own lines; null when it replays nothing. */
574
617
  const playReplay = (s, h, out) => {
@@ -616,7 +659,7 @@ sing) {
616
659
  const played = isWritten(s) ? playWritten(s, h, out) : playReplay(s, h, out);
617
660
  if (!played)
618
661
  return;
619
- events.push(...out);
662
+ append(events, out);
620
663
  record(h, out, played.replayOf, played.elided);
621
664
  };
622
665
  playSections();
@@ -645,6 +688,6 @@ sing) {
645
688
  };
646
689
  });
647
690
  if (pedal)
648
- diagnostics.push(...pedalWarnings(flattenBars(events)));
649
- return { events, sections: sectionsOut, diagnostics, stopped: capped, firsts };
691
+ append(diagnostics, pedalWarnings(flattenBars(events)));
692
+ return { events, sections: sectionsOut, diagnostics, stopped: capped, firsts, spans };
650
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
+ }
@@ -1,3 +1,4 @@
1
+ import { append } from "./many.js";
1
2
  /** At most this many lines per part (grammar 7.6). */
2
3
  export const MAX_LINES = 4;
3
4
  const isLabelled = (l) => (l.kind === "bars" || l.kind === "invalid") && l.part !== undefined;
@@ -35,9 +36,13 @@ function nameLines(lines, report) {
35
36
  }
36
37
  /** Push `item` onto the list at `key`, starting it if new: a copy per item would cost the list squared. */
37
38
  function pushAt(map, key, ...items) {
39
+ pushAllAt(map, key, items);
40
+ }
41
+ /** Push `items` onto the list at `key` in order, starting it if new: one push per item, never a spread. */
42
+ function pushAllAt(map, key, items) {
38
43
  const known = map.get(key);
39
44
  if (known)
40
- known.push(...items);
45
+ append(known, items);
41
46
  else
42
47
  map.set(key, items);
43
48
  }
@@ -79,7 +84,7 @@ function bareBeside(systems) {
79
84
  for (const [part, own] of system) {
80
85
  const bare = own.filter((l) => l.lineName === undefined);
81
86
  if (bare.length && bare.length < own.length)
82
- pushAt(out, part, ...bare);
87
+ pushAllAt(out, part, bare);
83
88
  }
84
89
  return out;
85
90
  }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Arrays as long as the input, used whole without spreading them into a
3
+ * call: a spread passes one argument per element, and an engine takes only
4
+ * so many (V8 about 100,000, Bun more), so `xs.push(...ys)` and
5
+ * `Math.max(...ys)` throw a `RangeError` on a large enough chart.
6
+ */
7
+ /** Append `items` to `to` in order, as `to.push(...items)` would. */
8
+ export declare function append<T>(to: T[], items: readonly T[]): void;
9
+ /** The largest of `from` and `xs`, as `Math.max(from, ...xs)` would be; -Infinity for none. */
10
+ export declare function largest(xs: Iterable<number>, from?: number): number;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Arrays as long as the input, used whole without spreading them into a
3
+ * call: a spread passes one argument per element, and an engine takes only
4
+ * so many (V8 about 100,000, Bun more), so `xs.push(...ys)` and
5
+ * `Math.max(...ys)` throw a `RangeError` on a large enough chart.
6
+ */
7
+ /** Append `items` to `to` in order, as `to.push(...items)` would. */
8
+ export function append(to, items) {
9
+ for (const x of items)
10
+ to.push(x);
11
+ }
12
+ /** The largest of `from` and `xs`, as `Math.max(from, ...xs)` would be; -Infinity for none. */
13
+ export function largest(xs, from = Number.NEGATIVE_INFINITY) {
14
+ let most = from;
15
+ for (const x of xs)
16
+ most = Math.max(most, x);
17
+ return most;
18
+ }
@@ -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
+ }
@@ -1,6 +1,8 @@
1
1
  import { readDocument } from "./document.js";
2
2
  import { expand, flattenBars, workFor } from "./expand.js";
3
3
  import { withFirstWritten } from "./firstWritten.js";
4
+ import { append, largest } from "./many.js";
5
+ import { withPageShift } from "./pageShift.js";
4
6
  import { projectPart, projectPartLines } from "./parts.js";
5
7
  import { pedalWarnings } from "./pedal.js";
6
8
  import { numberFromPickup } from "./pickup.js";
@@ -64,7 +66,7 @@ const lineOf = (e) => (e.kind === "bar" ? e.bar.line : e.line);
64
66
  /** The first event at which some part's timeline differs in shape from the lead's, or -1. */
65
67
  function stepAt(each) {
66
68
  const [lead = []] = each;
67
- const longest = Math.max(...each.map((events) => events.length));
69
+ const longest = largest(each.map((events) => events.length));
68
70
  for (let i = 0; i < longest; i++)
69
71
  if (each.some((events) => events[i]?.kind !== lead[i]?.kind))
70
72
  return i;
@@ -213,7 +215,7 @@ function playStreams(lines, parts, shown, voices) {
213
215
  const stopped = played.some((p) => p.stopped);
214
216
  const zipped = zipEvents(played.map((p) => p.events), (d) => diagnostics.push(d), stopped);
215
217
  const events = foldEvents(zipped, byPart(streams, shown), shown);
216
- diagnostics.push(...linedPedalWarnings(events, shown));
218
+ append(diagnostics, linedPedalWarnings(events, shown));
217
219
  // The bars carry the first stream's numbers (`zipBar`), so its lines' numbers are the chart's.
218
220
  const lead = played[0];
219
221
  return {
@@ -222,6 +224,7 @@ function playStreams(lines, parts, shown, voices) {
222
224
  diagnostics,
223
225
  stopped,
224
226
  firsts: lead?.firsts ?? new Map(),
227
+ spans: lead?.spans ?? new Map(),
225
228
  };
226
229
  }
227
230
  const lined = (parts) => parts.some((p) => p.lines?.length);
@@ -232,6 +235,8 @@ function sungChecks(voices, stopped) {
232
235
  return v.diagnostics;
233
236
  });
234
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);
235
240
  /** Read a whole barmark chart: the document as written and the bars in play order. Never throws. */
236
241
  export function parseChart(text) {
237
242
  const doc = readDocument(text);
@@ -247,7 +252,7 @@ export function parseChart(text) {
247
252
  part,
248
253
  parts: withSings(doc.parts, voice.all),
249
254
  credits: doc.credits,
250
- lines: withFirstWritten(doc.lines, doc.lines, played.firsts, pickup),
255
+ lines: numbered(doc.lines, doc.lines, played, pickup),
251
256
  events: played.events,
252
257
  bars,
253
258
  pickup,
@@ -303,8 +308,8 @@ export function extractPart(text, label, lineName) {
303
308
  const pickup = numberFromPickup(bars);
304
309
  // The lyric rows are their owner's, or the chart's when no part sings (grammar 7.7).
305
310
  const rows = voices.some((v) => v.singer === voice.owner);
306
- const numbered = withFirstWritten(extract.lines, doc.lines, played.firsts, pickup);
307
- 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");
308
313
  const kept = new Set(lines.map((l) => l.line));
309
314
  // A stand-in may sit on another part's line; that part's problems are not this one's.
310
315
  for (const l of doc.lines)
@@ -3,6 +3,7 @@ import { printDirection } from "./direction.js";
3
3
  import { beatsOf } from "./directives.js";
4
4
  import { readDocument } from "./document.js";
5
5
  import { printKey } from "./keys.js";
6
+ import { largest } from "./many.js";
6
7
  import { extractPart, parseChart } from "./parse.js";
7
8
  import { splitSyllable } from "./syllable.js";
8
9
  /** A slot with no attack of its own continues whatever sounds before it. A repeated chord name is a re-attack. */
@@ -210,7 +211,7 @@ function partsIndex(parts) {
210
211
  if (!at.has(p.label))
211
212
  at.set(p.label, i);
212
213
  });
213
- const width = Math.max(...parts.flatMap(labelsOf).map((label) => label.length));
214
+ const width = largest(parts.flatMap(labelsOf).map((label) => label.length));
214
215
  const made = { at, width };
215
216
  partsKnown.set(parts, made);
216
217
  return made;
@@ -233,7 +234,7 @@ const spanOf = (k, bars, n) => [
233
234
  const roomOf = (columns, [a, b]) => columns.slice(a, b + 1).reduce((x, y) => x + y, 0) + 3 * (b - a);
234
235
  /** Each column's width: the widest of the bar lines' cells, widened for a row's cell that won't fit. */
235
236
  function columnsOf(lines, rows, bars) {
236
- const columns = (lines[0]?.cells ?? []).map((_, i) => Math.max(...lines.map((p) => p.cells[i]?.length ?? 0)));
237
+ const columns = (lines[0]?.cells ?? []).map((_, i) => largest(lines.map((p) => p.cells[i]?.length ?? 0)));
237
238
  for (const r of rows)
238
239
  for (const [k, c] of r.cells.entries()) {
239
240
  const room = roomOf(columns, spanOf(k, bars, columns.length));
@@ -248,7 +249,7 @@ function columnsOf(lines, rows, bars) {
248
249
  * pipes lined up; a row's cell spans the cells of its bar (grammar 7.7).
249
250
  */
250
251
  function alignBlock(lines, rows, bars, width) {
251
- const w = Math.max(width, ...rows.map((r) => r.label.length));
252
+ const w = largest(rows.map((r) => r.label.length), width);
252
253
  const columns = columnsOf(lines, rows, bars);
253
254
  const print = (p, pad) => `${p.label.padEnd(w)} ${joinPieces({ ...p, cells: p.cells.map(pad) })}`.trimEnd();
254
255
  const texts = new Map();
@@ -302,7 +303,7 @@ const lastKnown = new WeakMap();
302
303
  function lastOf(covers) {
303
304
  let last = lastKnown.get(covers);
304
305
  if (last === undefined) {
305
- last = Math.max(...covers);
306
+ last = largest(covers);
306
307
  lastKnown.set(covers, last);
307
308
  }
308
309
  return last;
@@ -1,7 +1,8 @@
1
1
  import { BETWEEN_ENDINGS } from "./endingLines.js";
2
+ import { append, largest } from "./many.js";
2
3
  const passesToken = (b) => `|${(b.ending ?? []).join(",")}`;
3
4
  const asLine = (line) => ({ kind: "line", line, repeat: null });
4
- const highestPass = (endings) => Math.max(...endings.flatMap((b) => b.ending ?? []));
5
+ const highestPass = (endings) => largest(endings.flatMap((b) => b.ending ?? []));
5
6
  /** Every pass from 1 to the highest has exactly one ending, and the highest is at least 2. */
6
7
  function passProblems(endings, last) {
7
8
  const highest = highestPass(endings);
@@ -112,7 +113,7 @@ export function pairRepeats(lines, error) {
112
113
  const st = { items: [], open: null, endings: null };
113
114
  const finish = () => {
114
115
  if (st.endings)
115
- st.items.push(...closeEndings(st.endings, error));
116
+ append(st.items, closeEndings(st.endings, error));
116
117
  st.endings = null;
117
118
  };
118
119
  for (const l of lines) {
@@ -130,7 +131,7 @@ export function pairRepeats(lines, error) {
130
131
  finish();
131
132
  if (st.open) {
132
133
  error(st.open.line, "|: is never closed in this section", "|:");
133
- st.items.push(...st.open.entries.map((e) => ({ kind: "line", ...e })));
134
+ append(st.items, st.open.entries.map((e) => ({ kind: "line", ...e })));
134
135
  }
135
136
  return st.items;
136
137
  }
@@ -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;
@@ -93,6 +93,7 @@ function shorthandFor(intervals) {
93
93
  * by a flat sixth (`C(b6,9)`, not `C6/9(b6)`), else the first.
94
94
  */
95
95
  function bestSuffix(candidates, exact, intervals) {
96
+ // bounded: the candidates are suffixes of the fixed vocabulary, a few at most.
96
97
  const most = Math.max(...candidates.map(exact));
97
98
  const tied = candidates.filter((c) => exact(c) === most);
98
99
  const shorthand = shorthandFor(intervals);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barmark",
3
- "version": "0.26.0",
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": {