@xromdev/notation 0.1.5 → 0.1.7
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/dist/notation.js +13 -2
- package/dist/notation.js.map +1 -1
- package/dist/score.d.ts +5 -1
- package/dist/score.js +6 -2
- package/dist/score.js.map +1 -1
- package/package.json +1 -1
package/dist/notation.js
CHANGED
|
@@ -521,8 +521,19 @@ export function staffMeasures(items, totalTicks, grid = barGrid()) {
|
|
|
521
521
|
const filled = inBar.reduce((sum, item) => sum + item.ticks, 0);
|
|
522
522
|
// Filled to within a hair is full: a tuplet's steps are sums of fractions.
|
|
523
523
|
if (barTicks - filled > ON_GRID) {
|
|
524
|
-
|
|
525
|
-
|
|
524
|
+
// The rests the ribbon already ends on join the padding, and the whole gap is written anew:
|
|
525
|
+
// Ice Climber's Pause stops a tick after its last written head, and the tick to the end of
|
|
526
|
+
// the track and the tick on to the beat came out as two 64th rests instead of one 32nd.
|
|
527
|
+
let from = filled;
|
|
528
|
+
while (inBar.length) {
|
|
529
|
+
const last = inBar[inBar.length - 1];
|
|
530
|
+
if (last.midi !== null || last.tuplet || !Number.isInteger(last.start))
|
|
531
|
+
break;
|
|
532
|
+
inBar.pop();
|
|
533
|
+
from -= last.ticks;
|
|
534
|
+
}
|
|
535
|
+
let at = start + from;
|
|
536
|
+
for (const piece of decompose(from, barTicks - from, barTicks)) {
|
|
526
537
|
inBar.push({
|
|
527
538
|
start: at,
|
|
528
539
|
ticks: piece.ticks,
|
package/dist/notation.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"notation.js","sourceRoot":"","sources":["../src/notation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,2EAA2E;AAC3E,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AACpC,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC;AACnC;;;;;;;;GAQG;AACH,MAAM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CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;IAC/E,OAAO,EAAE,KAAK,EAAE,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,GAAG,IAAI,CAAC,EAAE,CAAC;AACzE,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,SAAS,CACvB,IAAqC,EACrC,KAAyB;IAEzB,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAC5B,MAAM,GAAG,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QAC/C,KAAK,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,KAAK,EAAE,CAAC;YACnC,MAAM,GAAG,GAAG,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;YAClD,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;YACnC,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;QACrC,CAAC;IACH,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["/**\n * Ticks read as NOTATION: note values, dots, ties and bar lines.\n *\n * Nothing here quantises, because nothing has to: one tick is exactly a\n * sixty-fourth note (a sixteenth of a quarter), so every note given already\n * sits on the grid notation is written on. That is what makes music read out\n * of a game cartridge writable at all — the usual failure of notation built\n * from MIDI is a performance that lands a few milliseconds off the beat, and\n * a sound driver gives no performance, only the integers it counts. Anything\n * else has to be quantised to sixty-fourths before it comes here.\n *\n * The rules were made on Battletoads (NES), whose driver counts in exactly\n * these ticks, and checked by ear on its twenty tracks; the examples in these\n * comments are the bars that decided them.\n *\n * Durations come out as VexFlow codes (`w h q 8 16 32 64`), pitches as VexFlow\n * keys (`c#/4`) — the shortest names there are, and what a renderer reads.\n */\n\n/** Engine ticks in a quarter note. The driver's own grid, not a choice. */\nexport const TICKS_PER_QUARTER = 16;\nexport const BEATS_PER_MEASURE = 4;\n/**\n * A bar of 4/4, which is what all but one track is written in and what every\n * caller gets by default.\n *\n * Not a constant of the music: Volkmire's Inferno Race is in 2/4, and its\n * sections — the change to D major among them — start on odd multiples of half\n * a 4/4 bar, so no 64-tick bar line can hold them. So everything here takes the\n * bar length it is barring to, and `MEASURE_TICKS` is only the default.\n */\nexport const MEASURE_TICKS = TICKS_PER_QUARTER * BEATS_PER_MEASURE;\n/** Quarters in a bar of `measureTicks` ticks. */\nexport const beatsIn = (measureTicks: number): number => measureTicks / TICKS_PER_QUARTER;\n\n/**\n * A bar of so many ticks as a time signature.\n *\n * In the note value that measures it WHOLE: 64 ticks are 4/4 and 32 are 2/4,\n * but an opening bar of 38 is no number of quarters — it is 19 thirty-seconds,\n * and 19/32 is what a reader is shown.\n */\nexport function timeSignatureOf(\n measureTicks: number,\n /**\n * The note value a bar is counted in, when the reading names one: 2 writes a\n * bar of 128 ticks as 4/2 rather than 8/4. Left out — or not dividing the bar,\n * as an opening bar of its own length may not — it is chosen as below.\n */\n beatValue?: number\n): { beats: number; beatValue: number } {\n if (beatValue) {\n const beat = (TICKS_PER_QUARTER * 4) / beatValue;\n if (Number.isInteger(beat) && measureTicks % beat === 0) {\n return { beats: measureTicks / beat, beatValue };\n }\n }\n for (const beatValue of [4, 8, 16, 32, 64] as const) {\n const beat = (TICKS_PER_QUARTER * 4) / beatValue;\n if (measureTicks % beat === 0) return { beats: measureTicks / beat, beatValue };\n }\n return { beats: measureTicks, beatValue: 64 };\n}\n\n/**\n * Where the bar lines of a piece fall: every bar `measureTicks` long, except\n * the first.\n *\n * The opening bar has its own length because a pickup written as a bar of rests\n * is a lie about the music: Volkmire's Inferno Race opens with a run and a held\n * note that together are six ticks longer than two of its 2/4 bars, and a\n * reader meets that as one bar of 19/32 and then 2/4 throughout, rather than as\n * a bar of rests, a bar line through the run, and a note tied over it.\n *\n * `firstBarTicks` equal to `measureTicks` is the ordinary case, and then the\n * grid is the plain multiples every other piece uses.\n *\n * `oddBars` are bars later in the piece with a length of their own — a bar of\n * 2/4 in a piece in 4/4. Arctic Caverns has one: after six bars of 4/4 the bass\n * runs up E F# G A B C D E in 32 ticks, and everything after that run, every\n * section and the loop's end, sits half a bar past the 4/4 grid.\n */\nexport interface BarGrid {\n measureTicks: number;\n firstBarTicks: number;\n /** Bars after the first with their own length, by bar index, in order. */\n oddBars?: readonly OddBar[];\n}\n\n/** A bar after the first whose length is not the metre's — see `BarGrid`. */\nexport interface OddBar {\n /** The bar's index, from 0 — never the first bar, which has `firstBarTicks`. */\n bar: number;\n ticks: number;\n}\n\nexport const barGrid = (\n measureTicks = MEASURE_TICKS,\n firstBarTicks = measureTicks,\n oddBars: readonly OddBar[] = []\n): BarGrid => ({\n measureTicks,\n firstBarTicks,\n ...(oddBars.length ? { oddBars: [...oddBars].sort((a, b) => a.bar - b.bar) } : {}),\n});\n\nconst oddBarsOf = (grid: BarGrid): readonly OddBar[] =>\n (grid.oddBars ?? []).filter((odd) => odd.bar >= 1);\n\n/** The tick a bar begins on. */\nexport const barStartOf = (grid: BarGrid, index: number): number => {\n if (index <= 0) return 0;\n let start = grid.firstBarTicks + (index - 1) * grid.measureTicks;\n for (const odd of oddBarsOf(grid)) {\n if (odd.bar >= index) break;\n start += odd.ticks - grid.measureTicks;\n }\n return start;\n};\n\n/** How long a bar is: the first and any odd bar have their own length, the rest the metre's. */\nexport const barTicksOf = (grid: BarGrid, index: number): number =>\n index === 0\n ? grid.firstBarTicks\n : (oddBarsOf(grid).find((odd) => odd.bar === index)?.ticks ?? grid.measureTicks);\n\n/** Which bar a tick falls in. Ticks before the piece belong to its first bar. */\nexport const barAt = (grid: BarGrid, tick: number): number => {\n if (tick < grid.firstBarTicks) return 0;\n let bar = 1;\n let start = grid.firstBarTicks;\n for (const odd of oddBarsOf(grid)) {\n const oddStart = start + (odd.bar - bar) * grid.measureTicks;\n if (tick < oddStart) break;\n if (tick < oddStart + odd.ticks) return odd.bar;\n bar = odd.bar + 1;\n start = oddStart + odd.ticks;\n }\n return bar + Math.floor((tick - start) / grid.measureTicks);\n};\n\n/** How many bars a piece of `totalTicks` takes, the last one counted however little it holds. */\nexport const barCountOf = (grid: BarGrid, totalTicks: number): number =>\n totalTicks <= grid.firstBarTicks ? 1 : barAt(grid, totalTicks - 1) + 1;\n\n/** One writable note value: how long it is, what it is called, how many dots. */\nexport interface NoteValue {\n ticks: number;\n /** VexFlow duration code. */\n duration: string;\n dots: number;\n}\n\n/** Longest first — `decompose` takes the first that fits its own grid. */\nconst VALUES: readonly NoteValue[] = [\n { ticks: 64, duration: 'w', dots: 0 },\n { ticks: 56, duration: 'h', dots: 2 },\n { ticks: 48, duration: 'h', dots: 1 },\n { ticks: 32, duration: 'h', dots: 0 },\n { ticks: 28, duration: 'q', dots: 2 },\n { ticks: 24, duration: 'q', dots: 1 },\n { ticks: 16, duration: 'q', dots: 0 },\n { ticks: 14, duration: '8', dots: 2 },\n { ticks: 12, duration: '8', dots: 1 },\n { ticks: 8, duration: '8', dots: 0 },\n // Seven ticks are one head, not a dotted sixteenth tied to a sixty-fourth: Level Complete, pulse 2,\n // where the two heads stood so close the tie vanished and one B3 read as struck twice.\n { ticks: 7, duration: '16', dots: 2 },\n { ticks: 6, duration: '16', dots: 1 },\n { ticks: 4, duration: '16', dots: 0 },\n { ticks: 3, duration: '32', dots: 1 },\n { ticks: 2, duration: '32', dots: 0 },\n { ticks: 1, duration: '64', dots: 0 },\n];\n\n/** What one written head costs. Dominates everything else: a tie is the ugliest thing on a staff. */\nconst PIECE_COST = 100;\n/** A value begun off its own grid — a syncopation. Worth avoiding, never worth a tie. */\nconst OFF_GRID_COST = 10;\n/** A value that hides beat three, the middle of a 4/4 bar. The last tie-break. */\nconst HIDES_MIDDLE_COST = 1;\n\nfunction pieceCost(value: NoteValue, pos: number, measureTicks: number): number {\n // A dotted value sits on the grid of the value it dots: two thirds of its length with one dot,\n // four sevenths with two.\n const grid = (value.ticks * 2 ** value.dots) / (2 ** (value.dots + 1) - 1);\n const half = measureTicks / 2;\n const hidesMiddle = pos % measureTicks !== 0 && pos < half && pos + value.ticks > half;\n return (\n PIECE_COST + (pos % grid === 0 ? 0 : OFF_GRID_COST) + (hidesMiddle ? HIDES_MIDDLE_COST : 0)\n );\n}\n\ninterface Spelling {\n cost: number;\n pieces: NoteValue[];\n /** Heads begun off their own grid. */\n offGrid: number;\n}\n\nconst decomposeCache = new Map<number, Spelling>();\n\n/**\n * A length as a sum of writable note values, from a position in the bar.\n *\n * The FEWEST heads, and only then the tidiest. The first version was greedy and\n * took a value only when it started on its own grid, which reads well in a\n * rulebook and terribly on a staff: four ticks from the second thirty-second of\n * a beat came out as a dotted thirty-second tied to a sixty-fourth — a\n * sixteenth written as two heads, which nobody writes. Here the head count is\n * minimised outright (a sixteenth begun off the beat is a syncopation, and a\n * syncopation is one head), and starting on the grid and keeping beat three\n * visible only break ties between spellings with the same count.\n */\nexport function decompose(\n position: number,\n length: number,\n measureTicks = MEASURE_TICKS\n): NoteValue[] {\n return solve(\n ((position % measureTicks) + measureTicks) % measureTicks,\n length,\n measureTicks\n ).pieces.slice();\n}\n\nfunction solve(pos: number, left: number, measureTicks: number): Spelling {\n if (left <= 0) return { cost: 0, pieces: [], offGrid: 0 };\n const key = (measureTicks * 4096 + pos) * 4096 + left;\n const cached = decomposeCache.get(key);\n if (cached) return cached;\n\n let best: Spelling | null = null;\n // Longest first, and only a strictly cheaper spelling replaces one found\n // earlier — so among equals the long value comes first.\n for (const value of VALUES) {\n if (value.ticks > left) continue;\n const rest = solve((pos + value.ticks) % measureTicks, left - value.ticks, measureTicks);\n const own = pieceCost(value, pos, measureTicks);\n const cost = own + rest.cost;\n if (!best || cost < best.cost) {\n const offGrid = rest.offGrid + (own - PIECE_COST >= OFF_GRID_COST ? 1 : 0);\n best = { cost, pieces: [value, ...rest.pieces], offGrid };\n }\n }\n decomposeCache.set(key, best!);\n return best!;\n}\n\n/** A note of one voice, in the integers the ROM holds. */\nexport interface TickNote {\n /** Ticks from the start of the piece. */\n start: number;\n ticks: number;\n /** MIDI number. */\n midi: number;\n}\n\n/**\n * One head of a tuplet: three notes written in the time of two.\n *\n * `num` heads in the time of `occupied`, and the bracket is drawn over the run\n * from `first` to `last` — VexFlow needs the group, not the single head.\n */\nexport interface TupletSpan {\n num: number;\n occupied: number;\n first: boolean;\n last: boolean;\n}\n\n/** One head or rest on the staff — already a writable value. */\nexport interface StaffItem {\n start: number;\n ticks: number;\n /** null is a rest. */\n midi: number | null;\n duration: string;\n dots: number;\n /** Set on each head of a tuplet — see `tupletGroups`. */\n tuplet?: TupletSpan;\n /**\n * Still the same sounding note as the head before it / after it.\n *\n * A tie is the difference between one note and two, and one crossing a bar\n * line is drawn as two half curves that meet at it.\n */\n tieStart: boolean;\n tieStop: boolean;\n}\n\nexport interface StaffMeasure {\n /** Bar number from the start of the piece, counting from 0. */\n index: number;\n /** Tick the bar starts on. */\n start: number;\n items: StaffItem[];\n}\n\n/**\n * A voice's notes as a continuous ribbon: rests where it is silent, cut at\n * every bar line, and every piece already a writable value.\n *\n * Monophonic by construction — the driver walks one stream per channel — so an\n * overlap can only mean the previous note is still counted as sounding, and the\n * cursor simply moves on rather than stacking a chord that the hardware cannot\n * play.\n */\n/**\n * The divisions a tuplet may fill: a written value, so the bracket spans\n * something a reader can name. Three heads in the time of two.\n */\nconst TUPLET_TOTALS = [8, 16, 32, 64];\n\n/** One head of a tuplet, with the value it is written as. */\ninterface TupletHead {\n span: TupletSpan;\n value: NoteValue;\n}\n\n/**\n * Where the music divides a written value into THREE.\n *\n * One tick is a sixty-fourth, so a third of anything is not a whole number and\n * the driver cannot hold a true triplet: it writes the nearest integers it can,\n * and the give-away is a run of three that sums to a written value and divides\n * as evenly as integers allow without dividing evenly. A quarter triplet is\n * 10+11+11 of the half's 32 ticks; a sixteenth triplet is 2+3+3 of the\n * eighth's 8. Spelt by `decompose` instead, each of those becomes two heads\n * under a tie, and a bar of them is unreadable — which is how this was found.\n *\n * The rule is deliberately narrow, and it is checked against the ROM rather\n * than reasoned about: over all twenty tracks it fires exactly twice — title\n * music's bar 39, where pulse 1, pulse 2, the triangle and the drums all take\n * it together, and Clinger Winger's drums, once a bar for five bars. Nothing\n * else in the cartridge matches, so nothing else is re-spelt.\n *\n * Even thirds are NOT tuplets: three heads of the same written value need no\n * bracket, and the ROM has none inside these totals anyway.\n */\nexport function tupletGroups(\n notes: readonly TickNote[],\n grid: BarGrid = barGrid()\n): Map<number, TupletHead> {\n const out = new Map<number, TupletHead>();\n for (let at = 0; at + 2 < notes.length; at++) {\n const run = notes.slice(at, at + 3);\n const ticks = run[0].ticks + run[1].ticks + run[2].ticks;\n if (!TUPLET_TOTALS.includes(ticks)) continue;\n // Adjacent, and inside one bar: a bracket cannot cross a bar line.\n if (\n run.some(\n (note, index) => index > 0 && run[index - 1].start + run[index - 1].ticks !== note.start\n )\n )\n continue;\n const bar = barAt(grid, run[0].start);\n const inBar = run[0].start - barStartOf(grid, bar);\n if (inBar > barTicksOf(grid, bar) - ticks) continue;\n // On its own division from the bar line, so the bracket is the beam group: an eighth's triplet\n // on an eighth, anything a beat or longer on a beat. Read from wherever three notes happen to\n // sum right, brackets began mid-group and ran across the beat (Terminator 2, Level 5).\n if (inBar % Math.min(ticks, TICKS_PER_QUARTER) !== 0) continue;\n const lengths = run.map((note) => note.ticks);\n if (Math.max(...lengths) - Math.min(...lengths) > 1) continue;\n if (lengths.some((length) => length * 3 === ticks)) continue;\n // Three in the time of two, so each head is written as half the division.\n const value = VALUES.find((candidate) => candidate.ticks === ticks / 2 && candidate.dots === 0);\n if (!value) continue;\n run.forEach((_, index) =>\n out.set(at + index, {\n value,\n span: { num: 3, occupied: 2, first: index === 0, last: index === 2 },\n })\n );\n at += 2;\n }\n return out;\n}\n\n/**\n * Spans an exact tuplet may fill, in ticks, in the order they are tried: the beat first, then\n * shorter, then longer. A bracket over a beat reads better than two over its halves — unless one\n * half needs none (`plainHalf`).\n */\nconst TUPLET_SPANS = [16, 8, 4, 32, 64];\n/** How many notes a tuplet may divide its span into — every count that is not a power of two. */\nconst TUPLET_COUNTS = [3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15];\n/**\n * Each count with the parts its step may be split into: whole steps for every count first, then\n * halves, then quarters — Alien 3 opens a 9:8 of thirty-seconds with four sixty-fourths. A grid\n * that whole steps of some count already write is read as that count: six sixteenths in a quarter\n * are a sextuplet, not a triplet of eighths split in two.\n */\nconst TUPLET_GRIDS: readonly (readonly [number, number])[] = [1, 2, 4].flatMap((split) =>\n TUPLET_COUNTS.map((num) => [num, split] as const)\n);\n/** How close a start must be to a tuplet's grid, in ticks, to stand on it. */\nconst ON_GRID = 1e-6;\n\n/** The notes a tuplet of `num` is written in the time of: the largest power of two below it. */\nexport const tupletOccupied = (num: number): number => 2 ** Math.floor(Math.log2(num - 1e-9));\n\n/** One exact tuplet run: notes `from`..`to` (exclusive) of the ordered list, and its items. */\ninterface TupletRun {\n to: number;\n start: number;\n span: number;\n items: StaffItem[];\n}\n\nconst near = (value: number) => Math.abs(value - Math.round(value)) < ON_GRID;\n\n/**\n * Tuplets of any count, read from notes whose starts and ends divide a written value exactly.\n *\n * A sound driver counts whole ticks, and its triplets are 10 + 11 + 11 (`tupletGroups`). Music from\n * anywhere else can say what it means: five notes from 0 to 16, each 3.2 ticks — a quintuplet of\n * sixteenths in a quarter. A run is read as a tuplet of `num` in the time of `tupletOccupied(num)`\n * when every start and end in it falls on its grid of `span / num`, the run fills `span` from a\n * point that span may start on, and at least one of its edges is off the grid of whole ticks — so a\n * line of ordinary values is never re-read. Inside, notes may be any whole number of the grid's\n * steps — a quarter and an eighth in an eighth triplet — or of a half or a quarter of a step, and\n * the steps no note takes are rests.\n *\n * Whole-tick music never has one: no span here divides by three, five or seven into whole ticks.\n */\nfunction exactTuplets(notes: readonly TickNote[], grid: BarGrid): Map<number, TupletRun> {\n const runs = new Map<number, TupletRun>();\n for (let from = 0; from < notes.length; from++) {\n const begin = notes[from].start;\n const bar = barAt(grid, begin + ON_GRID);\n const barStart = barStartOf(grid, bar);\n const barEnd = barStart + barTicksOf(grid, bar);\n let found: TupletRun | null = null;\n for (const span of TUPLET_SPANS) {\n if (found) break;\n // On the grid the span itself keeps — a beat for anything a beat or longer.\n const step = Math.min(span, TICKS_PER_QUARTER);\n for (let start = Math.floor((begin - barStart) / step) * step + barStart; start <= begin + ON_GRID && !found; start += step) {\n if (start + span > barEnd + ON_GRID) break;\n for (const [num, split] of TUPLET_GRIDS) {\n const cells = num * split;\n const unit = span / cells;\n const run: TickNote[] = [];\n for (let j = from; j < notes.length && notes[j].start < start + span - ON_GRID; j++) run.push(notes[j]);\n if (!run.length || Math.abs(run[0].start - begin) > ON_GRID) continue;\n // An earlier note that reaches into the span leaves it no clean start.\n if (from > 0 && notes[from - 1].start + notes[from - 1].ticks > start + ON_GRID) continue;\n const steps = run.map((note) => [(note.start - start) / unit, (note.start + note.ticks - start) / unit]);\n if (!steps.every(([a, b]) => near(a) && near(b) && b <= cells + ON_GRID && a >= -ON_GRID)) continue;\n const edges = run.flatMap((note) => [note.start, note.start + note.ticks]);\n if (edges.every((edge) => near(edge))) continue;\n // A half of the span that ordinary values write on their own wants a shorter bracket: a\n // sixteenth triplet and an eighth are a triplet over the first half, not a sextuplet.\n const plainHalf = (lo: number, hi: number) =>\n run\n .filter((note) => note.start < hi - ON_GRID && note.start + note.ticks > lo + ON_GRID)\n .every(\n (note) =>\n note.start >= lo - ON_GRID &&\n note.start + note.ticks <= hi + ON_GRID &&\n near(note.start) &&\n near(note.start + note.ticks)\n );\n if (span > 4 && (plainHalf(start, start + span / 2) || plainHalf(start + span / 2, start + span))) continue;\n // The pieces: notes and the steps between them, each a value one head writes.\n const occupied = tupletOccupied(num);\n const written = span / occupied / split;\n const pieces: { from: number; length: number; midi: number | null; at?: number }[] = [];\n let at = 0;\n for (let k = 0; k < run.length; k++) {\n const a = Math.round(steps[k][0]);\n const b = Math.round(steps[k][1]);\n if (a < at) break;\n if (a > at) pieces.push({ from: at, length: a - at, midi: null });\n pieces.push({ from: a, length: b - a, midi: run[k].midi, at: run[k].start });\n at = b;\n }\n if (at < cells) pieces.push({ from: at, length: cells - at, midi: null });\n const values = pieces.map((piece) =>\n VALUES.find((value) => Math.abs(value.ticks - piece.length * written) < ON_GRID)\n );\n if (pieces.reduce((sum, piece) => sum + piece.length, 0) !== cells || values.some((value) => !value)) continue;\n // Each piece from where it starts — a note's own start, so its marks find it — to the next.\n const starts = pieces.map((piece, index) =>\n piece.at !== undefined ? piece.at : index === 0 ? start : start + Math.round(piece.from * unit * 1e9) / 1e9\n );\n const items = pieces.map((piece, index): StaffItem => {\n const pieceStart = starts[index];\n const pieceEnd = index + 1 < pieces.length ? starts[index + 1] : start + span;\n return {\n start: pieceStart,\n ticks: pieceEnd - pieceStart,\n midi: piece.midi,\n duration: values[index]!.duration,\n dots: values[index]!.dots,\n tieStart: false,\n tieStop: false,\n tuplet: { num, occupied, first: index === 0, last: index === pieces.length - 1 },\n };\n });\n found = { to: from + run.length, start, span, items };\n break;\n }\n }\n }\n if (found) {\n runs.set(from, found);\n from = found.to - 1;\n }\n }\n return runs;\n}\n\n/**\n * The exact tuplets, a run on the same grid that carries on to the beat read as one: two\n * sixteenth triplets that fill a quarter are a sextuplet, as a reader writes six in a beat. Not\n * past the beat — twelve in a half is four triplets.\n */\nfunction exactTupletsByBeat(notes: readonly TickNote[], grid: BarGrid): Map<number, TupletRun> {\n const runs = exactTuplets(notes, grid);\n const merged = new Map<number, TupletRun>();\n const ordered = [...runs.entries()].sort((a, b) => a[0] - b[0]);\n for (let i = 0; i < ordered.length; i++) {\n const [from, run] = ordered[i];\n const next = ordered[i + 1];\n const num = run.items[0].tuplet!.num;\n const double = num * 2;\n if (\n next &&\n run.span * 2 <= TICKS_PER_QUARTER &&\n (run.start - barStartOf(grid, barAt(grid, run.start + ON_GRID))) % (run.span * 2) === 0 &&\n TUPLET_COUNTS.includes(double) &&\n next[0] === run.to &&\n Math.abs(next[1].start - (run.start + run.span)) < ON_GRID &&\n next[1].span === run.span &&\n next[1].items[0].tuplet!.num === num\n ) {\n const items = [...run.items, ...next[1].items].map((item, index, all) => ({\n ...item,\n tuplet: { num: double, occupied: tupletOccupied(double), first: index === 0, last: index === all.length - 1 },\n }));\n // The written value stays: the bracket counts the same steps, twice as many of them.\n merged.set(from, { to: next[1].to, start: run.start, span: run.span * 2, items });\n i++;\n continue;\n }\n merged.set(from, run);\n }\n return merged;\n}\n\nexport function staffItems(\n notes: readonly TickNote[],\n totalTicks: number,\n grid: BarGrid = barGrid()\n): StaffItem[] {\n const items: StaffItem[] = [];\n const ordered = [...notes].sort((a, b) => a.start - b.start);\n let cursor = 0;\n\n const push = (start: number, length: number, midi: number | null) => {\n // Off the tick grid and in no tuplet — a run that does not fill its bracket: the nearest ticks.\n let position = Math.round(start);\n let left = Math.round(start + length) - position;\n let first = true;\n while (left > 0) {\n const bar = barAt(grid, position);\n const barStart = barStartOf(grid, bar);\n const barTicks = barTicksOf(grid, bar);\n const chunk = Math.min(left, barStart + barTicks - position);\n const carriesOn = chunk < left;\n\n const pieces = decompose(position - barStart, chunk, barTicks);\n let at = position;\n pieces.forEach((piece, index) => {\n items.push({\n start: at,\n ticks: piece.ticks,\n midi,\n duration: piece.duration,\n dots: piece.dots,\n // A head is tied to the one before it when it is a continuation:\n // of an earlier bar's remainder, or of the piece beside it.\n tieStop: midi !== null && (!first || index > 0),\n tieStart: midi !== null && (carriesOn || index < pieces.length - 1),\n });\n at += piece.ticks;\n });\n\n position += chunk;\n left -= chunk;\n first = false;\n }\n };\n\n const tuplets = tupletGroups(ordered, grid);\n // Exact tuplets only where some note is off the whole-tick grid: whole-tick music has none.\n const exact = ordered.some((note) => !Number.isInteger(note.start) || !Number.isInteger(note.ticks))\n ? exactTupletsByBeat(ordered, grid)\n : null;\n let skipTo = -1;\n\n ordered.forEach((note, index) => {\n if (index < skipTo) return;\n const run = exact?.get(index);\n if (run) {\n if (run.start > cursor) push(cursor, run.start - cursor, null);\n items.push(...run.items);\n cursor = run.start + run.span;\n skipTo = run.to;\n return;\n }\n if (note.start > cursor) push(cursor, note.start - cursor, null);\n cursor = Math.max(cursor, note.start);\n\n const length = Math.min(note.ticks, Math.max(0, totalTicks - cursor));\n if (length <= 0) return;\n\n // A tuplet head is written whole, at the value the bracket says: its ticks\n // are not a written value and `decompose` would tie it into scraps.\n const head = tuplets.get(index);\n if (head) {\n items.push({\n start: cursor,\n ticks: length,\n midi: note.midi,\n duration: head.value.duration,\n dots: 0,\n tieStart: false,\n tieStop: false,\n tuplet: head.span,\n });\n cursor += length;\n return;\n }\n\n push(cursor, length, note.midi);\n cursor += length;\n });\n\n if (cursor < totalTicks) push(cursor, totalTicks - cursor, null);\n return items;\n}\n\n/**\n * The ribbon cut into bars, each one filled to the bar line.\n *\n * A bar short of its four beats is not a bar — a formatter given one spaces it\n * as though the missing time did not exist, and the staff stops lining up with\n * the music beside it — so whatever is left at the end is padded with rests.\n */\nexport function staffMeasures(\n items: readonly StaffItem[],\n totalTicks: number,\n grid: BarGrid = barGrid()\n): StaffMeasure[] {\n const count = Math.max(1, barCountOf(grid, totalTicks));\n const measures: StaffMeasure[] = [];\n // `staffItems` hands the ribbon over in order, and then each bar is the next\n // run of it: one walk instead of a filter over the whole piece per bar.\n let sorted = true;\n for (let at = 1; at < items.length && sorted; at++)\n sorted = items[at - 1].start <= items[at].start;\n let next = 0;\n\n for (let index = 0; index < count; index++) {\n const start = barStartOf(grid, index);\n const barTicks = barTicksOf(grid, index);\n let inBar: StaffItem[];\n if (sorted) {\n while (next < items.length && items[next].start < start) next++;\n inBar = [];\n while (next < items.length && items[next].start < start + barTicks) inBar.push(items[next++]);\n } else {\n inBar = items.filter((item) => item.start >= start && item.start < start + barTicks);\n }\n const filled = inBar.reduce((sum, item) => sum + item.ticks, 0);\n\n // Filled to within a hair is full: a tuplet's steps are sums of fractions.\n if (barTicks - filled > ON_GRID) {\n let at = start + filled;\n for (const piece of decompose(filled, barTicks - filled, barTicks)) {\n inBar.push({\n start: at,\n ticks: piece.ticks,\n midi: null,\n duration: piece.duration,\n dots: piece.dots,\n tieStart: false,\n tieStop: false,\n });\n at += piece.ticks;\n }\n }\n\n measures.push({ index, start, items: inBar });\n }\n return measures;\n}\n\nconst STEPS = ['c', 'c', 'd', 'd', 'e', 'f', 'f', 'g', 'g', 'a', 'a', 'b'];\nconst FLAT_STEPS = ['c', 'd', 'd', 'e', 'e', 'f', 'g', 'g', 'a', 'a', 'b', 'b'];\nconst BLACK = [false, true, false, true, false, false, true, false, true, false, true, false];\n/** The white keys with a flat spelling — B as C-flat, E as F-flat — by pitch class. */\nconst WHITE_FLATS: Readonly<Record<number, string>> = { 4: 'f', 11: 'c' };\n\n/**\n * A MIDI number as a VexFlow key — `c#/4` for 61, `db/4` in a key that flats D.\n *\n * A black key is spelt the way the KEY SIGNATURE has it when the signature\n * alters either of its letters, and as a sharp otherwise. A flat key spelt in\n * sharps prints D-sharp against a signature that flattens E — a sign on nearly\n * every note — which is what rat race looked like before flats could be written.\n * Spelling EVERY black key flat in a flat key was the next mistake: Volkmire's\n * Inferno, in E-flat, climbs F to F-sharp, and printing that as G-flat put a\n * flat on a note a reader took for a B-flat already in the key.\n *\n * Two white keys have a flat spelling of their own: B is C-flat and E is F-flat. They take it only\n * in a key that flattens that letter — six flats for C-flat. Rat race is in E-flat minor, whose\n * sixth degree is C-flat; written as B it printed a natural against the B-flat of the signature.\n */\nexport function staffKey(midi: number, key?: KeySignature): string {\n const index = ((midi % 12) + 12) % 12;\n const octave = Math.floor(midi / 12) - 1;\n const flatWhite = WHITE_FLATS[index];\n if (flatWhite && key?.accidental === 'b' && key.letters.includes(flatWhite)) {\n // C-flat sits in the octave above its B: C-flat 4 is B3.\n return `${flatWhite}b/${index === 11 ? octave + 1 : octave}`;\n }\n if (!BLACK[index]) return `${STEPS[index]}/${octave}`;\n const flat =\n (key?.accidental === 'b' && key.letters.includes(FLAT_STEPS[index])) ||\n (key?.spelt?.includes(FLAT_STEPS[index]) ?? false);\n return flat ? `${FLAT_STEPS[index]}b/${octave}` : `${STEPS[index]}#/${octave}`;\n}\n\n/** Letters by diatonic step, and the steps an interval of n semitones spans when spelt plainly. */\nconst LETTER_STEP: Readonly<Record<string, number>> = { c: 0, d: 1, e: 2, f: 3, g: 4, a: 5, b: 6 };\nconst PLAIN_STEPS = [0, 1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6];\n\n/** The other spelling of a black key: `c#/4` ↔ `db/4`. Null for a white key. */\nfunction otherSpelling(midi: number, spelt: string): string | null {\n const index = ((midi % 12) + 12) % 12;\n if (!BLACK[index]) return null;\n const octave = Math.floor(midi / 12) - 1;\n return spelt.includes('#') ? `${FLAT_STEPS[index]}b/${octave}` : `${STEPS[index]}#/${octave}`;\n}\n\n/** Diatonic position of a VexFlow key: letter step plus seven a an octave. */\nconst stepOf = (key: string) => {\n const [name, octave] = key.split('/');\n return LETTER_STEP[name[0]] + 7 * Number(octave);\n};\n\n/**\n * The heads of a chord as VexFlow keys, each black key spelt so the chord reads as intervals do.\n *\n * `staffKey` spells one note against the key, and for a line that is right: Volkmire's Inferno, in\n * E-flat, climbs F to F-sharp. A chord is read the other way — by the intervals between its heads.\n * Paganini's Caprice 17, in E-flat, strikes E-flat with G-flat: written E-flat and F-sharp, that is\n * an augmented second where a minor third sounds. So for the black keys of a chord both spellings\n * are tried, and the one whose intervals span the letters their size asks for wins — a third across\n * three letters, a second across two; where the intervals cannot tell, `staffKey` decides. In the\n * order given.\n */\nexport function chordKeys(midis: readonly number[], key?: KeySignature): string[] {\n const plain = midis.map((midi) => staffKey(midi, key));\n const choices = midis.map((midi, i) => {\n const other = otherSpelling(midi, plain[i]);\n return other ? [plain[i], other] : [plain[i]];\n });\n const cost = (keys: readonly string[]) => {\n let wrong = 0;\n for (let i = 0; i < keys.length; i++) {\n for (let j = i + 1; j < keys.length; j++) {\n const [lo, hi] = midis[i] <= midis[j] ? [i, j] : [j, i];\n const semitones = midis[hi] - midis[lo];\n const steps = stepOf(keys[hi]) - stepOf(keys[lo]);\n const expected = PLAIN_STEPS[semitones % 12] + 7 * Math.floor(semitones / 12);\n if (steps !== expected) wrong++;\n }\n }\n return wrong;\n };\n let best = plain;\n let bestCost = cost(plain);\n const walk = (at: number, picked: string[]) => {\n if (at === choices.length) {\n const c = cost(picked);\n if (c < bestCost) {\n bestCost = c;\n best = picked.slice();\n }\n return;\n }\n for (const option of choices[at]) walk(at + 1, [...picked, option]);\n };\n if (choices.some((options) => options.length > 1)) walk(0, []);\n return best;\n}\n\n/** What a key signature does: which letters it alters, and which way. */\nexport interface KeySignature {\n /** `#` for a sharp key, `b` for a flat one. C has neither and no letters. */\n accidental: '#' | 'b';\n letters: readonly string[];\n /** Letters whose black key is written flat although the key leaves the letter alone — see `keyOf`. */\n spelt?: readonly string[];\n}\n\nconst SHARP_ORDER = ['f', 'c', 'g', 'd', 'a', 'e', 'b'];\nconst FLAT_ORDER = ['b', 'e', 'a', 'd', 'g', 'c', 'f'];\n/** Signed number of sharps (+) or flats (−) by VexFlow major key name. */\nconst KEY_ALTERATIONS: Readonly<Record<string, number>> = {\n C: 0,\n G: 1,\n D: 2,\n A: 3,\n E: 4,\n B: 5,\n 'F#': 6,\n 'C#': 7,\n F: -1,\n Bb: -2,\n Eb: -3,\n Ab: -4,\n Db: -5,\n Gb: -6,\n Cb: -7,\n};\n\n/**\n * A key signature by its VexFlow name (`G` one sharp, `Eb` three flats).\n * A name it does not know is C — written with every sign at its note rather\n * than guessed at.\n */\nexport function keyOf(name?: string): KeySignature {\n const [signature, ...flats] = (name ?? '').split('+');\n const count = signature ? (KEY_ALTERATIONS[signature] ?? 0) : 0;\n const key: KeySignature =\n count < 0\n ? { accidental: 'b', letters: FLAT_ORDER.slice(0, -count) }\n : { accidental: '#', letters: SHARP_ORDER.slice(0, count) };\n return flats.length ? { ...key, spelt: flats.map((flat) => flat[0].toLowerCase()) } : key;\n}\n\n/**\n * The signature part of a key name, the one VexFlow is given — `F` of `F+Db+Ab`.\n *\n * What follows a `+` is spelling, not signature: black keys to write as those flats although the\n * key does not flatten their letters. Turbo tunnel, in D minor with one flat, falls D, D-flat, C in\n * the bass; the rule for black keys wrote the middle chord as C-sharp and G-sharp.\n */\nexport const signatureName = (name?: string): string | undefined => name?.split('+')[0];\n\n/**\n * Treble or bass for a voice, from where it actually sits.\n *\n * The median rather than the mean: one low pickup note must not drag a melody\n * onto ledger lines below the bass staff. The boundary is middle C's octave —\n * a voice whose middle is below A3 spends more of its time under the treble\n * staff than in it.\n */\nexport function chooseClef(notes: readonly { midi: number }[]): 'treble' | 'bass' {\n if (notes.length === 0) return 'treble';\n const pitches = notes.map((note) => note.midi).sort((a, b) => a - b);\n const median = pitches[Math.floor(pitches.length / 2)];\n return median < 57 ? 'bass' : 'treble';\n}\n\n/**\n * How hard a voice is to read from a given bar line: its heads, plus one for\n * every head that starts off its own grid.\n *\n * The measureTicks `voicePhase` minimises. A run of ticks written as\n * one note on the beat costs 1. The syncopation counts as much as a tie, and\n * that is deliberate: `decompose` writes an off-beat run as ONE head, so by\n * heads alone every bar line would look equally good, and the search would\n * happily put the whole piece a sixteenth off the beat.\n */\nexport function notationCost(\n notes: readonly TickNote[],\n offset: number,\n measureTicks = MEASURE_TICKS\n): number {\n let pieces = 0;\n for (const note of notes) {\n // A tuplet's note is off the tick grid, and counts at the whole ticks nearest it: left out,\n // a voice of Alien 3's 9:8 figures was read from its few plain notes, which said 3 ticks late.\n const start = Math.round(note.start);\n // + 2 bars so a shift past the first note still lands on a positive tick.\n // Measured on the plain grid: what it weighs is the phase of a voice\n // against the beat, which the opening bar's own length does not change.\n let position = start - offset + measureTicks * 2;\n let left = Math.max(1, Math.round(note.start + note.ticks) - start);\n while (left > 0) {\n const inBar = position % measureTicks;\n const chunk = Math.min(left, measureTicks - inBar);\n pieces += spellingCost(inBar, chunk, measureTicks);\n position += chunk;\n left -= chunk;\n }\n }\n return pieces;\n}\n\n/**\n * `solve`'s heads plus off-grid heads for a run inside one bar, from a flat\n * table per bar length. `voicePhase` asks this for every piece of every note,\n * four times over, and a `Map` keyed by a number past 2^31 is the slow part of\n * that — so whole-tick runs are looked up by index instead.\n */\nconst costTables = new Map<number, Int32Array>();\n\nfunction spellingCost(inBar: number, chunk: number, measureTicks: number): number {\n if (\n !Number.isInteger(measureTicks) ||\n !Number.isInteger(inBar) ||\n !Number.isInteger(chunk) ||\n inBar < 0\n ) {\n const spelling = solve(inBar, chunk, measureTicks);\n return spelling.pieces.length + spelling.offGrid;\n }\n let table = costTables.get(measureTicks);\n if (!table) {\n table = new Int32Array(measureTicks * (measureTicks + 1));\n costTables.set(measureTicks, table);\n }\n const index = inBar * (measureTicks + 1) + chunk;\n let cost = table[index];\n if (cost === 0) {\n const spelling = solve(inBar, chunk, measureTicks);\n // Stored one up, so 0 can mean \"not worked out yet\".\n cost = spelling.pieces.length + spelling.offGrid + 1;\n table[index] = cost;\n }\n return cost - 1;\n}\n\n/**\n * How many ticks one channel is written behind the beat. Never more than\n * `MAX_PHASE`.\n *\n * The delay is AUTHORED, not the driver's. Nearly every track opens a channel\n * or two with an explicit `$80` rest one sixty-fourth long, and Intruder\n * Excluder puts a three-tick rest ahead of pulse 2's copy of pulse 1's bass\n * line — a two-tick echo, some 60ms, and audible as one. (An earlier version of\n * this comment called it the cost of setup commands; the stream dump says\n * otherwise.)\n *\n * On a staff, though, it is the difference between a quarter note and a chain\n * of tied scraps, so the notes are written on the beat and the delay is\n * STATED: a staff should label every voice it moved, and not move its playhead.\n * Longer echoes (Surf City's six ticks) are past `MAX_PHASE` and are written as\n * they sound.\n */\nexport const MAX_PHASE = 3;\n\nexport function voicePhase(\n notes: readonly TickNote[],\n offset: number,\n measureTicks = MEASURE_TICKS\n): number {\n // A voice a reading has already put into tuplets stands where it is meant to: its heads are\n // fractions of a beat counted from the bar line, and a phase of whole ticks only knocks them off\n // that grid. Terminator 2's Level 5 moved pulse 1 three ticks and printed its sextuplets as dotted\n // thirty-seconds, while pulse 2, playing the same rhythm, kept its 6:4.\n if (notes.some((note) => !Number.isInteger(note.start) || !Number.isInteger(note.ticks))) return 0;\n let best = 0;\n let bestCost = Infinity;\n for (let phase = 0; phase <= MAX_PHASE; phase++) {\n const cost = notationCost(notes, offset + phase, measureTicks);\n if (cost < bestCost) {\n bestCost = cost;\n best = phase;\n }\n }\n return best;\n}\n\n/**\n * A voice moved `by` ticks along the staff's clock, cut at tick 0.\n *\n * Taking a channel's delay out can carry its first sliver before the music\n * starts: ragnarok's canyon opens the noise channel with a one-tick hit on\n * tick 0 and then plays everything a tick late. Refusing the phase for the sake\n * of that sliver — which is what a guard in `voicePhase` once did — left every\n * drum on an odd tick, and each of those gave the formatter a column of\n * its own: a gap between the first two sixteenths of pulse 1 in every bar. So\n * the phase is taken, and what lands before tick 0 is cut off there.\n */\nexport function shiftNotes<T extends TickNote>(notes: readonly T[], by: number): T[] {\n const out: T[] = [];\n for (const note of notes) {\n const start = note.start + by;\n const ticks = start < 0 ? note.ticks + start : note.ticks;\n if (ticks > 0) out.push({ ...note, start: Math.max(0, start), ticks });\n }\n return out;\n}\n\n/*\n * Where the bar line falls: at the track's FIRST TICK. There is no search.\n *\n * There used to be — a search tried all 64 bar lines and kept the one that\n * wrote the music with the fewest heads, on the reasoning a transcriber uses by\n * ear. It is blind to exactly the mistake that matters: this music repeats in\n * whole-bar patterns on a sixteenth grid, so a bar line an eighth or two off\n * writes it with almost the same number of heads. Ragnarok's canyon came out at\n * 17 (1060 heads) against 1 (1064), and every bar of the score opened two\n * eighths early — heard wrong at once, while the numbers called it a win. Nine\n * of the twenty tracks were moved off tick 0 that way, most by a margin under a\n * percent.\n *\n * Tick 0 is what the evidence says instead: every channel of a track starts\n * there, the repeat points sit on ticks 1..4 in most tracks, and the MusicXML\n * export has always barred from tick 0, and the two agree. A channel's own authored delay (at most `MAX_PHASE` ticks) is still\n * taken out per voice by `voicePhase`.\n */\n\n/**\n * Ticks to ADD to a piece's own clock to get the staff's, for a bar line\n * `offset` ticks in.\n *\n * Less than a bar, so a piece barred off its first tick gets a pickup bar\n * rather than notes before tick zero — and nothing at all for offset 0, which\n * is what every track uses: an empty bar in front of the music says the music\n * starts a bar late.\n */\nexport function staffShift(offset: number, measureTicks = MEASURE_TICKS): number {\n return (measureTicks - (offset % measureTicks)) % measureTicks;\n}\n\n/**\n * The three readings of a pickup — the notes before a piece's first bar line:\n *\n * - `anacrusis`, the default and the way music is written: the opening bar is the pickup alone, as\n * short as it is, under the metre's own time signature — no rests in front, no signature of its\n * own. A piece that opens with one ends with the bar's complement (`buildScore`), so the two make\n * one whole bar between them. Circus Charlie's Aerial Bar: two eighths, then 6/8.\n * - `merged`: the OPENING BAR is longer by the pickup and nothing moves — the run and the note it\n * lands on are one bar of 19/32, and the metre takes over after it. It reads better whenever the\n * pickup is not a whole phrase: a bar line through the middle of a run is worse than an irregular\n * first bar.\n * - `padded`: a whole bar of the metre, rests in front of the pickup, the music starting part way\n * into bar one. What every pickup was before `anacrusis`, kept for scores checked that way.\n *\n * `true` and `false` are the old flag: `merged` and `anacrusis`.\n */\nexport type Pickup = 'anacrusis' | 'merged' | 'padded';\n\n/** A pickup reading given as the old boolean flag or by name — see `Pickup`. */\nexport const pickupOf = (pickup: boolean | Pickup | undefined): Pickup =>\n pickup === true ? 'merged' : pickup === false || pickup === undefined ? 'anacrusis' : pickup;\n\n/**\n * How a piece is barred: where its bar lines fall, and what its notes are moved\n * by to sit behind them — see `Pickup` for the three readings of a pickup.\n */\nexport function barring(\n offset: number,\n measureTicks = MEASURE_TICKS,\n reading: boolean | Pickup = 'anacrusis',\n /** Bars later in the piece with a length of their own — see `BarGrid`. */\n oddBars: readonly OddBar[] = []\n): { grid: BarGrid; shift: number } {\n const pickup = ((offset % measureTicks) + measureTicks) % measureTicks;\n switch (pickupOf(reading)) {\n case 'merged':\n return { grid: barGrid(measureTicks, measureTicks + pickup, oddBars), shift: 0 };\n case 'anacrusis':\n if (pickup > 0) return { grid: barGrid(measureTicks, pickup, oddBars), shift: 0 };\n // falls through: no pickup, nothing to read\n case 'padded':\n return { grid: barGrid(measureTicks, measureTicks, oddBars), shift: staffShift(offset, measureTicks) };\n }\n}\n\nexport type Clef = 'treble' | 'bass';\n\n/**\n * The outer LINES of each staff, as MIDI numbers: E4..F5 and G2..A3.\n *\n * Not the centres — what matters for room is where the ledger lines start.\n */\nexport const STAFF_SPAN: Record<Clef, readonly [number, number]> = {\n treble: [64, 77],\n bass: [43, 57],\n};\n\n/**\n * The pitch each staff is centred on: B4 on the treble, D3 on the bass. Kept\n * for callers that want the middle line; the clef is not chosen by it.\n */\nexport const CLEF_CENTRE: Record<Clef, number> = { treble: 71, bass: 50 };\n\n/**\n * How much better the other clef has to be before a bar switches, in semitones\n * of the ladder it saves.\n *\n * Without it a line hovering between the two staves changes clef every other\n * bar, which is unreadable in a way that ledger lines are not.\n */\nexport const CLEF_HYSTERESIS = 3;\n\n/**\n * How much better a clef change PART WAY through a bar has to be than the best\n * clef for the whole bar, in semitones of the ladder it saves.\n *\n * Higher than `CLEF_HYSTERESIS`, because a change inside a bar is louder. At 3,\n * a line that crosses between the staves on every beat changed clef inside\n * bar after bar — Ragnarok's canyon went treble, bass, treble, bass through\n * bars 5 to 9 — for ladders that were only a few rungs shorter. Measured over\n * the twenty tracks' voices: at 3, 92 changes inside bars; at 6, the bar that\n * drops an octave still splits and the see-saw is gone.\n */\nexport const CLEF_SPLIT_MARGIN = 6;\n\n/**\n * What a bar costs on one clef: the TALLEST ladder of ledger lines in it, with\n * the average as a tie-break.\n *\n * The tallest, not the average, and that is the whole rule. Averaging is what a\n * first version did, and it reads the bar as a crowd: a bar of eight low notes\n * and two very high ones votes for the low clef, and the two high notes then\n * get a fourteen-rung ladder that runs off the top of the strip. What decides\n * whether a bar can be READ is its worst excursion — one note an octave out is\n * two ledger lines and fine, one note two octaves out is unreadable however\n * many of its neighbours sit comfortably.\n *\n * Measured over the twenty tracks, choosing by the worst excursion instead of\n * the average halves the bars carrying a ladder over 18 semitones (37 → 17) and\n * takes fewer clef changes to do it (129 → 112).\n */\n/** How far a pitch sits off a staff, in semitones: 0 on it. */\nfunction outside(midi: number, clef: Clef): number {\n const [low, high] = STAFF_SPAN[clef];\n return Math.max(0, midi - high, low - midi);\n}\n\nfunction clefCost(pitches: readonly number[], clef: Clef): number {\n const worst = pitches.reduce((max, midi) => Math.max(max, outside(midi, clef)), 0);\n const mean = pitches.reduce((sum, midi) => sum + outside(midi, clef), 0) / pitches.length;\n // The average never outweighs a semitone of the worst ladder; it only settles\n // bars the worst excursion calls a draw.\n return worst + mean / 100;\n}\n\n/**\n * A clef per bar — a real score changes clef, and for this music it has to.\n *\n * These channels are not instruments with a range: one voice carries the bass\n * for eight bars and then a melody three octaves up, and on one fixed clef a\n * TENTH of all the notes in the cartridge land more than an octave off the\n * staff — a ladder of ledger lines, most of it clipped by the strip's edge.\n * Chosen per bar the same figure is 1.35%, at a cost of one clef change every\n * twelve bars. What a bar costs on each clef is `clefCost`.\n *\n * A bar with nothing in it keeps the running clef rather than voting: a rest is\n * not evidence about register, and letting silence switch the clef puts the\n * change in the wrong bar.\n *\n * A bar can also change clef PART WAY THROUGH, once, where the music drops or\n * climbs into the other register. Chosen for the bar as a whole, a register\n * change inside it is paid for by every note on the wrong side of it: bar 5 of\n * Ragnarok's canyon is eleven E4s and then five E3s, and the whole bar went to\n * the bass clef — eleven heads on ledger lines to spare five. A split is taken\n * when it beats the best whole-bar clef by `CLEF_SPLIT_MARGIN`, and only from\n * the clef the bar opens in, so a bar never carries two changes.\n */\nexport function clefPlan(bars: readonly (readonly BarNote[])[], start: Clef = 'treble'): BarClef[] {\n const plan: BarClef[] = [];\n let current: Clef | null = null;\n\n for (const notes of bars) {\n if (notes.length === 0) {\n plan.push({ clef: current ?? start });\n continue;\n }\n const pitches = notes.map((note) => note.midi);\n const bass = clefCost(pitches, 'bass');\n const treble = clefCost(pitches, 'treble');\n let want: Clef = bass <= treble ? 'bass' : 'treble';\n if (current && want !== current && Math.abs(bass - treble) < CLEF_HYSTERESIS) want = current;\n\n const from = current ?? start;\n const split = bestSplit(notes, from);\n if (split && split.cost + CLEF_SPLIT_MARGIN <= clefCost(pitches, want)) {\n current = otherClef(from);\n plan.push({ clef: from, change: { tick: split.tick, clef: current } });\n } else {\n current = want;\n plan.push({ clef: want });\n }\n }\n return plan;\n}\n\n/** A note as the clef reads it: the tick of the bar it starts on, and its pitch. */\nexport interface BarNote {\n tick: number;\n midi: number;\n}\n\n/** The clef one bar opens in, and the one change inside it, if it has one. */\nexport interface BarClef {\n clef: Clef;\n /** From this tick of the bar on, the staff reads in `change.clef`. */\n change?: { tick: number; clef: Clef };\n}\n\n/** The clef a note starting on `tick` of the bar is written in. */\nexport function clefAt(bar: BarClef, tick: number): Clef {\n return bar.change && tick >= bar.change.tick ? bar.change.clef : bar.clef;\n}\n\n/** The clef a bar hands on to the next one. */\nexport function clefAfter(bar: BarClef): Clef {\n return bar.change?.clef ?? bar.clef;\n}\n\nfunction otherClef(clef: Clef): Clef {\n return clef === 'treble' ? 'bass' : 'treble';\n}\n\n/**\n * The cheapest place to leave `from` for the other clef inside a bar, and what\n * the worse half of the bar then costs.\n *\n * Only at a note: the change goes in front of the first head it is for. Never\n * at the first one — a bar that is all in the other clef changes at its bar\n * line. On a tie the LATER place wins, so the clef stands next to the notes\n * that need it rather than in front of ones that were fine either way.\n */\nfunction bestSplit(notes: readonly BarNote[], from: Clef): { tick: number; cost: number } | null {\n // Each half's `clefCost` from running totals rather than a filter per place:\n // the worst ladder and the sum of the ladders before it, and from it on.\n const ordered = [...notes].sort((a, b) => a.tick - b.tick);\n const n = ordered.length;\n const to = otherClef(from);\n const worstBefore = new Float64Array(n + 1);\n const sumBefore = new Float64Array(n + 1);\n for (let i = 0; i < n; i++) {\n const out = outside(ordered[i].midi, from);\n worstBefore[i + 1] = Math.max(worstBefore[i], out);\n sumBefore[i + 1] = sumBefore[i] + out;\n }\n const worstAfter = new Float64Array(n + 1);\n const sumAfter = new Float64Array(n + 1);\n for (let i = n - 1; i >= 0; i--) {\n const out = outside(ordered[i].midi, to);\n worstAfter[i] = Math.max(worstAfter[i + 1], out);\n sumAfter[i] = sumAfter[i + 1] + out;\n }\n let best: { tick: number; cost: number } | null = null;\n // Never at the first note: from the first head that starts later on.\n for (let at = 1; at < n; at++) {\n if (ordered[at].tick === ordered[at - 1].tick) continue;\n const cost = Math.max(\n worstBefore[at] + sumBefore[at] / at / 100,\n worstAfter[at] + sumAfter[at] / (n - at) / 100\n );\n if (!best || cost <= best.cost) best = { tick: ordered[at].tick, cost };\n }\n return best;\n}\n\n/** A pitch's distance outside its staff, in DIATONIC steps — one ledger position each. */\nfunction stepsOutside(midi: number, clef: Clef): { above: number; below: number } {\n const [low, high] = STAFF_SPAN[clef];\n const semitones = (value: number) => Math.max(0, Math.round((value * 7) / 12));\n return { above: semitones(midi - high), below: semitones(low - midi) };\n}\n\n/**\n * How far this music reaches above and below the staff, in ledger positions.\n *\n * What it is FOR: a strip has a fixed amount of room around the staff, and\n * splitting it evenly suits almost no voice. A bass line spends the whole track\n * under the staff and a lead over it — measured across the twenty tracks, only\n * a third of the voices fit an even split, while the same room divided in\n * proportion to where the notes actually go fits nearly all of them. The staff\n * is put where the music needs it rather than in the middle.\n *\n * Read over the WHOLE piece, not the bars on screen: a staff that slid up and\n * down as the melody moved would be unreadable, and would take the bar lines\n * and the pinned clef with it.\n */\nexport function staffRoom(\n bars: readonly (readonly BarNote[])[],\n clefs: readonly BarClef[]\n): { above: number; below: number } {\n let above = 0;\n let below = 0;\n bars.forEach((notes, index) => {\n const bar = clefs[index] ?? { clef: 'treble' };\n for (const { tick, midi } of notes) {\n const out = stepsOutside(midi, clefAt(bar, tick));\n above = Math.max(above, out.above);\n below = Math.max(below, out.below);\n }\n });\n return { above, below };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"notation.js","sourceRoot":"","sources":["../src/notation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,2EAA2E;AAC3E,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AACpC,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC;AACnC;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,iBAAiB,GAAG,iBAAiB,CAAC;AACnE,iDAAiD;AACjD,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,YAAoB,EAAU,EAAE,CAAC,YAAY,GAAG,iBAAiB,CAAC;AAE1F;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,YAAoB;AACpB;;;;GAIG;AACH,SAAkB;IAElB,IAAI,SAAS,EAAE,CAAC;QACd,MAAM,IAAI,GAAG,CAAC,iBAAiB,GAAG,CAAC,CAAC,GAAG,SAAS,CAAC;QACjD,IAAI,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,YAAY,GAAG,IAAI,KAAK,CAAC,EAAE,CAAC;YACxD,OAAO,EAAE,KAAK,EAAE,YAAY,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC;QACnD,CAAC;IACH,CAAC;IACD,KAAK,MAAM,SAAS,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAU,EAAE,CAAC;QACpD,MAAM,IAAI,GAAG,CAAC,iBAAiB,GAAG,CAAC,CAAC,GAAG,SAAS,CAAC;QACjD,IAAI,YAAY,GAAG,IAAI,KAAK,CAAC;YAAE,OAAO,EAAE,KAAK,EAAE,YAAY,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC;IAClF,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC;AAChD,CAAC;AA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C,KAAK,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,KAAK,EAAE,CAAC;YACnC,MAAM,GAAG,GAAG,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;YAClD,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;YACnC,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;QACrC,CAAC;IACH,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["/**\n * Ticks read as NOTATION: note values, dots, ties and bar lines.\n *\n * Nothing here quantises, because nothing has to: one tick is exactly a\n * sixty-fourth note (a sixteenth of a quarter), so every note given already\n * sits on the grid notation is written on. That is what makes music read out\n * of a game cartridge writable at all — the usual failure of notation built\n * from MIDI is a performance that lands a few milliseconds off the beat, and\n * a sound driver gives no performance, only the integers it counts. Anything\n * else has to be quantised to sixty-fourths before it comes here.\n *\n * The rules were made on Battletoads (NES), whose driver counts in exactly\n * these ticks, and checked by ear on its twenty tracks; the examples in these\n * comments are the bars that decided them.\n *\n * Durations come out as VexFlow codes (`w h q 8 16 32 64`), pitches as VexFlow\n * keys (`c#/4`) — the shortest names there are, and what a renderer reads.\n */\n\n/** Engine ticks in a quarter note. The driver's own grid, not a choice. */\nexport const TICKS_PER_QUARTER = 16;\nexport const BEATS_PER_MEASURE = 4;\n/**\n * A bar of 4/4, which is what all but one track is written in and what every\n * caller gets by default.\n *\n * Not a constant of the music: Volkmire's Inferno Race is in 2/4, and its\n * sections — the change to D major among them — start on odd multiples of half\n * a 4/4 bar, so no 64-tick bar line can hold them. So everything here takes the\n * bar length it is barring to, and `MEASURE_TICKS` is only the default.\n */\nexport const MEASURE_TICKS = TICKS_PER_QUARTER * BEATS_PER_MEASURE;\n/** Quarters in a bar of `measureTicks` ticks. */\nexport const beatsIn = (measureTicks: number): number => measureTicks / TICKS_PER_QUARTER;\n\n/**\n * A bar of so many ticks as a time signature.\n *\n * In the note value that measures it WHOLE: 64 ticks are 4/4 and 32 are 2/4,\n * but an opening bar of 38 is no number of quarters — it is 19 thirty-seconds,\n * and 19/32 is what a reader is shown.\n */\nexport function timeSignatureOf(\n measureTicks: number,\n /**\n * The note value a bar is counted in, when the reading names one: 2 writes a\n * bar of 128 ticks as 4/2 rather than 8/4. Left out — or not dividing the bar,\n * as an opening bar of its own length may not — it is chosen as below.\n */\n beatValue?: number\n): { beats: number; beatValue: number } {\n if (beatValue) {\n const beat = (TICKS_PER_QUARTER * 4) / beatValue;\n if (Number.isInteger(beat) && measureTicks % beat === 0) {\n return { beats: measureTicks / beat, beatValue };\n }\n }\n for (const beatValue of [4, 8, 16, 32, 64] as const) {\n const beat = (TICKS_PER_QUARTER * 4) / beatValue;\n if (measureTicks % beat === 0) return { beats: measureTicks / beat, beatValue };\n }\n return { beats: measureTicks, beatValue: 64 };\n}\n\n/**\n * Where the bar lines of a piece fall: every bar `measureTicks` long, except\n * the first.\n *\n * The opening bar has its own length because a pickup written as a bar of rests\n * is a lie about the music: Volkmire's Inferno Race opens with a run and a held\n * note that together are six ticks longer than two of its 2/4 bars, and a\n * reader meets that as one bar of 19/32 and then 2/4 throughout, rather than as\n * a bar of rests, a bar line through the run, and a note tied over it.\n *\n * `firstBarTicks` equal to `measureTicks` is the ordinary case, and then the\n * grid is the plain multiples every other piece uses.\n *\n * `oddBars` are bars later in the piece with a length of their own — a bar of\n * 2/4 in a piece in 4/4. Arctic Caverns has one: after six bars of 4/4 the bass\n * runs up E F# G A B C D E in 32 ticks, and everything after that run, every\n * section and the loop's end, sits half a bar past the 4/4 grid.\n */\nexport interface BarGrid {\n measureTicks: number;\n firstBarTicks: number;\n /** Bars after the first with their own length, by bar index, in order. */\n oddBars?: readonly OddBar[];\n}\n\n/** A bar after the first whose length is not the metre's — see `BarGrid`. */\nexport interface OddBar {\n /** The bar's index, from 0 — never the first bar, which has `firstBarTicks`. */\n bar: number;\n ticks: number;\n}\n\nexport const barGrid = (\n measureTicks = MEASURE_TICKS,\n firstBarTicks = measureTicks,\n oddBars: readonly OddBar[] = []\n): BarGrid => ({\n measureTicks,\n firstBarTicks,\n ...(oddBars.length ? { oddBars: [...oddBars].sort((a, b) => a.bar - b.bar) } : {}),\n});\n\nconst oddBarsOf = (grid: BarGrid): readonly OddBar[] =>\n (grid.oddBars ?? []).filter((odd) => odd.bar >= 1);\n\n/** The tick a bar begins on. */\nexport const barStartOf = (grid: BarGrid, index: number): number => {\n if (index <= 0) return 0;\n let start = grid.firstBarTicks + (index - 1) * grid.measureTicks;\n for (const odd of oddBarsOf(grid)) {\n if (odd.bar >= index) break;\n start += odd.ticks - grid.measureTicks;\n }\n return start;\n};\n\n/** How long a bar is: the first and any odd bar have their own length, the rest the metre's. */\nexport const barTicksOf = (grid: BarGrid, index: number): number =>\n index === 0\n ? grid.firstBarTicks\n : (oddBarsOf(grid).find((odd) => odd.bar === index)?.ticks ?? grid.measureTicks);\n\n/** Which bar a tick falls in. Ticks before the piece belong to its first bar. */\nexport const barAt = (grid: BarGrid, tick: number): number => {\n if (tick < grid.firstBarTicks) return 0;\n let bar = 1;\n let start = grid.firstBarTicks;\n for (const odd of oddBarsOf(grid)) {\n const oddStart = start + (odd.bar - bar) * grid.measureTicks;\n if (tick < oddStart) break;\n if (tick < oddStart + odd.ticks) return odd.bar;\n bar = odd.bar + 1;\n start = oddStart + odd.ticks;\n }\n return bar + Math.floor((tick - start) / grid.measureTicks);\n};\n\n/** How many bars a piece of `totalTicks` takes, the last one counted however little it holds. */\nexport const barCountOf = (grid: BarGrid, totalTicks: number): number =>\n totalTicks <= grid.firstBarTicks ? 1 : barAt(grid, totalTicks - 1) + 1;\n\n/** One writable note value: how long it is, what it is called, how many dots. */\nexport interface NoteValue {\n ticks: number;\n /** VexFlow duration code. */\n duration: string;\n dots: number;\n}\n\n/** Longest first — `decompose` takes the first that fits its own grid. */\nconst VALUES: readonly NoteValue[] = [\n { ticks: 64, duration: 'w', dots: 0 },\n { ticks: 56, duration: 'h', dots: 2 },\n { ticks: 48, duration: 'h', dots: 1 },\n { ticks: 32, duration: 'h', dots: 0 },\n { ticks: 28, duration: 'q', dots: 2 },\n { ticks: 24, duration: 'q', dots: 1 },\n { ticks: 16, duration: 'q', dots: 0 },\n { ticks: 14, duration: '8', dots: 2 },\n { ticks: 12, duration: '8', dots: 1 },\n { ticks: 8, duration: '8', dots: 0 },\n // Seven ticks are one head, not a dotted sixteenth tied to a sixty-fourth: Level Complete, pulse 2,\n // where the two heads stood so close the tie vanished and one B3 read as struck twice.\n { ticks: 7, duration: '16', dots: 2 },\n { ticks: 6, duration: '16', dots: 1 },\n { ticks: 4, duration: '16', dots: 0 },\n { ticks: 3, duration: '32', dots: 1 },\n { ticks: 2, duration: '32', dots: 0 },\n { ticks: 1, duration: '64', dots: 0 },\n];\n\n/** What one written head costs. Dominates everything else: a tie is the ugliest thing on a staff. */\nconst PIECE_COST = 100;\n/** A value begun off its own grid — a syncopation. Worth avoiding, never worth a tie. */\nconst OFF_GRID_COST = 10;\n/** A value that hides beat three, the middle of a 4/4 bar. The last tie-break. */\nconst HIDES_MIDDLE_COST = 1;\n\nfunction pieceCost(value: NoteValue, pos: number, measureTicks: number): number {\n // A dotted value sits on the grid of the value it dots: two thirds of its length with one dot,\n // four sevenths with two.\n const grid = (value.ticks * 2 ** value.dots) / (2 ** (value.dots + 1) - 1);\n const half = measureTicks / 2;\n const hidesMiddle = pos % measureTicks !== 0 && pos < half && pos + value.ticks > half;\n return (\n PIECE_COST + (pos % grid === 0 ? 0 : OFF_GRID_COST) + (hidesMiddle ? HIDES_MIDDLE_COST : 0)\n );\n}\n\ninterface Spelling {\n cost: number;\n pieces: NoteValue[];\n /** Heads begun off their own grid. */\n offGrid: number;\n}\n\nconst decomposeCache = new Map<number, Spelling>();\n\n/**\n * A length as a sum of writable note values, from a position in the bar.\n *\n * The FEWEST heads, and only then the tidiest. The first version was greedy and\n * took a value only when it started on its own grid, which reads well in a\n * rulebook and terribly on a staff: four ticks from the second thirty-second of\n * a beat came out as a dotted thirty-second tied to a sixty-fourth — a\n * sixteenth written as two heads, which nobody writes. Here the head count is\n * minimised outright (a sixteenth begun off the beat is a syncopation, and a\n * syncopation is one head), and starting on the grid and keeping beat three\n * visible only break ties between spellings with the same count.\n */\nexport function decompose(\n position: number,\n length: number,\n measureTicks = MEASURE_TICKS\n): NoteValue[] {\n return solve(\n ((position % measureTicks) + measureTicks) % measureTicks,\n length,\n measureTicks\n ).pieces.slice();\n}\n\nfunction solve(pos: number, left: number, measureTicks: number): Spelling {\n if (left <= 0) return { cost: 0, pieces: [], offGrid: 0 };\n const key = (measureTicks * 4096 + pos) * 4096 + left;\n const cached = decomposeCache.get(key);\n if (cached) return cached;\n\n let best: Spelling | null = null;\n // Longest first, and only a strictly cheaper spelling replaces one found\n // earlier — so among equals the long value comes first.\n for (const value of VALUES) {\n if (value.ticks > left) continue;\n const rest = solve((pos + value.ticks) % measureTicks, left - value.ticks, measureTicks);\n const own = pieceCost(value, pos, measureTicks);\n const cost = own + rest.cost;\n if (!best || cost < best.cost) {\n const offGrid = rest.offGrid + (own - PIECE_COST >= OFF_GRID_COST ? 1 : 0);\n best = { cost, pieces: [value, ...rest.pieces], offGrid };\n }\n }\n decomposeCache.set(key, best!);\n return best!;\n}\n\n/** A note of one voice, in the integers the ROM holds. */\nexport interface TickNote {\n /** Ticks from the start of the piece. */\n start: number;\n ticks: number;\n /** MIDI number. */\n midi: number;\n}\n\n/**\n * One head of a tuplet: three notes written in the time of two.\n *\n * `num` heads in the time of `occupied`, and the bracket is drawn over the run\n * from `first` to `last` — VexFlow needs the group, not the single head.\n */\nexport interface TupletSpan {\n num: number;\n occupied: number;\n first: boolean;\n last: boolean;\n}\n\n/** One head or rest on the staff — already a writable value. */\nexport interface StaffItem {\n start: number;\n ticks: number;\n /** null is a rest. */\n midi: number | null;\n duration: string;\n dots: number;\n /** Set on each head of a tuplet — see `tupletGroups`. */\n tuplet?: TupletSpan;\n /**\n * Still the same sounding note as the head before it / after it.\n *\n * A tie is the difference between one note and two, and one crossing a bar\n * line is drawn as two half curves that meet at it.\n */\n tieStart: boolean;\n tieStop: boolean;\n}\n\nexport interface StaffMeasure {\n /** Bar number from the start of the piece, counting from 0. */\n index: number;\n /** Tick the bar starts on. */\n start: number;\n items: StaffItem[];\n}\n\n/**\n * A voice's notes as a continuous ribbon: rests where it is silent, cut at\n * every bar line, and every piece already a writable value.\n *\n * Monophonic by construction — the driver walks one stream per channel — so an\n * overlap can only mean the previous note is still counted as sounding, and the\n * cursor simply moves on rather than stacking a chord that the hardware cannot\n * play.\n */\n/**\n * The divisions a tuplet may fill: a written value, so the bracket spans\n * something a reader can name. Three heads in the time of two.\n */\nconst TUPLET_TOTALS = [8, 16, 32, 64];\n\n/** One head of a tuplet, with the value it is written as. */\ninterface TupletHead {\n span: TupletSpan;\n value: NoteValue;\n}\n\n/**\n * Where the music divides a written value into THREE.\n *\n * One tick is a sixty-fourth, so a third of anything is not a whole number and\n * the driver cannot hold a true triplet: it writes the nearest integers it can,\n * and the give-away is a run of three that sums to a written value and divides\n * as evenly as integers allow without dividing evenly. A quarter triplet is\n * 10+11+11 of the half's 32 ticks; a sixteenth triplet is 2+3+3 of the\n * eighth's 8. Spelt by `decompose` instead, each of those becomes two heads\n * under a tie, and a bar of them is unreadable — which is how this was found.\n *\n * The rule is deliberately narrow, and it is checked against the ROM rather\n * than reasoned about: over all twenty tracks it fires exactly twice — title\n * music's bar 39, where pulse 1, pulse 2, the triangle and the drums all take\n * it together, and Clinger Winger's drums, once a bar for five bars. Nothing\n * else in the cartridge matches, so nothing else is re-spelt.\n *\n * Even thirds are NOT tuplets: three heads of the same written value need no\n * bracket, and the ROM has none inside these totals anyway.\n */\nexport function tupletGroups(\n notes: readonly TickNote[],\n grid: BarGrid = barGrid()\n): Map<number, TupletHead> {\n const out = new Map<number, TupletHead>();\n for (let at = 0; at + 2 < notes.length; at++) {\n const run = notes.slice(at, at + 3);\n const ticks = run[0].ticks + run[1].ticks + run[2].ticks;\n if (!TUPLET_TOTALS.includes(ticks)) continue;\n // Adjacent, and inside one bar: a bracket cannot cross a bar line.\n if (\n run.some(\n (note, index) => index > 0 && run[index - 1].start + run[index - 1].ticks !== note.start\n )\n )\n continue;\n const bar = barAt(grid, run[0].start);\n const inBar = run[0].start - barStartOf(grid, bar);\n if (inBar > barTicksOf(grid, bar) - ticks) continue;\n // On its own division from the bar line, so the bracket is the beam group: an eighth's triplet\n // on an eighth, anything a beat or longer on a beat. Read from wherever three notes happen to\n // sum right, brackets began mid-group and ran across the beat (Terminator 2, Level 5).\n if (inBar % Math.min(ticks, TICKS_PER_QUARTER) !== 0) continue;\n const lengths = run.map((note) => note.ticks);\n if (Math.max(...lengths) - Math.min(...lengths) > 1) continue;\n if (lengths.some((length) => length * 3 === ticks)) continue;\n // Three in the time of two, so each head is written as half the division.\n const value = VALUES.find((candidate) => candidate.ticks === ticks / 2 && candidate.dots === 0);\n if (!value) continue;\n run.forEach((_, index) =>\n out.set(at + index, {\n value,\n span: { num: 3, occupied: 2, first: index === 0, last: index === 2 },\n })\n );\n at += 2;\n }\n return out;\n}\n\n/**\n * Spans an exact tuplet may fill, in ticks, in the order they are tried: the beat first, then\n * shorter, then longer. A bracket over a beat reads better than two over its halves — unless one\n * half needs none (`plainHalf`).\n */\nconst TUPLET_SPANS = [16, 8, 4, 32, 64];\n/** How many notes a tuplet may divide its span into — every count that is not a power of two. */\nconst TUPLET_COUNTS = [3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15];\n/**\n * Each count with the parts its step may be split into: whole steps for every count first, then\n * halves, then quarters — Alien 3 opens a 9:8 of thirty-seconds with four sixty-fourths. A grid\n * that whole steps of some count already write is read as that count: six sixteenths in a quarter\n * are a sextuplet, not a triplet of eighths split in two.\n */\nconst TUPLET_GRIDS: readonly (readonly [number, number])[] = [1, 2, 4].flatMap((split) =>\n TUPLET_COUNTS.map((num) => [num, split] as const)\n);\n/** How close a start must be to a tuplet's grid, in ticks, to stand on it. */\nconst ON_GRID = 1e-6;\n\n/** The notes a tuplet of `num` is written in the time of: the largest power of two below it. */\nexport const tupletOccupied = (num: number): number => 2 ** Math.floor(Math.log2(num - 1e-9));\n\n/** One exact tuplet run: notes `from`..`to` (exclusive) of the ordered list, and its items. */\ninterface TupletRun {\n to: number;\n start: number;\n span: number;\n items: StaffItem[];\n}\n\nconst near = (value: number) => Math.abs(value - Math.round(value)) < ON_GRID;\n\n/**\n * Tuplets of any count, read from notes whose starts and ends divide a written value exactly.\n *\n * A sound driver counts whole ticks, and its triplets are 10 + 11 + 11 (`tupletGroups`). Music from\n * anywhere else can say what it means: five notes from 0 to 16, each 3.2 ticks — a quintuplet of\n * sixteenths in a quarter. A run is read as a tuplet of `num` in the time of `tupletOccupied(num)`\n * when every start and end in it falls on its grid of `span / num`, the run fills `span` from a\n * point that span may start on, and at least one of its edges is off the grid of whole ticks — so a\n * line of ordinary values is never re-read. Inside, notes may be any whole number of the grid's\n * steps — a quarter and an eighth in an eighth triplet — or of a half or a quarter of a step, and\n * the steps no note takes are rests.\n *\n * Whole-tick music never has one: no span here divides by three, five or seven into whole ticks.\n */\nfunction exactTuplets(notes: readonly TickNote[], grid: BarGrid): Map<number, TupletRun> {\n const runs = new Map<number, TupletRun>();\n for (let from = 0; from < notes.length; from++) {\n const begin = notes[from].start;\n const bar = barAt(grid, begin + ON_GRID);\n const barStart = barStartOf(grid, bar);\n const barEnd = barStart + barTicksOf(grid, bar);\n let found: TupletRun | null = null;\n for (const span of TUPLET_SPANS) {\n if (found) break;\n // On the grid the span itself keeps — a beat for anything a beat or longer.\n const step = Math.min(span, TICKS_PER_QUARTER);\n for (let start = Math.floor((begin - barStart) / step) * step + barStart; start <= begin + ON_GRID && !found; start += step) {\n if (start + span > barEnd + ON_GRID) break;\n for (const [num, split] of TUPLET_GRIDS) {\n const cells = num * split;\n const unit = span / cells;\n const run: TickNote[] = [];\n for (let j = from; j < notes.length && notes[j].start < start + span - ON_GRID; j++) run.push(notes[j]);\n if (!run.length || Math.abs(run[0].start - begin) > ON_GRID) continue;\n // An earlier note that reaches into the span leaves it no clean start.\n if (from > 0 && notes[from - 1].start + notes[from - 1].ticks > start + ON_GRID) continue;\n const steps = run.map((note) => [(note.start - start) / unit, (note.start + note.ticks - start) / unit]);\n if (!steps.every(([a, b]) => near(a) && near(b) && b <= cells + ON_GRID && a >= -ON_GRID)) continue;\n const edges = run.flatMap((note) => [note.start, note.start + note.ticks]);\n if (edges.every((edge) => near(edge))) continue;\n // A half of the span that ordinary values write on their own wants a shorter bracket: a\n // sixteenth triplet and an eighth are a triplet over the first half, not a sextuplet.\n const plainHalf = (lo: number, hi: number) =>\n run\n .filter((note) => note.start < hi - ON_GRID && note.start + note.ticks > lo + ON_GRID)\n .every(\n (note) =>\n note.start >= lo - ON_GRID &&\n note.start + note.ticks <= hi + ON_GRID &&\n near(note.start) &&\n near(note.start + note.ticks)\n );\n if (span > 4 && (plainHalf(start, start + span / 2) || plainHalf(start + span / 2, start + span))) continue;\n // The pieces: notes and the steps between them, each a value one head writes.\n const occupied = tupletOccupied(num);\n const written = span / occupied / split;\n const pieces: { from: number; length: number; midi: number | null; at?: number }[] = [];\n let at = 0;\n for (let k = 0; k < run.length; k++) {\n const a = Math.round(steps[k][0]);\n const b = Math.round(steps[k][1]);\n if (a < at) break;\n if (a > at) pieces.push({ from: at, length: a - at, midi: null });\n pieces.push({ from: a, length: b - a, midi: run[k].midi, at: run[k].start });\n at = b;\n }\n if (at < cells) pieces.push({ from: at, length: cells - at, midi: null });\n const values = pieces.map((piece) =>\n VALUES.find((value) => Math.abs(value.ticks - piece.length * written) < ON_GRID)\n );\n if (pieces.reduce((sum, piece) => sum + piece.length, 0) !== cells || values.some((value) => !value)) continue;\n // Each piece from where it starts — a note's own start, so its marks find it — to the next.\n const starts = pieces.map((piece, index) =>\n piece.at !== undefined ? piece.at : index === 0 ? start : start + Math.round(piece.from * unit * 1e9) / 1e9\n );\n const items = pieces.map((piece, index): StaffItem => {\n const pieceStart = starts[index];\n const pieceEnd = index + 1 < pieces.length ? starts[index + 1] : start + span;\n return {\n start: pieceStart,\n ticks: pieceEnd - pieceStart,\n midi: piece.midi,\n duration: values[index]!.duration,\n dots: values[index]!.dots,\n tieStart: false,\n tieStop: false,\n tuplet: { num, occupied, first: index === 0, last: index === pieces.length - 1 },\n };\n });\n found = { to: from + run.length, start, span, items };\n break;\n }\n }\n }\n if (found) {\n runs.set(from, found);\n from = found.to - 1;\n }\n }\n return runs;\n}\n\n/**\n * The exact tuplets, a run on the same grid that carries on to the beat read as one: two\n * sixteenth triplets that fill a quarter are a sextuplet, as a reader writes six in a beat. Not\n * past the beat — twelve in a half is four triplets.\n */\nfunction exactTupletsByBeat(notes: readonly TickNote[], grid: BarGrid): Map<number, TupletRun> {\n const runs = exactTuplets(notes, grid);\n const merged = new Map<number, TupletRun>();\n const ordered = [...runs.entries()].sort((a, b) => a[0] - b[0]);\n for (let i = 0; i < ordered.length; i++) {\n const [from, run] = ordered[i];\n const next = ordered[i + 1];\n const num = run.items[0].tuplet!.num;\n const double = num * 2;\n if (\n next &&\n run.span * 2 <= TICKS_PER_QUARTER &&\n (run.start - barStartOf(grid, barAt(grid, run.start + ON_GRID))) % (run.span * 2) === 0 &&\n TUPLET_COUNTS.includes(double) &&\n next[0] === run.to &&\n Math.abs(next[1].start - (run.start + run.span)) < ON_GRID &&\n next[1].span === run.span &&\n next[1].items[0].tuplet!.num === num\n ) {\n const items = [...run.items, ...next[1].items].map((item, index, all) => ({\n ...item,\n tuplet: { num: double, occupied: tupletOccupied(double), first: index === 0, last: index === all.length - 1 },\n }));\n // The written value stays: the bracket counts the same steps, twice as many of them.\n merged.set(from, { to: next[1].to, start: run.start, span: run.span * 2, items });\n i++;\n continue;\n }\n merged.set(from, run);\n }\n return merged;\n}\n\nexport function staffItems(\n notes: readonly TickNote[],\n totalTicks: number,\n grid: BarGrid = barGrid()\n): StaffItem[] {\n const items: StaffItem[] = [];\n const ordered = [...notes].sort((a, b) => a.start - b.start);\n let cursor = 0;\n\n const push = (start: number, length: number, midi: number | null) => {\n // Off the tick grid and in no tuplet — a run that does not fill its bracket: the nearest ticks.\n let position = Math.round(start);\n let left = Math.round(start + length) - position;\n let first = true;\n while (left > 0) {\n const bar = barAt(grid, position);\n const barStart = barStartOf(grid, bar);\n const barTicks = barTicksOf(grid, bar);\n const chunk = Math.min(left, barStart + barTicks - position);\n const carriesOn = chunk < left;\n\n const pieces = decompose(position - barStart, chunk, barTicks);\n let at = position;\n pieces.forEach((piece, index) => {\n items.push({\n start: at,\n ticks: piece.ticks,\n midi,\n duration: piece.duration,\n dots: piece.dots,\n // A head is tied to the one before it when it is a continuation:\n // of an earlier bar's remainder, or of the piece beside it.\n tieStop: midi !== null && (!first || index > 0),\n tieStart: midi !== null && (carriesOn || index < pieces.length - 1),\n });\n at += piece.ticks;\n });\n\n position += chunk;\n left -= chunk;\n first = false;\n }\n };\n\n const tuplets = tupletGroups(ordered, grid);\n // Exact tuplets only where some note is off the whole-tick grid: whole-tick music has none.\n const exact = ordered.some((note) => !Number.isInteger(note.start) || !Number.isInteger(note.ticks))\n ? exactTupletsByBeat(ordered, grid)\n : null;\n let skipTo = -1;\n\n ordered.forEach((note, index) => {\n if (index < skipTo) return;\n const run = exact?.get(index);\n if (run) {\n if (run.start > cursor) push(cursor, run.start - cursor, null);\n items.push(...run.items);\n cursor = run.start + run.span;\n skipTo = run.to;\n return;\n }\n if (note.start > cursor) push(cursor, note.start - cursor, null);\n cursor = Math.max(cursor, note.start);\n\n const length = Math.min(note.ticks, Math.max(0, totalTicks - cursor));\n if (length <= 0) return;\n\n // A tuplet head is written whole, at the value the bracket says: its ticks\n // are not a written value and `decompose` would tie it into scraps.\n const head = tuplets.get(index);\n if (head) {\n items.push({\n start: cursor,\n ticks: length,\n midi: note.midi,\n duration: head.value.duration,\n dots: 0,\n tieStart: false,\n tieStop: false,\n tuplet: head.span,\n });\n cursor += length;\n return;\n }\n\n push(cursor, length, note.midi);\n cursor += length;\n });\n\n if (cursor < totalTicks) push(cursor, totalTicks - cursor, null);\n return items;\n}\n\n/**\n * The ribbon cut into bars, each one filled to the bar line.\n *\n * A bar short of its four beats is not a bar — a formatter given one spaces it\n * as though the missing time did not exist, and the staff stops lining up with\n * the music beside it — so whatever is left at the end is padded with rests.\n */\nexport function staffMeasures(\n items: readonly StaffItem[],\n totalTicks: number,\n grid: BarGrid = barGrid()\n): StaffMeasure[] {\n const count = Math.max(1, barCountOf(grid, totalTicks));\n const measures: StaffMeasure[] = [];\n // `staffItems` hands the ribbon over in order, and then each bar is the next\n // run of it: one walk instead of a filter over the whole piece per bar.\n let sorted = true;\n for (let at = 1; at < items.length && sorted; at++)\n sorted = items[at - 1].start <= items[at].start;\n let next = 0;\n\n for (let index = 0; index < count; index++) {\n const start = barStartOf(grid, index);\n const barTicks = barTicksOf(grid, index);\n let inBar: StaffItem[];\n if (sorted) {\n while (next < items.length && items[next].start < start) next++;\n inBar = [];\n while (next < items.length && items[next].start < start + barTicks) inBar.push(items[next++]);\n } else {\n inBar = items.filter((item) => item.start >= start && item.start < start + barTicks);\n }\n const filled = inBar.reduce((sum, item) => sum + item.ticks, 0);\n\n // Filled to within a hair is full: a tuplet's steps are sums of fractions.\n if (barTicks - filled > ON_GRID) {\n // The rests the ribbon already ends on join the padding, and the whole gap is written anew:\n // Ice Climber's Pause stops a tick after its last written head, and the tick to the end of\n // the track and the tick on to the beat came out as two 64th rests instead of one 32nd.\n let from = filled;\n while (inBar.length) {\n const last = inBar[inBar.length - 1];\n if (last.midi !== null || last.tuplet || !Number.isInteger(last.start)) break;\n inBar.pop();\n from -= last.ticks;\n }\n let at = start + from;\n for (const piece of decompose(from, barTicks - from, barTicks)) {\n inBar.push({\n start: at,\n ticks: piece.ticks,\n midi: null,\n duration: piece.duration,\n dots: piece.dots,\n tieStart: false,\n tieStop: false,\n });\n at += piece.ticks;\n }\n }\n\n measures.push({ index, start, items: inBar });\n }\n return measures;\n}\n\nconst STEPS = ['c', 'c', 'd', 'd', 'e', 'f', 'f', 'g', 'g', 'a', 'a', 'b'];\nconst FLAT_STEPS = ['c', 'd', 'd', 'e', 'e', 'f', 'g', 'g', 'a', 'a', 'b', 'b'];\nconst BLACK = [false, true, false, true, false, false, true, false, true, false, true, false];\n/** The white keys with a flat spelling — B as C-flat, E as F-flat — by pitch class. */\nconst WHITE_FLATS: Readonly<Record<number, string>> = { 4: 'f', 11: 'c' };\n\n/**\n * A MIDI number as a VexFlow key — `c#/4` for 61, `db/4` in a key that flats D.\n *\n * A black key is spelt the way the KEY SIGNATURE has it when the signature\n * alters either of its letters, and as a sharp otherwise. A flat key spelt in\n * sharps prints D-sharp against a signature that flattens E — a sign on nearly\n * every note — which is what rat race looked like before flats could be written.\n * Spelling EVERY black key flat in a flat key was the next mistake: Volkmire's\n * Inferno, in E-flat, climbs F to F-sharp, and printing that as G-flat put a\n * flat on a note a reader took for a B-flat already in the key.\n *\n * Two white keys have a flat spelling of their own: B is C-flat and E is F-flat. They take it only\n * in a key that flattens that letter — six flats for C-flat. Rat race is in E-flat minor, whose\n * sixth degree is C-flat; written as B it printed a natural against the B-flat of the signature.\n */\nexport function staffKey(midi: number, key?: KeySignature): string {\n const index = ((midi % 12) + 12) % 12;\n const octave = Math.floor(midi / 12) - 1;\n const flatWhite = WHITE_FLATS[index];\n if (flatWhite && key?.accidental === 'b' && key.letters.includes(flatWhite)) {\n // C-flat sits in the octave above its B: C-flat 4 is B3.\n return `${flatWhite}b/${index === 11 ? octave + 1 : octave}`;\n }\n if (!BLACK[index]) return `${STEPS[index]}/${octave}`;\n const flat =\n (key?.accidental === 'b' && key.letters.includes(FLAT_STEPS[index])) ||\n (key?.spelt?.includes(FLAT_STEPS[index]) ?? false);\n return flat ? `${FLAT_STEPS[index]}b/${octave}` : `${STEPS[index]}#/${octave}`;\n}\n\n/** Letters by diatonic step, and the steps an interval of n semitones spans when spelt plainly. */\nconst LETTER_STEP: Readonly<Record<string, number>> = { c: 0, d: 1, e: 2, f: 3, g: 4, a: 5, b: 6 };\nconst PLAIN_STEPS = [0, 1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6];\n\n/** The other spelling of a black key: `c#/4` ↔ `db/4`. Null for a white key. */\nfunction otherSpelling(midi: number, spelt: string): string | null {\n const index = ((midi % 12) + 12) % 12;\n if (!BLACK[index]) return null;\n const octave = Math.floor(midi / 12) - 1;\n return spelt.includes('#') ? `${FLAT_STEPS[index]}b/${octave}` : `${STEPS[index]}#/${octave}`;\n}\n\n/** Diatonic position of a VexFlow key: letter step plus seven a an octave. */\nconst stepOf = (key: string) => {\n const [name, octave] = key.split('/');\n return LETTER_STEP[name[0]] + 7 * Number(octave);\n};\n\n/**\n * The heads of a chord as VexFlow keys, each black key spelt so the chord reads as intervals do.\n *\n * `staffKey` spells one note against the key, and for a line that is right: Volkmire's Inferno, in\n * E-flat, climbs F to F-sharp. A chord is read the other way — by the intervals between its heads.\n * Paganini's Caprice 17, in E-flat, strikes E-flat with G-flat: written E-flat and F-sharp, that is\n * an augmented second where a minor third sounds. So for the black keys of a chord both spellings\n * are tried, and the one whose intervals span the letters their size asks for wins — a third across\n * three letters, a second across two; where the intervals cannot tell, `staffKey` decides. In the\n * order given.\n */\nexport function chordKeys(midis: readonly number[], key?: KeySignature): string[] {\n const plain = midis.map((midi) => staffKey(midi, key));\n const choices = midis.map((midi, i) => {\n const other = otherSpelling(midi, plain[i]);\n return other ? [plain[i], other] : [plain[i]];\n });\n const cost = (keys: readonly string[]) => {\n let wrong = 0;\n for (let i = 0; i < keys.length; i++) {\n for (let j = i + 1; j < keys.length; j++) {\n const [lo, hi] = midis[i] <= midis[j] ? [i, j] : [j, i];\n const semitones = midis[hi] - midis[lo];\n const steps = stepOf(keys[hi]) - stepOf(keys[lo]);\n const expected = PLAIN_STEPS[semitones % 12] + 7 * Math.floor(semitones / 12);\n if (steps !== expected) wrong++;\n }\n }\n return wrong;\n };\n let best = plain;\n let bestCost = cost(plain);\n const walk = (at: number, picked: string[]) => {\n if (at === choices.length) {\n const c = cost(picked);\n if (c < bestCost) {\n bestCost = c;\n best = picked.slice();\n }\n return;\n }\n for (const option of choices[at]) walk(at + 1, [...picked, option]);\n };\n if (choices.some((options) => options.length > 1)) walk(0, []);\n return best;\n}\n\n/** What a key signature does: which letters it alters, and which way. */\nexport interface KeySignature {\n /** `#` for a sharp key, `b` for a flat one. C has neither and no letters. */\n accidental: '#' | 'b';\n letters: readonly string[];\n /** Letters whose black key is written flat although the key leaves the letter alone — see `keyOf`. */\n spelt?: readonly string[];\n}\n\nconst SHARP_ORDER = ['f', 'c', 'g', 'd', 'a', 'e', 'b'];\nconst FLAT_ORDER = ['b', 'e', 'a', 'd', 'g', 'c', 'f'];\n/** Signed number of sharps (+) or flats (−) by VexFlow major key name. */\nconst KEY_ALTERATIONS: Readonly<Record<string, number>> = {\n C: 0,\n G: 1,\n D: 2,\n A: 3,\n E: 4,\n B: 5,\n 'F#': 6,\n 'C#': 7,\n F: -1,\n Bb: -2,\n Eb: -3,\n Ab: -4,\n Db: -5,\n Gb: -6,\n Cb: -7,\n};\n\n/**\n * A key signature by its VexFlow name (`G` one sharp, `Eb` three flats).\n * A name it does not know is C — written with every sign at its note rather\n * than guessed at.\n */\nexport function keyOf(name?: string): KeySignature {\n const [signature, ...flats] = (name ?? '').split('+');\n const count = signature ? (KEY_ALTERATIONS[signature] ?? 0) : 0;\n const key: KeySignature =\n count < 0\n ? { accidental: 'b', letters: FLAT_ORDER.slice(0, -count) }\n : { accidental: '#', letters: SHARP_ORDER.slice(0, count) };\n return flats.length ? { ...key, spelt: flats.map((flat) => flat[0].toLowerCase()) } : key;\n}\n\n/**\n * The signature part of a key name, the one VexFlow is given — `F` of `F+Db+Ab`.\n *\n * What follows a `+` is spelling, not signature: black keys to write as those flats although the\n * key does not flatten their letters. Turbo tunnel, in D minor with one flat, falls D, D-flat, C in\n * the bass; the rule for black keys wrote the middle chord as C-sharp and G-sharp.\n */\nexport const signatureName = (name?: string): string | undefined => name?.split('+')[0];\n\n/**\n * Treble or bass for a voice, from where it actually sits.\n *\n * The median rather than the mean: one low pickup note must not drag a melody\n * onto ledger lines below the bass staff. The boundary is middle C's octave —\n * a voice whose middle is below A3 spends more of its time under the treble\n * staff than in it.\n */\nexport function chooseClef(notes: readonly { midi: number }[]): 'treble' | 'bass' {\n if (notes.length === 0) return 'treble';\n const pitches = notes.map((note) => note.midi).sort((a, b) => a - b);\n const median = pitches[Math.floor(pitches.length / 2)];\n return median < 57 ? 'bass' : 'treble';\n}\n\n/**\n * How hard a voice is to read from a given bar line: its heads, plus one for\n * every head that starts off its own grid.\n *\n * The measureTicks `voicePhase` minimises. A run of ticks written as\n * one note on the beat costs 1. The syncopation counts as much as a tie, and\n * that is deliberate: `decompose` writes an off-beat run as ONE head, so by\n * heads alone every bar line would look equally good, and the search would\n * happily put the whole piece a sixteenth off the beat.\n */\nexport function notationCost(\n notes: readonly TickNote[],\n offset: number,\n measureTicks = MEASURE_TICKS\n): number {\n let pieces = 0;\n for (const note of notes) {\n // A tuplet's note is off the tick grid, and counts at the whole ticks nearest it: left out,\n // a voice of Alien 3's 9:8 figures was read from its few plain notes, which said 3 ticks late.\n const start = Math.round(note.start);\n // + 2 bars so a shift past the first note still lands on a positive tick.\n // Measured on the plain grid: what it weighs is the phase of a voice\n // against the beat, which the opening bar's own length does not change.\n let position = start - offset + measureTicks * 2;\n let left = Math.max(1, Math.round(note.start + note.ticks) - start);\n while (left > 0) {\n const inBar = position % measureTicks;\n const chunk = Math.min(left, measureTicks - inBar);\n pieces += spellingCost(inBar, chunk, measureTicks);\n position += chunk;\n left -= chunk;\n }\n }\n return pieces;\n}\n\n/**\n * `solve`'s heads plus off-grid heads for a run inside one bar, from a flat\n * table per bar length. `voicePhase` asks this for every piece of every note,\n * four times over, and a `Map` keyed by a number past 2^31 is the slow part of\n * that — so whole-tick runs are looked up by index instead.\n */\nconst costTables = new Map<number, Int32Array>();\n\nfunction spellingCost(inBar: number, chunk: number, measureTicks: number): number {\n if (\n !Number.isInteger(measureTicks) ||\n !Number.isInteger(inBar) ||\n !Number.isInteger(chunk) ||\n inBar < 0\n ) {\n const spelling = solve(inBar, chunk, measureTicks);\n return spelling.pieces.length + spelling.offGrid;\n }\n let table = costTables.get(measureTicks);\n if (!table) {\n table = new Int32Array(measureTicks * (measureTicks + 1));\n costTables.set(measureTicks, table);\n }\n const index = inBar * (measureTicks + 1) + chunk;\n let cost = table[index];\n if (cost === 0) {\n const spelling = solve(inBar, chunk, measureTicks);\n // Stored one up, so 0 can mean \"not worked out yet\".\n cost = spelling.pieces.length + spelling.offGrid + 1;\n table[index] = cost;\n }\n return cost - 1;\n}\n\n/**\n * How many ticks one channel is written behind the beat. Never more than\n * `MAX_PHASE`.\n *\n * The delay is AUTHORED, not the driver's. Nearly every track opens a channel\n * or two with an explicit `$80` rest one sixty-fourth long, and Intruder\n * Excluder puts a three-tick rest ahead of pulse 2's copy of pulse 1's bass\n * line — a two-tick echo, some 60ms, and audible as one. (An earlier version of\n * this comment called it the cost of setup commands; the stream dump says\n * otherwise.)\n *\n * On a staff, though, it is the difference between a quarter note and a chain\n * of tied scraps, so the notes are written on the beat and the delay is\n * STATED: a staff should label every voice it moved, and not move its playhead.\n * Longer echoes (Surf City's six ticks) are past `MAX_PHASE` and are written as\n * they sound.\n */\nexport const MAX_PHASE = 3;\n\nexport function voicePhase(\n notes: readonly TickNote[],\n offset: number,\n measureTicks = MEASURE_TICKS\n): number {\n // A voice a reading has already put into tuplets stands where it is meant to: its heads are\n // fractions of a beat counted from the bar line, and a phase of whole ticks only knocks them off\n // that grid. Terminator 2's Level 5 moved pulse 1 three ticks and printed its sextuplets as dotted\n // thirty-seconds, while pulse 2, playing the same rhythm, kept its 6:4.\n if (notes.some((note) => !Number.isInteger(note.start) || !Number.isInteger(note.ticks))) return 0;\n let best = 0;\n let bestCost = Infinity;\n for (let phase = 0; phase <= MAX_PHASE; phase++) {\n const cost = notationCost(notes, offset + phase, measureTicks);\n if (cost < bestCost) {\n bestCost = cost;\n best = phase;\n }\n }\n return best;\n}\n\n/**\n * A voice moved `by` ticks along the staff's clock, cut at tick 0.\n *\n * Taking a channel's delay out can carry its first sliver before the music\n * starts: ragnarok's canyon opens the noise channel with a one-tick hit on\n * tick 0 and then plays everything a tick late. Refusing the phase for the sake\n * of that sliver — which is what a guard in `voicePhase` once did — left every\n * drum on an odd tick, and each of those gave the formatter a column of\n * its own: a gap between the first two sixteenths of pulse 1 in every bar. So\n * the phase is taken, and what lands before tick 0 is cut off there.\n */\nexport function shiftNotes<T extends TickNote>(notes: readonly T[], by: number): T[] {\n const out: T[] = [];\n for (const note of notes) {\n const start = note.start + by;\n const ticks = start < 0 ? note.ticks + start : note.ticks;\n if (ticks > 0) out.push({ ...note, start: Math.max(0, start), ticks });\n }\n return out;\n}\n\n/*\n * Where the bar line falls: at the track's FIRST TICK. There is no search.\n *\n * There used to be — a search tried all 64 bar lines and kept the one that\n * wrote the music with the fewest heads, on the reasoning a transcriber uses by\n * ear. It is blind to exactly the mistake that matters: this music repeats in\n * whole-bar patterns on a sixteenth grid, so a bar line an eighth or two off\n * writes it with almost the same number of heads. Ragnarok's canyon came out at\n * 17 (1060 heads) against 1 (1064), and every bar of the score opened two\n * eighths early — heard wrong at once, while the numbers called it a win. Nine\n * of the twenty tracks were moved off tick 0 that way, most by a margin under a\n * percent.\n *\n * Tick 0 is what the evidence says instead: every channel of a track starts\n * there, the repeat points sit on ticks 1..4 in most tracks, and the MusicXML\n * export has always barred from tick 0, and the two agree. A channel's own authored delay (at most `MAX_PHASE` ticks) is still\n * taken out per voice by `voicePhase`.\n */\n\n/**\n * Ticks to ADD to a piece's own clock to get the staff's, for a bar line\n * `offset` ticks in.\n *\n * Less than a bar, so a piece barred off its first tick gets a pickup bar\n * rather than notes before tick zero — and nothing at all for offset 0, which\n * is what every track uses: an empty bar in front of the music says the music\n * starts a bar late.\n */\nexport function staffShift(offset: number, measureTicks = MEASURE_TICKS): number {\n return (measureTicks - (offset % measureTicks)) % measureTicks;\n}\n\n/**\n * The three readings of a pickup — the notes before a piece's first bar line:\n *\n * - `anacrusis`, the default and the way music is written: the opening bar is the pickup alone, as\n * short as it is, under the metre's own time signature — no rests in front, no signature of its\n * own. A piece that opens with one ends with the bar's complement (`buildScore`), so the two make\n * one whole bar between them. Circus Charlie's Aerial Bar: two eighths, then 6/8.\n * - `merged`: the OPENING BAR is longer by the pickup and nothing moves — the run and the note it\n * lands on are one bar of 19/32, and the metre takes over after it. It reads better whenever the\n * pickup is not a whole phrase: a bar line through the middle of a run is worse than an irregular\n * first bar.\n * - `padded`: a whole bar of the metre, rests in front of the pickup, the music starting part way\n * into bar one. What every pickup was before `anacrusis`, kept for scores checked that way.\n *\n * `true` and `false` are the old flag: `merged` and `anacrusis`.\n */\nexport type Pickup = 'anacrusis' | 'merged' | 'padded';\n\n/** A pickup reading given as the old boolean flag or by name — see `Pickup`. */\nexport const pickupOf = (pickup: boolean | Pickup | undefined): Pickup =>\n pickup === true ? 'merged' : pickup === false || pickup === undefined ? 'anacrusis' : pickup;\n\n/**\n * How a piece is barred: where its bar lines fall, and what its notes are moved\n * by to sit behind them — see `Pickup` for the three readings of a pickup.\n */\nexport function barring(\n offset: number,\n measureTicks = MEASURE_TICKS,\n reading: boolean | Pickup = 'anacrusis',\n /** Bars later in the piece with a length of their own — see `BarGrid`. */\n oddBars: readonly OddBar[] = []\n): { grid: BarGrid; shift: number } {\n const pickup = ((offset % measureTicks) + measureTicks) % measureTicks;\n switch (pickupOf(reading)) {\n case 'merged':\n return { grid: barGrid(measureTicks, measureTicks + pickup, oddBars), shift: 0 };\n case 'anacrusis':\n if (pickup > 0) return { grid: barGrid(measureTicks, pickup, oddBars), shift: 0 };\n // falls through: no pickup, nothing to read\n case 'padded':\n return { grid: barGrid(measureTicks, measureTicks, oddBars), shift: staffShift(offset, measureTicks) };\n }\n}\n\nexport type Clef = 'treble' | 'bass';\n\n/**\n * The outer LINES of each staff, as MIDI numbers: E4..F5 and G2..A3.\n *\n * Not the centres — what matters for room is where the ledger lines start.\n */\nexport const STAFF_SPAN: Record<Clef, readonly [number, number]> = {\n treble: [64, 77],\n bass: [43, 57],\n};\n\n/**\n * The pitch each staff is centred on: B4 on the treble, D3 on the bass. Kept\n * for callers that want the middle line; the clef is not chosen by it.\n */\nexport const CLEF_CENTRE: Record<Clef, number> = { treble: 71, bass: 50 };\n\n/**\n * How much better the other clef has to be before a bar switches, in semitones\n * of the ladder it saves.\n *\n * Without it a line hovering between the two staves changes clef every other\n * bar, which is unreadable in a way that ledger lines are not.\n */\nexport const CLEF_HYSTERESIS = 3;\n\n/**\n * How much better a clef change PART WAY through a bar has to be than the best\n * clef for the whole bar, in semitones of the ladder it saves.\n *\n * Higher than `CLEF_HYSTERESIS`, because a change inside a bar is louder. At 3,\n * a line that crosses between the staves on every beat changed clef inside\n * bar after bar — Ragnarok's canyon went treble, bass, treble, bass through\n * bars 5 to 9 — for ladders that were only a few rungs shorter. Measured over\n * the twenty tracks' voices: at 3, 92 changes inside bars; at 6, the bar that\n * drops an octave still splits and the see-saw is gone.\n */\nexport const CLEF_SPLIT_MARGIN = 6;\n\n/**\n * What a bar costs on one clef: the TALLEST ladder of ledger lines in it, with\n * the average as a tie-break.\n *\n * The tallest, not the average, and that is the whole rule. Averaging is what a\n * first version did, and it reads the bar as a crowd: a bar of eight low notes\n * and two very high ones votes for the low clef, and the two high notes then\n * get a fourteen-rung ladder that runs off the top of the strip. What decides\n * whether a bar can be READ is its worst excursion — one note an octave out is\n * two ledger lines and fine, one note two octaves out is unreadable however\n * many of its neighbours sit comfortably.\n *\n * Measured over the twenty tracks, choosing by the worst excursion instead of\n * the average halves the bars carrying a ladder over 18 semitones (37 → 17) and\n * takes fewer clef changes to do it (129 → 112).\n */\n/** How far a pitch sits off a staff, in semitones: 0 on it. */\nfunction outside(midi: number, clef: Clef): number {\n const [low, high] = STAFF_SPAN[clef];\n return Math.max(0, midi - high, low - midi);\n}\n\nfunction clefCost(pitches: readonly number[], clef: Clef): number {\n const worst = pitches.reduce((max, midi) => Math.max(max, outside(midi, clef)), 0);\n const mean = pitches.reduce((sum, midi) => sum + outside(midi, clef), 0) / pitches.length;\n // The average never outweighs a semitone of the worst ladder; it only settles\n // bars the worst excursion calls a draw.\n return worst + mean / 100;\n}\n\n/**\n * A clef per bar — a real score changes clef, and for this music it has to.\n *\n * These channels are not instruments with a range: one voice carries the bass\n * for eight bars and then a melody three octaves up, and on one fixed clef a\n * TENTH of all the notes in the cartridge land more than an octave off the\n * staff — a ladder of ledger lines, most of it clipped by the strip's edge.\n * Chosen per bar the same figure is 1.35%, at a cost of one clef change every\n * twelve bars. What a bar costs on each clef is `clefCost`.\n *\n * A bar with nothing in it keeps the running clef rather than voting: a rest is\n * not evidence about register, and letting silence switch the clef puts the\n * change in the wrong bar.\n *\n * A bar can also change clef PART WAY THROUGH, once, where the music drops or\n * climbs into the other register. Chosen for the bar as a whole, a register\n * change inside it is paid for by every note on the wrong side of it: bar 5 of\n * Ragnarok's canyon is eleven E4s and then five E3s, and the whole bar went to\n * the bass clef — eleven heads on ledger lines to spare five. A split is taken\n * when it beats the best whole-bar clef by `CLEF_SPLIT_MARGIN`, and only from\n * the clef the bar opens in, so a bar never carries two changes.\n */\nexport function clefPlan(bars: readonly (readonly BarNote[])[], start: Clef = 'treble'): BarClef[] {\n const plan: BarClef[] = [];\n let current: Clef | null = null;\n\n for (const notes of bars) {\n if (notes.length === 0) {\n plan.push({ clef: current ?? start });\n continue;\n }\n const pitches = notes.map((note) => note.midi);\n const bass = clefCost(pitches, 'bass');\n const treble = clefCost(pitches, 'treble');\n let want: Clef = bass <= treble ? 'bass' : 'treble';\n if (current && want !== current && Math.abs(bass - treble) < CLEF_HYSTERESIS) want = current;\n\n const from = current ?? start;\n const split = bestSplit(notes, from);\n if (split && split.cost + CLEF_SPLIT_MARGIN <= clefCost(pitches, want)) {\n current = otherClef(from);\n plan.push({ clef: from, change: { tick: split.tick, clef: current } });\n } else {\n current = want;\n plan.push({ clef: want });\n }\n }\n return plan;\n}\n\n/** A note as the clef reads it: the tick of the bar it starts on, and its pitch. */\nexport interface BarNote {\n tick: number;\n midi: number;\n}\n\n/** The clef one bar opens in, and the one change inside it, if it has one. */\nexport interface BarClef {\n clef: Clef;\n /** From this tick of the bar on, the staff reads in `change.clef`. */\n change?: { tick: number; clef: Clef };\n}\n\n/** The clef a note starting on `tick` of the bar is written in. */\nexport function clefAt(bar: BarClef, tick: number): Clef {\n return bar.change && tick >= bar.change.tick ? bar.change.clef : bar.clef;\n}\n\n/** The clef a bar hands on to the next one. */\nexport function clefAfter(bar: BarClef): Clef {\n return bar.change?.clef ?? bar.clef;\n}\n\nfunction otherClef(clef: Clef): Clef {\n return clef === 'treble' ? 'bass' : 'treble';\n}\n\n/**\n * The cheapest place to leave `from` for the other clef inside a bar, and what\n * the worse half of the bar then costs.\n *\n * Only at a note: the change goes in front of the first head it is for. Never\n * at the first one — a bar that is all in the other clef changes at its bar\n * line. On a tie the LATER place wins, so the clef stands next to the notes\n * that need it rather than in front of ones that were fine either way.\n */\nfunction bestSplit(notes: readonly BarNote[], from: Clef): { tick: number; cost: number } | null {\n // Each half's `clefCost` from running totals rather than a filter per place:\n // the worst ladder and the sum of the ladders before it, and from it on.\n const ordered = [...notes].sort((a, b) => a.tick - b.tick);\n const n = ordered.length;\n const to = otherClef(from);\n const worstBefore = new Float64Array(n + 1);\n const sumBefore = new Float64Array(n + 1);\n for (let i = 0; i < n; i++) {\n const out = outside(ordered[i].midi, from);\n worstBefore[i + 1] = Math.max(worstBefore[i], out);\n sumBefore[i + 1] = sumBefore[i] + out;\n }\n const worstAfter = new Float64Array(n + 1);\n const sumAfter = new Float64Array(n + 1);\n for (let i = n - 1; i >= 0; i--) {\n const out = outside(ordered[i].midi, to);\n worstAfter[i] = Math.max(worstAfter[i + 1], out);\n sumAfter[i] = sumAfter[i + 1] + out;\n }\n let best: { tick: number; cost: number } | null = null;\n // Never at the first note: from the first head that starts later on.\n for (let at = 1; at < n; at++) {\n if (ordered[at].tick === ordered[at - 1].tick) continue;\n const cost = Math.max(\n worstBefore[at] + sumBefore[at] / at / 100,\n worstAfter[at] + sumAfter[at] / (n - at) / 100\n );\n if (!best || cost <= best.cost) best = { tick: ordered[at].tick, cost };\n }\n return best;\n}\n\n/** A pitch's distance outside its staff, in DIATONIC steps — one ledger position each. */\nfunction stepsOutside(midi: number, clef: Clef): { above: number; below: number } {\n const [low, high] = STAFF_SPAN[clef];\n const semitones = (value: number) => Math.max(0, Math.round((value * 7) / 12));\n return { above: semitones(midi - high), below: semitones(low - midi) };\n}\n\n/**\n * How far this music reaches above and below the staff, in ledger positions.\n *\n * What it is FOR: a strip has a fixed amount of room around the staff, and\n * splitting it evenly suits almost no voice. A bass line spends the whole track\n * under the staff and a lead over it — measured across the twenty tracks, only\n * a third of the voices fit an even split, while the same room divided in\n * proportion to where the notes actually go fits nearly all of them. The staff\n * is put where the music needs it rather than in the middle.\n *\n * Read over the WHOLE piece, not the bars on screen: a staff that slid up and\n * down as the melody moved would be unreadable, and would take the bar lines\n * and the pinned clef with it.\n */\nexport function staffRoom(\n bars: readonly (readonly BarNote[])[],\n clefs: readonly BarClef[]\n): { above: number; below: number } {\n let above = 0;\n let below = 0;\n bars.forEach((notes, index) => {\n const bar = clefs[index] ?? { clef: 'treble' };\n for (const { tick, midi } of notes) {\n const out = stepsOutside(midi, clefAt(bar, tick));\n above = Math.max(above, out.above);\n below = Math.max(below, out.below);\n }\n });\n return { above, below };\n}\n"]}
|
package/dist/score.d.ts
CHANGED
|
@@ -374,7 +374,11 @@ export declare const CROSS_BAR_RUN = 4;
|
|
|
374
374
|
* heads it reaches on the other side.
|
|
375
375
|
*/
|
|
376
376
|
export declare function crossBarRuns(notes: readonly ScoreNote[], grid: BarGrid, accents?: ReadonlySet<number>): Map<number, 'start' | 'join'>;
|
|
377
|
-
/**
|
|
377
|
+
/**
|
|
378
|
+
* Whether an effect is drawn along its note — and so has to carry on where the note does. Every
|
|
379
|
+
* vibrato is: its curve, or its wave, which ran out at the end of a line and was not taken up again
|
|
380
|
+
* on the next one (Shikinjou's Title, triangle, a D held over the line's end).
|
|
381
|
+
*/
|
|
378
382
|
export declare function drawnAlong(effect: PitchEffect, measureTicks?: number): boolean;
|
|
379
383
|
/** A noise hit: when, for how long, and which `$400E` period. */
|
|
380
384
|
export interface ScoreHit {
|
package/dist/score.js
CHANGED
|
@@ -686,11 +686,15 @@ export function crossBarRuns(notes, grid, accents = accentedStarts(notes)) {
|
|
|
686
686
|
});
|
|
687
687
|
return runs;
|
|
688
688
|
}
|
|
689
|
-
/**
|
|
689
|
+
/**
|
|
690
|
+
* Whether an effect is drawn along its note — and so has to carry on where the note does. Every
|
|
691
|
+
* vibrato is: its curve, or its wave, which ran out at the end of a line and was not taken up again
|
|
692
|
+
* on the next one (Shikinjou's Title, triangle, a D held over the line's end).
|
|
693
|
+
*/
|
|
690
694
|
export function drawnAlong(effect, measureTicks = MEASURE_TICKS) {
|
|
691
695
|
return (effect.kind === 'slide' ||
|
|
692
696
|
(effect.kind === 'bend' && effect.ticks >= measureTicks) ||
|
|
693
|
-
|
|
697
|
+
effect.kind === 'vibrato');
|
|
694
698
|
}
|
|
695
699
|
/**
|
|
696
700
|
* Puts what each note carries on its HEAD — the first piece of it, never a
|
package/dist/score.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"score.js","sourceRoot":"","sources":["../src/score.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,KAAK,EACL,UAAU,EACV,OAAO,EACP,UAAU,EACV,UAAU,EACV,OAAO,EACP,QAAQ,EAER,UAAU,EACV,UAAU,EACV,UAAU,EACV,aAAa,EACb,UAAU,GAKX,MAAM,eAAe,CAAC;AAEvB;;;GAGG;AACH,MAAM,CAAC,MAAM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AAI,CAAC;YACT,CAAC,CAAE,EAAE,GAAG,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,EAAgB;YACxE,CAAC,CAAC,IAAI,CAAC,OAAO;gBACZ,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE;gBAC1D,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,CACnC,CACF,EACD,EAAE,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CACnC,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;IAChE,CAAC;IAED,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;AAC7D,CAAC","sourcesContent":["/**\n * A track as a SCORE: each pitched channel on a grand staff, the noise channel\n * on a percussion staff, and the dynamics its volumes imply.\n *\n * Built on `./notation`, so a bar here is spelled exactly the way a single\n * scrolling staff spells it — same bar line, same phase, same\n * note values. What this file adds is the part a page of music needs and a\n * single strip does not: which of two staves a note goes on, and what the\n * volume column says in the words a player reads.\n */\n\nimport {\n MEASURE_TICKS,\n TICKS_PER_QUARTER,\n barAt,\n barCountOf,\n barGrid,\n barStartOf,\n barTicksOf,\n barring,\n pickupOf,\n type Pickup,\n chooseClef,\n shiftNotes,\n staffItems,\n staffMeasures,\n voicePhase,\n type BarGrid,\n type OddBar,\n type StaffItem,\n type TickNote,\n} from './notation.js';\n\n/**\n * Middle C: in a beam group kept on the bass, the heads from here up still go\n * onto the treble and the beam crosses to them — see `crossStaffVoice`.\n */\nexport const GRAND_STAFF_SPLIT = 60;\n\nexport function splitGrandStaff<T extends { midi: number }>(\n notes: readonly T[],\n split = GRAND_STAFF_SPLIT\n): { treble: T[]; bass: T[] } {\n const treble: T[] = [];\n const bass: T[] = [];\n for (const note of notes) (note.midi >= split ? treble : bass).push(note);\n return { treble, bass };\n}\n\n/** A beam group that never goes below E3 — three ledger lines under the treble — is written on the treble. */\nexport const TREBLE_FLOOR = 52;\n\n/** Durations beamed together, one group per beat — `beamsFor`'s set. */\nconst BEAMED = new Set(['8', '16', '32', '64']);\n\n/**\n * A grand-staff part as ONE voice, each item saying which of the two staves it\n * stands on.\n *\n * Decided per BEAM GROUP — the beamed notes of one beat, or a note on its own —\n * because a beam is what a reader follows:\n *\n * - a group that never goes below E3 (`TREBLE_FLOOR`) is on the treble, E3\n * included. Ragnarok's canyon, pulse 1, bar 29, the third beat: A3 G3 C4 A3\n * E4 C4 G4 E4 — a reader wanted it all on the treble.\n * - a group that does go below E3 stays on the bass, E3s and all — bar 29's\n * second beat, E3 G3 C3 E3…, which \"would be ugly otherwise\". Only its heads\n * from middle C up cross to the treble, and the beam crosses with them — the\n * piano's cross-staff writing, drawn as one beam between the\n * staves with no rest on either side. Bar 30's lone G5 among B2s is that case.\n *\n * Every rule tried per BAR before this failed on a bar of this music: a bar\n * that starts low and climbs three octaves has a bass half and a treble half,\n * and the only choices a whole bar has are to tear its beams with rests or put\n * half of it on four ledger lines.\n *\n * A piece tied on from the head before it stays where that head stood; a rest\n * stands where the head before it in the bar did (else the first head after\n * it), and a bar with no heads at all is the treble's, so the bass shows its\n * own bar rest rather than a second one.\n */\nexport function crossStaffVoice(bars: readonly (readonly ScoreItem[])[]): ScoreItem[][] {\n let carried: 'treble' | 'bass' = 'treble';\n /*\n * A head whose beam runs on into the next bar (`crossBarRuns`) belongs to the group on the OTHER\n * side of the bar line, not to the beat it sits in — so it is written after that group has\n * chosen, and put on the same staff. Ragnarok's canyon, bar 25: the last E3 ends a beat of G4s\n * and went to the treble with them, while the D3 E3 it is beamed to are on the bass, and the\n * beam fell across the whole grand staff.\n */\n let hanging: ScoreItem[] | null = null;\n const written = bars.map((items) => {\n /*\n * The beat a head stands on, counted from ITS OWN bar line — the bar's\n * first item, since a bar is filled from its line. Counted with `%` off the\n * piece's clock instead, as this once was, it is right only while every bar\n * is the same length and the first starts on tick 0: Volkmire's Inferno\n * Race, barred from tick 6 with an opening bar of 19/32, had the two halves\n * of one arpeggio sorted into each other's beats, and the run came out torn\n * between the staves.\n */\n const barStart = items[0]?.start ?? 0;\n const groups = new Map<string, number[]>();\n items.forEach((item, index) => {\n if (item.midi === null) return;\n const key = BEAMED.has(item.duration)\n ? `beat${Math.floor((item.start - barStart) / TICKS_PER_QUARTER)}`\n : `note${index}`;\n groups.set(key, [...(groups.get(key) ?? []), index]);\n });\n\n const chosen: ('treble' | 'bass')[] = items.map(() => 'treble');\n for (const members of groups.values()) {\n const low = Math.min(...members.map((index) => items[index].midi as number));\n for (const index of members) {\n const midi = items[index].midi as number;\n chosen[index] = low >= TREBLE_FLOOR || midi >= GRAND_STAFF_SPLIT ? 'treble' : 'bass';\n }\n }\n\n let previous = carried;\n const heads = items.map((item, index) => {\n if (item.midi === null) return item;\n const staff = item.tieStop ? previous : chosen[index];\n previous = staff;\n return { ...item, staff };\n });\n carried = previous;\n\n const firstHead = heads.find((item) => item.midi !== null)?.staff ?? 'treble';\n let before: 'treble' | 'bass' | undefined;\n const bar = heads.map((item) => {\n if (item.midi !== null) {\n before = item.staff;\n return item;\n }\n return { ...item, staff: before ?? firstHead };\n });\n\n const reached = bar.find((item) => item.across === 'join');\n if (hanging && reached) {\n for (const item of hanging) item.staff = reached.staff;\n carried = reached.staff ?? carried;\n }\n hanging = bar.filter((item) => item.across === 'start');\n return bar;\n });\n return written;\n}\n\n/** The highest a part may reach and still be written on the bass staff alone: E4, two ledger lines up. */\nexport const BASS_ONLY_MAX = 64;\n/** The lowest a part may reach and still be written on the treble staff alone: G3, two ledger lines down. */\nexport const TREBLE_ONLY_MIN = 55;\n\n/**\n * The staves a part needs: one when every note it plays sits within two ledger\n * lines of a single staff, both otherwise.\n *\n * A grand staff whose other half is a whole track of rests is furniture: the\n * triangle carries the bass in every one of the twenty tracks, and in\n * Ragnarok's canyon it reaches D#4 at most — a ledger line and a half above the\n * bass staff. Where both single staves would do, the part's middle decides.\n */\nexport function partStaves(notes: readonly { midi: number }[]): ('treble' | 'bass')[] {\n if (notes.length === 0) return ['treble'];\n let low = Infinity;\n let high = -Infinity;\n for (const note of notes) {\n low = Math.min(low, note.midi);\n high = Math.max(high, note.midi);\n }\n const bass = high <= BASS_ONLY_MAX;\n const treble = low >= TREBLE_ONLY_MIN;\n if (bass && treble) return [chooseClef(notes)];\n if (bass) return ['bass'];\n if (treble) return ['treble'];\n return ['treble', 'bass'];\n}\n\nexport type Dynamic = 'pp' | 'p' | 'mp' | 'mf' | 'f' | 'ff';\nconst DYNAMICS: readonly Dynamic[] = ['pp', 'p', 'mp', 'mf', 'f', 'ff'];\n\n/**\n * The APU's 0..15 volume in six steps.\n *\n * A READING, not a fact: the nibble is linear in output level and a dynamic is\n * a word about loudness, so the steps are even in the nibble and nothing more\n * is claimed for them.\n */\nexport function dynamicOf(volume: number): Dynamic {\n const level = Math.max(0, Math.min(15, Math.round(volume)));\n return DYNAMICS[Math.min(DYNAMICS.length - 1, Math.floor((level * DYNAMICS.length) / 16))];\n}\n\n/** A change of level closer than this, in ticks, is folded into the mark before it. A quarter note. */\nexport const DYNAMIC_HOLD = 16;\n\n/** The words a mark can carry after its level: a figure's shape, or \"the same again\". */\nexport type DynamicWords = 'dim.' | 'cresc.' | 'sim.';\n\nexport interface DynamicMark {\n tick: number;\n dynamic: Dynamic;\n /**\n * How the figure goes from here: `dim.` and `cresc.` are a hairpin after the\n * level, `sim.` is the word alone — the level is the figure's own — with a\n * dashed line for as long as it holds.\n */\n words?: DynamicWords;\n /** With `words`: the tick of the last note the hairpin or the `sim.` covers. */\n until?: number; /**\n * A hairpin from a level the reader is already at: the hairpin alone, no\n * letter — ragnarok's 7 7 4 2, an mp going on from the mp before it.\n */\n bare?: boolean;\n}\n\n/** Onset to onset, notes closer than this can make one shaped figure. An eighth note. */\nexport const FIGURE_GAP = 8;\n\n/**\n * And no closer than this, a sixteenth. Faster is one note's envelope struck\n * again and again — Arctic Caverns' 8 4 2 1 in thirty-seconds on one pitch, an\n * echo — not a figure a player shapes.\n */\nexport const FIGURE_STEP = 4;\n\n/** A run of notes whose level only falls, or only rises: `[from, to]` are indices, inclusive. */\nexport interface ShapedFigure {\n from: number;\n to: number;\n words: 'dim.' | 'cresc.';\n}\n\n/**\n * Runs of at least three notes, each `FIGURE_STEP` to `FIGURE_GAP` after the one before, whose\n * level moves one way every step and by two or more in all — the 4 3 2 1 under\n * every beat of a fading figure. The six steps of `dynamicOf` cannot show that:\n * 4 and 3 are both p, and the hold folds the pp of 2 and 1 back into it.\n *\n * `notes` must be in order of start.\n */\nexport function shapedFigures(\n notes: readonly { start: number; volume: number }[],\n gap = FIGURE_GAP\n): ShapedFigure[] {\n const figures: ShapedFigure[] = [];\n let from = 0;\n while (from < notes.length - 2) {\n const step = Math.sign(notes[from + 1].volume - notes[from].volume);\n let to = from;\n while (\n step !== 0 &&\n to + 1 < notes.length &&\n notes[to + 1].start - notes[to].start <= gap &&\n notes[to + 1].start - notes[to].start >= FIGURE_STEP &&\n Math.sign(notes[to + 1].volume - notes[to].volume) === step\n ) {\n to++;\n }\n if (to - from >= 2 && Math.abs(notes[to].volume - notes[from].volume) >= 2) {\n figures.push({ from, to, words: step < 0 ? 'dim.' : 'cresc.' });\n from = to + 1;\n } else {\n from++;\n }\n }\n return figures;\n}\n\n/**\n * Two figures `sim.` can stand for: the same levels in the same rhythm. Only\n * that — ragnarok's 7 4 2 1 followed by a 7 4 2 is a figure of its own, with a\n * hairpin of its own.\n */\nfunction sameFigure(\n notes: readonly { start: number; volume: number }[],\n a: ShapedFigure,\n b: ShapedFigure\n): boolean {\n if (a.to - a.from !== b.to - b.from) return false;\n for (let i = 0; i <= a.to - a.from; i++) {\n if (notes[a.from + i].volume !== notes[b.from + i].volume) return false;\n if (\n i > 0 &&\n notes[a.from + i].start - notes[a.from + i - 1].start !==\n notes[b.from + i].start - notes[b.from + i - 1].start\n ) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Where a voice's level changes, as the marks a score prints.\n *\n * Only at a change, and never two within `DYNAMIC_HOLD`: the driver can move a\n * volume on every note, and a mark under every head is noise. Inside the hold\n * the LOUDER level stands — the accent is what a reader has to see — and a\n * change that comes straight back to the level before it is dropped.\n *\n * A shaped figure (`shapedFigures`) is written as its level and a hairpin under\n * the first, `sim.` under the next one just like it, its dashes running on over\n * the ones after that, until some other mark is printed. A figure that turns straight\n * into one going the other way — wookie hole's 6 4 2 1 2 4 6 8 on one held\n * note — is a level swaying, not a figure, and is read note by note as before.\n * After a hairpin the reader is where it ends, so going back to where it began\n * is written — ragnarok's mp over the 7 after 7 4 2 1 — unless a `sim.` that\n * goes on already says the figure comes round again.\n */\nexport function dynamicMarks(\n notes: readonly { start: number; volume: number }[],\n hold = DYNAMIC_HOLD\n): DynamicMark[] {\n const sorted = [...notes].sort((a, b) => a.start - b.start);\n const found = shapedFigures(sorted);\n const swaying = (a: ShapedFigure | undefined, b: ShapedFigure | undefined) =>\n !!a && !!b && b.from === a.to + 1 && a.words !== b.words;\n const figureAt = new Map<number, ShapedFigure>();\n found.forEach((figure, i) => {\n if (!swaying(found[i - 1], figure) && !swaying(figure, found[i + 1])) {\n figureAt.set(figure.from, figure);\n }\n });\n\n const marks: DynamicMark[] = [];\n // The level the reader is at.\n let heard: Dynamic | null = null;\n // The figure the last words were about, and whether its `sim.` has been printed.\n let stated: ShapedFigure | null = null;\n let similar = false;\n // A plain mark breaks a run of `sim.`; taken back, it gives the run back.\n const broken = new Map<DynamicMark, { stated: ShapedFigure | null; similar: boolean }>();\n const pop = () => {\n const mark = marks.pop()!;\n const run = broken.get(mark);\n if (run) ({ stated, similar } = run);\n };\n /**\n * The next figure after note `i` is one more like `like`, and nothing between says otherwise —\n * Intruder Excluder's 6 6 before each 6 4 2 1 is the same figure coming round, not news.\n */\n const starts = [...figureAt.keys()].sort((a, b) => a - b);\n const simGoesOn = (i: number, like: ShapedFigure) => {\n const next = starts.find((start) => start > i);\n if (next === undefined || !sameFigure(sorted, like, figureAt.get(next)!)) return false;\n const level = dynamicOf(sorted[i].volume);\n for (let k = i + 1; k < next; k++) if (dynamicOf(sorted[k].volume) !== level) return false;\n return true;\n };\n for (let i = 0; i < sorted.length; i++) {\n const note = sorted[i];\n const dynamic = dynamicOf(note.volume);\n const figure = figureAt.get(i);\n const last = marks[marks.length - 1];\n if (figure) {\n // `p`, and a beat later `mp` and a hairpin: the figure's mark says it, as the louder.\n // At the same level the mark stays and the hairpin goes on from it, bare.\n if (\n last &&\n !last.words &&\n note.start - last.tick < hold &&\n DYNAMICS.indexOf(last.dynamic) < DYNAMICS.indexOf(dynamic)\n ) {\n pop();\n // Its level is now the figure's to state.\n heard = marks[marks.length - 1]?.dynamic ?? null;\n }\n const until = sorted[figure.to].start;\n if (stated && sameFigure(sorted, stated, figure)) {\n if (similar) marks[marks.length - 1].until = until;\n else marks.push({ tick: note.start, dynamic, words: 'sim.', until });\n similar = true;\n } else {\n const mark: DynamicMark = { tick: note.start, dynamic, words: figure.words, until };\n if (heard === dynamic) mark.bare = true;\n marks.push(mark);\n stated = figure;\n similar = false;\n }\n // The hairpin has taken the reader down (or up) to where the figure ends.\n heard = dynamicOf(sorted[figure.to].volume);\n i = figure.to;\n continue;\n }\n if (heard === dynamic) continue;\n // Back at the level of a run of `sim.` that goes on: the `sim.` says so already.\n if (stated && dynamic === dynamicOf(sorted[stated.from].volume) && simGoesOn(i, stated)) {\n heard = dynamic;\n continue;\n }\n heard = dynamic;\n if (last && !last.words && note.start - last.tick < hold) {\n if (DYNAMICS.indexOf(dynamic) > DYNAMICS.indexOf(last.dynamic)) last.dynamic = dynamic;\n if (marks[marks.length - 2]?.dynamic === last.dynamic) pop();\n heard = marks[marks.length - 1].dynamic;\n continue;\n }\n const mark: DynamicMark = { tick: note.start, dynamic };\n broken.set(mark, { stated, similar });\n stated = null;\n marks.push(mark);\n }\n return marks;\n}\n\n/**\n * Where each NES noise period (`$400E`, 0..15) sits on the percussion staff:\n * high noise at the top and low noise at the bottom.\n */\nconst NOISE_LINES = [\n 'g/5',\n 'g/5',\n 'g/5',\n 'f/5',\n 'f/5',\n 'e/5',\n 'e/5',\n 'd/5',\n 'd/5',\n 'c/5',\n 'b/4',\n 'a/4',\n 'g/4',\n 'f/4',\n 'e/4',\n 'e/4',\n];\n\n/**\n * The notehead: a cross for a closed or pedal hat, a circled cross for an open\n * one, a plain head for everything with a skin. The pieces are the ones\n * `@xromdev/drumroll` draws on its kit (`NOISE_DRUM_KINDS`).\n */\nconst NOISE_HEADS = ['x', 'x', 'x', 'x', 'cx', 'cx', '', '', '', '', '', '', '', '', '', ''];\n\n/** A noise period as a VexFlow key on the percussion staff. Only the low nibble is the period. */\nexport function noiseKey(period: number): string {\n const index = period & 0x0f;\n return NOISE_HEADS[index] ? `${NOISE_LINES[index]}/${NOISE_HEADS[index]}` : NOISE_LINES[index];\n}\n\n/** A pitched note, with the volume it starts at when the channel has one. */\nexport interface ScoreNote extends TickNote {\n volume?: number;\n /** The note's pitch curve — `[position 0..1, semitones]` — as a piano roll draws it. */\n bend?: readonly (readonly [number, number])[];\n /** Grace notes in front of it, as MIDI numbers in the order they are played. */\n grace?: readonly number[];\n /** A repeat of the note before, quieter — an echo, written in brackets (`echoNotes`). */\n echo?: boolean;\n /**\n * Played short: its `ticks` are the value it is WRITTEN as, and it sounds for\n * less — a staccato dot over the head instead of a rest after it.\n */\n staccato?: boolean;\n}\n\n/** What a pitch curve is written as. `ticks` is the whole note's length, over which it moves. */\nexport type PitchEffect =\n | {\n kind: 'slide';\n /** Where it arrives, in semitones from the written pitch; to a tenth. */\n semitones: number;\n /** Where along the note the movement begins, 0..1. */\n from: number;\n ticks: number;\n /**\n * It lands on the next written note. When it does not — a sweep too wide to be a bend that\n * ends on no note (ragnarok's canyon, triangle, bar 15: E3 down to B2, then a D3) — the\n * staff draws where it lands as a small note in brackets. Set by `effectsOf`.\n */\n arrives?: boolean;\n }\n | {\n /** The pitch moves on the note it started on — a guitarist's bend, or its release downwards. */\n kind: 'bend';\n semitones: number;\n from: number;\n ticks: number;\n }\n | {\n kind: 'vibrato';\n depth: number;\n ticks: number;\n /**\n * The curve itself, `[position 0..1, semitones]`, kept for a vibrato wider than a semitone:\n * a wave glyph says nothing of a swing like Turbo Tunnel Race's, bar 31, a D6 going up four\n * semitones and down two and a half, so the staff draws the curve itself.\n */\n curve?: readonly (readonly [number, number])[];\n };\n\n/** A vibrato swinging further than this, in semitones, is drawn as its curve rather than a wave. */\nexport const WIDE_VIBRATO = 1;\n\n/**\n * A movement smaller than this, in semitones, is not written at all.\n *\n * 261 of the cartridge's 304 curves are a drift of a fifth of a semitone at the\n * end of a note. The roll draws them as a hairline, which is right for a picture\n * of the sound; on a staff a mark on every one of them would be noise over a\n * third of the notes of some tracks.\n */\nexport const DRIFT_LIMIT = 0.5;\n/** Changes of direction that make a curve a vibrato rather than a slide. */\nconst VIBRATO_TURNS = 3;\n/** A swing back smaller than this, in semitones, is the curve's own jitter, not a change of direction. */\nconst TURN_MIN = 0.25;\n/** The shallowest vibrato written, in semitones either way: Surf City's is a tenth. */\nconst LIGHT_VIBRATO = 0.09;\n\n/**\n * How many times a curve really changes direction.\n *\n * Counted with hysteresis: a move only turns once the curve has come back\n * `TURN_MIN` from the furthest point it reached. Counting every sign change of\n * the slope read ragnarok's canyon's triangle, bar 15 — a flicker of 0.05\n * semitones and then a steady fall of five to a B — as a vibrato, and it was\n * drawn as a wave where a reader sees a glissando.\n */\nfunction turnsOf(values: readonly number[], turnMin = TURN_MIN): number {\n let turns = 0;\n let direction = 0;\n let pivot = values[0] ?? 0;\n for (const value of values) {\n const move = value - pivot;\n if (direction === 0) {\n if (Math.abs(move) >= turnMin) {\n direction = Math.sign(move);\n pivot = value;\n }\n } else if (Math.sign(move) === direction) {\n pivot = value;\n } else if (Math.abs(move) >= turnMin) {\n turns++;\n direction = -direction;\n pivot = value;\n }\n }\n return turns;\n}\n\n/**\n * A note's pitch curve read as notation: a slide to where it arrives, a\n * vibrato, or nothing.\n *\n * Over the twenty tracks that is 33 slides (one to four semitones), 10 vibratos,\n * and the drifts left out — the same split the Battletoads music tooling\n * makes between a slide and a vibrato.\n */\n/** How far into a note a strike may reach and still be read as its attack, 0..1. */\n/**\n * Alien 3's kick takes three frames of a seventeen-frame bass note — 18% — and at 15% the\n * vibrato after it was still read with the kick in it.\n */\nexport const STRIKE_SHARE = 0.25;\n\n/**\n * The curve without the strike it opens with, if it opens with one: a pitch\n * away from the note at its first point that comes back to it within\n * `STRIKE_SHARE` of the note. That is how a sound driver hits a note — a\n * triangle bass kicked from an octave up, a frame of a deep thump — and it is\n * timbre, not a movement of the pitch: Alien 3's vibrato on a long G3 read six\n * semitones deep with the kick in front of it, and was drawn as a curve.\n */\nfunction withoutStrike(\n curve: readonly (readonly [number, number])[]\n): readonly (readonly [number, number])[] {\n if (Math.abs(curve[0][1]) < DRIFT_LIMIT) return curve;\n const back = curve.findIndex(([, semitones]) => Math.abs(semitones) < 0.05);\n if (back <= 0 || curve[back][0] > STRIKE_SHARE) return curve;\n return curve.slice(back);\n}\n\nexport function pitchEffect(\n whole: readonly (readonly [number, number])[],\n ticks: number\n): PitchEffect | null {\n const curve = whole.length >= 2 ? withoutStrike(whole) : whole;\n if (curve.length < 2) return null;\n const values = curve.map(([, semitones]) => semitones);\n const peak = Math.max(...values.map(Math.abs));\n if (peak < DRIFT_LIMIT) {\n /*\n * Under half a semitone a curve is not written — unless it SWINGS. Surf City wobbles a tenth of\n * a semitone and Intermission a sixth, both audible; wookie hole's\n * and ragnarok's marks, which a looser rule also calls vibrato, are one-way drifts at the end\n * of a two-tick note and stay unwritten. Turns tell the two apart, counted against the curve's\n * OWN depth: a fixed grain either misses a tenth-of-a-semitone swing or counts a drift's jitter.\n */\n return peak >= LIGHT_VIBRATO && turnsOf(values, peak / 2) >= VIBRATO_TURNS\n ? { kind: 'vibrato', depth: peak, ticks }\n : null;\n }\n\n if (turnsOf(values) >= VIBRATO_TURNS) {\n const depth = Math.max(...values.map(Math.abs));\n return depth > WIDE_VIBRATO\n ? { kind: 'vibrato', depth, ticks, curve }\n : { kind: 'vibrato', depth, ticks };\n }\n\n const end = values[values.length - 1];\n if (Math.abs(end) < DRIFT_LIMIT) return null;\n const moving = values.findIndex((semitones) => Math.abs(semitones) >= 0.1);\n const from = curve[Math.max(0, moving - 1)][0];\n return { kind: 'slide', semitones: Math.round(end * 10) / 10, from, ticks };\n}\n\n/** The most a note's pitch may move on its own and still be a bend: a tone and a half. */\nexport const BEND_MAX = 3;\n/** Ticks between a slide's end and the next note that still count as the slide arriving in it. */\nconst GLISS_GAP = 1;\n\n/**\n * Each note's effect, read against the note AFTER it in the part.\n *\n * A curve does not say whether the pitch is sliding somewhere or bending on the\n * spot; the music around it does. A slide that ends on the pitch the very next\n * note is written at arrives in that note — a glissando, as in the title music's\n * G4 up to A4. One that goes nowhere written is the note itself bending:\n * ragnarok's canyon, pulse 1, bar 5, a D#4 pulled up 1.3 semitones and then left\n * for an A3 — a guitarist's bend, which a reader said at once, where \"gliss.\" had\n * been printed. Past `BEND_MAX` nothing bends that far, and the sweeps of fifteen\n * to twenty-eight semitones that open a few tracks stay lines.\n *\n * Except when the note after it comes straight back to the pitch the curve left:\n * that is a bend and its release, however far it went. Clinger Winger, pulse 1,\n * an E2 pushed up six and a half semitones over four bars and then struck again\n * as E2 — a reader heard a bend where a line marked \"gliss.\" had been drawn.\n * Across the whole ROM this reads that one note differently and no other.\n */\nexport function effectsOf(notes: readonly ScoreNote[]): Map<number, PitchEffect> {\n const ordered = [...notes].sort((a, b) => a.start - b.start);\n const effects = new Map<number, PitchEffect>();\n ordered.forEach((note, index) => {\n const effect = note.bend ? pitchEffect(note.bend, note.ticks) : null;\n if (!effect) return;\n if (effect.kind === 'slide') {\n const next = ordered[index + 1];\n const follows = next !== undefined && next.start - (note.start + note.ticks) <= GLISS_GAP;\n const arrives = follows && Math.abs(next.midi - (note.midi + effect.semitones)) <= 0.5;\n const returns = follows && next.midi === note.midi;\n if (!arrives && (returns || Math.abs(effect.semitones) <= BEND_MAX)) {\n effects.set(note.start, { ...effect, kind: 'bend' });\n return;\n }\n effects.set(note.start, { ...effect, arrives });\n return;\n }\n effects.set(note.start, effect);\n });\n return effects;\n}\n\n/**\n * A bend's size, in semitones, to one decimal — the arrow says which way.\n *\n * Always the number. The guitar's words (½ for a semitone, \"full\" for a tone)\n * were printed for sizes near a step and the number for the rest, so one page\n * said \"½\" over a bend of 0.9 semitones and \"1.3\" over the next: two systems\n * side by side, and a \"½\" read as half a semitone.\n */\nexport function bendLabel(semitones: number): string {\n return Math.abs(semitones).toFixed(1);\n}\n\n/** The pitch movement a tied piece carries on from the head of its note. */\nexport interface EffectCarry {\n /** Where the note starts, and the pitch it is written at. */\n start: number;\n midi: number;\n effect: PitchEffect;\n}\n\n/** A staff item, with the pitch effect of the note it is the head of. */\nexport type ScoreItem = StaffItem & {\n effect?: PitchEffect;\n /**\n * On a piece tied on after the head: the movement it is part of, when that movement is drawn\n * along the note — a glissando or a bend held a bar or more — so a line that runs onto the next\n * system can be carried on there and land where the note ends.\n */\n carry?: EffectCarry;\n /** On a grand staff's voice: the stave the item stands on — see `crossStaffVoice`. */\n staff?: 'treble' | 'bass';\n /** The grace notes of the note this is the head of — see `ScoreNote.grace`. */\n grace?: readonly number[];\n /** The note is leaned on — see `accentedStarts`. */\n accent?: boolean;\n /** The note is an echo — see `ScoreNote.echo`. Its head is written in brackets. */\n echo?: boolean;\n /** The note is played short — see `ScoreNote.staccato`. A dot over its head. */\n staccato?: boolean;\n /**\n * On a percussion head: the noise is let ring — a hit longer than `LET_RING_TICKS`, written at its\n * full length, tied over bar lines, and marked \"l.v.\" (laissez vibrer).\n */\n letRing?: boolean;\n /**\n * The other heads on this one's stem, struck at the same moment: on a percussion staff, drums by\n * period — a cartridge plays its noise channel and its DMC samples at once, a hat over a kick; on\n * a pitched staff, notes by MIDI number — a violin's double and triple stops.\n */\n chord?: readonly number[];\n /**\n * The APU level the note STARTS at, 0..15, as the ROM holds it — for a renderer to print under\n * the head when asked. The dynamics are a reading of these numbers in six steps, which is what a\n * player needs; the number itself is what the cartridge says, and the two answer different\n * questions. Only on a head, and only where the channel has a volume at all: the triangle has\n * none, so its notes carry nothing.\n */\n volume?: number;\n /** Its beam runs across the bar line — see `crossBarRuns`. */\n across?: 'start' | 'join';\n /** Beams are grouped by this number rather than by the beat — see `accentBeamGroups`. */\n beamGroup?: number;\n};\n\n/**\n * How much louder than BOTH its neighbours a note has to start to be written as\n * accented, in nibble steps.\n *\n * Three is the step the tracks themselves use: the driver holds a level and\n * drops or lifts the next note by 3 — ragnarok's canyon, bar 25, alternates 4\n * and 7 through the bar, and 7 against 4 is what the ear hears as the accent.\n */\nexport const ACCENT_STEP = 3;\n\n/**\n * The notes a voice leans on: louder than the note before it by `ACCENT_STEP`,\n * no quieter than the note after it, and NOT on a beat.\n *\n * Off the beat is the whole point. The driver moves the volume constantly, and\n * a mark on every rise would put one under a third of the heads of some tracks\n * while saying nothing a reader cannot see from the dynamics. What a reader\n * cannot see is a voice that leans between the beats: ragnarok's canyon, bar 25,\n * plays sixteenths at 9 9 7 7 4 7 4 7 4 2 7 7 4 7 4 9 — every beat of the bar\n * but the first is a 4, and the 7s fall in the gaps. On paper that is an even\n * run of sixteenths; in the ears it is a syncopation, and accents are what make\n * the two agree.\n *\n * Read on the notes as the staff has them — after `voicePhase` has taken out a\n * channel's authored delay — or a voice written a tick late would count as\n * off the beat throughout.\n */\nexport function accentedStarts(\n notes: readonly ScoreNote[],\n beat = TICKS_PER_QUARTER,\n step = ACCENT_STEP\n): Set<number> {\n const sounded = [...notes]\n .filter((note): note is ScoreNote & { volume: number } => note.volume !== undefined)\n .sort((a, b) => a.start - b.start);\n const starts = new Set<number>();\n sounded.forEach((note, index) => {\n const before = sounded[index - 1];\n const after = sounded[index + 1];\n if (!before || !after) return;\n if (note.start % beat === 0) return;\n if (note.volume - before.volume < step) return;\n if (note.volume < after.volume) return;\n starts.add(note.start);\n });\n return starts;\n}\n\n/**\n * Beam groups that follow the ACCENTS rather than the beat, for a passage that\n * is written in one pulse and played in another.\n *\n * Ragnarok's canyon from bar 25 is the case, and it is a case, not a rule:\n * beats 2, 3 and 4 of every bar sit at volume 4 while the notes between them\n * are at 7, so beaming by the quarter draws four even groups over a bar whose\n * weight lands in five uneven ones — 3 2 3 3 2, each beginning on a note the\n * ROM leans on. Tried as a general rule over the cartridge it made beams of 14,\n * 16 and 32 heads elsewhere (wookie hole, Arctic Caverns), which is why the\n * passage asks for it by tick.\n *\n * Numbers a group per head from `from` on: a new one at every accent, and one\n * after the bar's LOUDEST head when what follows is quieter — the figure's own\n * peak, which ends a group rather than joining the run under it. Bar 25 is the\n * one that needs the second rule: bars 26 to 28 open on the two heads a beam\n * has already carried over the bar line, while 25 opens on the same pair with\n * nothing to carry them, and without it they were swallowed by the five heads\n * up to the first accent.\n */\nexport function accentBeamGroups(\n bars: ScoreItem[][],\n /** The passage the rule covers, in the staff's ticks: `[from, to)`. */\n { from, to }: { from: number; to: number },\n /** Each head's volume by its start tick — the levels the groups are read from. */\n levels: ReadonlyMap<number, number>\n): ScoreItem[][] {\n let group = 0;\n return bars.map((items) => {\n const within = (item: ScoreItem) => item.start >= from && item.start < to;\n const heads = items.filter((item) => item.midi !== null && within(item));\n /*\n * A voice with nothing to lean on keeps the beat. The rule has cuts only where a voice pushes,\n * and the triangle holds one level right through this passage: numbered along with the others\n * it had no cut at all, and its bar came out under a single beam from end to end.\n */\n if (!heads.some((item) => item.accent)) return items;\n const peak = Math.max(...heads.map((item) => levels.get(item.start) ?? 0), 0);\n let previous: number | null = null;\n return items.map((item) => {\n if (!within(item) || item.midi === null) return item;\n const level = levels.get(item.start);\n if (item.accent || (previous !== null && previous >= peak && (level ?? 0) < previous))\n group++;\n previous = level ?? previous;\n return { ...item, beamGroup: group };\n });\n });\n}\n\n/** The most notes a beam is carried across a bar line onto — the figure, and no more. */\nexport const CROSS_BAR_RUN = 4;\n\n/**\n * Figures a bar line cuts in half: a run that starts on the bar's last note and\n * carries the same level into the next bar.\n *\n * Beams do not cross bar lines, and for good reason — the bar line is what a\n * reader counts from. The exception earns itself when the figure is plainly one\n * gesture and the bar line falls inside it: ragnarok's canyon, bars 25 to 28,\n * ends each bar on an accented E3 and opens the next with D3 E3 at the same\n * level 9, the run around it sitting at 7 and 4. Three heads, one gesture, and\n * written bar by bar it reads as a stray sixteenth and a pair.\n *\n * Narrow on purpose: the last note must be ACCENTED (see `accentedStarts`), the\n * run must be unbroken, every note must hold the same volume, and it stops after\n * `CROSS_BAR_RUN` heads. Over the whole cartridge that is three places, all of\n * them this figure. Loosened to \"the level holds\" alone it caught 148, some of\n * them 240 notes long — a beam over half a track.\n *\n * Returns the start tick of each note in a crossing run, mapped to its part in\n * it: the `start` is the note the beam leaves the bar on, the `join`s are the\n * heads it reaches on the other side.\n */\nexport function crossBarRuns(\n notes: readonly ScoreNote[],\n grid: BarGrid,\n accents: ReadonlySet<number> = accentedStarts(notes)\n): Map<number, 'start' | 'join'> {\n const sounded = [...notes]\n .filter((note): note is ScoreNote & { volume: number } => note.volume !== undefined)\n .sort((a, b) => a.start - b.start);\n const runs = new Map<number, 'start' | 'join'>();\n sounded.forEach((note, index) => {\n if (note.ticks >= TICKS_PER_QUARTER || !accents.has(note.start)) return;\n const next = sounded[index + 1];\n if (!next || next.start !== note.start + note.ticks) return;\n if (barAt(grid, next.start) === barAt(grid, note.start)) return;\n if (next.volume !== note.volume) return;\n const chain: ScoreNote[] = [note];\n for (let at = index + 1; at < sounded.length && chain.length < CROSS_BAR_RUN; at++) {\n const head = sounded[at];\n const before = chain[chain.length - 1];\n if (head.start !== before.start + before.ticks || head.volume !== note.volume) break;\n chain.push(head);\n }\n if (chain.length < 2) return;\n runs.set(note.start, 'start');\n for (const head of chain.slice(1)) runs.set(head.start, 'join');\n });\n return runs;\n}\n\n/** Whether an effect is drawn along its note — and so has to carry on where the note does. */\nexport function drawnAlong(effect: PitchEffect, measureTicks = MEASURE_TICKS): boolean {\n return (\n effect.kind === 'slide' ||\n (effect.kind === 'bend' && effect.ticks >= measureTicks) ||\n (effect.kind === 'vibrato' && effect.curve !== undefined)\n );\n}\n\n/**\n * Puts what each note carries on its HEAD — the first piece of it, never a\n * piece tied on after a bar line, which would mark one note twice: its effect,\n * grace notes, accent, echo, level, and its part in a beam across the bar line.\n * The pieces tied on after a head get a `carry` instead, when the effect is\n * drawn along the note.\n *\n * In place, and in one walk: the bars are the ones `buildScore` has just made,\n * and copying every head once for each thing it might carry was a fifth of the\n * time a score took to work out. The marks go on in the order above, so a\n * head's fields read the same whichever of them it has.\n */\nfunction attachHeads(\n bars: StaffItem[][],\n marks: {\n effects?: ReadonlyMap<number, PitchEffect>;\n graces?: ReadonlyMap<number, readonly number[]>;\n accents?: ReadonlySet<number>;\n echoes?: ReadonlySet<number>;\n levels?: ReadonlyMap<number, number>;\n across?: ReadonlyMap<number, 'start' | 'join'>;\n staccatos?: ReadonlySet<number>;\n chords?: ReadonlyMap<number, readonly number[]>;\n }\n): ScoreItem[][] {\n const effects = marks.effects?.size ? marks.effects : null;\n const graces = marks.graces?.size ? marks.graces : null;\n const accents = marks.accents?.size ? marks.accents : null;\n const echoes = marks.echoes?.size ? marks.echoes : null;\n const levels = marks.levels?.size ? marks.levels : null;\n const across = marks.across?.size ? marks.across : null;\n const staccatos = marks.staccatos?.size ? marks.staccatos : null;\n const chords = marks.chords?.size ? marks.chords : null;\n if (!effects && !graces && !accents && !echoes && !levels && !across && !staccatos && !chords) {\n return bars;\n }\n let active: EffectCarry | null = null;\n for (const items of bars) {\n for (const plain of items) {\n const item = plain as ScoreItem;\n const head = item.midi !== null && !item.tieStop;\n if (effects) {\n if (head && effects.has(item.start)) {\n const effect = effects.get(item.start)!;\n active = drawnAlong(effect) ? { start: item.start, midi: item.midi!, effect } : null;\n item.effect = effect;\n } else if (active && item.tieStop && item.midi === active.midi) {\n item.carry = active;\n } else if (!item.tieStop) {\n active = null;\n }\n }\n if (!head) continue;\n if (graces?.has(item.start)) item.grace = graces.get(item.start);\n if (accents?.has(item.start)) item.accent = true;\n if (echoes?.has(item.start)) item.echo = true;\n if (levels?.has(item.start)) item.volume = levels.get(item.start);\n if (across?.has(item.start)) item.across = across.get(item.start);\n if (staccatos?.has(item.start)) item.staccato = true;\n if (chords?.has(item.start)) item.chord = chords.get(item.start);\n }\n }\n return bars;\n}\n\n/** Each note's own APU level by where it starts — what `attachHeads` puts on its head. */\nfunction levelsOf(notes: readonly { start: number; volume?: number }[]): Map<number, number> {\n const levels = new Map<number, number>();\n for (const note of notes) if (note.volume !== undefined) levels.set(note.start, note.volume);\n return levels;\n}\n\n/** A noise hit: when, for how long, and which `$400E` period. */\nexport interface ScoreHit {\n start: number;\n ticks: number;\n period: number;\n /** The APU level the hit starts at, 0..15 — see `ScoreItem.volume`. */\n volume?: number;\n}\n\nexport type ScoreStaveKind = 'treble' | 'bass' | 'percussion';\n\nexport interface ScoreStave {\n partId: string;\n kind: ScoreStaveKind;\n /**\n * One list of items per bar. Filled to the bar line — except on a grand\n * staff, where it is only what stands on THIS stave, for the layout.\n */\n bars: ScoreItem[][];\n /** On a grand staff's upper stave: the part's whole voice, filled to the bar line, drawn across both. */\n voiceBars?: ScoreItem[][];\n /** On a grand staff's lower stave: its notes belong to the voice of the stave above. */\n follows?: boolean;\n}\n\nexport interface ScoreModel {\n /** Ticks added to the piece's clock to get the score's — see `staffShift`. */\n shift: number;\n /** Where the bar lines fall: the metre, and the opening bar's own length. */\n grid: BarGrid;\n barCount: number;\n staves: ScoreStave[];\n /** Each part's marks, in the SCORE's ticks. */\n dynamics: Record<string, DynamicMark[]>;\n /**\n * Each part's own delay taken out (`voicePhase`), in ticks: its notes sit\n * this much EARLIER on the staff than on the piece's clock. Anything that\n * compares a staff tick with the piece's — hiding what has not been read\n * yet — has to take it out too.\n */\n phases: Record<string, number>;\n}\n\n/** Where a piece changes key: the tick the new key starts on, and its VexFlow name. */\nexport interface KeyChange {\n /** In the PIECE's ticks, as the ROM holds them. */\n tick: number;\n key: string;\n}\n\n/**\n * The key each bar of a score is written in.\n *\n * A change takes effect from the bar its tick falls in — the tick is moved onto\n * the staff's clock by `shift` first — so it stays with the music when the bar\n * line or the metre is read differently. Volkmire's Inferno Race turns from D\n * minor to D major on tick 870, which is bar 29 of its 2/4 score.\n */\nexport function barKeys(\n barCount: number,\n shift: number,\n grid: BarGrid,\n opening: string,\n changes: readonly KeyChange[] = []\n): string[] {\n const names = Array.from({ length: barCount }, () => opening);\n for (const change of changes) {\n const from = Math.max(0, barAt(grid, change.tick + shift));\n for (let bar = from; bar < names.length; bar++) names[bar] = change.key;\n }\n return names;\n}\n\n/** The part id the percussion staff carries. */\nexport const DRUMS_PART = 'drums';\n\n/** A noise hit longer than this (a half note) is let ring, not struck — see `ScoreItem.letRing`. */\nexport const LET_RING_TICKS = TICKS_PER_QUARTER * 2;\n\n/** How a score is barred and read — everything `buildScore` takes beyond the notes. */\nexport interface ScoreOptions {\n /** The tick the bar lines are counted from. Default 0. */\n offset?: number;\n /** Ticks in a bar: 64 is 4/4, 32 is 2/4. Default `MEASURE_TICKS`. */\n measureTicks?: number;\n /**\n * Write the pickup as part of the opening bar rather than in a bar of its own.\n *\n * The music then starts on the score's first tick, and the opening bar is as\n * much longer than the metre as the pickup is — one bar of 19/32 in front of\n * Volkmire's Inferno Race's 2/4, instead of a bar of rests with the run in it.\n * `false`, the default, is the anacrusis: a short opening bar, and a closing bar short by as\n * much. All three readings, `padded` among them, are in `Pickup`.\n */\n mergePickup?: boolean | Pickup;\n /**\n * The passage read by its accents: the only place accents are marked (`accentedStarts`), and\n * where the beams follow them rather than the beat (`accentBeamGroups`). None given, no accents.\n * In the PIECE's ticks, like everything a caller gives; `shift` moves it onto the staff's clock.\n */\n accentBeams?: { from: number; to: number };\n /** Bars later in the piece with a length of their own — see `BarGrid`. */\n oddBars?: readonly OddBar[];\n /**\n * Take a part's own delay of up to `MAX_PHASE` ticks out (`voicePhase`). Default true: a sound\n * driver delays a channel a tick or two on purpose, and the staff writes it on the beat. Music\n * that is already on its beat — a MIDI file — wants it off, or a voice is moved off the beat it\n * keeps.\n */\n alignVoices?: boolean;\n}\n\n/**\n * The whole score, worked out once.\n *\n * `options.offset` is the tick the bar lines are counted from and\n * `options.measureTicks` the length of a bar; any other notation view of the\n * same piece should use the same two, so they all bar the music the same way.\n */\n/**\n * An anacrusis is paid back at the end: a piece that opens with a short bar and stops short of a\n * whole closing bar by exactly as much gets its closing bar that long, so the two make one bar\n * between them — Aerial Bar's two eighths in front, four at the end. A closing bar of any other\n * length is left whole, rests and all.\n */\nexport function withClosingBar(grid: BarGrid, end: number, reading: Pickup): BarGrid {\n if (reading !== 'anacrusis' || grid.firstBarTicks >= grid.measureTicks) return grid;\n const last = barCountOf(grid, end) - 1;\n if (last < 1 || grid.oddBars?.some((odd) => odd.bar === last)) return grid;\n const tail = end - barStartOf(grid, last);\n if (tail <= 0 || tail + grid.firstBarTicks !== barTicksOf(grid, last)) return grid;\n return barGrid(grid.measureTicks, grid.firstBarTicks, [...(grid.oddBars ?? []), { bar: last, ticks: tail }]);\n}\n\nexport function buildScore(\n parts: readonly {\n id: string;\n notes: readonly ScoreNote[];\n /** Which staves, when the caller decides rather than the notes (`partStaves`). */\n staves?: readonly ('treble' | 'bass')[];\n }[],\n drums: readonly ScoreHit[],\n totalTicks: number,\n {\n offset = 0,\n measureTicks = MEASURE_TICKS,\n mergePickup = false,\n accentBeams,\n oddBars = [],\n alignVoices = true,\n }: ScoreOptions = {}\n): ScoreModel {\n const barred = barring(offset, measureTicks, mergePickup, oddBars);\n const { shift } = barred;\n const end = totalTicks + shift;\n const grid = withClosingBar(barred.grid, end, pickupOf(mergePickup));\n const barCount = barCountOf(grid, end);\n const barsOf = (notes: readonly TickNote[]) =>\n staffMeasures(staffItems(notes, end, grid), end, grid).map((bar) => bar.items);\n const phases: Record<string, number> = {};\n const moved = <T extends TickNote>(notes: readonly T[], id?: string): T[] => {\n const phase = alignVoices && notes.length > 0 ? voicePhase(notes, offset, measureTicks) : 0;\n if (id !== undefined) phases[id] = phase;\n return shiftNotes(notes, shift - phase);\n };\n\n const staves: ScoreStave[] = [];\n const dynamics: Record<string, DynamicMark[]> = {};\n\n for (const part of parts) {\n /*\n * Notes struck together are one head with a chord on its stem: the highest — the line a\n * reader follows — is the head the rhythm, the staff and the marks are read from, and it\n * holds as long as the longest of them. A part with one note at a time is untouched.\n */\n const together = new Map<number, ScoreNote[]>();\n for (const note of part.notes)\n together.set(note.start, [...(together.get(note.start) ?? []), note]);\n const groups = [...together.values()];\n const leads = groups.map((group) =>\n group.length === 1\n ? group[0]\n : {\n ...group.reduce((top, note) => (note.midi > top.midi ? note : top)),\n ticks: Math.max(...group.map((note) => note.ticks)),\n }\n );\n const notes = moved(leads, part.id);\n const pitchChords = new Map<number, number[]>();\n groups.forEach((group, index) => {\n if (group.length < 2) return;\n const others = [...new Set(group.map((note) => note.midi))]\n .filter((midi) => midi !== leads[index].midi)\n .sort((a, b) => a - b);\n if (others.length) pitchChords.set(notes[index].start, others);\n });\n const range = pitchChords.size\n ? [...notes, ...[...pitchChords.values()].flat().map((midi) => ({ midi }))]\n : notes;\n const kinds = part.staves ? [...part.staves] : partStaves(range);\n // Read over the whole part: the note after a slide may be on the other staff.\n const effects = effectsOf(notes);\n /*\n * Accents only inside the passage read by its accents (`accentBeams`) — a\n * reading by ear, made for ragnarok's canyon, bars 25 to 28. Let loose over\n * the cartridge the rule marked every loud note off the beat, and Arctic\n * Caverns' echo — every second note far quieter than the one before, an\n * imitation of an echo — came out as a column of accents it does not have.\n */\n const accents = accentBeams\n ? new Set(\n [...accentedStarts(notes)].filter(\n (start) => start >= accentBeams.from + shift && start < accentBeams.to + shift\n )\n )\n : new Set<number>();\n const across = crossBarRuns(notes, grid, accents);\n const heads = () => {\n const written = attachHeads(barsOf(notes), {\n effects,\n graces: new Map(\n notes.filter((note) => note.grace?.length).map((note) => [note.start, note.grace!])\n ),\n accents,\n echoes: new Set(notes.filter((note) => note.echo).map((note) => note.start)),\n levels: levelsOf(notes),\n across,\n staccatos: new Set(notes.filter((note) => note.staccato).map((note) => note.start)),\n chords: pitchChords,\n });\n if (!accentBeams) return written;\n return accentBeamGroups(\n written,\n { from: accentBeams.from + shift, to: accentBeams.to + shift },\n levelsOf(notes)\n );\n };\n if (kinds.length === 1) {\n staves.push({ partId: part.id, kind: kinds[0], bars: heads() });\n } else {\n const voice = crossStaffVoice(heads());\n const on = (staff: 'treble' | 'bass') =>\n voice.map((items) => items.filter((item) => item.staff === staff));\n staves.push({\n partId: part.id,\n kind: 'treble',\n bars: on('treble'),\n voiceBars: voice,\n });\n staves.push({\n partId: part.id,\n kind: 'bass',\n bars: on('bass'),\n follows: true,\n });\n }\n const loud = notes.filter(\n (note): note is ScoreNote & { volume: number } => note.volume !== undefined\n );\n dynamics[part.id] = dynamicMarks(loud);\n }\n\n if (drums.length > 0) {\n /*\n * Hits at the same moment are one chord: the longest is the head the staff's rhythm is\n * written from, the others stand on its stem. A staff of one voice wrote them one after\n * another, and every hat over a kick pushed the rest of the bar a value late.\n */\n const groups = new Map<number, ScoreHit[]>();\n for (const hit of drums) groups.set(hit.start, [...(groups.get(hit.start) ?? []), hit]);\n const leads = [...groups.values()].map((group) =>\n group.reduce((longest, hit) => (hit.ticks > longest.ticks ? hit : longest))\n );\n const others = [...groups.values()].map((group, index) => [\n ...new Set(\n group\n .filter((hit) => hit !== leads[index])\n .map((hit) => hit.period & 0x0f)\n .filter((period) => period !== (leads[index].period & 0x0f))\n ),\n ]);\n const hits = moved(\n leads.map((hit) => ({\n start: hit.start,\n ticks: hit.ticks,\n midi: hit.period & 0x0f,\n volume: hit.volume,\n }))\n );\n const chords = new Map<number, number[]>();\n hits.forEach((hit, index) => {\n if (others[index]?.length) chords.set(hit.start, others[index]);\n });\n /*\n * A drum is struck once. What is left of its slot after the first head —\n * the rest of a long value, or the part carried over a bar line — is\n * written as rest: tied on a percussion staff it reads as a roll, and as a\n * second head it reads as a second hit.\n *\n * Not so a noise that is let ring: Circus Charlie's applause is one hit of\n * 136 ticks fading 11 → 2, and rests after its head said the hall fell\n * silent while it was still heard. A hit longer than `LET_RING_TICKS` keeps\n * its whole length, tied over the bar lines, and its head is marked \"l.v.\".\n */\n // The hit an item belongs to is the last one struck at or before it.\n const struck = [...hits].sort((a, b) => a.start - b.start);\n const rings = (item: StaffItem) => {\n if (item.midi === null) return false;\n let hit: (typeof struck)[number] | undefined;\n for (const candidate of struck) if (candidate.start <= item.start) hit = candidate;\n return !!hit && hit.ticks > LET_RING_TICKS && item.start < hit.start + hit.ticks;\n };\n const bars = attachHeads(\n barsOf(hits).map((items) =>\n items.map((item): StaffItem =>\n rings(item)\n ? ({ ...item, ...(item.tieStop ? {} : { letRing: true }) } as ScoreItem)\n : item.tieStop\n ? { ...item, midi: null, tieStart: false, tieStop: false }\n : { ...item, tieStart: false }\n )\n ),\n { levels: levelsOf(hits), chords }\n );\n staves.push({ partId: DRUMS_PART, kind: 'percussion', bars });\n }\n\n return { shift, grid, barCount, staves, dynamics, phases };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"score.js","sourceRoot":"","sources":["../src/score.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,KAAK,EACL,UAAU,EACV,OAAO,EACP,UAAU,EACV,UAAU,EACV,OAAO,EACP,QAAQ,EAER,UAAU,EACV,UAAU,EACV,UAAU,EACV,aAAa,EACb,UAAU,GAKX,MAAM,eAAe,CAAC;AAEvB;;;GAGG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAEpC,MAAM,UAAU,eAAe,CAC7B,KAAmB,EACnB,KAAK,GAAG,iB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AAE,IAAI,EAAE,CAAC,EAAgB;YACxE,CAAC,CAAC,IAAI,CAAC,OAAO;gBACZ,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE;gBAC1D,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,CACnC,CACF,EACD,EAAE,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CACnC,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;IAChE,CAAC;IAED,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;AAC7D,CAAC","sourcesContent":["/**\n * A track as a SCORE: each pitched channel on a grand staff, the noise channel\n * on a percussion staff, and the dynamics its volumes imply.\n *\n * Built on `./notation`, so a bar here is spelled exactly the way a single\n * scrolling staff spells it — same bar line, same phase, same\n * note values. What this file adds is the part a page of music needs and a\n * single strip does not: which of two staves a note goes on, and what the\n * volume column says in the words a player reads.\n */\n\nimport {\n MEASURE_TICKS,\n TICKS_PER_QUARTER,\n barAt,\n barCountOf,\n barGrid,\n barStartOf,\n barTicksOf,\n barring,\n pickupOf,\n type Pickup,\n chooseClef,\n shiftNotes,\n staffItems,\n staffMeasures,\n voicePhase,\n type BarGrid,\n type OddBar,\n type StaffItem,\n type TickNote,\n} from './notation.js';\n\n/**\n * Middle C: in a beam group kept on the bass, the heads from here up still go\n * onto the treble and the beam crosses to them — see `crossStaffVoice`.\n */\nexport const GRAND_STAFF_SPLIT = 60;\n\nexport function splitGrandStaff<T extends { midi: number }>(\n notes: readonly T[],\n split = GRAND_STAFF_SPLIT\n): { treble: T[]; bass: T[] } {\n const treble: T[] = [];\n const bass: T[] = [];\n for (const note of notes) (note.midi >= split ? treble : bass).push(note);\n return { treble, bass };\n}\n\n/** A beam group that never goes below E3 — three ledger lines under the treble — is written on the treble. */\nexport const TREBLE_FLOOR = 52;\n\n/** Durations beamed together, one group per beat — `beamsFor`'s set. */\nconst BEAMED = new Set(['8', '16', '32', '64']);\n\n/**\n * A grand-staff part as ONE voice, each item saying which of the two staves it\n * stands on.\n *\n * Decided per BEAM GROUP — the beamed notes of one beat, or a note on its own —\n * because a beam is what a reader follows:\n *\n * - a group that never goes below E3 (`TREBLE_FLOOR`) is on the treble, E3\n * included. Ragnarok's canyon, pulse 1, bar 29, the third beat: A3 G3 C4 A3\n * E4 C4 G4 E4 — a reader wanted it all on the treble.\n * - a group that does go below E3 stays on the bass, E3s and all — bar 29's\n * second beat, E3 G3 C3 E3…, which \"would be ugly otherwise\". Only its heads\n * from middle C up cross to the treble, and the beam crosses with them — the\n * piano's cross-staff writing, drawn as one beam between the\n * staves with no rest on either side. Bar 30's lone G5 among B2s is that case.\n *\n * Every rule tried per BAR before this failed on a bar of this music: a bar\n * that starts low and climbs three octaves has a bass half and a treble half,\n * and the only choices a whole bar has are to tear its beams with rests or put\n * half of it on four ledger lines.\n *\n * A piece tied on from the head before it stays where that head stood; a rest\n * stands where the head before it in the bar did (else the first head after\n * it), and a bar with no heads at all is the treble's, so the bass shows its\n * own bar rest rather than a second one.\n */\nexport function crossStaffVoice(bars: readonly (readonly ScoreItem[])[]): ScoreItem[][] {\n let carried: 'treble' | 'bass' = 'treble';\n /*\n * A head whose beam runs on into the next bar (`crossBarRuns`) belongs to the group on the OTHER\n * side of the bar line, not to the beat it sits in — so it is written after that group has\n * chosen, and put on the same staff. Ragnarok's canyon, bar 25: the last E3 ends a beat of G4s\n * and went to the treble with them, while the D3 E3 it is beamed to are on the bass, and the\n * beam fell across the whole grand staff.\n */\n let hanging: ScoreItem[] | null = null;\n const written = bars.map((items) => {\n /*\n * The beat a head stands on, counted from ITS OWN bar line — the bar's\n * first item, since a bar is filled from its line. Counted with `%` off the\n * piece's clock instead, as this once was, it is right only while every bar\n * is the same length and the first starts on tick 0: Volkmire's Inferno\n * Race, barred from tick 6 with an opening bar of 19/32, had the two halves\n * of one arpeggio sorted into each other's beats, and the run came out torn\n * between the staves.\n */\n const barStart = items[0]?.start ?? 0;\n const groups = new Map<string, number[]>();\n items.forEach((item, index) => {\n if (item.midi === null) return;\n const key = BEAMED.has(item.duration)\n ? `beat${Math.floor((item.start - barStart) / TICKS_PER_QUARTER)}`\n : `note${index}`;\n groups.set(key, [...(groups.get(key) ?? []), index]);\n });\n\n const chosen: ('treble' | 'bass')[] = items.map(() => 'treble');\n for (const members of groups.values()) {\n const low = Math.min(...members.map((index) => items[index].midi as number));\n for (const index of members) {\n const midi = items[index].midi as number;\n chosen[index] = low >= TREBLE_FLOOR || midi >= GRAND_STAFF_SPLIT ? 'treble' : 'bass';\n }\n }\n\n let previous = carried;\n const heads = items.map((item, index) => {\n if (item.midi === null) return item;\n const staff = item.tieStop ? previous : chosen[index];\n previous = staff;\n return { ...item, staff };\n });\n carried = previous;\n\n const firstHead = heads.find((item) => item.midi !== null)?.staff ?? 'treble';\n let before: 'treble' | 'bass' | undefined;\n const bar = heads.map((item) => {\n if (item.midi !== null) {\n before = item.staff;\n return item;\n }\n return { ...item, staff: before ?? firstHead };\n });\n\n const reached = bar.find((item) => item.across === 'join');\n if (hanging && reached) {\n for (const item of hanging) item.staff = reached.staff;\n carried = reached.staff ?? carried;\n }\n hanging = bar.filter((item) => item.across === 'start');\n return bar;\n });\n return written;\n}\n\n/** The highest a part may reach and still be written on the bass staff alone: E4, two ledger lines up. */\nexport const BASS_ONLY_MAX = 64;\n/** The lowest a part may reach and still be written on the treble staff alone: G3, two ledger lines down. */\nexport const TREBLE_ONLY_MIN = 55;\n\n/**\n * The staves a part needs: one when every note it plays sits within two ledger\n * lines of a single staff, both otherwise.\n *\n * A grand staff whose other half is a whole track of rests is furniture: the\n * triangle carries the bass in every one of the twenty tracks, and in\n * Ragnarok's canyon it reaches D#4 at most — a ledger line and a half above the\n * bass staff. Where both single staves would do, the part's middle decides.\n */\nexport function partStaves(notes: readonly { midi: number }[]): ('treble' | 'bass')[] {\n if (notes.length === 0) return ['treble'];\n let low = Infinity;\n let high = -Infinity;\n for (const note of notes) {\n low = Math.min(low, note.midi);\n high = Math.max(high, note.midi);\n }\n const bass = high <= BASS_ONLY_MAX;\n const treble = low >= TREBLE_ONLY_MIN;\n if (bass && treble) return [chooseClef(notes)];\n if (bass) return ['bass'];\n if (treble) return ['treble'];\n return ['treble', 'bass'];\n}\n\nexport type Dynamic = 'pp' | 'p' | 'mp' | 'mf' | 'f' | 'ff';\nconst DYNAMICS: readonly Dynamic[] = ['pp', 'p', 'mp', 'mf', 'f', 'ff'];\n\n/**\n * The APU's 0..15 volume in six steps.\n *\n * A READING, not a fact: the nibble is linear in output level and a dynamic is\n * a word about loudness, so the steps are even in the nibble and nothing more\n * is claimed for them.\n */\nexport function dynamicOf(volume: number): Dynamic {\n const level = Math.max(0, Math.min(15, Math.round(volume)));\n return DYNAMICS[Math.min(DYNAMICS.length - 1, Math.floor((level * DYNAMICS.length) / 16))];\n}\n\n/** A change of level closer than this, in ticks, is folded into the mark before it. A quarter note. */\nexport const DYNAMIC_HOLD = 16;\n\n/** The words a mark can carry after its level: a figure's shape, or \"the same again\". */\nexport type DynamicWords = 'dim.' | 'cresc.' | 'sim.';\n\nexport interface DynamicMark {\n tick: number;\n dynamic: Dynamic;\n /**\n * How the figure goes from here: `dim.` and `cresc.` are a hairpin after the\n * level, `sim.` is the word alone — the level is the figure's own — with a\n * dashed line for as long as it holds.\n */\n words?: DynamicWords;\n /** With `words`: the tick of the last note the hairpin or the `sim.` covers. */\n until?: number; /**\n * A hairpin from a level the reader is already at: the hairpin alone, no\n * letter — ragnarok's 7 7 4 2, an mp going on from the mp before it.\n */\n bare?: boolean;\n}\n\n/** Onset to onset, notes closer than this can make one shaped figure. An eighth note. */\nexport const FIGURE_GAP = 8;\n\n/**\n * And no closer than this, a sixteenth. Faster is one note's envelope struck\n * again and again — Arctic Caverns' 8 4 2 1 in thirty-seconds on one pitch, an\n * echo — not a figure a player shapes.\n */\nexport const FIGURE_STEP = 4;\n\n/** A run of notes whose level only falls, or only rises: `[from, to]` are indices, inclusive. */\nexport interface ShapedFigure {\n from: number;\n to: number;\n words: 'dim.' | 'cresc.';\n}\n\n/**\n * Runs of at least three notes, each `FIGURE_STEP` to `FIGURE_GAP` after the one before, whose\n * level moves one way every step and by two or more in all — the 4 3 2 1 under\n * every beat of a fading figure. The six steps of `dynamicOf` cannot show that:\n * 4 and 3 are both p, and the hold folds the pp of 2 and 1 back into it.\n *\n * `notes` must be in order of start.\n */\nexport function shapedFigures(\n notes: readonly { start: number; volume: number }[],\n gap = FIGURE_GAP\n): ShapedFigure[] {\n const figures: ShapedFigure[] = [];\n let from = 0;\n while (from < notes.length - 2) {\n const step = Math.sign(notes[from + 1].volume - notes[from].volume);\n let to = from;\n while (\n step !== 0 &&\n to + 1 < notes.length &&\n notes[to + 1].start - notes[to].start <= gap &&\n notes[to + 1].start - notes[to].start >= FIGURE_STEP &&\n Math.sign(notes[to + 1].volume - notes[to].volume) === step\n ) {\n to++;\n }\n if (to - from >= 2 && Math.abs(notes[to].volume - notes[from].volume) >= 2) {\n figures.push({ from, to, words: step < 0 ? 'dim.' : 'cresc.' });\n from = to + 1;\n } else {\n from++;\n }\n }\n return figures;\n}\n\n/**\n * Two figures `sim.` can stand for: the same levels in the same rhythm. Only\n * that — ragnarok's 7 4 2 1 followed by a 7 4 2 is a figure of its own, with a\n * hairpin of its own.\n */\nfunction sameFigure(\n notes: readonly { start: number; volume: number }[],\n a: ShapedFigure,\n b: ShapedFigure\n): boolean {\n if (a.to - a.from !== b.to - b.from) return false;\n for (let i = 0; i <= a.to - a.from; i++) {\n if (notes[a.from + i].volume !== notes[b.from + i].volume) return false;\n if (\n i > 0 &&\n notes[a.from + i].start - notes[a.from + i - 1].start !==\n notes[b.from + i].start - notes[b.from + i - 1].start\n ) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Where a voice's level changes, as the marks a score prints.\n *\n * Only at a change, and never two within `DYNAMIC_HOLD`: the driver can move a\n * volume on every note, and a mark under every head is noise. Inside the hold\n * the LOUDER level stands — the accent is what a reader has to see — and a\n * change that comes straight back to the level before it is dropped.\n *\n * A shaped figure (`shapedFigures`) is written as its level and a hairpin under\n * the first, `sim.` under the next one just like it, its dashes running on over\n * the ones after that, until some other mark is printed. A figure that turns straight\n * into one going the other way — wookie hole's 6 4 2 1 2 4 6 8 on one held\n * note — is a level swaying, not a figure, and is read note by note as before.\n * After a hairpin the reader is where it ends, so going back to where it began\n * is written — ragnarok's mp over the 7 after 7 4 2 1 — unless a `sim.` that\n * goes on already says the figure comes round again.\n */\nexport function dynamicMarks(\n notes: readonly { start: number; volume: number }[],\n hold = DYNAMIC_HOLD\n): DynamicMark[] {\n const sorted = [...notes].sort((a, b) => a.start - b.start);\n const found = shapedFigures(sorted);\n const swaying = (a: ShapedFigure | undefined, b: ShapedFigure | undefined) =>\n !!a && !!b && b.from === a.to + 1 && a.words !== b.words;\n const figureAt = new Map<number, ShapedFigure>();\n found.forEach((figure, i) => {\n if (!swaying(found[i - 1], figure) && !swaying(figure, found[i + 1])) {\n figureAt.set(figure.from, figure);\n }\n });\n\n const marks: DynamicMark[] = [];\n // The level the reader is at.\n let heard: Dynamic | null = null;\n // The figure the last words were about, and whether its `sim.` has been printed.\n let stated: ShapedFigure | null = null;\n let similar = false;\n // A plain mark breaks a run of `sim.`; taken back, it gives the run back.\n const broken = new Map<DynamicMark, { stated: ShapedFigure | null; similar: boolean }>();\n const pop = () => {\n const mark = marks.pop()!;\n const run = broken.get(mark);\n if (run) ({ stated, similar } = run);\n };\n /**\n * The next figure after note `i` is one more like `like`, and nothing between says otherwise —\n * Intruder Excluder's 6 6 before each 6 4 2 1 is the same figure coming round, not news.\n */\n const starts = [...figureAt.keys()].sort((a, b) => a - b);\n const simGoesOn = (i: number, like: ShapedFigure) => {\n const next = starts.find((start) => start > i);\n if (next === undefined || !sameFigure(sorted, like, figureAt.get(next)!)) return false;\n const level = dynamicOf(sorted[i].volume);\n for (let k = i + 1; k < next; k++) if (dynamicOf(sorted[k].volume) !== level) return false;\n return true;\n };\n for (let i = 0; i < sorted.length; i++) {\n const note = sorted[i];\n const dynamic = dynamicOf(note.volume);\n const figure = figureAt.get(i);\n const last = marks[marks.length - 1];\n if (figure) {\n // `p`, and a beat later `mp` and a hairpin: the figure's mark says it, as the louder.\n // At the same level the mark stays and the hairpin goes on from it, bare.\n if (\n last &&\n !last.words &&\n note.start - last.tick < hold &&\n DYNAMICS.indexOf(last.dynamic) < DYNAMICS.indexOf(dynamic)\n ) {\n pop();\n // Its level is now the figure's to state.\n heard = marks[marks.length - 1]?.dynamic ?? null;\n }\n const until = sorted[figure.to].start;\n if (stated && sameFigure(sorted, stated, figure)) {\n if (similar) marks[marks.length - 1].until = until;\n else marks.push({ tick: note.start, dynamic, words: 'sim.', until });\n similar = true;\n } else {\n const mark: DynamicMark = { tick: note.start, dynamic, words: figure.words, until };\n if (heard === dynamic) mark.bare = true;\n marks.push(mark);\n stated = figure;\n similar = false;\n }\n // The hairpin has taken the reader down (or up) to where the figure ends.\n heard = dynamicOf(sorted[figure.to].volume);\n i = figure.to;\n continue;\n }\n if (heard === dynamic) continue;\n // Back at the level of a run of `sim.` that goes on: the `sim.` says so already.\n if (stated && dynamic === dynamicOf(sorted[stated.from].volume) && simGoesOn(i, stated)) {\n heard = dynamic;\n continue;\n }\n heard = dynamic;\n if (last && !last.words && note.start - last.tick < hold) {\n if (DYNAMICS.indexOf(dynamic) > DYNAMICS.indexOf(last.dynamic)) last.dynamic = dynamic;\n if (marks[marks.length - 2]?.dynamic === last.dynamic) pop();\n heard = marks[marks.length - 1].dynamic;\n continue;\n }\n const mark: DynamicMark = { tick: note.start, dynamic };\n broken.set(mark, { stated, similar });\n stated = null;\n marks.push(mark);\n }\n return marks;\n}\n\n/**\n * Where each NES noise period (`$400E`, 0..15) sits on the percussion staff:\n * high noise at the top and low noise at the bottom.\n */\nconst NOISE_LINES = [\n 'g/5',\n 'g/5',\n 'g/5',\n 'f/5',\n 'f/5',\n 'e/5',\n 'e/5',\n 'd/5',\n 'd/5',\n 'c/5',\n 'b/4',\n 'a/4',\n 'g/4',\n 'f/4',\n 'e/4',\n 'e/4',\n];\n\n/**\n * The notehead: a cross for a closed or pedal hat, a circled cross for an open\n * one, a plain head for everything with a skin. The pieces are the ones\n * `@xromdev/drumroll` draws on its kit (`NOISE_DRUM_KINDS`).\n */\nconst NOISE_HEADS = ['x', 'x', 'x', 'x', 'cx', 'cx', '', '', '', '', '', '', '', '', '', ''];\n\n/** A noise period as a VexFlow key on the percussion staff. Only the low nibble is the period. */\nexport function noiseKey(period: number): string {\n const index = period & 0x0f;\n return NOISE_HEADS[index] ? `${NOISE_LINES[index]}/${NOISE_HEADS[index]}` : NOISE_LINES[index];\n}\n\n/** A pitched note, with the volume it starts at when the channel has one. */\nexport interface ScoreNote extends TickNote {\n volume?: number;\n /** The note's pitch curve — `[position 0..1, semitones]` — as a piano roll draws it. */\n bend?: readonly (readonly [number, number])[];\n /** Grace notes in front of it, as MIDI numbers in the order they are played. */\n grace?: readonly number[];\n /** A repeat of the note before, quieter — an echo, written in brackets (`echoNotes`). */\n echo?: boolean;\n /**\n * Played short: its `ticks` are the value it is WRITTEN as, and it sounds for\n * less — a staccato dot over the head instead of a rest after it.\n */\n staccato?: boolean;\n}\n\n/** What a pitch curve is written as. `ticks` is the whole note's length, over which it moves. */\nexport type PitchEffect =\n | {\n kind: 'slide';\n /** Where it arrives, in semitones from the written pitch; to a tenth. */\n semitones: number;\n /** Where along the note the movement begins, 0..1. */\n from: number;\n ticks: number;\n /**\n * It lands on the next written note. When it does not — a sweep too wide to be a bend that\n * ends on no note (ragnarok's canyon, triangle, bar 15: E3 down to B2, then a D3) — the\n * staff draws where it lands as a small note in brackets. Set by `effectsOf`.\n */\n arrives?: boolean;\n }\n | {\n /** The pitch moves on the note it started on — a guitarist's bend, or its release downwards. */\n kind: 'bend';\n semitones: number;\n from: number;\n ticks: number;\n }\n | {\n kind: 'vibrato';\n depth: number;\n ticks: number;\n /**\n * The curve itself, `[position 0..1, semitones]`, kept for a vibrato wider than a semitone:\n * a wave glyph says nothing of a swing like Turbo Tunnel Race's, bar 31, a D6 going up four\n * semitones and down two and a half, so the staff draws the curve itself.\n */\n curve?: readonly (readonly [number, number])[];\n };\n\n/** A vibrato swinging further than this, in semitones, is drawn as its curve rather than a wave. */\nexport const WIDE_VIBRATO = 1;\n\n/**\n * A movement smaller than this, in semitones, is not written at all.\n *\n * 261 of the cartridge's 304 curves are a drift of a fifth of a semitone at the\n * end of a note. The roll draws them as a hairline, which is right for a picture\n * of the sound; on a staff a mark on every one of them would be noise over a\n * third of the notes of some tracks.\n */\nexport const DRIFT_LIMIT = 0.5;\n/** Changes of direction that make a curve a vibrato rather than a slide. */\nconst VIBRATO_TURNS = 3;\n/** A swing back smaller than this, in semitones, is the curve's own jitter, not a change of direction. */\nconst TURN_MIN = 0.25;\n/** The shallowest vibrato written, in semitones either way: Surf City's is a tenth. */\nconst LIGHT_VIBRATO = 0.09;\n\n/**\n * How many times a curve really changes direction.\n *\n * Counted with hysteresis: a move only turns once the curve has come back\n * `TURN_MIN` from the furthest point it reached. Counting every sign change of\n * the slope read ragnarok's canyon's triangle, bar 15 — a flicker of 0.05\n * semitones and then a steady fall of five to a B — as a vibrato, and it was\n * drawn as a wave where a reader sees a glissando.\n */\nfunction turnsOf(values: readonly number[], turnMin = TURN_MIN): number {\n let turns = 0;\n let direction = 0;\n let pivot = values[0] ?? 0;\n for (const value of values) {\n const move = value - pivot;\n if (direction === 0) {\n if (Math.abs(move) >= turnMin) {\n direction = Math.sign(move);\n pivot = value;\n }\n } else if (Math.sign(move) === direction) {\n pivot = value;\n } else if (Math.abs(move) >= turnMin) {\n turns++;\n direction = -direction;\n pivot = value;\n }\n }\n return turns;\n}\n\n/**\n * A note's pitch curve read as notation: a slide to where it arrives, a\n * vibrato, or nothing.\n *\n * Over the twenty tracks that is 33 slides (one to four semitones), 10 vibratos,\n * and the drifts left out — the same split the Battletoads music tooling\n * makes between a slide and a vibrato.\n */\n/** How far into a note a strike may reach and still be read as its attack, 0..1. */\n/**\n * Alien 3's kick takes three frames of a seventeen-frame bass note — 18% — and at 15% the\n * vibrato after it was still read with the kick in it.\n */\nexport const STRIKE_SHARE = 0.25;\n\n/**\n * The curve without the strike it opens with, if it opens with one: a pitch\n * away from the note at its first point that comes back to it within\n * `STRIKE_SHARE` of the note. That is how a sound driver hits a note — a\n * triangle bass kicked from an octave up, a frame of a deep thump — and it is\n * timbre, not a movement of the pitch: Alien 3's vibrato on a long G3 read six\n * semitones deep with the kick in front of it, and was drawn as a curve.\n */\nfunction withoutStrike(\n curve: readonly (readonly [number, number])[]\n): readonly (readonly [number, number])[] {\n if (Math.abs(curve[0][1]) < DRIFT_LIMIT) return curve;\n const back = curve.findIndex(([, semitones]) => Math.abs(semitones) < 0.05);\n if (back <= 0 || curve[back][0] > STRIKE_SHARE) return curve;\n return curve.slice(back);\n}\n\nexport function pitchEffect(\n whole: readonly (readonly [number, number])[],\n ticks: number\n): PitchEffect | null {\n const curve = whole.length >= 2 ? withoutStrike(whole) : whole;\n if (curve.length < 2) return null;\n const values = curve.map(([, semitones]) => semitones);\n const peak = Math.max(...values.map(Math.abs));\n if (peak < DRIFT_LIMIT) {\n /*\n * Under half a semitone a curve is not written — unless it SWINGS. Surf City wobbles a tenth of\n * a semitone and Intermission a sixth, both audible; wookie hole's\n * and ragnarok's marks, which a looser rule also calls vibrato, are one-way drifts at the end\n * of a two-tick note and stay unwritten. Turns tell the two apart, counted against the curve's\n * OWN depth: a fixed grain either misses a tenth-of-a-semitone swing or counts a drift's jitter.\n */\n return peak >= LIGHT_VIBRATO && turnsOf(values, peak / 2) >= VIBRATO_TURNS\n ? { kind: 'vibrato', depth: peak, ticks }\n : null;\n }\n\n if (turnsOf(values) >= VIBRATO_TURNS) {\n const depth = Math.max(...values.map(Math.abs));\n return depth > WIDE_VIBRATO\n ? { kind: 'vibrato', depth, ticks, curve }\n : { kind: 'vibrato', depth, ticks };\n }\n\n const end = values[values.length - 1];\n if (Math.abs(end) < DRIFT_LIMIT) return null;\n const moving = values.findIndex((semitones) => Math.abs(semitones) >= 0.1);\n const from = curve[Math.max(0, moving - 1)][0];\n return { kind: 'slide', semitones: Math.round(end * 10) / 10, from, ticks };\n}\n\n/** The most a note's pitch may move on its own and still be a bend: a tone and a half. */\nexport const BEND_MAX = 3;\n/** Ticks between a slide's end and the next note that still count as the slide arriving in it. */\nconst GLISS_GAP = 1;\n\n/**\n * Each note's effect, read against the note AFTER it in the part.\n *\n * A curve does not say whether the pitch is sliding somewhere or bending on the\n * spot; the music around it does. A slide that ends on the pitch the very next\n * note is written at arrives in that note — a glissando, as in the title music's\n * G4 up to A4. One that goes nowhere written is the note itself bending:\n * ragnarok's canyon, pulse 1, bar 5, a D#4 pulled up 1.3 semitones and then left\n * for an A3 — a guitarist's bend, which a reader said at once, where \"gliss.\" had\n * been printed. Past `BEND_MAX` nothing bends that far, and the sweeps of fifteen\n * to twenty-eight semitones that open a few tracks stay lines.\n *\n * Except when the note after it comes straight back to the pitch the curve left:\n * that is a bend and its release, however far it went. Clinger Winger, pulse 1,\n * an E2 pushed up six and a half semitones over four bars and then struck again\n * as E2 — a reader heard a bend where a line marked \"gliss.\" had been drawn.\n * Across the whole ROM this reads that one note differently and no other.\n */\nexport function effectsOf(notes: readonly ScoreNote[]): Map<number, PitchEffect> {\n const ordered = [...notes].sort((a, b) => a.start - b.start);\n const effects = new Map<number, PitchEffect>();\n ordered.forEach((note, index) => {\n const effect = note.bend ? pitchEffect(note.bend, note.ticks) : null;\n if (!effect) return;\n if (effect.kind === 'slide') {\n const next = ordered[index + 1];\n const follows = next !== undefined && next.start - (note.start + note.ticks) <= GLISS_GAP;\n const arrives = follows && Math.abs(next.midi - (note.midi + effect.semitones)) <= 0.5;\n const returns = follows && next.midi === note.midi;\n if (!arrives && (returns || Math.abs(effect.semitones) <= BEND_MAX)) {\n effects.set(note.start, { ...effect, kind: 'bend' });\n return;\n }\n effects.set(note.start, { ...effect, arrives });\n return;\n }\n effects.set(note.start, effect);\n });\n return effects;\n}\n\n/**\n * A bend's size, in semitones, to one decimal — the arrow says which way.\n *\n * Always the number. The guitar's words (½ for a semitone, \"full\" for a tone)\n * were printed for sizes near a step and the number for the rest, so one page\n * said \"½\" over a bend of 0.9 semitones and \"1.3\" over the next: two systems\n * side by side, and a \"½\" read as half a semitone.\n */\nexport function bendLabel(semitones: number): string {\n return Math.abs(semitones).toFixed(1);\n}\n\n/** The pitch movement a tied piece carries on from the head of its note. */\nexport interface EffectCarry {\n /** Where the note starts, and the pitch it is written at. */\n start: number;\n midi: number;\n effect: PitchEffect;\n}\n\n/** A staff item, with the pitch effect of the note it is the head of. */\nexport type ScoreItem = StaffItem & {\n effect?: PitchEffect;\n /**\n * On a piece tied on after the head: the movement it is part of, when that movement is drawn\n * along the note — a glissando or a bend held a bar or more — so a line that runs onto the next\n * system can be carried on there and land where the note ends.\n */\n carry?: EffectCarry;\n /** On a grand staff's voice: the stave the item stands on — see `crossStaffVoice`. */\n staff?: 'treble' | 'bass';\n /** The grace notes of the note this is the head of — see `ScoreNote.grace`. */\n grace?: readonly number[];\n /** The note is leaned on — see `accentedStarts`. */\n accent?: boolean;\n /** The note is an echo — see `ScoreNote.echo`. Its head is written in brackets. */\n echo?: boolean;\n /** The note is played short — see `ScoreNote.staccato`. A dot over its head. */\n staccato?: boolean;\n /**\n * On a percussion head: the noise is let ring — a hit longer than `LET_RING_TICKS`, written at its\n * full length, tied over bar lines, and marked \"l.v.\" (laissez vibrer).\n */\n letRing?: boolean;\n /**\n * The other heads on this one's stem, struck at the same moment: on a percussion staff, drums by\n * period — a cartridge plays its noise channel and its DMC samples at once, a hat over a kick; on\n * a pitched staff, notes by MIDI number — a violin's double and triple stops.\n */\n chord?: readonly number[];\n /**\n * The APU level the note STARTS at, 0..15, as the ROM holds it — for a renderer to print under\n * the head when asked. The dynamics are a reading of these numbers in six steps, which is what a\n * player needs; the number itself is what the cartridge says, and the two answer different\n * questions. Only on a head, and only where the channel has a volume at all: the triangle has\n * none, so its notes carry nothing.\n */\n volume?: number;\n /** Its beam runs across the bar line — see `crossBarRuns`. */\n across?: 'start' | 'join';\n /** Beams are grouped by this number rather than by the beat — see `accentBeamGroups`. */\n beamGroup?: number;\n};\n\n/**\n * How much louder than BOTH its neighbours a note has to start to be written as\n * accented, in nibble steps.\n *\n * Three is the step the tracks themselves use: the driver holds a level and\n * drops or lifts the next note by 3 — ragnarok's canyon, bar 25, alternates 4\n * and 7 through the bar, and 7 against 4 is what the ear hears as the accent.\n */\nexport const ACCENT_STEP = 3;\n\n/**\n * The notes a voice leans on: louder than the note before it by `ACCENT_STEP`,\n * no quieter than the note after it, and NOT on a beat.\n *\n * Off the beat is the whole point. The driver moves the volume constantly, and\n * a mark on every rise would put one under a third of the heads of some tracks\n * while saying nothing a reader cannot see from the dynamics. What a reader\n * cannot see is a voice that leans between the beats: ragnarok's canyon, bar 25,\n * plays sixteenths at 9 9 7 7 4 7 4 7 4 2 7 7 4 7 4 9 — every beat of the bar\n * but the first is a 4, and the 7s fall in the gaps. On paper that is an even\n * run of sixteenths; in the ears it is a syncopation, and accents are what make\n * the two agree.\n *\n * Read on the notes as the staff has them — after `voicePhase` has taken out a\n * channel's authored delay — or a voice written a tick late would count as\n * off the beat throughout.\n */\nexport function accentedStarts(\n notes: readonly ScoreNote[],\n beat = TICKS_PER_QUARTER,\n step = ACCENT_STEP\n): Set<number> {\n const sounded = [...notes]\n .filter((note): note is ScoreNote & { volume: number } => note.volume !== undefined)\n .sort((a, b) => a.start - b.start);\n const starts = new Set<number>();\n sounded.forEach((note, index) => {\n const before = sounded[index - 1];\n const after = sounded[index + 1];\n if (!before || !after) return;\n if (note.start % beat === 0) return;\n if (note.volume - before.volume < step) return;\n if (note.volume < after.volume) return;\n starts.add(note.start);\n });\n return starts;\n}\n\n/**\n * Beam groups that follow the ACCENTS rather than the beat, for a passage that\n * is written in one pulse and played in another.\n *\n * Ragnarok's canyon from bar 25 is the case, and it is a case, not a rule:\n * beats 2, 3 and 4 of every bar sit at volume 4 while the notes between them\n * are at 7, so beaming by the quarter draws four even groups over a bar whose\n * weight lands in five uneven ones — 3 2 3 3 2, each beginning on a note the\n * ROM leans on. Tried as a general rule over the cartridge it made beams of 14,\n * 16 and 32 heads elsewhere (wookie hole, Arctic Caverns), which is why the\n * passage asks for it by tick.\n *\n * Numbers a group per head from `from` on: a new one at every accent, and one\n * after the bar's LOUDEST head when what follows is quieter — the figure's own\n * peak, which ends a group rather than joining the run under it. Bar 25 is the\n * one that needs the second rule: bars 26 to 28 open on the two heads a beam\n * has already carried over the bar line, while 25 opens on the same pair with\n * nothing to carry them, and without it they were swallowed by the five heads\n * up to the first accent.\n */\nexport function accentBeamGroups(\n bars: ScoreItem[][],\n /** The passage the rule covers, in the staff's ticks: `[from, to)`. */\n { from, to }: { from: number; to: number },\n /** Each head's volume by its start tick — the levels the groups are read from. */\n levels: ReadonlyMap<number, number>\n): ScoreItem[][] {\n let group = 0;\n return bars.map((items) => {\n const within = (item: ScoreItem) => item.start >= from && item.start < to;\n const heads = items.filter((item) => item.midi !== null && within(item));\n /*\n * A voice with nothing to lean on keeps the beat. The rule has cuts only where a voice pushes,\n * and the triangle holds one level right through this passage: numbered along with the others\n * it had no cut at all, and its bar came out under a single beam from end to end.\n */\n if (!heads.some((item) => item.accent)) return items;\n const peak = Math.max(...heads.map((item) => levels.get(item.start) ?? 0), 0);\n let previous: number | null = null;\n return items.map((item) => {\n if (!within(item) || item.midi === null) return item;\n const level = levels.get(item.start);\n if (item.accent || (previous !== null && previous >= peak && (level ?? 0) < previous))\n group++;\n previous = level ?? previous;\n return { ...item, beamGroup: group };\n });\n });\n}\n\n/** The most notes a beam is carried across a bar line onto — the figure, and no more. */\nexport const CROSS_BAR_RUN = 4;\n\n/**\n * Figures a bar line cuts in half: a run that starts on the bar's last note and\n * carries the same level into the next bar.\n *\n * Beams do not cross bar lines, and for good reason — the bar line is what a\n * reader counts from. The exception earns itself when the figure is plainly one\n * gesture and the bar line falls inside it: ragnarok's canyon, bars 25 to 28,\n * ends each bar on an accented E3 and opens the next with D3 E3 at the same\n * level 9, the run around it sitting at 7 and 4. Three heads, one gesture, and\n * written bar by bar it reads as a stray sixteenth and a pair.\n *\n * Narrow on purpose: the last note must be ACCENTED (see `accentedStarts`), the\n * run must be unbroken, every note must hold the same volume, and it stops after\n * `CROSS_BAR_RUN` heads. Over the whole cartridge that is three places, all of\n * them this figure. Loosened to \"the level holds\" alone it caught 148, some of\n * them 240 notes long — a beam over half a track.\n *\n * Returns the start tick of each note in a crossing run, mapped to its part in\n * it: the `start` is the note the beam leaves the bar on, the `join`s are the\n * heads it reaches on the other side.\n */\nexport function crossBarRuns(\n notes: readonly ScoreNote[],\n grid: BarGrid,\n accents: ReadonlySet<number> = accentedStarts(notes)\n): Map<number, 'start' | 'join'> {\n const sounded = [...notes]\n .filter((note): note is ScoreNote & { volume: number } => note.volume !== undefined)\n .sort((a, b) => a.start - b.start);\n const runs = new Map<number, 'start' | 'join'>();\n sounded.forEach((note, index) => {\n if (note.ticks >= TICKS_PER_QUARTER || !accents.has(note.start)) return;\n const next = sounded[index + 1];\n if (!next || next.start !== note.start + note.ticks) return;\n if (barAt(grid, next.start) === barAt(grid, note.start)) return;\n if (next.volume !== note.volume) return;\n const chain: ScoreNote[] = [note];\n for (let at = index + 1; at < sounded.length && chain.length < CROSS_BAR_RUN; at++) {\n const head = sounded[at];\n const before = chain[chain.length - 1];\n if (head.start !== before.start + before.ticks || head.volume !== note.volume) break;\n chain.push(head);\n }\n if (chain.length < 2) return;\n runs.set(note.start, 'start');\n for (const head of chain.slice(1)) runs.set(head.start, 'join');\n });\n return runs;\n}\n\n/**\n * Whether an effect is drawn along its note — and so has to carry on where the note does. Every\n * vibrato is: its curve, or its wave, which ran out at the end of a line and was not taken up again\n * on the next one (Shikinjou's Title, triangle, a D held over the line's end).\n */\nexport function drawnAlong(effect: PitchEffect, measureTicks = MEASURE_TICKS): boolean {\n return (\n effect.kind === 'slide' ||\n (effect.kind === 'bend' && effect.ticks >= measureTicks) ||\n effect.kind === 'vibrato'\n );\n}\n\n/**\n * Puts what each note carries on its HEAD — the first piece of it, never a\n * piece tied on after a bar line, which would mark one note twice: its effect,\n * grace notes, accent, echo, level, and its part in a beam across the bar line.\n * The pieces tied on after a head get a `carry` instead, when the effect is\n * drawn along the note.\n *\n * In place, and in one walk: the bars are the ones `buildScore` has just made,\n * and copying every head once for each thing it might carry was a fifth of the\n * time a score took to work out. The marks go on in the order above, so a\n * head's fields read the same whichever of them it has.\n */\nfunction attachHeads(\n bars: StaffItem[][],\n marks: {\n effects?: ReadonlyMap<number, PitchEffect>;\n graces?: ReadonlyMap<number, readonly number[]>;\n accents?: ReadonlySet<number>;\n echoes?: ReadonlySet<number>;\n levels?: ReadonlyMap<number, number>;\n across?: ReadonlyMap<number, 'start' | 'join'>;\n staccatos?: ReadonlySet<number>;\n chords?: ReadonlyMap<number, readonly number[]>;\n }\n): ScoreItem[][] {\n const effects = marks.effects?.size ? marks.effects : null;\n const graces = marks.graces?.size ? marks.graces : null;\n const accents = marks.accents?.size ? marks.accents : null;\n const echoes = marks.echoes?.size ? marks.echoes : null;\n const levels = marks.levels?.size ? marks.levels : null;\n const across = marks.across?.size ? marks.across : null;\n const staccatos = marks.staccatos?.size ? marks.staccatos : null;\n const chords = marks.chords?.size ? marks.chords : null;\n if (!effects && !graces && !accents && !echoes && !levels && !across && !staccatos && !chords) {\n return bars;\n }\n let active: EffectCarry | null = null;\n for (const items of bars) {\n for (const plain of items) {\n const item = plain as ScoreItem;\n const head = item.midi !== null && !item.tieStop;\n if (effects) {\n if (head && effects.has(item.start)) {\n const effect = effects.get(item.start)!;\n active = drawnAlong(effect) ? { start: item.start, midi: item.midi!, effect } : null;\n item.effect = effect;\n } else if (active && item.tieStop && item.midi === active.midi) {\n item.carry = active;\n } else if (!item.tieStop) {\n active = null;\n }\n }\n if (!head) continue;\n if (graces?.has(item.start)) item.grace = graces.get(item.start);\n if (accents?.has(item.start)) item.accent = true;\n if (echoes?.has(item.start)) item.echo = true;\n if (levels?.has(item.start)) item.volume = levels.get(item.start);\n if (across?.has(item.start)) item.across = across.get(item.start);\n if (staccatos?.has(item.start)) item.staccato = true;\n if (chords?.has(item.start)) item.chord = chords.get(item.start);\n }\n }\n return bars;\n}\n\n/** Each note's own APU level by where it starts — what `attachHeads` puts on its head. */\nfunction levelsOf(notes: readonly { start: number; volume?: number }[]): Map<number, number> {\n const levels = new Map<number, number>();\n for (const note of notes) if (note.volume !== undefined) levels.set(note.start, note.volume);\n return levels;\n}\n\n/** A noise hit: when, for how long, and which `$400E` period. */\nexport interface ScoreHit {\n start: number;\n ticks: number;\n period: number;\n /** The APU level the hit starts at, 0..15 — see `ScoreItem.volume`. */\n volume?: number;\n}\n\nexport type ScoreStaveKind = 'treble' | 'bass' | 'percussion';\n\nexport interface ScoreStave {\n partId: string;\n kind: ScoreStaveKind;\n /**\n * One list of items per bar. Filled to the bar line — except on a grand\n * staff, where it is only what stands on THIS stave, for the layout.\n */\n bars: ScoreItem[][];\n /** On a grand staff's upper stave: the part's whole voice, filled to the bar line, drawn across both. */\n voiceBars?: ScoreItem[][];\n /** On a grand staff's lower stave: its notes belong to the voice of the stave above. */\n follows?: boolean;\n}\n\nexport interface ScoreModel {\n /** Ticks added to the piece's clock to get the score's — see `staffShift`. */\n shift: number;\n /** Where the bar lines fall: the metre, and the opening bar's own length. */\n grid: BarGrid;\n barCount: number;\n staves: ScoreStave[];\n /** Each part's marks, in the SCORE's ticks. */\n dynamics: Record<string, DynamicMark[]>;\n /**\n * Each part's own delay taken out (`voicePhase`), in ticks: its notes sit\n * this much EARLIER on the staff than on the piece's clock. Anything that\n * compares a staff tick with the piece's — hiding what has not been read\n * yet — has to take it out too.\n */\n phases: Record<string, number>;\n}\n\n/** Where a piece changes key: the tick the new key starts on, and its VexFlow name. */\nexport interface KeyChange {\n /** In the PIECE's ticks, as the ROM holds them. */\n tick: number;\n key: string;\n}\n\n/**\n * The key each bar of a score is written in.\n *\n * A change takes effect from the bar its tick falls in — the tick is moved onto\n * the staff's clock by `shift` first — so it stays with the music when the bar\n * line or the metre is read differently. Volkmire's Inferno Race turns from D\n * minor to D major on tick 870, which is bar 29 of its 2/4 score.\n */\nexport function barKeys(\n barCount: number,\n shift: number,\n grid: BarGrid,\n opening: string,\n changes: readonly KeyChange[] = []\n): string[] {\n const names = Array.from({ length: barCount }, () => opening);\n for (const change of changes) {\n const from = Math.max(0, barAt(grid, change.tick + shift));\n for (let bar = from; bar < names.length; bar++) names[bar] = change.key;\n }\n return names;\n}\n\n/** The part id the percussion staff carries. */\nexport const DRUMS_PART = 'drums';\n\n/** A noise hit longer than this (a half note) is let ring, not struck — see `ScoreItem.letRing`. */\nexport const LET_RING_TICKS = TICKS_PER_QUARTER * 2;\n\n/** How a score is barred and read — everything `buildScore` takes beyond the notes. */\nexport interface ScoreOptions {\n /** The tick the bar lines are counted from. Default 0. */\n offset?: number;\n /** Ticks in a bar: 64 is 4/4, 32 is 2/4. Default `MEASURE_TICKS`. */\n measureTicks?: number;\n /**\n * Write the pickup as part of the opening bar rather than in a bar of its own.\n *\n * The music then starts on the score's first tick, and the opening bar is as\n * much longer than the metre as the pickup is — one bar of 19/32 in front of\n * Volkmire's Inferno Race's 2/4, instead of a bar of rests with the run in it.\n * `false`, the default, is the anacrusis: a short opening bar, and a closing bar short by as\n * much. All three readings, `padded` among them, are in `Pickup`.\n */\n mergePickup?: boolean | Pickup;\n /**\n * The passage read by its accents: the only place accents are marked (`accentedStarts`), and\n * where the beams follow them rather than the beat (`accentBeamGroups`). None given, no accents.\n * In the PIECE's ticks, like everything a caller gives; `shift` moves it onto the staff's clock.\n */\n accentBeams?: { from: number; to: number };\n /** Bars later in the piece with a length of their own — see `BarGrid`. */\n oddBars?: readonly OddBar[];\n /**\n * Take a part's own delay of up to `MAX_PHASE` ticks out (`voicePhase`). Default true: a sound\n * driver delays a channel a tick or two on purpose, and the staff writes it on the beat. Music\n * that is already on its beat — a MIDI file — wants it off, or a voice is moved off the beat it\n * keeps.\n */\n alignVoices?: boolean;\n}\n\n/**\n * The whole score, worked out once.\n *\n * `options.offset` is the tick the bar lines are counted from and\n * `options.measureTicks` the length of a bar; any other notation view of the\n * same piece should use the same two, so they all bar the music the same way.\n */\n/**\n * An anacrusis is paid back at the end: a piece that opens with a short bar and stops short of a\n * whole closing bar by exactly as much gets its closing bar that long, so the two make one bar\n * between them — Aerial Bar's two eighths in front, four at the end. A closing bar of any other\n * length is left whole, rests and all.\n */\nexport function withClosingBar(grid: BarGrid, end: number, reading: Pickup): BarGrid {\n if (reading !== 'anacrusis' || grid.firstBarTicks >= grid.measureTicks) return grid;\n const last = barCountOf(grid, end) - 1;\n if (last < 1 || grid.oddBars?.some((odd) => odd.bar === last)) return grid;\n const tail = end - barStartOf(grid, last);\n if (tail <= 0 || tail + grid.firstBarTicks !== barTicksOf(grid, last)) return grid;\n return barGrid(grid.measureTicks, grid.firstBarTicks, [...(grid.oddBars ?? []), { bar: last, ticks: tail }]);\n}\n\nexport function buildScore(\n parts: readonly {\n id: string;\n notes: readonly ScoreNote[];\n /** Which staves, when the caller decides rather than the notes (`partStaves`). */\n staves?: readonly ('treble' | 'bass')[];\n }[],\n drums: readonly ScoreHit[],\n totalTicks: number,\n {\n offset = 0,\n measureTicks = MEASURE_TICKS,\n mergePickup = false,\n accentBeams,\n oddBars = [],\n alignVoices = true,\n }: ScoreOptions = {}\n): ScoreModel {\n const barred = barring(offset, measureTicks, mergePickup, oddBars);\n const { shift } = barred;\n const end = totalTicks + shift;\n const grid = withClosingBar(barred.grid, end, pickupOf(mergePickup));\n const barCount = barCountOf(grid, end);\n const barsOf = (notes: readonly TickNote[]) =>\n staffMeasures(staffItems(notes, end, grid), end, grid).map((bar) => bar.items);\n const phases: Record<string, number> = {};\n const moved = <T extends TickNote>(notes: readonly T[], id?: string): T[] => {\n const phase = alignVoices && notes.length > 0 ? voicePhase(notes, offset, measureTicks) : 0;\n if (id !== undefined) phases[id] = phase;\n return shiftNotes(notes, shift - phase);\n };\n\n const staves: ScoreStave[] = [];\n const dynamics: Record<string, DynamicMark[]> = {};\n\n for (const part of parts) {\n /*\n * Notes struck together are one head with a chord on its stem: the highest — the line a\n * reader follows — is the head the rhythm, the staff and the marks are read from, and it\n * holds as long as the longest of them. A part with one note at a time is untouched.\n */\n const together = new Map<number, ScoreNote[]>();\n for (const note of part.notes)\n together.set(note.start, [...(together.get(note.start) ?? []), note]);\n const groups = [...together.values()];\n const leads = groups.map((group) =>\n group.length === 1\n ? group[0]\n : {\n ...group.reduce((top, note) => (note.midi > top.midi ? note : top)),\n ticks: Math.max(...group.map((note) => note.ticks)),\n }\n );\n const notes = moved(leads, part.id);\n const pitchChords = new Map<number, number[]>();\n groups.forEach((group, index) => {\n if (group.length < 2) return;\n const others = [...new Set(group.map((note) => note.midi))]\n .filter((midi) => midi !== leads[index].midi)\n .sort((a, b) => a - b);\n if (others.length) pitchChords.set(notes[index].start, others);\n });\n const range = pitchChords.size\n ? [...notes, ...[...pitchChords.values()].flat().map((midi) => ({ midi }))]\n : notes;\n const kinds = part.staves ? [...part.staves] : partStaves(range);\n // Read over the whole part: the note after a slide may be on the other staff.\n const effects = effectsOf(notes);\n /*\n * Accents only inside the passage read by its accents (`accentBeams`) — a\n * reading by ear, made for ragnarok's canyon, bars 25 to 28. Let loose over\n * the cartridge the rule marked every loud note off the beat, and Arctic\n * Caverns' echo — every second note far quieter than the one before, an\n * imitation of an echo — came out as a column of accents it does not have.\n */\n const accents = accentBeams\n ? new Set(\n [...accentedStarts(notes)].filter(\n (start) => start >= accentBeams.from + shift && start < accentBeams.to + shift\n )\n )\n : new Set<number>();\n const across = crossBarRuns(notes, grid, accents);\n const heads = () => {\n const written = attachHeads(barsOf(notes), {\n effects,\n graces: new Map(\n notes.filter((note) => note.grace?.length).map((note) => [note.start, note.grace!])\n ),\n accents,\n echoes: new Set(notes.filter((note) => note.echo).map((note) => note.start)),\n levels: levelsOf(notes),\n across,\n staccatos: new Set(notes.filter((note) => note.staccato).map((note) => note.start)),\n chords: pitchChords,\n });\n if (!accentBeams) return written;\n return accentBeamGroups(\n written,\n { from: accentBeams.from + shift, to: accentBeams.to + shift },\n levelsOf(notes)\n );\n };\n if (kinds.length === 1) {\n staves.push({ partId: part.id, kind: kinds[0], bars: heads() });\n } else {\n const voice = crossStaffVoice(heads());\n const on = (staff: 'treble' | 'bass') =>\n voice.map((items) => items.filter((item) => item.staff === staff));\n staves.push({\n partId: part.id,\n kind: 'treble',\n bars: on('treble'),\n voiceBars: voice,\n });\n staves.push({\n partId: part.id,\n kind: 'bass',\n bars: on('bass'),\n follows: true,\n });\n }\n const loud = notes.filter(\n (note): note is ScoreNote & { volume: number } => note.volume !== undefined\n );\n dynamics[part.id] = dynamicMarks(loud);\n }\n\n if (drums.length > 0) {\n /*\n * Hits at the same moment are one chord: the longest is the head the staff's rhythm is\n * written from, the others stand on its stem. A staff of one voice wrote them one after\n * another, and every hat over a kick pushed the rest of the bar a value late.\n */\n const groups = new Map<number, ScoreHit[]>();\n for (const hit of drums) groups.set(hit.start, [...(groups.get(hit.start) ?? []), hit]);\n const leads = [...groups.values()].map((group) =>\n group.reduce((longest, hit) => (hit.ticks > longest.ticks ? hit : longest))\n );\n const others = [...groups.values()].map((group, index) => [\n ...new Set(\n group\n .filter((hit) => hit !== leads[index])\n .map((hit) => hit.period & 0x0f)\n .filter((period) => period !== (leads[index].period & 0x0f))\n ),\n ]);\n const hits = moved(\n leads.map((hit) => ({\n start: hit.start,\n ticks: hit.ticks,\n midi: hit.period & 0x0f,\n volume: hit.volume,\n }))\n );\n const chords = new Map<number, number[]>();\n hits.forEach((hit, index) => {\n if (others[index]?.length) chords.set(hit.start, others[index]);\n });\n /*\n * A drum is struck once. What is left of its slot after the first head —\n * the rest of a long value, or the part carried over a bar line — is\n * written as rest: tied on a percussion staff it reads as a roll, and as a\n * second head it reads as a second hit.\n *\n * Not so a noise that is let ring: Circus Charlie's applause is one hit of\n * 136 ticks fading 11 → 2, and rests after its head said the hall fell\n * silent while it was still heard. A hit longer than `LET_RING_TICKS` keeps\n * its whole length, tied over the bar lines, and its head is marked \"l.v.\".\n */\n // The hit an item belongs to is the last one struck at or before it.\n const struck = [...hits].sort((a, b) => a.start - b.start);\n const rings = (item: StaffItem) => {\n if (item.midi === null) return false;\n let hit: (typeof struck)[number] | undefined;\n for (const candidate of struck) if (candidate.start <= item.start) hit = candidate;\n return !!hit && hit.ticks > LET_RING_TICKS && item.start < hit.start + hit.ticks;\n };\n const bars = attachHeads(\n barsOf(hits).map((items) =>\n items.map((item): StaffItem =>\n rings(item)\n ? ({ ...item, ...(item.tieStop ? {} : { letRing: true }) } as ScoreItem)\n : item.tieStop\n ? { ...item, midi: null, tieStart: false, tieStop: false }\n : { ...item, tieStart: false }\n )\n ),\n { levels: levelsOf(hits), chords }\n );\n staves.push({ partId: DRUMS_PART, kind: 'percussion', bars });\n }\n\n return { shift, grid, barCount, staves, dynamics, phases };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xromdev/notation",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.7",
|
|
4
4
|
"description": "Notes in ticks, read as a score: note values, ties, tuplets, bar lines, key spelling, clefs, grand staff and dynamics — no DOM, no renderer.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Oleksandr Maksymov",
|