@nodelyra/not-angka 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (251) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +38 -2
  3. package/THIRD_PARTY.md +24 -0
  4. package/dist/esm/cursor/activeChord.d.ts +12 -0
  5. package/dist/esm/cursor/activeChord.js +36 -0
  6. package/dist/esm/cursor/beatDot.d.ts +30 -0
  7. package/dist/esm/cursor/beatDot.js +49 -0
  8. package/dist/esm/cursor/drawnTop.d.ts +9 -0
  9. package/dist/esm/cursor/drawnTop.js +16 -0
  10. package/dist/esm/cursor/pageBoxes.d.ts +28 -0
  11. package/dist/esm/cursor/pageBoxes.js +75 -0
  12. package/dist/esm/cursor/playbackCursor.d.ts +25 -0
  13. package/dist/esm/cursor/playbackCursor.js +42 -0
  14. package/dist/esm/cursor/playingStyle.d.ts +16 -0
  15. package/dist/esm/cursor/playingStyle.js +34 -0
  16. package/dist/esm/cursor/playingTones.d.ts +8 -0
  17. package/dist/esm/cursor/playingTones.js +16 -0
  18. package/dist/esm/cursor/target.d.ts +47 -0
  19. package/dist/esm/cursor/target.js +63 -0
  20. package/dist/esm/export/pageText.d.ts +8 -0
  21. package/dist/esm/export/pageText.js +80 -0
  22. package/dist/esm/export/svgExport.d.ts +46 -0
  23. package/dist/esm/export/svgExport.js +88 -0
  24. package/dist/esm/geometry/metrics.d.ts +42 -0
  25. package/dist/esm/geometry/metrics.js +52 -0
  26. package/dist/esm/geometry/pageSetup.d.ts +61 -0
  27. package/dist/esm/geometry/pageSetup.js +85 -0
  28. package/dist/esm/geometry/paper.d.ts +16 -0
  29. package/dist/esm/geometry/paper.js +16 -0
  30. package/dist/esm/index.d.ts +35 -0
  31. package/dist/esm/index.js +23 -0
  32. package/dist/esm/layout/LayoutEngine.d.ts +64 -0
  33. package/dist/esm/layout/LayoutEngine.js +92 -0
  34. package/dist/esm/layout/arcs.d.ts +20 -0
  35. package/dist/esm/layout/arcs.js +53 -0
  36. package/dist/esm/layout/barlineShapes.d.ts +52 -0
  37. package/dist/esm/layout/barlineShapes.js +71 -0
  38. package/dist/esm/layout/directions.d.ts +48 -0
  39. package/dist/esm/layout/directions.js +122 -0
  40. package/dist/esm/layout/elementBoxes.d.ts +17 -0
  41. package/dist/esm/layout/elementBoxes.js +72 -0
  42. package/dist/esm/layout/floating.d.ts +29 -0
  43. package/dist/esm/layout/floating.js +39 -0
  44. package/dist/esm/layout/keyMarks.d.ts +26 -0
  45. package/dist/esm/layout/keyMarks.js +30 -0
  46. package/dist/esm/layout/lyricAlign.d.ts +6 -0
  47. package/dist/esm/layout/lyricAlign.js +15 -0
  48. package/dist/esm/layout/lyricWords.d.ts +13 -0
  49. package/dist/esm/layout/lyricWords.js +27 -0
  50. package/dist/esm/layout/lyricsLayout.d.ts +55 -0
  51. package/dist/esm/layout/lyricsLayout.js +122 -0
  52. package/dist/esm/layout/markings.d.ts +97 -0
  53. package/dist/esm/layout/markings.js +150 -0
  54. package/dist/esm/layout/measurePlan.d.ts +74 -0
  55. package/dist/esm/layout/measurePlan.js +232 -0
  56. package/dist/esm/layout/measureSegments.d.ts +24 -0
  57. package/dist/esm/layout/measureSegments.js +64 -0
  58. package/dist/esm/layout/notationMetrics.d.ts +110 -0
  59. package/dist/esm/layout/notationMetrics.js +122 -0
  60. package/dist/esm/layout/systemBreaking.d.ts +59 -0
  61. package/dist/esm/layout/systemBreaking.js +137 -0
  62. package/dist/esm/layout/systemLayout.d.ts +138 -0
  63. package/dist/esm/layout/systemLayout.js +266 -0
  64. package/dist/esm/layout/tupletSpacing.d.ts +9 -0
  65. package/dist/esm/layout/tupletSpacing.js +33 -0
  66. package/dist/esm/layout/tuplets.d.ts +30 -0
  67. package/dist/esm/layout/tuplets.js +39 -0
  68. package/dist/esm/model/hiddenParts.d.ts +23 -0
  69. package/dist/esm/model/hiddenParts.js +39 -0
  70. package/dist/esm/model/locate.d.ts +18 -0
  71. package/dist/esm/model/locate.js +31 -0
  72. package/dist/esm/model/lowVoices.d.ts +9 -0
  73. package/dist/esm/model/lowVoices.js +20 -0
  74. package/dist/esm/model/partColors.d.ts +13 -0
  75. package/dist/esm/model/partColors.js +10 -0
  76. package/dist/esm/model/partSpan.d.ts +25 -0
  77. package/dist/esm/model/partSpan.js +49 -0
  78. package/dist/esm/model/rowPresence.d.ts +14 -0
  79. package/dist/esm/model/rowPresence.js +19 -0
  80. package/dist/esm/model/sharedLyrics.d.ts +23 -0
  81. package/dist/esm/model/sharedLyrics.js +68 -0
  82. package/dist/esm/model/textBars.d.ts +12 -0
  83. package/dist/esm/model/textBars.js +21 -0
  84. package/dist/esm/model/tickRanges.d.ts +22 -0
  85. package/dist/esm/model/tickRanges.js +34 -0
  86. package/dist/esm/model/unisons.d.ts +69 -0
  87. package/dist/esm/model/unisons.js +181 -0
  88. package/dist/esm/notation/chords.d.ts +12 -0
  89. package/dist/esm/notation/chords.js +29 -0
  90. package/dist/esm/notation/elision.d.ts +24 -0
  91. package/dist/esm/notation/elision.js +47 -0
  92. package/dist/esm/notation/keys.d.ts +50 -0
  93. package/dist/esm/notation/keys.js +59 -0
  94. package/dist/esm/notation/lyricAlign.d.ts +7 -0
  95. package/dist/esm/notation/lyricAlign.js +15 -0
  96. package/dist/esm/notation/navigation.d.ts +3 -0
  97. package/dist/esm/notation/navigation.js +5 -0
  98. package/dist/esm/notation/pitch.d.ts +39 -0
  99. package/dist/esm/notation/pitch.js +74 -0
  100. package/dist/esm/notation/pitchName.d.ts +2 -0
  101. package/dist/esm/notation/pitchName.js +3 -0
  102. package/dist/esm/notation/profile.d.ts +35 -0
  103. package/dist/esm/notation/profile.js +16 -0
  104. package/dist/esm/notation/rhythm.d.ts +59 -0
  105. package/dist/esm/notation/rhythm.js +116 -0
  106. package/dist/esm/notation/time.d.ts +98 -0
  107. package/dist/esm/notation/time.js +85 -0
  108. package/dist/esm/performance/compilePerformance.d.ts +7 -0
  109. package/dist/esm/performance/compilePerformance.js +8 -0
  110. package/dist/esm/performance/dynamics.d.ts +6 -0
  111. package/dist/esm/performance/dynamics.js +78 -0
  112. package/dist/esm/performance/model.d.ts +56 -0
  113. package/dist/esm/performance/model.js +1 -0
  114. package/dist/esm/performance/playOrder.d.ts +16 -0
  115. package/dist/esm/performance/playOrder.js +64 -0
  116. package/dist/esm/performance/readScore.d.ts +4 -0
  117. package/dist/esm/performance/readScore.js +58 -0
  118. package/dist/esm/performance/timeline.d.ts +10 -0
  119. package/dist/esm/performance/timeline.js +144 -0
  120. package/dist/esm/playback/audioOutput.d.ts +46 -0
  121. package/dist/esm/playback/audioOutput.js +106 -0
  122. package/dist/esm/playback/clock.d.ts +16 -0
  123. package/dist/esm/playback/clock.js +44 -0
  124. package/dist/esm/playback/createPlayerStore.d.ts +79 -0
  125. package/dist/esm/playback/createPlayerStore.js +135 -0
  126. package/dist/esm/playback/cues.d.ts +34 -0
  127. package/dist/esm/playback/cues.js +52 -0
  128. package/dist/esm/playback/errors.d.ts +6 -0
  129. package/dist/esm/playback/errors.js +6 -0
  130. package/dist/esm/playback/metronome.d.ts +13 -0
  131. package/dist/esm/playback/metronome.js +15 -0
  132. package/dist/esm/playback/mix.d.ts +9 -0
  133. package/dist/esm/playback/mix.js +8 -0
  134. package/dist/esm/playback/pass.d.ts +27 -0
  135. package/dist/esm/playback/pass.js +36 -0
  136. package/dist/esm/playback/schedule.d.ts +7 -0
  137. package/dist/esm/playback/schedule.js +12 -0
  138. package/dist/esm/playback/session.d.ts +46 -0
  139. package/dist/esm/playback/session.js +107 -0
  140. package/dist/esm/playback/source.d.ts +6 -0
  141. package/dist/esm/playback/source.js +1 -0
  142. package/dist/esm/playback/start.d.ts +28 -0
  143. package/dist/esm/playback/start.js +38 -0
  144. package/dist/esm/playback/timing.d.ts +14 -0
  145. package/dist/esm/playback/timing.js +11 -0
  146. package/dist/esm/playback/types.d.ts +60 -0
  147. package/dist/esm/playback/types.js +1 -0
  148. package/dist/esm/playback/volume.d.ts +12 -0
  149. package/dist/esm/playback/volume.js +8 -0
  150. package/dist/esm/player/ControlBar.d.ts +22 -0
  151. package/dist/esm/player/ControlBar.js +77 -0
  152. package/dist/esm/player/CursorPainter.d.ts +17 -0
  153. package/dist/esm/player/CursorPainter.js +53 -0
  154. package/dist/esm/player/InfoLine.d.ts +6 -0
  155. package/dist/esm/player/InfoLine.js +23 -0
  156. package/dist/esm/player/PageView.d.ts +10 -0
  157. package/dist/esm/player/PageView.js +16 -0
  158. package/dist/esm/player/actions.d.ts +24 -0
  159. package/dist/esm/player/actions.js +26 -0
  160. package/dist/esm/player/balanceSystems.d.ts +8 -0
  161. package/dist/esm/player/balanceSystems.js +18 -0
  162. package/dist/esm/player/createExcerptPlayer.d.ts +33 -0
  163. package/dist/esm/player/createExcerptPlayer.js +169 -0
  164. package/dist/esm/player/createScorePlayer.d.ts +24 -0
  165. package/dist/esm/player/createScorePlayer.js +118 -0
  166. package/dist/esm/player/dom.d.ts +6 -0
  167. package/dist/esm/player/dom.js +15 -0
  168. package/dist/esm/player/embeddedFonts.d.ts +1 -0
  169. package/dist/esm/player/embeddedFonts.js +3 -0
  170. package/dist/esm/player/exclusivePlayback.d.ts +10 -0
  171. package/dist/esm/player/exclusivePlayback.js +13 -0
  172. package/dist/esm/player/followCursor.d.ts +5 -0
  173. package/dist/esm/player/followCursor.js +16 -0
  174. package/dist/esm/player/icons.d.ts +7 -0
  175. package/dist/esm/player/icons.js +9 -0
  176. package/dist/esm/player/injectFonts.d.ts +8 -0
  177. package/dist/esm/player/injectFonts.js +19 -0
  178. package/dist/esm/player/loadExcerpt.d.ts +21 -0
  179. package/dist/esm/player/loadExcerpt.js +123 -0
  180. package/dist/esm/player/loadScore.d.ts +12 -0
  181. package/dist/esm/player/loadScore.js +12 -0
  182. package/dist/esm/player/mountExcerpts.d.ts +30 -0
  183. package/dist/esm/player/mountExcerpts.js +109 -0
  184. package/dist/esm/player/playhead.d.ts +12 -0
  185. package/dist/esm/player/playhead.js +14 -0
  186. package/dist/esm/player/shadowStyles.d.ts +5 -0
  187. package/dist/esm/player/shadowStyles.js +23 -0
  188. package/dist/esm/player/staticSvg.d.ts +7 -0
  189. package/dist/esm/player/staticSvg.js +10 -0
  190. package/dist/esm/player/styles.d.ts +28 -0
  191. package/dist/esm/player/styles.js +98 -0
  192. package/dist/esm/player/theme.d.ts +8 -0
  193. package/dist/esm/player/theme.js +13 -0
  194. package/dist/esm/player/types.d.ts +76 -0
  195. package/dist/esm/player/types.js +12 -0
  196. package/dist/esm/rendering/SystemRenderer.d.ts +6 -0
  197. package/dist/esm/rendering/SystemRenderer.js +58 -0
  198. package/dist/esm/rendering/accidentalRenderer.d.ts +4 -0
  199. package/dist/esm/rendering/accidentalRenderer.js +41 -0
  200. package/dist/esm/rendering/arcRenderer.d.ts +9 -0
  201. package/dist/esm/rendering/arcRenderer.js +32 -0
  202. package/dist/esm/rendering/barlineRenderer.d.ts +8 -0
  203. package/dist/esm/rendering/barlineRenderer.js +59 -0
  204. package/dist/esm/rendering/directionRenderer.d.ts +4 -0
  205. package/dist/esm/rendering/directionRenderer.js +50 -0
  206. package/dist/esm/rendering/durationLineRenderer.d.ts +9 -0
  207. package/dist/esm/rendering/durationLineRenderer.js +27 -0
  208. package/dist/esm/rendering/dynamicGlyphs.d.ts +25 -0
  209. package/dist/esm/rendering/dynamicGlyphs.js +56 -0
  210. package/dist/esm/rendering/frameRenderer.d.ts +17 -0
  211. package/dist/esm/rendering/frameRenderer.js +252 -0
  212. package/dist/esm/rendering/keyMarkRenderer.d.ts +8 -0
  213. package/dist/esm/rendering/keyMarkRenderer.js +57 -0
  214. package/dist/esm/rendering/lyricsRenderer.d.ts +4 -0
  215. package/dist/esm/rendering/lyricsRenderer.js +44 -0
  216. package/dist/esm/rendering/primitives.d.ts +64 -0
  217. package/dist/esm/rendering/primitives.js +1 -0
  218. package/dist/esm/rendering/sliceRenderer.d.ts +19 -0
  219. package/dist/esm/rendering/sliceRenderer.js +79 -0
  220. package/dist/esm/rendering/textBarRenderer.d.ts +8 -0
  221. package/dist/esm/rendering/textBarRenderer.js +28 -0
  222. package/dist/esm/rendering/tupletRenderer.d.ts +7 -0
  223. package/dist/esm/rendering/tupletRenderer.js +42 -0
  224. package/dist/esm/schema/normalize.d.ts +14 -0
  225. package/dist/esm/schema/normalize.js +123 -0
  226. package/dist/esm/schema/pageMeta.d.ts +11 -0
  227. package/dist/esm/schema/pageMeta.js +1 -0
  228. package/dist/esm/schema/scoreJson.d.ts +59 -0
  229. package/dist/esm/schema/scoreJson.js +1 -0
  230. package/dist/esm/schema/scoreView.d.ts +16 -0
  231. package/dist/esm/schema/scoreView.js +24 -0
  232. package/dist/esm/schema/types.d.ts +339 -0
  233. package/dist/esm/schema/types.js +1 -0
  234. package/dist/esm/text/creditLines.d.ts +12 -0
  235. package/dist/esm/text/creditLines.js +11 -0
  236. package/dist/esm/text/fonts.d.ts +50 -0
  237. package/dist/esm/text/fonts.js +98 -0
  238. package/dist/esm/text/headerFooter.d.ts +13 -0
  239. package/dist/esm/text/headerFooter.js +21 -0
  240. package/dist/esm/text/textLines.d.ts +7 -0
  241. package/dist/esm/text/textLines.js +13 -0
  242. package/dist/index.cjs +65 -0
  243. package/dist/index.cjs.map +1 -0
  244. package/dist/nodelyra-player.global.js +65 -0
  245. package/dist/nodelyra-player.global.js.map +1 -0
  246. package/dist/nodelyra-player.lite.global.js +63 -0
  247. package/dist/nodelyra-player.lite.global.js.map +1 -0
  248. package/examples/blog-excerpt.html +54 -0
  249. package/examples/twinkle.html +23 -0
  250. package/examples/twinkle.json +91 -0
  251. package/package.json +70 -4
@@ -0,0 +1,58 @@
1
+ const written = (event) => event.type === "note"
2
+ ? { id: event.id, duration: event.duration, degree: event.degree, octave: event.octave ?? 0, accidental: event.accidental ?? null, tie: Boolean(event.tie) }
3
+ : { id: event.id, duration: event.duration, degree: null, octave: 0, accidental: null, tie: false };
4
+ const markOf = (measure) => {
5
+ const directions = measure.directions ?? [];
6
+ return {
7
+ id: measure.id,
8
+ time: measure.time ?? null,
9
+ barline: measure.barline ?? "single",
10
+ repeatStart: Boolean(measure.repeat_start),
11
+ volta: measure.volta ?? null,
12
+ navigation: measure.navigation ?? null,
13
+ restBars: measure.text_bar?.bars ?? 0,
14
+ key: measure.key ?? null,
15
+ keyAt: measure.key_at ?? 0,
16
+ tempo: measure.tempo ?? null,
17
+ dynamics: directions.flatMap((d) => (d.type === "dynamic" ? [{ at: d.at, level: d.level }] : [])),
18
+ hairpins: directions.flatMap((d) => d.type === "hairpin" ? [{ at: d.at, shape: d.shape, endMeasure: d.end.measure, endAt: d.end.at }] : []),
19
+ };
20
+ };
21
+ /** "partId:barIndex" -> the part whose notes it sings there: a whole-bar unison group (ADR 0012). */
22
+ function unisonLeads(measures) {
23
+ const leads = new Map();
24
+ measures.forEach((measure, index) => {
25
+ for (const group of measure.unisons ?? []) {
26
+ // Over part of a bar every part keeps its own (identical) notes; only a whole-bar group
27
+ // leaves the others empty.
28
+ if ((group.from ?? 0) !== 0 || (group.to ?? null) !== null)
29
+ continue;
30
+ for (const partId of group.parts.slice(1))
31
+ leads.set(`${partId}:${index}`, group.parts[0]);
32
+ }
33
+ });
34
+ return leads;
35
+ }
36
+ const partOf = (part, byId, leads) => ({
37
+ id: part.id,
38
+ name: part.name ?? "",
39
+ kind: part.kind ?? "vocal",
40
+ // In a unison bar a part sounds its lead part's notes.
41
+ measures: part.measures.map((_, index) => {
42
+ const source = byId.get(leads.get(`${part.id}:${index}`) ?? part.id) ?? part;
43
+ return (source.measures[index]?.events ?? []).map(written);
44
+ }),
45
+ });
46
+ /** A validated score document as the compiler reads it (port of `score_from_document`). */
47
+ export function readScore(score) {
48
+ const byId = new Map(score.parts.map((p) => [p.id, p]));
49
+ const leads = unisonLeads(score.measures);
50
+ return {
51
+ key: score.settings.key,
52
+ time: score.settings.time,
53
+ tempo: score.settings.tempo,
54
+ pickup: score.settings.pickup ?? 0,
55
+ measures: score.measures.map(markOf),
56
+ parts: score.parts.map((p) => partOf(p, byId, leads)),
57
+ };
58
+ }
@@ -0,0 +1,10 @@
1
+ import type { Performance } from "../playback/types.js";
2
+ import type { PlaybackScore } from "./model.js";
3
+ /**
4
+ * Score -> Performance (a port of `backend/apps/playback/timeline.py`; the shared cases in
5
+ * `docs/fixtures/performance-cases.json` keep the two equal). Measures play in `playOrder`; a
6
+ * measure lasts as long as its longest part; a tied pair sounds as one note; digits are read in
7
+ * the key in force where they start; each note carries the loudness in force when it starts; rests
8
+ * sound nothing, but cues list every written note and rest so a cursor can follow the notation.
9
+ */
10
+ export declare function buildPerformance(score: PlaybackScore): Performance;
@@ -0,0 +1,144 @@
1
+ import { parseMeter, TICKS_PER_QUARTER, isValidPickup } from "../notation/time.js";
2
+ import { toMidi } from "../notation/pitch.js";
3
+ import { levelCurve } from "./dynamics.js";
4
+ import { playOrder } from "./playOrder.js";
5
+ /** The time signature in force in each measure (a change holds until the next one). */
6
+ function metersOf(score) {
7
+ let current = score.time;
8
+ return score.measures.map((m) => (current = m.time ?? current));
9
+ }
10
+ /** Per measure: the key before its change, the key from it on, and where in the bar it takes over. */
11
+ function keysOf(score) {
12
+ let current = score.key;
13
+ return score.measures.map((m) => {
14
+ const before = current;
15
+ current = m.key ?? current;
16
+ return { before, after: current, at: m.key ? m.keyAt : 0 };
17
+ });
18
+ }
19
+ const barTicks = (time) => parseMeter(time).measureTicks;
20
+ /** The score's pickup when it fits the first bar's meter, else 0. */
21
+ const pickupOf = (score, meters) => meters.length > 0 && isValidPickup(score.pickup, parseMeter(meters[0])) ? score.pickup : 0;
22
+ /** How long a measure with no events lasts: a full bar, or the pickup and its complement. */
23
+ function emptyLength(index, count, meter, pickup) {
24
+ if (pickup && index === 0)
25
+ return pickup;
26
+ if (pickup && index === count - 1 && count > 1)
27
+ return barTicks(meter) - pickup;
28
+ return barTicks(meter);
29
+ }
30
+ function measureLength(score, index, meter, pickup) {
31
+ const { restBars } = score.measures[index];
32
+ if (restBars)
33
+ return restBars * barTicks(meter);
34
+ const content = Math.max(0, ...score.parts.map((p) => p.measures[index].reduce((sum, e) => sum + e.duration, 0)));
35
+ return content || emptyLength(index, score.measures.length, meter, pickup);
36
+ }
37
+ const phaseOf = (index, meter, pickup) => (pickup && index === 0 ? barTicks(meter) - pickup : 0);
38
+ /** Each written event of a part in playing order, with its start, bar index and onset in the bar. */
39
+ function* placed(part, played, indexes) {
40
+ for (let i = 0; i < played.length; i += 1) {
41
+ let onset = 0;
42
+ for (const event of part.measures[indexes[i]]) {
43
+ yield { event, start: played[i].start + onset, index: indexes[i], onset };
44
+ onset += event.duration;
45
+ }
46
+ }
47
+ }
48
+ /** Joins a tied note to the next note of its part when it has the same pitch and starts where it ends. */
49
+ function* partNotes(score, part, played, indexes) {
50
+ const keys = keysOf(score);
51
+ let pending = null;
52
+ let pendingTied = false;
53
+ for (const { event, start, index, onset } of placed(part, played, indexes)) {
54
+ if (event.degree === null) {
55
+ if (pending)
56
+ yield pending;
57
+ pending = null;
58
+ pendingTied = false;
59
+ continue;
60
+ }
61
+ const key = onset >= keys[index].at ? keys[index].after : keys[index].before;
62
+ const pitch = toMidi({ degree: event.degree, octave: event.octave, accidental: event.accidental }, key);
63
+ let note = { part_id: part.id, event_id: event.id, pitch, start, duration: event.duration };
64
+ if (pending && pendingTied && note.pitch === pending.pitch && note.start === pending.start + pending.duration) {
65
+ note = { ...pending, duration: pending.duration + note.duration };
66
+ }
67
+ else if (pending) {
68
+ yield pending;
69
+ }
70
+ pending = note;
71
+ pendingTied = event.tie;
72
+ }
73
+ if (pending)
74
+ yield pending;
75
+ }
76
+ const partCues = (part, played, indexes) => [...placed(part, played, indexes)].map(({ event, start }) => ({
77
+ part_id: part.id,
78
+ event_id: event.id,
79
+ start,
80
+ duration: event.duration,
81
+ }));
82
+ function playedMeasures(score, meters, lengths, indexes, pickup) {
83
+ let start = 0;
84
+ return indexes.map((index) => {
85
+ const meter = meters[index];
86
+ const measure = {
87
+ measure_id: score.measures[index].id,
88
+ start,
89
+ duration: lengths[index],
90
+ beat_duration: parseMeter(meter).beatTicks,
91
+ phase: phaseOf(index, meter, pickup),
92
+ };
93
+ start += lengths[index];
94
+ return measure;
95
+ });
96
+ }
97
+ /**
98
+ * Where the tempo differs from the one before, by played bar. A bar without its own tempo keeps
99
+ * the one in force as it is played, so a repeat that jumps back keeps going at the tempo reached
100
+ * unless the bar it returns to names its own.
101
+ */
102
+ function tempoChanges(score, played, indexes) {
103
+ const changes = [];
104
+ let current = score.tempo;
105
+ played.forEach((measure, i) => {
106
+ const wanted = score.measures[indexes[i]].tempo;
107
+ if (wanted !== null && wanted !== current) {
108
+ changes.push({ start: measure.start, tempo: wanted });
109
+ current = wanted;
110
+ }
111
+ });
112
+ return changes;
113
+ }
114
+ const byStartThenPart = (a, b) => a.start - b.start || (a.part_id < b.part_id ? -1 : a.part_id > b.part_id ? 1 : 0);
115
+ /**
116
+ * Score -> Performance (a port of `backend/apps/playback/timeline.py`; the shared cases in
117
+ * `docs/fixtures/performance-cases.json` keep the two equal). Measures play in `playOrder`; a
118
+ * measure lasts as long as its longest part; a tied pair sounds as one note; digits are read in
119
+ * the key in force where they start; each note carries the loudness in force when it starts; rests
120
+ * sound nothing, but cues list every written note and rest so a cursor can follow the notation.
121
+ */
122
+ export function buildPerformance(score) {
123
+ const meters = metersOf(score);
124
+ const pickup = pickupOf(score, meters);
125
+ const lengths = meters.map((meter, i) => measureLength(score, i, meter, pickup));
126
+ const indexes = playOrder(score.measures);
127
+ const played = playedMeasures(score, meters, lengths, indexes, pickup);
128
+ const levelAt = levelCurve(score.measures, played, indexes);
129
+ const notes = score.parts
130
+ .flatMap((part) => [...partNotes(score, part, played, indexes)])
131
+ .map((note) => ({ ...note, level: levelAt(note.start) }))
132
+ .sort(byStartThenPart);
133
+ const cues = score.parts.flatMap((part) => partCues(part, played, indexes)).sort(byStartThenPart);
134
+ return {
135
+ tempo: score.tempo,
136
+ ticks_per_quarter: TICKS_PER_QUARTER,
137
+ duration: played.reduce((sum, m) => sum + m.duration, 0),
138
+ parts: score.parts.map(({ id, name, kind }) => ({ id, name, kind })),
139
+ measures: played,
140
+ notes,
141
+ cues,
142
+ tempo_changes: tempoChanges(score, played, indexes),
143
+ };
144
+ }
@@ -0,0 +1,46 @@
1
+ import type { PartKind } from "../schema/types.js";
2
+ import { type VolumeChannel } from "./volume.js";
3
+ /** One note of a part to sound, in the output's own clock (seconds). */
4
+ export type ToneRequest = {
5
+ partId: string;
6
+ pitch: number;
7
+ at: number;
8
+ duration: number;
9
+ /** How loud, 0..1, from the dynamics in force (ADR 0011). */
10
+ level: number;
11
+ kind: PartKind;
12
+ };
13
+ /** What the player needs from a sound device. Swap it for a fake in tests. */
14
+ export interface AudioOutput {
15
+ /** The output's clock, in seconds; notes are scheduled against it, never against timers. */
16
+ now(): number;
17
+ /** Ready to sound (browsers start audio suspended until a user gesture). */
18
+ resume(): Promise<void>;
19
+ play(tone: ToneRequest): void;
20
+ /** A metronome click at `at` (output clock), stronger on the downbeat. */
21
+ click(at: number, downbeat: boolean): void;
22
+ /** Set how loud a channel is (0..1), at once, including notes already sounding. */
23
+ setVolume(channel: VolumeChannel, level: number): void;
24
+ /** Set how loud one part is (0..1) within the music, at once. Parts not set play at full. */
25
+ setPartVolume(partId: string, level: number): void;
26
+ /** Silence everything already scheduled. */
27
+ silence(): void;
28
+ close(): void;
29
+ }
30
+ export declare const frequencyOf: (pitch: number) => number;
31
+ /**
32
+ * How long silencing fades out what is sounding (seconds). Cutting a wave off mid-swing is heard
33
+ * as a crack on play, pause and stop; a few milliseconds of fade is heard as a clean stop.
34
+ */
35
+ export declare const SILENCE_FADE = 0.02;
36
+ /** Runs `then` after `ms` milliseconds (the browser's timer by default; a fake in tests). */
37
+ export type Later = (then: () => void, ms: number) => void;
38
+ /**
39
+ * A simple Web Audio synthesizer: one oscillator with a short envelope per note. Volumes are
40
+ * lasting gain stages: one per channel (music, metronome) and one per part inside the music.
41
+ * What is scheduled goes through a bus in front of them (one per part, one for the clicks),
42
+ * which `silence` fades out and replaces, so stopping never resets a volume and never cracks:
43
+ *
44
+ * note -> part bus -> part volume -> music volume -> out; click -> click bus -> metronome volume -> out
45
+ */
46
+ export declare function createWebAudioOutput(context?: AudioContext, later?: Later): AudioOutput;
@@ -0,0 +1,106 @@
1
+ import { gainOf } from "./volume.js";
2
+ /** The waveform each kind of part sounds with. */
3
+ const WAVEFORMS = {
4
+ vocal: "sine",
5
+ };
6
+ const LEVEL = 0.18; // per note; several parts together stay below clipping
7
+ /** The click: a short high blip, higher and louder on the downbeat. */
8
+ const CLICK = {
9
+ length: 0.04,
10
+ downbeat: { frequency: 1760, level: 0.35 },
11
+ beat: { frequency: 1320, level: 0.22 },
12
+ };
13
+ const ATTACK = 0.01;
14
+ const RELEASE = 0.04;
15
+ export const frequencyOf = (pitch) => 440 * 2 ** ((pitch - 69) / 12);
16
+ /** How fast a volume change settles (seconds): quick, without a click. */
17
+ const VOLUME_GLIDE = 0.015;
18
+ /**
19
+ * How long silencing fades out what is sounding (seconds). Cutting a wave off mid-swing is heard
20
+ * as a crack on play, pause and stop; a few milliseconds of fade is heard as a clean stop.
21
+ */
22
+ export const SILENCE_FADE = 0.02;
23
+ /** Waits this long (ms) past the fade before unplugging the faded buses, so none is cut early. */
24
+ const UNPLUG_MARGIN_MS = 50;
25
+ /**
26
+ * A simple Web Audio synthesizer: one oscillator with a short envelope per note. Volumes are
27
+ * lasting gain stages: one per channel (music, metronome) and one per part inside the music.
28
+ * What is scheduled goes through a bus in front of them (one per part, one for the clicks),
29
+ * which `silence` fades out and replaces, so stopping never resets a volume and never cracks:
30
+ *
31
+ * note -> part bus -> part volume -> music volume -> out; click -> click bus -> metronome volume -> out
32
+ */
33
+ export function createWebAudioOutput(context = new AudioContext(), later = (then, ms) => void setTimeout(then, ms)) {
34
+ const volume = {
35
+ music: gainTo(context.destination),
36
+ metronome: gainTo(context.destination),
37
+ };
38
+ const partVolume = new Map();
39
+ let clickBus = gainTo(volume.metronome);
40
+ let partBus = new Map();
41
+ function gainTo(target) {
42
+ const gain = context.createGain();
43
+ gain.connect(target);
44
+ return gain;
45
+ }
46
+ function volumeOf(partId) {
47
+ let gain = partVolume.get(partId);
48
+ if (!gain)
49
+ partVolume.set(partId, (gain = gainTo(volume.music)));
50
+ return gain;
51
+ }
52
+ function busOf(partId) {
53
+ let bus = partBus.get(partId);
54
+ if (!bus)
55
+ partBus.set(partId, (bus = gainTo(volumeOf(partId))));
56
+ return bus;
57
+ }
58
+ const glide = (gain, level) => gain.gain.setTargetAtTime(gainOf(level), context.currentTime, VOLUME_GLIDE);
59
+ return {
60
+ now: () => context.currentTime,
61
+ resume: () => context.resume(),
62
+ play({ partId, pitch, at, duration, level, kind }) {
63
+ const oscillator = context.createOscillator();
64
+ const envelope = context.createGain();
65
+ const end = at + Math.max(duration, ATTACK + RELEASE);
66
+ oscillator.type = WAVEFORMS[kind];
67
+ oscillator.frequency.value = frequencyOf(pitch);
68
+ const peak = LEVEL * Math.min(1, Math.max(0, level));
69
+ envelope.gain.setValueAtTime(0, at);
70
+ envelope.gain.linearRampToValueAtTime(peak, at + ATTACK);
71
+ envelope.gain.setValueAtTime(peak, end - RELEASE);
72
+ envelope.gain.linearRampToValueAtTime(0, end);
73
+ oscillator.connect(envelope).connect(busOf(partId));
74
+ oscillator.start(at);
75
+ oscillator.stop(end);
76
+ },
77
+ click(at, downbeat) {
78
+ const { frequency, level } = downbeat ? CLICK.downbeat : CLICK.beat;
79
+ const oscillator = context.createOscillator();
80
+ const envelope = context.createGain();
81
+ oscillator.frequency.value = frequency;
82
+ envelope.gain.setValueAtTime(level, at);
83
+ envelope.gain.exponentialRampToValueAtTime(0.001, at + CLICK.length);
84
+ oscillator.connect(envelope).connect(clickBus);
85
+ oscillator.start(at);
86
+ oscillator.stop(at + CLICK.length);
87
+ },
88
+ setVolume: (channel, level) => glide(volume[channel], level),
89
+ setPartVolume: (partId, level) => glide(volumeOf(partId), level),
90
+ silence() {
91
+ // What is already scheduled is wired to the old buses: fading them to nothing silences it
92
+ // all without a crack, and new notes go to fresh buses at once.
93
+ const faded = [clickBus, ...partBus.values()];
94
+ const now = context.currentTime;
95
+ for (const bus of faded) {
96
+ bus.gain.cancelScheduledValues(now);
97
+ bus.gain.setValueAtTime(bus.gain.value, now);
98
+ bus.gain.linearRampToValueAtTime(0, now + SILENCE_FADE);
99
+ }
100
+ later(() => faded.forEach((bus) => bus.disconnect()), SILENCE_FADE * 1000 + UNPLUG_MARGIN_MS);
101
+ clickBus = gainTo(volume.metronome);
102
+ partBus = new Map();
103
+ },
104
+ close: () => void context.close(),
105
+ };
106
+ }
@@ -0,0 +1,16 @@
1
+ import type { Performance } from "./types.js";
2
+ /** Between ticks and seconds at the pace the music goes: one tempo, or the tempo changing by bar. */
3
+ export type TickClock = {
4
+ /** Seconds from the start of the performance to `tick`. */
5
+ seconds: (tick: number) => number;
6
+ /** The tick playing `seconds` from the start (the inverse of `seconds`). */
7
+ tick: (seconds: number) => number;
8
+ };
9
+ /** The clock of one tempo, for tests and for performances that never change tempo. */
10
+ export declare const constantClock: (secondsPerTick: number) => TickClock;
11
+ /**
12
+ * The clock of a performance. `tempo` replaces the score's tempo (the rehearsal tempo); the score's
13
+ * changes keep their proportion to it, so playing at half speed halves every tempo. A change at
14
+ * tick 0 is the start tempo; ticks before the start or past the end go on at the nearest pace.
15
+ */
16
+ export declare function tickClock({ tempo, ticks_per_quarter, tempo_changes }: Pick<Performance, "tempo" | "ticks_per_quarter" | "tempo_changes">, override?: number | null): TickClock;
@@ -0,0 +1,44 @@
1
+ /** The clock of one tempo, for tests and for performances that never change tempo. */
2
+ export const constantClock = (secondsPerTick) => ({
3
+ seconds: (tick) => tick * secondsPerTick,
4
+ tick: (seconds) => seconds / secondsPerTick,
5
+ });
6
+ /**
7
+ * The clock of a performance. `tempo` replaces the score's tempo (the rehearsal tempo); the score's
8
+ * changes keep their proportion to it, so playing at half speed halves every tempo. A change at
9
+ * tick 0 is the start tempo; ticks before the start or past the end go on at the nearest pace.
10
+ */
11
+ export function tickClock({ tempo, ticks_per_quarter, tempo_changes }, override = null) {
12
+ const scale = (override ?? tempo) / tempo;
13
+ const perTick = (bpm) => 60 / (bpm * scale * ticks_per_quarter);
14
+ const changes = (tempo_changes ?? []).filter((change) => change.start > 0);
15
+ const first = (tempo_changes ?? []).find((change) => change.start <= 0);
16
+ const segments = [{ from: 0, at: 0, perTick: perTick(first?.tempo ?? tempo) }];
17
+ for (const change of changes) {
18
+ const last = segments[segments.length - 1];
19
+ segments.push({ from: change.start, at: last.at + (change.start - last.from) * last.perTick, perTick: perTick(change.tempo) });
20
+ }
21
+ /** The last segment that starts at or before `value` (by `key`), or the first. */
22
+ const find = (value, key) => {
23
+ let low = 0;
24
+ let high = segments.length - 1;
25
+ while (low < high) {
26
+ const middle = (low + high + 1) >> 1;
27
+ if (segments[middle][key] <= value)
28
+ low = middle;
29
+ else
30
+ high = middle - 1;
31
+ }
32
+ return segments[low];
33
+ };
34
+ return {
35
+ seconds: (tick) => {
36
+ const segment = find(tick, "from");
37
+ return segment.at + (tick - segment.from) * segment.perTick;
38
+ },
39
+ tick: (seconds) => {
40
+ const segment = find(seconds, "at");
41
+ return segment.from + (seconds - segment.at) / segment.perTick;
42
+ },
43
+ };
44
+ }
@@ -0,0 +1,79 @@
1
+ import { type StoreApi } from "zustand/vanilla";
2
+ import type { ScoreInput } from "../schema/types.js";
3
+ import type { PerformanceSource } from "./source.js";
4
+ import type { AudioOutput } from "./audioOutput.js";
5
+ import type { CueTrack } from "./cues.js";
6
+ import { type Mix } from "./mix.js";
7
+ import { type Repeat } from "./session.js";
8
+ import { type StartPoint } from "./start.js";
9
+ import { type VolumeChannel, type Volumes } from "./volume.js";
10
+ export type { Repeat } from "./session.js";
11
+ export type PlayerStatus = "idle" | "loading" | "playing" | "paused" | "error";
12
+ export type PlayerState = {
13
+ status: PlayerStatus;
14
+ /** Why the last play failed (status "error"). */
15
+ message: string;
16
+ /** Seconds since the start of the performance, at the tempo being played. */
17
+ position: number;
18
+ /** Length of the last performance, in seconds at the tempo being played. */
19
+ duration: number;
20
+ mix: Mix;
21
+ /** What is being played, for the cursor (null when not playing). */
22
+ track: CueTrack | null;
23
+ /** Rehearsal tempo in BPM, used instead of the score's (null = the score's). Never saved. */
24
+ tempo: number | null;
25
+ /** Click every beat while playing (on by default). Never saved. */
26
+ metronome: boolean;
27
+ /** How loud the music and the metronome are (0..1). Never saved. */
28
+ volumes: Volumes;
29
+ /** Go back to the start of what is playing (the selection) at its end. Never saved. */
30
+ loop: boolean;
31
+ /** How loud each part is within the music (0..1; a part not listed plays at full). Never saved. */
32
+ partVolumes: Readonly<Record<string, number>>;
33
+ /** How many times playing ran to its end (not stopped): tells an end from a Stop. */
34
+ ends: number;
35
+ };
36
+ /** What Play needs, built only when playing starts (a pause or resume needs none). */
37
+ export type PlayRequest = {
38
+ input: ScoreInput;
39
+ points: readonly StartPoint[];
40
+ };
41
+ export type PlayerActions = {
42
+ /**
43
+ * Compile the score and play what is selected (`points`: notes, rests or measures): from one
44
+ * place to the end, from the earliest to the end of the latest of several, or everything.
45
+ */
46
+ play: (input: ScoreInput, points?: readonly StartPoint[]) => Promise<void>;
47
+ /** Play, pause or resume, whichever comes next (the Space key). */
48
+ togglePlayback: (request: () => PlayRequest) => void;
49
+ /** Hold playing where it is (the cursor stays); `resume` goes on from there. */
50
+ pause: () => void;
51
+ resume: () => void;
52
+ stop: () => void;
53
+ toggleMute: (partId: string) => void;
54
+ toggleSolo: (partId: string) => void;
55
+ /** Turn a channel up or down (0..1); applies at once, also while playing. */
56
+ setVolume: (channel: VolumeChannel, level: number) => void;
57
+ /** Turn one part up or down (0..1) within the music; applies at once, also while playing. */
58
+ setPartVolume: (partId: string, level: number) => void;
59
+ /** Switch looping on or off; applies while playing (as the end comes near). */
60
+ toggleLoop: () => void;
61
+ /** Switch the beat clicks on or off; applies at once while playing. */
62
+ toggleMetronome: () => void;
63
+ /** Play at this tempo (null = the score's); applies at once while playing. */
64
+ setTempo: (tempo: number | null) => void;
65
+ /** Stop and release the sound device (the editor is closing). */
66
+ dispose: () => void;
67
+ };
68
+ export type PlayerStore = PlayerState & PlayerActions;
69
+ export type PlayerDeps = {
70
+ source: PerformanceSource;
71
+ /** Made on the first play (browsers allow audio only after a user gesture). */
72
+ createOutput: () => AudioOutput;
73
+ repeat?: Repeat;
74
+ };
75
+ /**
76
+ * The player: compiles a score through the injected source and plays it as a session on an
77
+ * audio output (engine/session.ts). Build one per mounted editor.
78
+ */
79
+ export declare function createPlayerStore(deps: PlayerDeps): StoreApi<PlayerStore>;
@@ -0,0 +1,135 @@
1
+ import { createStore } from "zustand/vanilla";
2
+ import { UserFacingError } from "./errors.js";
3
+ import { FULL_MIX, toggled } from "./mix.js";
4
+ import { startSession } from "./session.js";
5
+ import { playRange } from "./start.js";
6
+ import { clampPlayTempo } from "./timing.js";
7
+ import { clampVolume, DEFAULT_VOLUMES } from "./volume.js";
8
+ /** What toggling does in each state: start, pause, resume, or wait for loading to finish. */
9
+ const TOGGLES = {
10
+ idle: (player, request) => {
11
+ const { input, points } = request();
12
+ void player.play(input, points);
13
+ },
14
+ error: (player, request) => TOGGLES.idle(player, request),
15
+ loading: () => { },
16
+ playing: (player) => player.pause(),
17
+ paused: (player) => player.resume(),
18
+ };
19
+ const intervalRepeat = (tick, ms) => {
20
+ const id = setInterval(tick, ms);
21
+ return () => clearInterval(id);
22
+ };
23
+ /**
24
+ * The player: compiles a score through the injected source and plays it as a session on an
25
+ * audio output (engine/session.ts). Build one per mounted editor.
26
+ */
27
+ export function createPlayerStore(deps) {
28
+ const repeat = deps.repeat ?? intervalRepeat;
29
+ let output = null;
30
+ let session = null;
31
+ let run = 0; // a play that was stopped while loading must not start afterwards
32
+ return createStore()((set, get) => {
33
+ /** The sound device, made on first use with the current volumes (channels and parts). */
34
+ const openOutput = () => {
35
+ const device = deps.createOutput();
36
+ for (const [channel, level] of Object.entries(get().volumes))
37
+ device.setVolume(channel, level);
38
+ for (const [partId, level] of Object.entries(get().partVolumes))
39
+ device.setPartVolume(partId, level);
40
+ return device;
41
+ };
42
+ const halt = () => {
43
+ run += 1;
44
+ session?.stop();
45
+ session = null;
46
+ };
47
+ /** Back to the start, idle: stopped, or (`ended`) played to the end, in one update. */
48
+ const finish = (ended) => {
49
+ halt();
50
+ set((s) => ({ status: "idle", position: 0, track: null, ends: ended ? s.ends + 1 : s.ends }));
51
+ };
52
+ return {
53
+ status: "idle",
54
+ message: "",
55
+ position: 0,
56
+ duration: 0,
57
+ mix: FULL_MIX,
58
+ track: null,
59
+ tempo: null,
60
+ metronome: true, // on by default: rehearsal starts with the beat
61
+ volumes: DEFAULT_VOLUMES,
62
+ partVolumes: {},
63
+ loop: false,
64
+ ends: 0,
65
+ play: async (input, points = []) => {
66
+ halt();
67
+ const current = run;
68
+ set({ status: "loading", message: "", position: 0 });
69
+ try {
70
+ const performance = await deps.source.perform(input);
71
+ output ?? (output = openOutput());
72
+ await output.resume();
73
+ if (current !== run)
74
+ return;
75
+ set({ status: "playing" });
76
+ session = startSession({
77
+ performance,
78
+ device: output,
79
+ range: playRange(performance, points),
80
+ tempo: get().tempo,
81
+ repeat,
82
+ mix: () => get().mix,
83
+ metronome: () => get().metronome,
84
+ loop: () => get().loop,
85
+ onProgress: (progress) => set(progress),
86
+ onEnd: () => finish(true),
87
+ });
88
+ }
89
+ catch (e) {
90
+ if (current !== run)
91
+ return;
92
+ set({ status: "error", message: e instanceof UserFacingError ? e.message : "" }); // the bar words a generic failure
93
+ }
94
+ },
95
+ togglePlayback: (request) => TOGGLES[get().status](get(), request),
96
+ pause: () => {
97
+ if (get().status !== "playing")
98
+ return;
99
+ session?.pause();
100
+ set({ status: "paused" });
101
+ },
102
+ resume: () => {
103
+ if (get().status !== "paused")
104
+ return;
105
+ set({ status: "playing" });
106
+ session?.resume();
107
+ },
108
+ stop: () => finish(false),
109
+ toggleMute: (partId) => set(({ mix }) => ({ mix: { ...mix, muted: toggled(mix.muted, partId) } })),
110
+ toggleSolo: (partId) => set(({ mix }) => ({ mix: { ...mix, solo: toggled(mix.solo, partId) } })),
111
+ setVolume: (channel, level) => {
112
+ const clamped = clampVolume(level);
113
+ set(({ volumes }) => ({ volumes: { ...volumes, [channel]: clamped } }));
114
+ output?.setVolume(channel, clamped);
115
+ },
116
+ setPartVolume: (partId, level) => {
117
+ const clamped = clampVolume(level);
118
+ set(({ partVolumes }) => ({ partVolumes: { ...partVolumes, [partId]: clamped } }));
119
+ output?.setPartVolume(partId, clamped);
120
+ },
121
+ toggleLoop: () => set(({ loop }) => ({ loop: !loop })),
122
+ toggleMetronome: () => set(({ metronome }) => ({ metronome: !metronome })),
123
+ setTempo: (tempo) => {
124
+ const next = tempo === null ? null : clampPlayTempo(tempo);
125
+ set({ tempo: next });
126
+ session?.setTempo(next);
127
+ },
128
+ dispose: () => {
129
+ get().stop();
130
+ output?.close();
131
+ output = null;
132
+ },
133
+ };
134
+ });
135
+ }