jpfun 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/README.md +141 -11
  2. package/dist/converter/midi/convert.d.ts +50 -0
  3. package/dist/converter/midi/convert.js +700 -0
  4. package/dist/converter/midi/index.d.ts +5 -0
  5. package/dist/converter/midi/index.js +11 -0
  6. package/dist/converter/midi/json.d.ts +38 -0
  7. package/dist/converter/midi/json.js +1 -0
  8. package/dist/converter/midi/triplet.d.ts +30 -0
  9. package/dist/converter/midi/triplet.js +75 -0
  10. package/dist/converter/musicxml/dom.d.ts +25 -0
  11. package/dist/converter/musicxml/dom.js +65 -0
  12. package/dist/converter/musicxml/features.d.ts +51 -0
  13. package/dist/converter/musicxml/features.js +232 -0
  14. package/dist/converter/musicxml/index.d.ts +9 -0
  15. package/dist/converter/musicxml/index.js +1140 -0
  16. package/dist/converter/musicxml/model.d.ts +123 -0
  17. package/dist/converter/musicxml/model.js +1 -0
  18. package/dist/converter/source.d.ts +22 -0
  19. package/dist/converter/source.js +51 -0
  20. package/dist/core.d.ts +22 -0
  21. package/dist/core.js +22 -0
  22. package/dist/diagnostic.js +5 -2
  23. package/dist/fraction.d.ts +24 -0
  24. package/dist/fraction.js +132 -0
  25. package/dist/functions/ASTtypes.d.ts +51 -31
  26. package/dist/functions/ASTtypes.js +59 -38
  27. package/dist/functions/adjust/index.d.ts +2 -0
  28. package/dist/functions/adjust/index.js +193 -0
  29. package/dist/functions/arpeggio/index.d.ts +2 -0
  30. package/dist/functions/arpeggio/index.js +180 -0
  31. package/dist/functions/arpeggio/shape.d.ts +7 -0
  32. package/dist/functions/arpeggio/shape.js +122 -0
  33. package/dist/functions/bar/index.d.ts +8 -0
  34. package/dist/functions/bar/index.js +62 -25
  35. package/dist/functions/beam/auto.d.ts +1 -1
  36. package/dist/functions/beam/auto.js +33 -16
  37. package/dist/functions/beam/index.js +10 -6
  38. package/dist/functions/beam/layout.d.ts +4 -3
  39. package/dist/functions/beam/layout.js +43 -65
  40. package/dist/functions/box/index.js +37 -36
  41. package/dist/functions/br/index.js +10 -8
  42. package/dist/functions/dash/index.js +40 -7
  43. package/dist/functions/default.js +19 -8
  44. package/dist/functions/div/index.d.ts +16 -0
  45. package/dist/functions/div/index.js +45 -17
  46. package/dist/functions/dot/index.js +23 -25
  47. package/dist/functions/dyn/index.d.ts +2 -0
  48. package/dist/functions/dyn/index.js +242 -0
  49. package/dist/functions/grace/index.d.ts +8 -11
  50. package/dist/functions/grace/index.js +84 -79
  51. package/dist/functions/head/index.d.ts +2 -0
  52. package/dist/functions/head/index.js +496 -0
  53. package/dist/functions/key/index.js +98 -3
  54. package/dist/functions/meter/index.d.ts +2 -0
  55. package/dist/functions/meter/index.js +155 -0
  56. package/dist/functions/note/accidentals.d.ts +24 -3
  57. package/dist/functions/note/accidentals.js +31 -1
  58. package/dist/functions/note/index.js +106 -79
  59. package/dist/functions/note/noteNameFSM.js +52 -63
  60. package/dist/functions/page/index.d.ts +11 -2
  61. package/dist/functions/page/index.js +65 -4
  62. package/dist/functions/program/index.d.ts +2 -0
  63. package/dist/functions/program/index.js +30 -0
  64. package/dist/functions/set/index.js +43 -32
  65. package/dist/functions/stack/index.js +26 -22
  66. package/dist/functions/symbol/index.d.ts +31 -0
  67. package/dist/functions/symbol/index.js +139 -0
  68. package/dist/functions/symbol/ornament.d.ts +15 -0
  69. package/dist/functions/symbol/ornament.js +73 -0
  70. package/dist/functions/symbol/shape.d.ts +24 -0
  71. package/dist/functions/symbol/shape.js +52 -0
  72. package/dist/functions/symbol/symbols/accent.d.ts +2 -0
  73. package/dist/functions/symbol/symbols/accent.js +24 -0
  74. package/dist/functions/symbol/symbols/dc.d.ts +4 -0
  75. package/dist/functions/symbol/symbols/dc.js +82 -0
  76. package/dist/functions/symbol/symbols/ds.d.ts +2 -0
  77. package/dist/functions/symbol/symbols/ds.js +93 -0
  78. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  79. package/dist/functions/symbol/symbols/dynamics.js +168 -0
  80. package/dist/functions/symbol/symbols/fermata.d.ts +2 -0
  81. package/dist/functions/symbol/symbols/fermata.js +24 -0
  82. package/dist/functions/symbol/symbols/fine.d.ts +2 -0
  83. package/dist/functions/symbol/symbols/fine.js +12 -0
  84. package/dist/functions/symbol/symbols/mordent.d.ts +2 -0
  85. package/dist/functions/symbol/symbols/mordent.js +56 -0
  86. package/dist/functions/symbol/symbols/prall.d.ts +2 -0
  87. package/dist/functions/symbol/symbols/prall.js +42 -0
  88. package/dist/functions/symbol/symbols/segno.d.ts +4 -0
  89. package/dist/functions/symbol/symbols/segno.js +82 -0
  90. package/dist/functions/symbol/symbols/tr.d.ts +2 -0
  91. package/dist/functions/symbol/symbols/tr.js +71 -0
  92. package/dist/functions/tempo/glyph.d.ts +12 -0
  93. package/dist/functions/tempo/glyph.js +30 -0
  94. package/dist/functions/tempo/index.js +57 -4
  95. package/dist/functions/temporal.d.ts +138 -0
  96. package/dist/functions/temporal.js +101 -0
  97. package/dist/functions/text/index.js +86 -27
  98. package/dist/functions/tie/index.js +136 -152
  99. package/dist/functions/tuplet/index.d.ts +2 -0
  100. package/dist/functions/tuplet/index.js +218 -0
  101. package/dist/functions/up/index.d.ts +1 -0
  102. package/dist/functions/up/index.js +258 -182
  103. package/dist/functions/voice/index.js +203 -109
  104. package/dist/functions/volta/index.d.ts +2 -0
  105. package/dist/functions/volta/index.js +230 -0
  106. package/dist/iife/core.d.ts +1 -0
  107. package/dist/iife/core.js +3 -0
  108. package/dist/iife/from-midi.d.ts +1 -0
  109. package/dist/iife/from-midi.js +15 -0
  110. package/dist/iife/from-musicxml.d.ts +1 -0
  111. package/dist/iife/from-musicxml.js +3 -0
  112. package/dist/iife/full.d.ts +1 -0
  113. package/dist/iife/full.js +3 -0
  114. package/dist/index.d.ts +3 -17
  115. package/dist/index.js +3 -17
  116. package/dist/jpfun.core.min.js +153 -0
  117. package/dist/jpfun.from-midi.min.js +9 -0
  118. package/dist/jpfun.from-musicxml.min.js +12 -0
  119. package/dist/jpfun.min.js +166 -0
  120. package/dist/layout/default.js +2 -3
  121. package/dist/layout/engine.d.ts +6 -12
  122. package/dist/layout/engine.js +115 -64
  123. package/dist/layout/model.d.ts +12 -5
  124. package/dist/layout/model.js +31 -18
  125. package/dist/layout/page.js +5 -4
  126. package/dist/layout/path.d.ts +19 -0
  127. package/dist/layout/path.js +101 -0
  128. package/dist/layout/types.d.ts +71 -20
  129. package/dist/layout/types.js +3 -1
  130. package/dist/lowering/loweringContext.d.ts +20 -20
  131. package/dist/lowering/loweringContext.js +153 -101
  132. package/dist/lowering/track.d.ts +5 -9
  133. package/dist/lowering/track.js +7 -2
  134. package/dist/lowering/types.d.ts +26 -112
  135. package/dist/lowering/types.js +1 -92
  136. package/dist/parser/parse-utils/call-utils.d.ts +0 -2
  137. package/dist/parser/parse-utils/call-utils.js +0 -6
  138. package/dist/parser/parse-utils/note-utils.d.ts +8 -0
  139. package/dist/parser/parse-utils/note-utils.js +35 -13
  140. package/dist/parser/parse-utils/string-utils.d.ts +10 -0
  141. package/dist/parser/parse-utils/string-utils.js +24 -0
  142. package/dist/parser/parserContext.d.ts +11 -9
  143. package/dist/parser/parserContext.js +65 -55
  144. package/dist/parser/preprocess.js +17 -11
  145. package/dist/pipeline.d.ts +6 -5
  146. package/dist/pipeline.js +4 -5
  147. package/dist/playback/compile.d.ts +18 -0
  148. package/dist/playback/compile.js +414 -0
  149. package/dist/playback/event.d.ts +105 -0
  150. package/dist/playback/event.js +105 -0
  151. package/dist/playback/time.d.ts +14 -0
  152. package/dist/playback/time.js +81 -0
  153. package/dist/playback/types.d.ts +129 -0
  154. package/dist/playback/types.js +3 -0
  155. package/dist/render/canvas.d.ts +4 -4
  156. package/dist/render/canvas.js +20 -5
  157. package/dist/render/index.d.ts +1 -0
  158. package/dist/render/index.js +1 -0
  159. package/dist/render/paint.d.ts +8 -0
  160. package/dist/render/paint.js +101 -0
  161. package/dist/render/svg.d.ts +3 -3
  162. package/dist/render/svg.js +10 -8
  163. package/dist/render/text.d.ts +22 -0
  164. package/dist/render/text.js +42 -0
  165. package/dist/render/types.d.ts +1 -1
  166. package/grammar.md +132 -13
  167. package/package.json +19 -6
@@ -0,0 +1,1140 @@
1
+ /**
2
+ * MusicXML -> jpFun 的转换流水线:
3
+ * 1. 接收调用方解析好的 XML 根元素,并把 partwise/timewise 统一成“每个 part 的小节序列”;
4
+ * 2. 按 part + staff + voice 建立 lane,使用 Fraction 保存精确时间;
5
+ * 3. 收集拍号、调号、速度、反复、歌词、力度和连音等语义;
6
+ * 4. 把普通事件和 tuplet 变成连续 RenderBlock,并为跨事件关系分配标签;
7
+ * 5. 按统一时间线生成 N:/L: 系统和文档末尾关系。
8
+ *
9
+ * XML 文本解析和 .mxl 解压都属于应用边界,core 不依赖具体 XML parser
10
+ */
11
+ import { Fraction } from "../../fraction.js";
12
+ import { NoteNameMap } from "../../parser/parse-utils/note-utils.js";
13
+ import { child, children, descendant, nameOf, number, text, } from "./dom.js";
14
+ import { directionDynamic, directionTexts, endingPasses, metronomeBpm, mergeArpeggio, noteArpeggio, noteLyrics, noteModifiers, parsePitch, parseTimeSignature, partMeasures, timeModification, } from "./features.js";
15
+ import { attachAbove, quote, renderHead, renderPitch, renderSystems } from "../source.js";
16
+ const MAJOR_KEYS = ["Cb", "Gb", "Db", "Ab", "Eb", "Bb", "F", "C", "G", "D", "A", "E", "B", "F#", "C#"];
17
+ const MINOR_KEYS = ["Ab", "Eb", "Bb", "F", "C", "G", "D", "A", "E", "B", "F#", "C#", "G#", "D#", "A#"];
18
+ // name = token[0] acc = token.slice(1)
19
+ const RELATIVE_NAMES = ["1", "1#", "2", "2#", "3", "4", "4#", "5", "5#", "6", "6#", "7"];
20
+ function add(left, right) {
21
+ return left.clone().add(right);
22
+ }
23
+ function keyOf(value) {
24
+ return value.toString();
25
+ }
26
+ function fractionFromKey(value) {
27
+ const [numerator, denominator = "1"] = value.split("/");
28
+ return new Fraction(Number(numerator), Number(denominator));
29
+ }
30
+ function lowerBoundAt(items, at, getAt) {
31
+ let low = 0;
32
+ let high = items.length;
33
+ while (low < high) {
34
+ const middle = (low + high) >> 1;
35
+ if (getAt(items[middle]).compare(at) < 0)
36
+ low = middle + 1;
37
+ else
38
+ high = middle;
39
+ }
40
+ return low;
41
+ }
42
+ function insideSpan(spans, at) {
43
+ const span = spans[lowerBoundAt(spans, at, item => item.start) - 1];
44
+ return !!span && span.end.compare(at) > 0;
45
+ }
46
+ function lyricToken(value) {
47
+ const continuation = value.endsWith("-");
48
+ const body = continuation ? value.slice(0, -1) : value;
49
+ const escaped = body.replace(/[\\{}@-]/g, "\\$&") + (continuation ? "-" : "");
50
+ // 花括号让会被歌词词法拆分的一个 XML lyric 仍只占一个歌词槽。
51
+ const hasNonAscii = [...body].some(char => char.codePointAt(0) > 0x7f);
52
+ return /\s/.test(body) || (hasNonAscii && ([...body].length > 1 || body.length > 1 || continuation))
53
+ ? `{${escaped}}`
54
+ : escaped;
55
+ }
56
+ function setBar(bars, at, token) {
57
+ const key = keyOf(at);
58
+ const current = bars.get(key);
59
+ if (!current || current === "|") {
60
+ bars.set(key, token);
61
+ return;
62
+ }
63
+ if (current === "|:" && token.startsWith(":|")) {
64
+ bars.set(key, token === ":|" ? ":|:" : `${token} |:`);
65
+ }
66
+ else if (token === "|:" && current.includes(":|")) {
67
+ bars.set(key, current === ":|" ? ":|:" : `${current} |:`);
68
+ }
69
+ else if (token === "||" && !current.includes("|:") && !current.includes(":|")) {
70
+ bars.set(key, token);
71
+ }
72
+ }
73
+ /**
74
+ * 把 DOM 转成 ParsedScore
75
+ * 每个 part 独立推进游标,第一 part 的小节长度作为多 part 对齐基准
76
+ * backup/forward 只移动当前小节游标,不直接产生可见音符
77
+ */
78
+ function parseScore(root) {
79
+ const partNames = new Map();
80
+ const instrumentsByPart = new Map();
81
+ const partList = child(root, "part-list");
82
+ if (partList) {
83
+ // 乐器定义按 part 和 instrument id 建索引,note 只保留最终 program
84
+ for (const scorePart of children(partList, "score-part")) {
85
+ const partId = scorePart.getAttribute("id") ?? "";
86
+ partNames.set(partId, text(scorePart, "part-name"));
87
+ const byId = new Map();
88
+ let fallback;
89
+ // 一个 part 可声明多个 instrument,首个定义同时作为无 id note 的回退
90
+ for (const midi of children(scorePart, "midi-instrument")) {
91
+ const channelSource = text(midi, "midi-channel");
92
+ const programSource = text(midi, "midi-program");
93
+ const channel = channelSource === "" ? undefined : Number(channelSource);
94
+ const program = programSource === "" ? undefined : Number(programSource) - 1;
95
+ if (channel !== undefined && (!Number.isSafeInteger(channel) || channel < 1 || channel > 16)) {
96
+ throw new RangeError("MusicXML midi-channel must be an integer in 1..16");
97
+ }
98
+ if (program !== undefined && (!Number.isSafeInteger(program) || program < 0 || program > 127)) {
99
+ throw new RangeError("MusicXML midi-program must be an integer in 1..128");
100
+ }
101
+ const instrument = { channel, program };
102
+ fallback ??= instrument;
103
+ byId.set(midi.getAttribute("id") ?? "", instrument);
104
+ }
105
+ instrumentsByPart.set(partId, { fallback, byId });
106
+ }
107
+ }
108
+ // 标题作者等文档级元数据不进入时间线
109
+ const credits = children(root, "credit");
110
+ const credit = (type) => {
111
+ const item = credits.find(value => text(value, "credit-type") === type);
112
+ return item ? text(item, "credit-words") : "";
113
+ };
114
+ const workTitle = text(child(root, "work"), "work-title");
115
+ // 优先采用语义明确的标题字段,并过滤 MuseScore 的默认占位标题
116
+ const title = text(root, "movement-title")
117
+ || (workTitle !== "Untitled Score" && workTitle !== "未命名乐谱" ? workTitle : "")
118
+ || credit("title");
119
+ const subtitle = credit("subtitle");
120
+ const creator = credit("composer") || (() => {
121
+ const identification = child(root, "identification");
122
+ const creators = identification ? children(identification, "creator") : [];
123
+ return text(creators.find(item => item.getAttribute("type") === "composer") ?? creators[0]);
124
+ })();
125
+ // 页面配置只有在 scaling 和完整尺寸同时存在时才接管 jpFun 默认值
126
+ let page;
127
+ const defaults = child(root, "defaults");
128
+ const scaling = defaults && child(defaults, "scaling");
129
+ const pageLayout = defaults && child(defaults, "page-layout");
130
+ if (scaling && pageLayout && child(pageLayout, "page-width") && child(pageLayout, "page-height")) {
131
+ // MusicXML 的 tenths 经毫米标尺换算成 CSS 像素
132
+ const millimeters = number(scaling, "millimeters");
133
+ const tenths = number(scaling, "tenths");
134
+ const pixelsPerTenth = millimeters / tenths * 96 / 25.4;
135
+ const marginList = children(pageLayout, "page-margins");
136
+ const margins = marginList.find(item => item.getAttribute("type") === "odd") ?? marginList[0];
137
+ if (Number.isFinite(pixelsPerTenth) && pixelsPerTenth > 0) {
138
+ page = {
139
+ width: number(pageLayout, "page-width") * pixelsPerTenth,
140
+ height: number(pageLayout, "page-height") * pixelsPerTenth,
141
+ top: margins ? number(margins, "top-margin", 48 / pixelsPerTenth) * pixelsPerTenth : 48,
142
+ bottom: margins ? number(margins, "bottom-margin", 48 / pixelsPerTenth) * pixelsPerTenth : 48,
143
+ left: margins ? number(margins, "left-margin", 40 / pixelsPerTenth) * pixelsPerTenth : 40,
144
+ right: margins ? number(margins, "right-margin", 40 / pixelsPerTenth) * pixelsPerTenth : 40,
145
+ };
146
+ }
147
+ }
148
+ // 先收集按时间定位的原始语义;关系端点在所有 part 解析完后统一配对
149
+ const lanes = new Map();
150
+ const meters = new Map();
151
+ const keys = new Map();
152
+ const tempos = new Map();
153
+ const directions = [];
154
+ const wedgePoints = [];
155
+ const endingPoints = new Map();
156
+ const bars = new Map();
157
+ const measureBoundaries = new Set();
158
+ const lineBreaks = new Set();
159
+ let scoreEnd = new Fraction();
160
+ let order = 0;
161
+ // 主时间解析:逐 part、逐小节扫描 attributes/direction/note/barline
162
+ const measuresByPart = partMeasures(root);
163
+ const partOrder = new Map([...measuresByPart.keys()].map((id, index) => [id, index]));
164
+ // 第一 part 决定全谱小节边界,其他 part 必须落在同一时间框架内
165
+ const controlPartId = measuresByPart.keys().next().value;
166
+ const controlMeasureLengths = [];
167
+ // 每个 part 独立解析,最终事件统一落到从乐谱开头计算的绝对时间
168
+ for (const [partId, measures] of measuresByPart) {
169
+ const partInstruments = instrumentsByPart.get(partId);
170
+ let divisions = 1;
171
+ let partTime = new Fraction();
172
+ let activeMeter = { numerator: 4, denominator: 4 };
173
+ const lastEvent = new Map();
174
+ const pendingGraces = new Map();
175
+ // 小节游标从零开始,partTime 保存当前小节在全谱中的绝对起点
176
+ for (let measureIndex = 0; measureIndex < measures.length; measureIndex++) {
177
+ const { body: measure, container: measureContainer } = measures[measureIndex];
178
+ let cursor = new Fraction();
179
+ let measureEnd = new Fraction();
180
+ if (measureContainer.getAttribute("implicit") !== "yes" && measureIndex > 0) {
181
+ setBar(bars, partTime, "|");
182
+ if (partId === controlPartId)
183
+ measureBoundaries.add(keyOf(partTime));
184
+ }
185
+ const print = child(measure, "print") ?? (measureContainer === measure ? undefined : child(measureContainer, "print"));
186
+ if (print?.getAttribute("new-system") === "yes" || print?.getAttribute("new-page") === "yes") {
187
+ if (!partTime.isZero())
188
+ lineBreaks.add(keyOf(partTime));
189
+ }
190
+ const measureItems = children(measure);
191
+ // 小节线的样式、反复和房子共享同一个绝对时间点
192
+ const recordBarline = (barline, at) => {
193
+ const repeatElement = child(barline, "repeat");
194
+ const repeat = repeatElement?.getAttribute("direction");
195
+ if (repeat === "forward")
196
+ setBar(bars, at, "|:");
197
+ else if (repeat === "backward") {
198
+ const timesValue = repeatElement?.getAttribute("times");
199
+ const times = timesValue ? Number(timesValue) : 2;
200
+ if (!Number.isSafeInteger(times) || times < 2)
201
+ throw new RangeError("MusicXML repeat times must be an integer of at least 2");
202
+ setBar(bars, at, new Array(times - 1).fill(":|").join(" "));
203
+ }
204
+ else if (text(barline, "bar-style") === "light-heavy")
205
+ setBar(bars, at, "||");
206
+ const ending = child(barline, "ending");
207
+ const endingType = ending?.getAttribute("type");
208
+ if (ending && (endingType === "start" || endingType === "stop" || endingType === "discontinue")) {
209
+ const passes = endingPasses(ending.getAttribute("number") ?? "");
210
+ if (passes.length > 0)
211
+ endingPoints.set(`${keyOf(at)}\0${endingType}\0${passes.join(",")}`, {
212
+ at: at.clone(),
213
+ type: endingType,
214
+ passes,
215
+ });
216
+ }
217
+ };
218
+ // 必须按 XML 原始顺序扫描,backup forward 和 chord 都依赖当前游标或前一事件
219
+ for (const item of measureItems) {
220
+ const tag = nameOf(item);
221
+ // attributes 从当前位置起更新 divisions 拍号和调号
222
+ if (tag === "attributes") {
223
+ const at = add(partTime, cursor);
224
+ if (child(item, "divisions"))
225
+ divisions = number(item, "divisions");
226
+ if (!Number.isSafeInteger(divisions) || divisions <= 0)
227
+ throw new RangeError("MusicXML divisions must be a positive integer");
228
+ const time = child(item, "time");
229
+ if (time) {
230
+ const { numerator, denominator } = parseTimeSignature(time);
231
+ activeMeter = { numerator, denominator };
232
+ meters.set(keyOf(at), { at, numerator, denominator });
233
+ }
234
+ const key = child(item, "key");
235
+ if (key) {
236
+ const fifths = number(key, "fifths", 0);
237
+ if (!Number.isSafeInteger(fifths))
238
+ throw new RangeError("MusicXML fifths must be an integer");
239
+ keys.set(keyOf(at), {
240
+ at,
241
+ fifths,
242
+ mode: text(key, "mode") || "major",
243
+ });
244
+ }
245
+ continue;
246
+ }
247
+ // backup 和 forward 只重定位当前小节游标,用于交错 voice
248
+ if (tag === "backup" || tag === "forward") {
249
+ const duration = new Fraction(number(item, "duration"), divisions);
250
+ if (tag === "backup")
251
+ cursor.sub(duration);
252
+ else
253
+ cursor.add(duration);
254
+ if (cursor.compare(0) < 0)
255
+ throw new RangeError("MusicXML backup moves before the measure start");
256
+ measureEnd = measureEnd.compare(cursor) < 0 ? cursor.clone() : measureEnd;
257
+ continue;
258
+ }
259
+ // direction 收集精确时间上的速度、力度、文字和楔形线端点
260
+ if (tag === "direction") {
261
+ const offset = new Fraction(number(item, "offset", 0), divisions);
262
+ const at = add(add(partTime, cursor), offset);
263
+ const sound = child(item, "sound");
264
+ const tempo = sound?.getAttribute("tempo");
265
+ const bpm = tempo !== null && tempo !== undefined && tempo !== "" ? Number(tempo) : metronomeBpm(item);
266
+ if (bpm !== undefined) {
267
+ if (!Number.isFinite(bpm) || bpm <= 0)
268
+ throw new RangeError("MusicXML tempo must be positive and finite");
269
+ tempos.set(keyOf(at), { at, bpm });
270
+ }
271
+ const dynamic = directionDynamic(item);
272
+ const texts = directionTexts(item);
273
+ if (dynamic || texts.length > 0)
274
+ directions.push({
275
+ at,
276
+ partId,
277
+ staff: text(item, "staff") || "1",
278
+ voice: text(item, "voice") || "",
279
+ placement: item.getAttribute("placement") === "below" ? "below" : "above",
280
+ dynamic,
281
+ texts,
282
+ });
283
+ const wedge = descendant(item, "wedge");
284
+ const wedgeType = wedge?.getAttribute("type");
285
+ if (wedgeType === "crescendo" || wedgeType === "diminuendo" || wedgeType === "stop") {
286
+ wedgePoints.push({
287
+ at,
288
+ partId,
289
+ staff: text(item, "staff") || "1",
290
+ voice: text(item, "voice") || "",
291
+ number: wedge?.getAttribute("number") || "1",
292
+ type: wedgeType,
293
+ });
294
+ }
295
+ continue;
296
+ }
297
+ // measure 直属 sound 也可能携带速度,不要求包在 direction 中
298
+ const tempo = tag === "sound" ? item.getAttribute("tempo") : null;
299
+ if (tempo !== null && tempo !== "") {
300
+ const bpm = Number(tempo);
301
+ if (!Number.isFinite(bpm) || bpm <= 0)
302
+ throw new RangeError("MusicXML tempo must be positive and finite");
303
+ const at = add(partTime, cursor);
304
+ tempos.set(keyOf(at), { at, bpm });
305
+ continue;
306
+ }
307
+ if (tag === "barline" && item.getAttribute("location") === "middle") {
308
+ recordBarline(item, add(partTime, cursor));
309
+ continue;
310
+ }
311
+ if (tag !== "note")
312
+ continue;
313
+ // note 先确定 lane 与 instrument,再区分打击乐、倚音、和弦成员和普通起音
314
+ const voice = text(item, "voice") || "1";
315
+ const staff = text(item, "staff") || "1";
316
+ const laneKey = `${partId}\0${staff}\0${voice}`;
317
+ const instrumentId = child(item, "instrument")?.getAttribute("id") ?? "";
318
+ const instrument = instrumentId
319
+ ? partInstruments?.byId.get(instrumentId)
320
+ : partInstruments?.fallback;
321
+ const pitch = parsePitch(item);
322
+ const rest = child(item, "rest") !== undefined;
323
+ if (!pitch && !rest) {
324
+ throw new TypeError("MusicXML note must contain pitch, unpitched, or rest");
325
+ }
326
+ const chord = child(item, "chord") !== undefined;
327
+ const grace = child(item, "grace");
328
+ // 打击乐尚未建模,但普通音符仍须推进游标以保持后续事件位置
329
+ if (instrument?.channel === 10) {
330
+ if (grace)
331
+ continue;
332
+ const duration = new Fraction(number(item, "duration"), divisions);
333
+ if (duration.compare(0) <= 0)
334
+ throw new RangeError("MusicXML non-grace notes require a positive duration");
335
+ if (!chord)
336
+ cursor.add(duration);
337
+ if (measureEnd.compare(cursor) < 0)
338
+ measureEnd = cursor.clone();
339
+ continue;
340
+ }
341
+ // lane 在首次遇到可保留事件时创建,纯打击乐轨不会留下空 lane
342
+ let lane = lanes.get(laneKey);
343
+ if (!lane) {
344
+ lane = {
345
+ partId,
346
+ partName: partNames.get(partId) ?? partId,
347
+ staff,
348
+ voice,
349
+ events: [],
350
+ };
351
+ lanes.set(laneKey, lane);
352
+ }
353
+ const previousEvent = lastEvent.get(laneKey);
354
+ if (grace) {
355
+ if (!pitch)
356
+ continue;
357
+ // 后倚音挂到前一事件,前倚音暂存到下一次真实起音
358
+ const stealTimePrevious = grace.getAttribute("steal-time-previous");
359
+ if (stealTimePrevious !== null && stealTimePrevious !== "" && previousEvent) {
360
+ const groups = previousEvent.postGraces;
361
+ if (chord && groups.length > 0)
362
+ groups.at(-1).push(pitch);
363
+ else
364
+ groups.push([pitch]);
365
+ }
366
+ else {
367
+ const groups = pendingGraces.get(laneKey) ?? [];
368
+ if (chord && groups.length > 0)
369
+ groups.at(-1).push(pitch);
370
+ else
371
+ groups.push([pitch]);
372
+ pendingGraces.set(laneKey, groups);
373
+ }
374
+ continue;
375
+ }
376
+ const duration = new Fraction(number(item, "duration"), divisions);
377
+ if (duration.compare(0) <= 0)
378
+ throw new RangeError("MusicXML non-grace notes require a positive duration");
379
+ const start = chord ? previousEvent?.start.clone() ?? add(partTime, cursor) : add(partTime, cursor);
380
+ let event = chord ? previousEvent : undefined;
381
+ const lyrics = noteLyrics(item);
382
+ const modifiers = noteModifiers(item);
383
+ const arpeggio = noteArpeggio(item);
384
+ // chord 成员只有起点和时值都一致时才合并到前一事件
385
+ if (!event || !event.start.equals(start) || !event.duration.equals(duration) || event.rest) {
386
+ event = {
387
+ start,
388
+ duration,
389
+ pitches: [],
390
+ rest,
391
+ order: order++,
392
+ modifiers,
393
+ annotations: [],
394
+ preGraces: pendingGraces.get(laneKey) ?? [],
395
+ postGraces: [],
396
+ lyrics,
397
+ arpeggio,
398
+ program: instrument?.program,
399
+ timeModification: timeModification(item),
400
+ };
401
+ pendingGraces.delete(laneKey);
402
+ lane.events.push(event);
403
+ lastEvent.set(laneKey, event);
404
+ }
405
+ else {
406
+ event.program ??= instrument?.program;
407
+ event.arpeggio = mergeArpeggio(event.arpeggio, arpeggio);
408
+ for (const modifier of modifiers) {
409
+ if (!event.modifiers.some(item => item.name === modifier.name && item.placement === modifier.placement)) {
410
+ event.modifiers.push(modifier);
411
+ }
412
+ }
413
+ }
414
+ if (pitch)
415
+ event.pitches.push(pitch);
416
+ for (const [verse, words] of lyrics) {
417
+ if (words && !event.lyrics.has(verse))
418
+ event.lyrics.set(verse, words);
419
+ }
420
+ if (!chord)
421
+ cursor.add(duration);
422
+ const relativeEnd = add(start, duration).sub(partTime);
423
+ if (measureEnd.compare(relativeEnd) < 0)
424
+ measureEnd = relativeEnd;
425
+ }
426
+ // 扫描完成后才能确定弱起长度和多 voice 的最远结束位置
427
+ const expected = new Fraction(activeMeter.numerator * 4, activeMeter.denominator);
428
+ // 弱起小节采用实际长度,普通小节至少占满当前拍号长度
429
+ const implicit = measureContainer.getAttribute("implicit") === "yes" || (measureIndex === 0 && measureEnd.compare(expected) < 0);
430
+ const ownLength = implicit ? measureEnd : measureEnd.compare(expected) > 0 ? measureEnd : expected;
431
+ let length = ownLength;
432
+ if (partId === controlPartId)
433
+ controlMeasureLengths[measureIndex] = ownLength.clone();
434
+ else if (controlMeasureLengths[measureIndex]) {
435
+ length = controlMeasureLengths[measureIndex].clone();
436
+ if (measureEnd.compare(length) > 0) {
437
+ throw new RangeError(`MusicXML part ${partId} exceeds the controlling measure duration`);
438
+ }
439
+ }
440
+ // 左右小节线依赖最终小节长度,中间小节线已在顺序扫描时处理
441
+ const measureFinish = add(partTime, length);
442
+ for (const barline of measureItems.filter(item => nameOf(item) === "barline")) {
443
+ const location = barline.getAttribute("location");
444
+ if (location === "middle")
445
+ continue;
446
+ recordBarline(barline, location === "left" ? partTime : measureFinish);
447
+ }
448
+ partTime.add(length);
449
+ if (scoreEnd.compare(partTime) < 0)
450
+ scoreEnd = partTime.clone();
451
+ }
452
+ setBar(bars, partTime, "||");
453
+ }
454
+ const laneList = [...lanes.values()];
455
+ // 将 start/stop 形式的范围标记配对,渲染阶段只消费完整区间
456
+ const wedges = [];
457
+ const activeWedges = new Map();
458
+ // wedge 按 part staff voice 和 number 配对,允许多个楔形线并行存在
459
+ for (const point of wedgePoints.sort((left, right) => left.at.compare(right.at))) {
460
+ const key = `${point.partId}\0${point.staff}\0${point.voice}\0${point.number}`;
461
+ if (point.type === "stop") {
462
+ const from = activeWedges.get(key);
463
+ if (from)
464
+ wedges.push({ from, end: point.at });
465
+ activeWedges.delete(key);
466
+ }
467
+ else
468
+ activeWedges.set(key, point);
469
+ }
470
+ const endings = [];
471
+ let activeEnding;
472
+ // ending 沿全谱时间顺序配对,起点持有适用遍数
473
+ for (const point of [...endingPoints.values()].sort((left, right) => left.at.compare(right.at))) {
474
+ if (point.type === "start")
475
+ activeEnding = point;
476
+ else if (activeEnding) {
477
+ endings.push({ from: activeEnding, end: point.at });
478
+ activeEnding = undefined;
479
+ }
480
+ }
481
+ // 只有房子没有音符时也要保留一条 lane 承载生成的端点
482
+ if (endings.length > 0 && laneList.length === 0 && controlPartId !== undefined) {
483
+ laneList.push({
484
+ partId: controlPartId,
485
+ partName: partNames.get(controlPartId) ?? controlPartId,
486
+ staff: "1",
487
+ voice: "1",
488
+ events: [],
489
+ });
490
+ }
491
+ const topLane = laneList[0];
492
+ // 为没有真实起音的房子补休止端点,保证 volta 始终能绑定可见事件
493
+ if (topLane)
494
+ for (const ending of endings) {
495
+ if (ending.from.at.compare(ending.end) >= 0)
496
+ continue;
497
+ const direction = directions.find(item => item.at.compare(ending.from.at) >= 0
498
+ && item.at.compare(ending.end) < 0);
499
+ const hostPartId = direction?.partId ?? topLane.partId;
500
+ const hostStaff = direction?.staff ?? topLane.staff;
501
+ const hostLanes = laneList.filter(lane => lane.partId === hostPartId && lane.staff === hostStaff);
502
+ const hasEndpoint = hostLanes.some(lane => lane.events.some(event => event.start.compare(ending.from.at) >= 0 && event.start.compare(ending.end) < 0));
503
+ if (!hasEndpoint) {
504
+ // 空房子需要一个不可冲突的休止事件作为 volta 标签端点
505
+ let hostLane = hostLanes.find(lane => !lane.events.some(event => event.start.compare(ending.end) < 0
506
+ && add(event.start, event.duration).compare(ending.from.at) > 0));
507
+ if (!hostLane) {
508
+ const voices = hostLanes.map(lane => Number(lane.voice)).filter(Number.isFinite);
509
+ hostLane = {
510
+ partId: hostPartId,
511
+ partName: partNames.get(hostPartId) ?? hostPartId,
512
+ staff: hostStaff,
513
+ voice: String(Math.max(0, ...voices) + 1),
514
+ events: [],
515
+ };
516
+ laneList.push(hostLane);
517
+ }
518
+ hostLane.events.push({
519
+ start: ending.from.at.clone(),
520
+ duration: ending.end.clone().sub(ending.from.at),
521
+ pitches: [],
522
+ rest: true,
523
+ order: order++,
524
+ modifiers: [],
525
+ annotations: [],
526
+ preGraces: [],
527
+ postGraces: [],
528
+ lyrics: new Map(),
529
+ });
530
+ hostLane.events.sort((left, right) => left.start.compare(right.start) || left.order - right.order);
531
+ }
532
+ }
533
+ // direction 没有明确 voice 时作用于同 staff 的所有 lane;文字只显示一次
534
+ for (const direction of directions) {
535
+ const candidates = laneList.filter(lane => lane.partId === direction.partId && lane.staff === direction.staff
536
+ && (!direction.voice || lane.voice === direction.voice));
537
+ const targets = candidates.length > 0
538
+ ? candidates
539
+ : laneList.filter(item => item.partId === direction.partId).slice(0, 1);
540
+ for (const lane of targets) {
541
+ const contained = lane.events.find(item => item.start.compare(direction.at) <= 0
542
+ && add(item.start, item.duration).compare(direction.at) > 0);
543
+ let event = contained ?? lane.events.find(item => item.start.compare(direction.at) >= 0);
544
+ if (!event)
545
+ event = lane.events.at(-1);
546
+ if (event && direction.dynamic)
547
+ event.modifiers.push({ name: direction.dynamic, placement: direction.placement });
548
+ }
549
+ if (direction.texts.length > 0) {
550
+ const events = targets.flatMap(lane => lane.events);
551
+ const textTarget = events.find(event => event.start.compare(direction.at) < 0
552
+ && add(event.start, event.duration).compare(direction.at) > 0)
553
+ ?? events.filter(event => event.start.compare(direction.at) >= 0)
554
+ .sort((left, right) => left.start.compare(right.start) || left.order - right.order)[0]
555
+ ?? events.at(-1);
556
+ textTarget?.annotations.push(...direction.texts.map(text => ({
557
+ ...text,
558
+ placement: direction.placement,
559
+ })));
560
+ }
561
+ }
562
+ // 输出顺序保持原 part 次序,再按 staff 和 voice 排列
563
+ return {
564
+ title,
565
+ subtitle,
566
+ creator,
567
+ page,
568
+ lanes: laneList.sort((left, right) => partOrder.get(left.partId) - partOrder.get(right.partId)
569
+ || Number(left.staff) - Number(right.staff)
570
+ || Number(left.voice) - Number(right.voice)),
571
+ meters: [...meters.values()].sort((left, right) => left.at.compare(right.at)),
572
+ keys: [...keys.values()].sort((left, right) => left.at.compare(right.at)),
573
+ tempos: [...tempos.values()].sort((left, right) => left.at.compare(right.at)),
574
+ wedges,
575
+ endings,
576
+ bars,
577
+ measureBoundaries,
578
+ lineBreaks,
579
+ end: scoreEnd,
580
+ };
581
+ }
582
+ /** 将 MusicXML 的 fifths + mode 转成 jpFun 可表示的主音拼写 */
583
+ function tonicName(key) {
584
+ if (!Number.isSafeInteger(key.fifths) || key.fifths < -7 || key.fifths > 7) {
585
+ throw new RangeError("jpFun supports MusicXML key signatures from -7 to 7 fifths");
586
+ }
587
+ const mode = key.mode.toLowerCase();
588
+ if (mode === "minor" || mode === "aeolian")
589
+ return MINOR_KEYS[key.fifths + 7];
590
+ if (mode === "major" || mode === "ionian")
591
+ return MAJOR_KEYS[key.fifths + 7];
592
+ const modalDegree = {
593
+ dorian: [1, 2], phrygian: [2, 4], lydian: [3, 5], mixolydian: [4, 7], locrian: [6, 11],
594
+ };
595
+ const shift = modalDegree[mode];
596
+ if (!shift)
597
+ throw new RangeError(`Unsupported MusicXML mode ${key.mode}`);
598
+ const major = MAJOR_KEYS[key.fifths + 7];
599
+ const letters = "CDEFGAB";
600
+ const letter = letters[(letters.indexOf(major[0]) + shift[0]) % letters.length];
601
+ const majorPitch = NoteNameMap[major[0]] + (major[1] === "#" ? 1 : major[1] === "b" ? -1 : 0);
602
+ const targetPitch = ((majorPitch + shift[1]) % 12 + 12) % 12;
603
+ const alteration = ((targetPitch - NoteNameMap[letter] + 18) % 12) - 6;
604
+ if (alteration < -1 || alteration > 1)
605
+ throw new RangeError(`MusicXML mode ${key.mode} requires an unsupported tonic spelling`);
606
+ return letter + (alteration === 1 ? "#" : alteration === -1 ? "b" : "");
607
+ }
608
+ function pointAt(points, at) {
609
+ const index = lowerBoundAt(points, at, point => point.at);
610
+ return index < points.length && points[index].at.equals(at)
611
+ ? points[index]
612
+ : points[Math.max(0, index - 1)];
613
+ }
614
+ /** 生成单个音高;octave=0 等有歧义的情况回退到显式 note */
615
+ function pitchSource(pitch, mode, key, metadata, suffix = "") {
616
+ let name;
617
+ let accidental;
618
+ let octave;
619
+ if (mode === "absolute") {
620
+ name = pitch.step;
621
+ accidental = pitch.alter > 0 ? "#".repeat(pitch.alter) : "b".repeat(-pitch.alter);
622
+ octave = pitch.octave;
623
+ }
624
+ else {
625
+ const midi = (pitch.octave + 1) * 12 + NoteNameMap[pitch.step] + pitch.alter;
626
+ const tonic = tonicName(key);
627
+ const tonicAlter = tonic[1] === "#" ? 1 : tonic[1] === "b" ? -1 : 0;
628
+ const difference = midi - 60 - NoteNameMap[tonic[0]] - tonicAlter;
629
+ const pitchClass = ((difference % 12) + 12) % 12;
630
+ name = RELATIVE_NAMES[pitchClass][0];
631
+ accidental = RELATIVE_NAMES[pitchClass].slice(1);
632
+ octave = Math.floor(difference / 12);
633
+ }
634
+ const label = metadata.labels.get(pitch);
635
+ return renderPitch({ name, accidental, octave }, mode, suffix) + (label ? `@${label}` : "");
636
+ }
637
+ /** 把和弦、倚音、力度和文字组合成一个 jpFun 原子表达式 */
638
+ function eventSource(event, mode, key, metadata, suffix = "") {
639
+ let source;
640
+ if (event.rest || event.pitches.length === 0)
641
+ source = `0${suffix}`;
642
+ else if (event.pitches.length === 1)
643
+ source = pitchSource(event.pitches[0], mode, key, metadata, suffix);
644
+ else
645
+ source = `{${event.pitches.map((pitch, index) => pitchSource(pitch, mode, key, metadata, index === 0 ? suffix : "")).join(" ^ ")}}`;
646
+ if (event.arpeggio && event.pitches.length >= 2) {
647
+ source = event.arpeggio === "none"
648
+ ? `@arp(${source})`
649
+ : `@arp(${source}, direction=${event.arpeggio})`;
650
+ }
651
+ const graceSource = (groups) => groups.map(group => group.length === 1
652
+ ? pitchSource(group[0], mode, key, metadata)
653
+ : `{${group.map(pitch => pitchSource(pitch, mode, key, metadata)).join(" ^ ")}}`);
654
+ if (event.preGraces.length > 0)
655
+ source = `{{${graceSource(event.preGraces).join(" ")}} > ${source}}`;
656
+ if (event.postGraces.length > 0)
657
+ source = `{${source} < {${graceSource(event.postGraces).join(" ")}}}`;
658
+ for (const modifier of event.modifiers) {
659
+ source = `{${source} ${modifier.placement === "below" ? "_" : "^"} $${modifier.name}}`;
660
+ }
661
+ for (const annotation of event.annotations) {
662
+ const text = quote(annotation.text);
663
+ source = `{${source} ${annotation.placement === "below" ? "_" : "^"} ${annotation.boxed ? `@box(${text})` : text}}`;
664
+ }
665
+ const label = metadata.labels.get(event);
666
+ if (label && event.pitches.length !== 1)
667
+ source += `@${label}`;
668
+ return source;
669
+ }
670
+ function powerOfTwo(value) {
671
+ return value > 0 && Number.isInteger(Math.log2(value));
672
+ }
673
+ function addDivisions(source, power) {
674
+ const divisions = "/".repeat(power);
675
+ // 标签必须留在减时线之后,否则词法层会把斜线吞进标签名
676
+ const label = source.match(/@mx\d+$/)?.[0];
677
+ return label ? source.slice(0, -label.length) + divisions + label : source + divisions;
678
+ }
679
+ function durationParts(duration) {
680
+ const result = [];
681
+ let numerator = duration.numerator;
682
+ // 从最大二进制块向下拆分,首块尽量吸收连续小块形成附点
683
+ for (let bit = Math.floor(Math.log2(numerator)); bit >= 0; bit--) {
684
+ const value = 2 ** bit;
685
+ if (numerator < value)
686
+ continue;
687
+ numerator -= value;
688
+ const fractionPower = Math.log2(duration.denominator) - bit;
689
+ let dots = 0;
690
+ if (result.length === 0 && fractionPower >= 0) {
691
+ for (let nextBit = bit - 1; nextBit >= 0 && numerator >= 2 ** nextBit; nextBit--) {
692
+ numerator -= 2 ** nextBit;
693
+ dots++;
694
+ }
695
+ }
696
+ result.push({ fractionPower, dots });
697
+ }
698
+ return result;
699
+ }
700
+ /**
701
+ * 把精确 Fraction 时值写成 `/`、`.` 和 continuation 序列。
702
+ * 非二进制分母必须已由外层 tuplet 块吸收,否则无法无损表示。
703
+ */
704
+ function durationSource(head, continuation, duration) {
705
+ if (!powerOfTwo(duration.denominator)) {
706
+ throw new RangeError(`MusicXML duration ${duration} requires a tuplet that jpFun cannot infer`);
707
+ }
708
+ const result = [];
709
+ for (const [index, { fractionPower, dots }] of durationParts(duration).entries()) {
710
+ const first = index === 0;
711
+ const suffix = `${"/".repeat(Math.max(0, fractionPower))}${".".repeat(dots)}`;
712
+ const renderedWithSuffix = first && typeof head === "function";
713
+ let source;
714
+ if (renderedWithSuffix)
715
+ source = head(suffix);
716
+ else
717
+ source = first ? head : continuation;
718
+ if (!renderedWithSuffix && fractionPower > 0)
719
+ source = addDivisions(source, fractionPower);
720
+ if (!renderedWithSuffix && dots > 0)
721
+ source += ".".repeat(dots);
722
+ else if (fractionPower < 0) {
723
+ const count = 2 ** -fractionPower;
724
+ result.push(source, ...new Array(count - 1).fill(continuation));
725
+ continue;
726
+ }
727
+ result.push(source);
728
+ }
729
+ return result.join(" ");
730
+ }
731
+ function restSlotCount(duration) {
732
+ if (!powerOfTwo(duration.denominator))
733
+ return 0;
734
+ return durationParts(duration).reduce((count, part) => count + (part.fractionPower < 0 ? 2 ** -part.fractionPower : 1), 0);
735
+ }
736
+ /**
737
+ * 将 lane 事件变成不可再切分的 RenderBlock。
738
+ * 普通事件一对一成块;连续 time-modification 事件先恢复书面时值,
739
+ * 再整体输出 @tuplet,保留跨小节组内的小节线。
740
+ */
741
+ function renderBlocks(lane, pitchMode, score, keys, adjustments, programs, metadata) {
742
+ const blocks = [];
743
+ const adjustmentPoints = [...adjustments?.values() ?? []]
744
+ .sort((left, right) => left.at.compare(right.at));
745
+ for (let index = 0; index < lane.events.length;) {
746
+ const event = lane.events[index];
747
+ const modification = event.timeModification;
748
+ if (!modification) {
749
+ blocks.push({ start: event.start, end: add(event.start, event.duration), event });
750
+ index++;
751
+ continue;
752
+ }
753
+ const group = [event];
754
+ const marked = modification.start;
755
+ while (++index < lane.events.length) {
756
+ const previous = group.at(-1);
757
+ if (previous.timeModification?.stop)
758
+ break;
759
+ const next = lane.events[index];
760
+ const nextModification = next.timeModification;
761
+ if (!nextModification
762
+ || nextModification.actual !== modification.actual
763
+ || nextModification.normal !== modification.normal
764
+ || !add(previous.start, previous.duration).equals(next.start)
765
+ || (!marked && group.length >= modification.actual))
766
+ break;
767
+ group.push(next);
768
+ }
769
+ if (group.length < 2)
770
+ throw new RangeError("MusicXML tuplet group must contain at least two consecutive events");
771
+ // 状态变化把成员切成更小片段,片段时值再从实际比例还原为书面比例
772
+ const slices = group.map(item => {
773
+ const end = add(item.start, item.duration);
774
+ let from = lowerBoundAt(adjustmentPoints, item.start, point => point.at);
775
+ if (adjustmentPoints[from]?.at.equals(item.start))
776
+ from++;
777
+ const to = lowerBoundAt(adjustmentPoints, end, point => point.at);
778
+ const points = [
779
+ item.start,
780
+ ...adjustmentPoints.slice(from, to).map(point => point.at),
781
+ end,
782
+ ];
783
+ return points.slice(0, -1).map((at, index) => ({
784
+ at,
785
+ duration: points[index + 1].clone().sub(at)
786
+ .mul(modification.actual, modification.normal),
787
+ }));
788
+ });
789
+ const writtenDurations = slices.flatMap(item => item.map(slice => slice.duration));
790
+ // 最短书面时值作为一个单位,由总单位数推导 jpFun 的 normal 参数
791
+ const shortest = writtenDurations.reduce((left, right) => left.compare(right) <= 0 ? left : right);
792
+ const writtenTotal = writtenDurations.reduce((sum, value) => sum.add(value), new Fraction());
793
+ const actualUnits = writtenTotal.div(shortest);
794
+ const normalUnits = actualUnits.clone().mul(modification.normal, modification.actual);
795
+ if (actualUnits.denominator !== 1 || normalUnits.denominator !== 1) {
796
+ throw new RangeError("MusicXML tuplet ratio cannot be represented by jpFun");
797
+ }
798
+ const lyricEvents = [];
799
+ const tokens = group.map((item, groupIndex) => {
800
+ const key = pointAt(keys, item.start);
801
+ const prefix = [];
802
+ const program = programs.get(keyOf(item.start));
803
+ if (program !== undefined)
804
+ prefix.push(`@program(${program})`);
805
+ if (groupIndex > 0) {
806
+ const bar = score.bars.get(keyOf(item.start));
807
+ if (bar)
808
+ prefix.push(bar);
809
+ }
810
+ const continuation = item.rest ? "0" : "-";
811
+ let slotCount = item.rest ? 0 : 1;
812
+ for (const [pointIndex, { at, duration }] of slices[groupIndex].entries()) {
813
+ const changes = adjustments?.get(keyOf(at))?.sources ?? [];
814
+ const head = pointIndex === 0 || changes.length > 0
815
+ ? (suffix) => attachAbove(pointIndex === 0 ? eventSource(item, pitchMode, key, metadata, suffix) : `${continuation}${suffix}`, changes)
816
+ : continuation;
817
+ prefix.push(durationSource(head, continuation, duration));
818
+ if (item.rest)
819
+ slotCount += restSlotCount(duration);
820
+ }
821
+ lyricEvents.push({ event: item, slotCount });
822
+ prefix.push(...metadata.afterSources.get(item) ?? []);
823
+ return prefix.join(" ");
824
+ });
825
+ const end = add(group.at(-1).start, group.at(-1).duration);
826
+ blocks.push({
827
+ start: group[0].start,
828
+ end,
829
+ source: `@tuplet({${tokens.join(" ")}}, ${normalUnits.numerator})`,
830
+ lyricEvents,
831
+ });
832
+ }
833
+ return blocks;
834
+ }
835
+ /**
836
+ * 为 tie、wedge 和 ending 找到实际音符端点,并生成稳定标签。
837
+ * tie 紧跟它的 stop 事件;dyn/volta 是完整区间关系,放在文档末尾。
838
+ */
839
+ function labelRelations(score) {
840
+ let labelIndex = 0;
841
+ const relations = [];
842
+ const metadata = {
843
+ labels: new Map(),
844
+ afterSources: new Map(),
845
+ };
846
+ const pitchLabel = (pitch) => {
847
+ const label = metadata.labels.get(pitch) ?? `mx${labelIndex++}`;
848
+ metadata.labels.set(pitch, label);
849
+ return label;
850
+ };
851
+ const active = new Map();
852
+ const endingActive = new Map();
853
+ const endings = [...score.endings].sort((left, right) => left.from.at.compare(right.from.at));
854
+ // 房子内维护独立 tie 状态,避免某一遍的端点污染房子外的主时间流
855
+ const containingEnding = (at) => {
856
+ const index = lowerBoundAt(endings, at, item => item.from.at);
857
+ const candidate = endings[index]?.from.at.equals(at) ? endings[index] : endings[index - 1];
858
+ return candidate && at.compare(candidate.end) < 0 ? candidate : undefined;
859
+ };
860
+ for (const lane of score.lanes) {
861
+ for (const event of lane.events) {
862
+ const ending = containingEnding(event.start);
863
+ const localActive = ending
864
+ ? endingActive.get(ending) ?? new Map()
865
+ : active;
866
+ if (ending)
867
+ endingActive.set(ending, localActive);
868
+ const orderedPitches = [
869
+ ...event.preGraces.flat(),
870
+ ...event.pitches,
871
+ ...event.postGraces.flat(),
872
+ ];
873
+ for (const pitch of orderedPitches) {
874
+ const key = `${lane.partId}\0${lane.staff}\0${lane.voice}\0${pitch.step}\0${pitch.alter}\0${pitch.octave}`;
875
+ const previous = localActive.get(key) ?? (ending ? active.get(key) : undefined);
876
+ if (pitch.tieStop && previous) {
877
+ const after = metadata.afterSources.get(event) ?? [];
878
+ after.push(`@tie(${pitchLabel(previous)}, ${pitchLabel(pitch)})`);
879
+ metadata.afterSources.set(event, after);
880
+ }
881
+ if (pitch.tieStart)
882
+ localActive.set(key, pitch);
883
+ else if (pitch.tieStop)
884
+ localActive.delete(key);
885
+ }
886
+ }
887
+ }
888
+ const eventLabel = (event) => {
889
+ if (event.pitches.length === 1)
890
+ return pitchLabel(event.pitches[0]);
891
+ const label = metadata.labels.get(event) ?? `mx${labelIndex++}`;
892
+ metadata.labels.set(event, label);
893
+ return label;
894
+ };
895
+ for (const wedge of score.wedges) {
896
+ // 连续楔形区间落到实际起音端点后再输出离散的 dyn 关系
897
+ const lanes = score.lanes.filter(item => item.partId === wedge.from.partId && item.staff === wedge.from.staff
898
+ && (!wedge.from.voice || item.voice === wedge.from.voice));
899
+ const targets = lanes.length > 0 ? lanes : score.lanes.filter(item => item.partId === wedge.from.partId).slice(0, 1);
900
+ for (const lane of targets) {
901
+ const sounding = lane.events.filter(event => !event.rest && event.pitches.length > 0);
902
+ const from = sounding.find(event => event.start.compare(wedge.from.at) <= 0
903
+ && add(event.start, event.duration).compare(wedge.from.at) > 0)
904
+ ?? sounding.find(event => event.start.compare(wedge.from.at) >= 0);
905
+ let to;
906
+ for (const event of sounding) {
907
+ if (event.start.compare(wedge.end) >= 0)
908
+ break;
909
+ to = event;
910
+ }
911
+ if (!from || !to || from.start.compare(to.start) >= 0)
912
+ continue;
913
+ const delta = wedge.from.type === "crescendo" ? 24 : -24;
914
+ relations.push(`@dyn(${eventLabel(from)}, ${eventLabel(to)}, ${delta})`);
915
+ }
916
+ }
917
+ const events = score.lanes.flatMap(lane => lane.events)
918
+ .sort((left, right) => left.start.compare(right.start) || left.order - right.order);
919
+ for (const ending of endings) {
920
+ const fromIndex = lowerBoundAt(events, ending.from.at, event => event.start);
921
+ const toIndex = lowerBoundAt(events, ending.end, event => event.start);
922
+ if (fromIndex >= toIndex)
923
+ continue;
924
+ const from = events[fromIndex];
925
+ const to = events[toIndex - 1];
926
+ relations.push(`@volta(${eventLabel(from)}, ${eventLabel(to)}, ${ending.from.passes.join(", ")})`);
927
+ }
928
+ return { relations, metadata };
929
+ }
930
+ /** 将完整 ParsedScore 序列化为 jpFun 源码 */
931
+ function renderScore(score, options) {
932
+ const pitchMode = options.pitchMode ?? "absolute";
933
+ if (pitchMode !== "relative" && pitchMode !== "absolute")
934
+ throw new TypeError("pitchMode must be relative or absolute");
935
+ const barsPerLine = options.barsPerLine ?? 4;
936
+ if (!Number.isSafeInteger(barsPerLine) || barsPerLine <= 0)
937
+ throw new RangeError("barsPerLine must be a positive integer");
938
+ // 缺失的零时刻状态由 jpFun 默认值补齐,保证 head 始终完整
939
+ const meters = score.meters.length === 0 || !score.meters[0].at.isZero()
940
+ ? [{ at: new Fraction(), numerator: 4, denominator: 4 }, ...score.meters]
941
+ : score.meters;
942
+ const keys = score.keys.length === 0 || !score.keys[0].at.isZero()
943
+ ? [{ at: new Fraction(), fifths: 0, mode: "major" }, ...score.keys]
944
+ : score.keys;
945
+ const tempos = score.tempos.length === 0 || !score.tempos[0].at.isZero()
946
+ ? [{ at: new Fraction(), bpm: 120 }, ...score.tempos]
947
+ : score.tempos;
948
+ // 初始状态进入 head;中途状态作为精确时间点只写在最上方 lane
949
+ const scoreAdjustments = new Map();
950
+ const addAdjustment = (at, source) => {
951
+ const key = keyOf(at);
952
+ const point = scoreAdjustments.get(key) ?? { at, sources: [] };
953
+ point.sources.push(source);
954
+ scoreAdjustments.set(key, point);
955
+ };
956
+ for (const item of keys.slice(1))
957
+ addAdjustment(item.at, `@1(${tonicName(item)}4)`);
958
+ for (const item of meters.slice(1))
959
+ addAdjustment(item.at, `@meter(${item.numerator}, ${item.denominator})`);
960
+ for (const item of tempos.slice(1))
961
+ addAdjustment(item.at, `@tempo(${item.bpm})`);
962
+ // 每条 lane 只记录 program 真正变化的起点
963
+ const programsByLane = score.lanes.map(lane => {
964
+ const programs = new Map();
965
+ let active;
966
+ for (const event of lane.events) {
967
+ if (event.program !== undefined && event.program !== active) {
968
+ active = event.program;
969
+ programs.set(keyOf(event.start), active);
970
+ }
971
+ }
972
+ return programs;
973
+ });
974
+ // 关系先分配标签,随后 eventSource 才能把标签写进正确音符
975
+ const { relations, metadata } = labelRelations(score);
976
+ const barTimes = [...score.bars.keys()].map(fractionFromKey)
977
+ .sort((left, right) => left.compare(right));
978
+ const measureBars = [...score.measureBoundaries].map(fractionFromKey)
979
+ .sort((left, right) => left.compare(right));
980
+ if (score.lineBreaks.size === 0) {
981
+ let barsOnLine = 0;
982
+ for (const at of measureBars) {
983
+ if (++barsOnLine === barsPerLine) {
984
+ score.lineBreaks.add(keyOf(at));
985
+ barsOnLine = 0;
986
+ }
987
+ }
988
+ }
989
+ const initialKey = keys[0];
990
+ const initialMeter = meters[0];
991
+ const initialTempo = tempos[0];
992
+ const page = score.page
993
+ ? `@page(width=${score.page.width}px, height=${score.page.height}px, top=${score.page.top}px, bottom=${score.page.bottom}px, left=${score.page.left}px, right=${score.page.right}px)\n`
994
+ : "";
995
+ // 明确的 MusicXML 换行优先;若会切开 tuplet,则丢弃该断点以保持时值组完整
996
+ const blocksByLane = score.lanes.map((lane, index) => renderBlocks(lane, pitchMode, score, keys, index === 0 ? scoreAdjustments : undefined, programsByLane[index], metadata));
997
+ const tupletSpans = blocksByLane.flatMap(blocks => blocks
998
+ .filter(block => block.source)
999
+ .map(block => ({ start: block.start, end: block.end })))
1000
+ .sort((left, right) => left.start.compare(right.start) || left.end.compare(right.end));
1001
+ const mergedTupletSpans = [];
1002
+ for (const span of tupletSpans) {
1003
+ const previous = mergedTupletSpans.at(-1);
1004
+ if (previous && span.start.compare(previous.end) < 0) {
1005
+ if (span.end.compare(previous.end) > 0)
1006
+ previous.end = span.end;
1007
+ }
1008
+ else
1009
+ mergedTupletSpans.push(span);
1010
+ }
1011
+ const lineBreaks = new Map([...score.lineBreaks]
1012
+ .map(value => [value, fractionFromKey(value)])
1013
+ .filter(([, at]) => !insideSpan(mergedTupletSpans, at)));
1014
+ // 每条 lane 独立沿同一组时间点输出;最后再按系统转置成完整 N: 组
1015
+ const voices = score.lanes.map((lane, laneIndex) => {
1016
+ const verses = new Set();
1017
+ for (const event of lane.events)
1018
+ for (const verse of event.lyrics.keys())
1019
+ verses.add(verse);
1020
+ const orderedVerses = [...verses].sort((left, right) => left.localeCompare(right, undefined, { numeric: true }));
1021
+ const outputs = [[]];
1022
+ const lyricTokens = [new Map(orderedVerses.map(verse => [verse, []]))];
1023
+ // 歌词槽与可见 note/rest 槽同步推进;缺词位置显式写 @ 占位
1024
+ const addLyricSlots = (event, count) => {
1025
+ for (const verse of orderedVerses) {
1026
+ const tokens = lyricTokens.at(-1).get(verse);
1027
+ for (let index = 0; index < count; index++) {
1028
+ const value = index === 0 && event ? event.lyrics.get(verse) : undefined;
1029
+ tokens.push(value ? lyricToken(value) : "@");
1030
+ }
1031
+ }
1032
+ };
1033
+ const blocks = blocksByLane[laneIndex];
1034
+ const tupletBlocks = blocks.filter(block => block.source);
1035
+ // 所有事件边界与控制点汇成一条时间线,每个相邻点只输出一个连续片段
1036
+ const points = new Map();
1037
+ points.set("0", new Fraction());
1038
+ points.set(keyOf(score.end), score.end);
1039
+ for (const block of blocks) {
1040
+ points.set(keyOf(block.start), block.start);
1041
+ points.set(keyOf(block.end), block.end);
1042
+ }
1043
+ for (const at of barTimes)
1044
+ if (!insideSpan(tupletBlocks, at))
1045
+ points.set(keyOf(at), at);
1046
+ for (const [value, at] of lineBreaks)
1047
+ points.set(value, at);
1048
+ if (laneIndex === 0) {
1049
+ for (const [value, point] of scoreAdjustments) {
1050
+ if (!insideSpan(tupletBlocks, point.at))
1051
+ points.set(value, point.at);
1052
+ }
1053
+ }
1054
+ const timeline = [...points.values()].sort((left, right) => left.compare(right));
1055
+ let blockIndex = 0;
1056
+ for (let index = 0; index < timeline.length; index++) {
1057
+ const at = timeline[index];
1058
+ while (blockIndex < blocks.length && blocks[blockIndex].end.compare(at) <= 0) {
1059
+ blockIndex++;
1060
+ }
1061
+ const bar = score.bars.get(keyOf(at));
1062
+ if (bar && (!at.isZero() || bar !== "|"))
1063
+ outputs.at(-1).push(bar);
1064
+ if (lineBreaks.has(keyOf(at))) {
1065
+ outputs.push([]);
1066
+ lyricTokens.push(new Map(orderedVerses.map(verse => [verse, []])));
1067
+ }
1068
+ const next = timeline[index + 1];
1069
+ if (!next)
1070
+ continue;
1071
+ const duration = next.clone().sub(at);
1072
+ if (duration.isZero())
1073
+ continue;
1074
+ const changes = laneIndex === 0 ? scoreAdjustments.get(keyOf(at))?.sources ?? [] : [];
1075
+ const block = blocks[blockIndex];
1076
+ if (block?.source) {
1077
+ if (!block.start.equals(at) || !block.end.equals(next)) {
1078
+ throw new RangeError("MusicXML tuplet cannot cross a barline or state change");
1079
+ }
1080
+ outputs.at(-1).push(block.source);
1081
+ for (const item of block.lyricEvents ?? []) {
1082
+ addLyricSlots(item.event, item.slotCount);
1083
+ }
1084
+ continue;
1085
+ }
1086
+ const program = programsByLane[laneIndex].get(keyOf(at));
1087
+ if (program !== undefined)
1088
+ outputs.at(-1).push(`@program(${program})`);
1089
+ const event = block?.event;
1090
+ if (event && block.start.compare(at) <= 0 && block.end.compare(next) >= 0) {
1091
+ const start = event.start.equals(at);
1092
+ const key = pointAt(keys, event.start);
1093
+ const continuation = event.rest ? "0" : "-";
1094
+ // 中途状态挂到 continuation,起音片段则重新生成完整事件源码
1095
+ const head = start || changes.length > 0
1096
+ ? (suffix) => attachAbove(start ? eventSource(event, pitchMode, key, metadata, suffix) : `${continuation}${suffix}`, changes)
1097
+ : continuation;
1098
+ outputs.at(-1).push(durationSource(head, continuation, duration));
1099
+ if (start)
1100
+ outputs.at(-1).push(...metadata.afterSources.get(event) ?? []);
1101
+ if (event.rest)
1102
+ addLyricSlots(start ? event : undefined, restSlotCount(duration));
1103
+ else if (start)
1104
+ addLyricSlots(event, 1);
1105
+ }
1106
+ else {
1107
+ const head = changes.length > 0
1108
+ ? (suffix) => attachAbove(`0${suffix}`, changes)
1109
+ : "0";
1110
+ outputs.at(-1).push(durationSource(head, "0", duration));
1111
+ addLyricSlots(undefined, restSlotCount(duration));
1112
+ }
1113
+ }
1114
+ const partName = lane.partName && (!score.lanes[laneIndex - 1] || score.lanes[laneIndex - 1].partId !== lane.partId)
1115
+ ? lane.partName
1116
+ : "";
1117
+ return outputs.map((output, lineIndex) => {
1118
+ const lyrics = orderedVerses.map(verse => quote(lyricTokens[lineIndex].get(verse).join(" ")));
1119
+ const lyricLines = lyrics.map(lyric => `L: ${lyric}`).join("\n");
1120
+ const name = lineIndex === 0 && partName ? `(${quote(partName)})` : "";
1121
+ return `N${name}: { ${output.join(" ")} }${lyricLines ? `\n${lyricLines}` : ""}`;
1122
+ });
1123
+ });
1124
+ const head = renderHead({
1125
+ title: score.title,
1126
+ subtitle: score.subtitle,
1127
+ author: score.creator,
1128
+ key: `${tonicName(initialKey)}4`,
1129
+ meter: [initialMeter.numerator, initialMeter.denominator],
1130
+ tempo: initialTempo.bpm,
1131
+ });
1132
+ const body = renderSystems(voices);
1133
+ return `${page}${head}\n\n${body}${relations.length > 0 ? `\n${relations.join(" ")}` : ""}`;
1134
+ }
1135
+ /** 将解析好的 MusicXML 根元素同步转换为可重新解析的 jpFun 源码 */
1136
+ export function musicXmlToJpFun(root, options = {}) {
1137
+ if (!root || root.nodeType !== 1)
1138
+ throw new TypeError("MusicXML root must be an element");
1139
+ return renderScore(parseScore(root), options);
1140
+ }