jpfun 0.3.0 → 0.4.1

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 (129) hide show
  1. package/README.md +73 -1
  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/functions/ASTtypes.d.ts +30 -26
  23. package/dist/functions/ASTtypes.js +25 -23
  24. package/dist/functions/adjust/index.js +13 -6
  25. package/dist/functions/arpeggio/index.d.ts +2 -0
  26. package/dist/functions/arpeggio/index.js +184 -0
  27. package/dist/functions/arpeggio/shape.d.ts +7 -0
  28. package/dist/functions/arpeggio/shape.js +122 -0
  29. package/dist/functions/bar/index.js +30 -23
  30. package/dist/functions/beam/auto.d.ts +1 -1
  31. package/dist/functions/beam/auto.js +1 -1
  32. package/dist/functions/beam/index.js +6 -1
  33. package/dist/functions/beam/layout.d.ts +3 -3
  34. package/dist/functions/beam/layout.js +5 -3
  35. package/dist/functions/box/index.js +10 -3
  36. package/dist/functions/br/index.js +10 -6
  37. package/dist/functions/dash/index.js +12 -9
  38. package/dist/functions/default.js +6 -2
  39. package/dist/functions/div/index.d.ts +4 -1
  40. package/dist/functions/div/index.js +8 -7
  41. package/dist/functions/dot/index.js +18 -25
  42. package/dist/functions/dyn/index.d.ts +2 -0
  43. package/dist/functions/dyn/index.js +242 -0
  44. package/dist/functions/grace/index.d.ts +1 -1
  45. package/dist/functions/grace/index.js +17 -11
  46. package/dist/functions/head/index.js +168 -159
  47. package/dist/functions/key/index.js +12 -7
  48. package/dist/functions/meter/index.js +14 -6
  49. package/dist/functions/note/index.js +73 -31
  50. package/dist/functions/note/noteNameFSM.js +52 -63
  51. package/dist/functions/page/index.d.ts +5 -1
  52. package/dist/functions/page/index.js +38 -16
  53. package/dist/functions/program/index.d.ts +2 -0
  54. package/dist/functions/program/index.js +39 -0
  55. package/dist/functions/set/index.js +13 -8
  56. package/dist/functions/stack/index.js +7 -5
  57. package/dist/functions/symbol/index.d.ts +13 -3
  58. package/dist/functions/symbol/index.js +71 -22
  59. package/dist/functions/symbol/shape.d.ts +2 -0
  60. package/dist/functions/symbol/shape.js +14 -10
  61. package/dist/functions/symbol/symbols/dc.d.ts +4 -0
  62. package/dist/functions/symbol/symbols/dc.js +82 -0
  63. package/dist/functions/symbol/symbols/{f.d.ts → ds.d.ts} +1 -1
  64. package/dist/functions/symbol/symbols/ds.js +93 -0
  65. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  66. package/dist/functions/symbol/symbols/dynamics.js +168 -0
  67. package/dist/functions/symbol/symbols/{p.d.ts → fine.d.ts} +1 -1
  68. package/dist/functions/symbol/symbols/fine.js +12 -0
  69. package/dist/functions/symbol/symbols/mordent.js +44 -31
  70. package/dist/functions/symbol/symbols/prall.d.ts +2 -0
  71. package/dist/functions/symbol/symbols/prall.js +42 -0
  72. package/dist/functions/symbol/symbols/segno.d.ts +4 -0
  73. package/dist/functions/symbol/symbols/segno.js +82 -0
  74. package/dist/functions/symbol/symbols/tr.js +0 -4
  75. package/dist/functions/tempo/index.js +12 -4
  76. package/dist/functions/temporal.d.ts +138 -0
  77. package/dist/functions/temporal.js +101 -0
  78. package/dist/functions/text/index.js +25 -10
  79. package/dist/functions/tie/index.js +45 -30
  80. package/dist/functions/tuplet/index.js +21 -8
  81. package/dist/functions/up/index.js +38 -33
  82. package/dist/functions/voice/index.js +153 -68
  83. package/dist/functions/volta/index.js +62 -55
  84. package/dist/iife/core.d.ts +1 -0
  85. package/dist/iife/core.js +3 -0
  86. package/dist/iife/from-midi.d.ts +1 -0
  87. package/dist/iife/from-midi.js +15 -0
  88. package/dist/iife/from-musicxml.d.ts +1 -0
  89. package/dist/iife/from-musicxml.js +3 -0
  90. package/dist/iife/full.d.ts +1 -0
  91. package/dist/iife/full.js +3 -0
  92. package/dist/index.d.ts +3 -21
  93. package/dist/index.js +3 -21
  94. package/dist/jpfun.core.min.js +119 -0
  95. package/dist/jpfun.from-midi.min.js +9 -0
  96. package/dist/jpfun.from-musicxml.min.js +12 -0
  97. package/dist/jpfun.min.js +111 -122
  98. package/dist/layout/default.js +2 -3
  99. package/dist/layout/engine.d.ts +2 -1
  100. package/dist/layout/engine.js +71 -26
  101. package/dist/layout/model.d.ts +4 -4
  102. package/dist/layout/model.js +15 -12
  103. package/dist/layout/page.js +5 -4
  104. package/dist/layout/path.js +3 -3
  105. package/dist/layout/types.d.ts +20 -2
  106. package/dist/lowering/loweringContext.d.ts +3 -1
  107. package/dist/lowering/loweringContext.js +28 -14
  108. package/dist/lowering/track.d.ts +4 -8
  109. package/dist/lowering/track.js +6 -1
  110. package/dist/lowering/types.d.ts +5 -128
  111. package/dist/lowering/types.js +1 -98
  112. package/dist/parser/parse-utils/string-utils.d.ts +2 -0
  113. package/dist/parser/parse-utils/string-utils.js +4 -0
  114. package/dist/parser/parserContext.d.ts +7 -8
  115. package/dist/parser/parserContext.js +41 -36
  116. package/dist/pipeline.d.ts +6 -5
  117. package/dist/pipeline.js +4 -5
  118. package/dist/playback/compile.d.ts +1 -1
  119. package/dist/playback/compile.js +15 -2
  120. package/dist/playback/event.d.ts +17 -3
  121. package/dist/playback/event.js +30 -12
  122. package/dist/playback/time.js +1 -1
  123. package/dist/playback/types.d.ts +5 -4
  124. package/dist/render/text.d.ts +6 -1
  125. package/dist/render/text.js +8 -1
  126. package/grammar.md +111 -57
  127. package/package.json +11 -2
  128. package/dist/functions/symbol/symbols/f.js +0 -55
  129. package/dist/functions/symbol/symbols/p.js +0 -61
@@ -0,0 +1,700 @@
1
+ import { identifyTriplets } from "./triplet.js";
2
+ import { attachAbove, quote, renderHead, renderPitch, renderSystems } from "../source.js";
3
+ const DEFAULT_BPM = 120;
4
+ const DEFAULT_TIME_SIGNATURE = [4, 4];
5
+ const AUTO_LINE_TARGET_RATIO = 1.03;
6
+ const AUTO_LINE_LIMIT_RATIO = 1.25;
7
+ const AUTO_LINE_UNDERFILL_PENALTY = 4;
8
+ const AUTO_LINE_MAX_BARS = 8;
9
+ const RELATIVE_NAMES = ["1", "1#", "2", "2#", "3", "4", "4#", "5", "5#", "6", "6#", "7"];
10
+ const ABSOLUTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
11
+ function expectSafeInteger(value, name, min = 0, max = Number.MAX_SAFE_INTEGER) {
12
+ if (!Number.isSafeInteger(value) || value < min || value > max) {
13
+ throw new RangeError(`${name} must be an integer in ${min}..${max}`);
14
+ }
15
+ }
16
+ function expectArray(value, name) {
17
+ if (!Array.isArray(value))
18
+ throw new TypeError(`${name} must be an array`);
19
+ }
20
+ function durationDivisions(durationTicks, ticksPerQuarter, alignRate) {
21
+ let divisions = 1;
22
+ while (ticksPerQuarter * alignRate > durationTicks * 2 ** divisions)
23
+ divisions++;
24
+ return divisions;
25
+ }
26
+ function coalesceSorted(items) {
27
+ const result = new Map();
28
+ for (const item of items)
29
+ result.set(item.at, item);
30
+ return [...result.values()];
31
+ }
32
+ function heapPush(heap, value, compare) {
33
+ let index = heap.length;
34
+ heap.push(value);
35
+ while (index > 0) {
36
+ const parent = (index - 1) >> 1;
37
+ if (compare(heap[parent], value) <= 0)
38
+ break;
39
+ heap[index] = heap[parent];
40
+ index = parent;
41
+ }
42
+ heap[index] = value;
43
+ }
44
+ function heapPop(heap, compare) {
45
+ const result = heap[0];
46
+ const value = heap.pop();
47
+ if (heap.length === 0)
48
+ return result;
49
+ let index = 0;
50
+ while (true) {
51
+ const left = index * 2 + 1;
52
+ if (left >= heap.length)
53
+ break;
54
+ const right = left + 1;
55
+ const child = right < heap.length && compare(heap[right], heap[left]) < 0 ? right : left;
56
+ if (compare(heap[child], value) >= 0)
57
+ break;
58
+ heap[index] = heap[child];
59
+ index = child;
60
+ }
61
+ heap[index] = value;
62
+ return result;
63
+ }
64
+ function noteName(midi, mode) {
65
+ const pitchClass = midi % 12;
66
+ const octave = Math.floor(midi / 12) - 1;
67
+ const source = mode === "absolute" ? ABSOLUTE_NAMES[pitchClass] : RELATIVE_NAMES[pitchClass];
68
+ return renderPitch({
69
+ name: source[0],
70
+ accidental: source.slice(1),
71
+ octave: mode === "absolute" ? octave : octave - 4,
72
+ }, mode);
73
+ }
74
+ function meterDuration(point, scale) {
75
+ return point.numerator * 4 * scale / point.denominator;
76
+ }
77
+ function pointAt(points, at) {
78
+ let left = 0;
79
+ let right = points.length - 1;
80
+ while (left < right) {
81
+ const middle = Math.ceil((left + right) / 2);
82
+ if (points[middle].at <= at)
83
+ left = middle;
84
+ else
85
+ right = middle - 1;
86
+ }
87
+ return points[left];
88
+ }
89
+ function quantizeTime(raw, divisions, meters, scale) {
90
+ const meter = pointAt(meters, raw);
91
+ const measureLength = meterDuration(meter, scale);
92
+ const measure = Math.max(0, Math.floor((raw - meter.at) / measureLength));
93
+ const measureStart = meter.at + measure * measureLength;
94
+ const step = scale / 2 ** divisions;
95
+ return measureStart + Math.round((raw - measureStart) / step) * step;
96
+ }
97
+ /**
98
+ * 把拍号变化吸附到最近的小节边界。
99
+ * 后续量化、三连音 blocker 和小节线都共享这一份结果,避免各阶段边界不一致。
100
+ */
101
+ function normalizeMeterTicks(points, ticksPerQuarter) {
102
+ const coalesced = new Map();
103
+ for (const point of points)
104
+ coalesced.set(point.ticks, point);
105
+ const result = [];
106
+ for (const candidate of coalesced.values()) {
107
+ const previous = result.at(-1);
108
+ if (!previous) {
109
+ result.push(candidate);
110
+ continue;
111
+ }
112
+ const measureTicks = previous.numerator * 4 * ticksPerQuarter / previous.denominator;
113
+ const count = Math.max(0, Math.round((candidate.ticks - previous.ticks) / measureTicks));
114
+ const point = { ...candidate, ticks: previous.ticks + count * measureTicks };
115
+ if (point.ticks === previous.ticks)
116
+ result[result.length - 1] = point;
117
+ else
118
+ result.push(point);
119
+ }
120
+ return result;
121
+ }
122
+ /** 返回拍号变化之间所有真正的小节边界,三连音不能跨过这些位置 */
123
+ function measureBoundaries(meters, rawEnd, ticksPerQuarter) {
124
+ const result = [];
125
+ for (let index = 0; index < meters.length; index++) {
126
+ const meter = meters[index];
127
+ const next = meters[index + 1]?.ticks ?? rawEnd;
128
+ const duration = meter.numerator * 4 * ticksPerQuarter / meter.denominator;
129
+ for (let at = meter.ticks + duration; at < next && at < rawEnd; at += duration)
130
+ result.push(at);
131
+ }
132
+ return result;
133
+ }
134
+ /** 同起点、同终点的音符组成和弦;不同长度的重叠音仍保持独立 */
135
+ function combineChords(notes) {
136
+ const groups = new Map();
137
+ for (const note of notes) {
138
+ const key = `${note.start}:${note.end}`;
139
+ const item = groups.get(key);
140
+ if (item) {
141
+ item.notes.push(note);
142
+ }
143
+ else {
144
+ groups.set(key, {
145
+ start: note.start,
146
+ end: note.end,
147
+ notes: [note],
148
+ triplet: note.triplet,
149
+ });
150
+ }
151
+ }
152
+ const result = [...groups.values()];
153
+ for (const item of result)
154
+ item.notes.sort((left, right) => left.midi - right.midi);
155
+ return result.sort((left, right) => left.start - right.start || left.end - right.end);
156
+ }
157
+ /** 把同一识别组的三个槽折叠为一个三连音原子,其余和弦原样保留 */
158
+ function groupTriplets(chords) {
159
+ const groups = new Map();
160
+ const result = [];
161
+ for (const chord of chords) {
162
+ if (chord.triplet) {
163
+ const members = groups.get(chord.triplet.group) ?? [];
164
+ members.push(chord);
165
+ groups.set(chord.triplet.group, members);
166
+ }
167
+ else
168
+ result.push(chord);
169
+ }
170
+ for (const members of groups.values()) {
171
+ members.sort((left, right) => left.triplet.slot - right.triplet.slot);
172
+ result.push({ start: members[0].start, end: members.at(-1).end, members });
173
+ }
174
+ return result.sort((left, right) => left.start - right.start || left.end - right.end);
175
+ }
176
+ /**
177
+ * 贪心分配重叠内容:能接在已有 lane 尾部就复用,否则新建 lane。
178
+ * lane 最后按平均音高从低到高排序,最高 lane 用来承载全谱 tempo/meter 标记。
179
+ */
180
+ function splitLanes(items) {
181
+ const lanes = [];
182
+ // active 按结束时间回收 lane,available 按原索引优先复用空闲 lane
183
+ const active = [];
184
+ const available = [];
185
+ const compareActive = (left, right) => left.end - right.end || left.laneIndex - right.laneIndex;
186
+ const compareLaneIndex = (left, right) => left - right;
187
+ for (const item of items) {
188
+ while (active.length > 0 && active[0].end <= item.start) {
189
+ heapPush(available, heapPop(active, compareActive).laneIndex, compareLaneIndex);
190
+ }
191
+ const laneIndex = available.length > 0 ? heapPop(available, compareLaneIndex) : lanes.length;
192
+ const lane = lanes[laneIndex] ?? { items: [] };
193
+ if (laneIndex === lanes.length)
194
+ lanes.push(lane);
195
+ lane.items.push(item);
196
+ heapPush(active, { end: item.end, laneIndex }, compareActive);
197
+ }
198
+ // 低音 lane 排在前面,最高 lane 固定承载全谱状态以保持输出稳定
199
+ const averagePitch = (lane) => {
200
+ let sum = 0;
201
+ let count = 0;
202
+ for (const item of lane.items) {
203
+ const chords = "members" in item ? item.members : [item];
204
+ for (const chord of chords) {
205
+ for (const note of chord.notes) {
206
+ sum += note.midi;
207
+ count++;
208
+ }
209
+ }
210
+ }
211
+ return sum / count;
212
+ };
213
+ return lanes.map(lane => ({ lane, averagePitch: averagePitch(lane) }))
214
+ .sort((left, right) => left.averagePitch - right.averagePitch)
215
+ .map(item => item.lane);
216
+ }
217
+ /** 只把传递重叠的事件放进同一区域;每个区域独立生成局部 @stack,边界不会切断事件 */
218
+ function splitRegions(items) {
219
+ const regions = [];
220
+ let group = [];
221
+ let end = 0;
222
+ const flush = () => {
223
+ if (group.length === 0)
224
+ return;
225
+ regions.push({ start: group[0].start, end, lanes: splitLanes(group) });
226
+ group = [];
227
+ };
228
+ for (const item of items) {
229
+ if (group.length > 0 && item.start >= end)
230
+ flush();
231
+ group.push(item);
232
+ end = Math.max(end, item.end);
233
+ }
234
+ flush();
235
+ return regions;
236
+ }
237
+ /** 把整数时值分解为 jpFun 的 `/` 与 `.` 后缀;剩余部分会另写为 dash/rest */
238
+ function rhythmSuffixes(duration, scale) {
239
+ const result = [];
240
+ let remaining = duration;
241
+ let first = true;
242
+ while (remaining > 0) {
243
+ const base = 2 ** Math.floor(Math.log2(Math.min(remaining, scale)));
244
+ remaining -= base;
245
+ let dots = 0;
246
+ if (first && remaining < scale) {
247
+ for (let next = base / 2; next >= 1 && remaining >= next; next /= 2) {
248
+ remaining -= next;
249
+ dots++;
250
+ }
251
+ }
252
+ const divisions = Math.log2(scale / base);
253
+ result.push("/".repeat(divisions) + ".".repeat(dots));
254
+ first = false;
255
+ }
256
+ return result;
257
+ }
258
+ /**
259
+ * 自动换行不猜“几个音符算一行”:先在超宽页面上排出单行自然宽度,
260
+ * 再按小节的实际对象边界做动态规划,使各行接近默认页面内容宽。
261
+ */
262
+ function automaticLineBreaks(source, bars, scale, capability) {
263
+ // 超宽页面关闭自动换行,从真实布局对象取得每个小节的自然宽度
264
+ const naturalWidth = Math.max(1_000_000, source.length * 64);
265
+ const naturalSource = `@page(width=${naturalWidth}px, height=0px, top=0px, bottom=0px, left=0px, right=0px)\n${source}`;
266
+ const layout = capability.compileScore(naturalSource).layout;
267
+ const bodyLine = Math.max(...layout.objects.filter(node => !node.T.isZero()).map(node => node.layoutLine));
268
+ const bodyObjects = layout.objects.filter(node => node.layoutLine === bodyLine && node.box.w > 0);
269
+ const measureBounds = bars.map(() => ({ left: Infinity, right: -Infinity }));
270
+ // 按对象起点归入小节,小节线本身属于左侧刚结束的小节
271
+ for (const node of bodyObjects) {
272
+ const at = Math.round(node.t.toNumber() * scale);
273
+ let low = 0;
274
+ let high = bars.length;
275
+ while (low < high) {
276
+ const middle = (low + high) >>> 1;
277
+ const end = bars[middle];
278
+ if (at < end || (at === end && node.mergeKey === capability.anchorKey))
279
+ high = middle;
280
+ else
281
+ low = middle + 1;
282
+ }
283
+ let measure = low;
284
+ if (measure >= bars.length)
285
+ measure = bars.length - 1;
286
+ const bounds = measureBounds[measure];
287
+ bounds.left = Math.min(bounds.left, node.box.x);
288
+ bounds.right = Math.max(bounds.right, node.box.x + node.box.w);
289
+ }
290
+ const contentWidth = capability.page.width
291
+ - capability.page.marginLeft - capability.page.marginRight;
292
+ const targetWidth = contentWidth * AUTO_LINE_TARGET_RATIO;
293
+ const limitWidth = contentWidth * AUTO_LINE_LIMIT_RATIO;
294
+ // best[end] 保存排完前 end 个小节的最小累计失衡和上一断点
295
+ const best = [
296
+ { imbalance: 0, previous: -1 },
297
+ ];
298
+ for (let end = 1; end <= bars.length; end++) {
299
+ let choice;
300
+ // 向前枚举当前行起点,只保留宽度和最大小节数允许的候选
301
+ for (let start = end - 1; start >= Math.max(0, end - AUTO_LINE_MAX_BARS); start--) {
302
+ let left = Infinity;
303
+ let right = -Infinity;
304
+ for (let measure = start; measure < end; measure++) {
305
+ left = Math.min(left, measureBounds[measure].left);
306
+ right = Math.max(right, measureBounds[measure].right);
307
+ }
308
+ const width = right - left;
309
+ if (width > limitWidth && start < end - 1)
310
+ continue;
311
+ const before = best[start];
312
+ if (!before)
313
+ continue;
314
+ const difference = width - targetWidth;
315
+ const candidate = {
316
+ imbalance: before.imbalance + difference ** 2
317
+ * (width < contentWidth ? AUTO_LINE_UNDERFILL_PENALTY : 1),
318
+ previous: start,
319
+ };
320
+ if (!choice || candidate.imbalance < choice.imbalance)
321
+ choice = candidate;
322
+ }
323
+ best[end] = choice;
324
+ }
325
+ // 从终点沿 previous 回溯得到全局最优断点
326
+ const lineBreaks = new Set();
327
+ for (let end = bars.length; best[end].previous > 0; end = best[end].previous) {
328
+ lineBreaks.add(bars[best[end].previous - 1]);
329
+ }
330
+ return lineBreaks;
331
+ }
332
+ function itemHead(item, pitchMode, suffix = "", labels) {
333
+ const labelAt = (index) => labels ? `@${labels[index]}` : "";
334
+ return item.notes.length === 1
335
+ ? `${noteName(item.notes[0].midi, pitchMode)}${suffix}${labelAt(0)}`
336
+ : `{${item.notes.map((note, index) => `${noteName(note.midi, pitchMode)}${index === 0 ? suffix : ""}${labelAt(index)}`).join(" ^ ")}}`;
337
+ }
338
+ /**
339
+ * 把一个 lane 沿“音符起止、小节、元事件”切成时间片并输出源码。
340
+ * dash 只允许延续本小节内已经出现的音;跨小节或不足一拍时重写同音,
341
+ * 每个和弦成员分别收集完整标签链,音结束时一次输出 @tie(x, y, ...)。
342
+ */
343
+ function renderLane(lane, rangeStart, rangeEnd, rhythmScale, timeFactor, pitchMode, bars, lineBreaks, adjustments, programs, nextTieLabel) {
344
+ // 事件边界与所有控制点共同切分时间线,保证每个片段内语义不变
345
+ const points = new Set([rangeStart, rangeEnd]);
346
+ for (const item of lane.items) {
347
+ points.add(item.start);
348
+ points.add(item.end);
349
+ }
350
+ for (const at of bars)
351
+ if (at > rangeStart && at < rangeEnd)
352
+ points.add(at);
353
+ for (const at of adjustments?.keys() ?? []) {
354
+ if (at >= rangeStart && at < rangeEnd)
355
+ points.add(at);
356
+ }
357
+ for (const at of programs?.keys() ?? []) {
358
+ if (at >= rangeStart && at < rangeEnd)
359
+ points.add(at);
360
+ }
361
+ const timeline = [...points].sort((left, right) => left - right);
362
+ const timelineIndex = new Map(timeline.map((at, index) => [at, index]));
363
+ const tieChains = new Map();
364
+ // 每次重写和弦都为每个成员生成标签并追加到各自的 tie 链
365
+ const extendTieChains = (chains) => chains.map(chain => {
366
+ const label = nextTieLabel();
367
+ chain.push(label);
368
+ return label;
369
+ });
370
+ // 预扫描找出不能只用 dash 延续的音符,提前为其建立逐音高标签链
371
+ for (const item of lane.items) {
372
+ if ("members" in item)
373
+ continue;
374
+ const startIndex = timelineIndex.get(item.start);
375
+ for (let index = startIndex; timeline[index] < item.end; index++) {
376
+ const suffixes = rhythmSuffixes((timeline[index + 1] - timeline[index]) / timeFactor, rhythmScale);
377
+ if ((timeline[index] > item.start && bars.has(timeline[index]))
378
+ || suffixes.some((suffix, suffixIndex) => (timeline[index] > item.start || suffixIndex > 0) && suffix.includes("/"))) {
379
+ tieChains.set(item, item.notes.map(() => []));
380
+ break;
381
+ }
382
+ }
383
+ }
384
+ const outputs = Array.from({ length: lineBreaks.size + 1 }, () => []);
385
+ let outputIndex = [...lineBreaks].filter(at => at <= rangeStart).length;
386
+ let itemIndex = 0;
387
+ // 沿时间片单向推进当前事件,依次输出控制项、音符或补齐休止
388
+ for (let index = 0; index < timeline.length; index++) {
389
+ const at = timeline[index];
390
+ while (itemIndex < lane.items.length && lane.items[itemIndex].end <= at)
391
+ itemIndex++;
392
+ if (at > rangeStart && at < rangeEnd && bars.has(at))
393
+ outputs[outputIndex].push("|");
394
+ if (at > rangeStart && at < rangeEnd && lineBreaks.has(at))
395
+ outputIndex++;
396
+ const next = timeline[index + 1];
397
+ if (next === undefined)
398
+ continue;
399
+ const program = programs?.get(at);
400
+ if (program !== undefined)
401
+ outputs[outputIndex].push(`@program(${program})`);
402
+ const changes = adjustments?.get(at) ?? [];
403
+ const item = lane.items[itemIndex];
404
+ if (item && item.start <= at && item.end >= next) {
405
+ // 三连音作为原子一次输出,外层时间线直接跳到整组末尾
406
+ if ("members" in item && at === item.start) {
407
+ const writtenDuration = (item.members[0].end - item.members[0].start) * 3 / (2 * timeFactor);
408
+ const suffix = rhythmSuffixes(writtenDuration, rhythmScale).join("");
409
+ const content = item.members.map(member => itemHead(member, pitchMode, suffix)).join(" ");
410
+ outputs[outputIndex].push(attachAbove(`@tuplet({${content}}, 2)`, changes));
411
+ index = timelineIndex.get(item.end) - 1;
412
+ continue;
413
+ }
414
+ if ("members" in item)
415
+ throw new Error("MIDI triplet rendering must start at its first slot");
416
+ const suffixes = rhythmSuffixes((next - at) / timeFactor, rhythmScale);
417
+ // 普通音符可能拆成多个二进制片段,只有首片段承载状态变化
418
+ for (let suffixIndex = 0; suffixIndex < suffixes.length; suffixIndex++) {
419
+ const suffix = suffixes[suffixIndex];
420
+ const continuation = at > item.start || suffixIndex > 0;
421
+ let token;
422
+ const chains = tieChains.get(item);
423
+ if (!continuation) {
424
+ if (chains) {
425
+ token = itemHead(item, pitchMode, suffix, extendTieChains(chains));
426
+ }
427
+ else {
428
+ token = itemHead(item, pitchMode, suffix);
429
+ }
430
+ }
431
+ else if ((suffixIndex === 0 && bars.has(at)) || suffix.includes("/")) {
432
+ token = itemHead(item, pitchMode, suffix, extendTieChains(chains));
433
+ }
434
+ else {
435
+ token = `-${suffix}`;
436
+ }
437
+ if (suffixIndex === 0)
438
+ token = attachAbove(token, changes);
439
+ outputs[outputIndex].push(token);
440
+ if (chains && next === item.end && suffixIndex === suffixes.length - 1) {
441
+ outputs[outputIndex].push(...chains.map(labels => `@tie(${labels.join(", ")})`));
442
+ }
443
+ }
444
+ }
445
+ else {
446
+ // 没有事件覆盖的时间片用可见休止补齐每条 lane
447
+ outputs[outputIndex].push(...rhythmSuffixes((next - at) / timeFactor, rhythmScale)
448
+ .map((suffix, index) => index === 0 ? attachAbove(`0${suffix}`, changes) : `0${suffix}`));
449
+ }
450
+ }
451
+ return outputs.map(output => output.join(" "));
452
+ }
453
+ function renderTrack(track, scoreEnd, bars, lineBreaks, render, showName) {
454
+ const lineCount = lineBreaks.size + 1;
455
+ const outputs = Array.from({ length: lineCount }, () => []);
456
+ const segments = [];
457
+ let cursor = 0;
458
+ // 在重叠区域之间插入空区域,让每条 track 覆盖完整乐谱时长
459
+ for (const region of track.regions) {
460
+ if (cursor < region.start)
461
+ segments.push({ start: cursor, end: region.start, lanes: [{ items: [] }] });
462
+ segments.push(region);
463
+ cursor = region.end;
464
+ }
465
+ if (cursor < scoreEnd)
466
+ segments.push({ start: cursor, end: scoreEnd, lanes: [{ items: [] }] });
467
+ // 每个重叠区域独立渲染,多 lane 只在该区域局部组成 @stack
468
+ for (const region of segments) {
469
+ if (region.start > 0 && bars.has(region.start)) {
470
+ const lineIndex = [...lineBreaks].filter(at => at < region.start).length;
471
+ outputs[lineIndex].push("|");
472
+ }
473
+ const lanes = region.lanes.map(lane => render(region, lane));
474
+ for (let lineIndex = 0; lineIndex < lineCount; lineIndex++) {
475
+ if (!lanes.some(lines => lines[lineIndex]))
476
+ continue;
477
+ const content = lanes.length === 1
478
+ ? lanes[0][lineIndex]
479
+ : `@stack(${lanes.map(lines => `{ ${lines[lineIndex]} }`).join(", ")})`;
480
+ outputs[lineIndex].push(content);
481
+ }
482
+ }
483
+ if (bars.has(scoreEnd))
484
+ outputs[lineCount - 1].push("|");
485
+ return outputs.map((output, lineIndex) => {
486
+ const name = showName && lineIndex === 0 && track.source.name ? `(${quote(track.source.name)})` : "";
487
+ return `N${name}: { ${output.join(" ")} }`;
488
+ });
489
+ }
490
+ /**
491
+ * 公开转换入口。options 只控制表示方式;量化后的 track/note 仍保留原始字段,
492
+ * 方便后续加入力度、乐器和踏板时直接扩展现有时间线。
493
+ */
494
+ export function convertMidiJsonToJpFun(input, options = {}, layoutCapability) {
495
+ // 入口先验证容器形状和影响全局算法的选项
496
+ if (!input || typeof input !== "object" || !input.header || typeof input.header !== "object") {
497
+ throw new TypeError("MIDI JSON must contain a header");
498
+ }
499
+ expectArray(input.tracks, "tracks");
500
+ expectArray(input.header.tempos, "header.tempos");
501
+ expectArray(input.header.timeSignatures, "header.timeSignatures");
502
+ if (typeof input.header.name !== "string")
503
+ throw new TypeError("header.name must be a string");
504
+ const ticksPerQuarter = input.header.tick;
505
+ expectSafeInteger(ticksPerQuarter, "header.tick", 1, 0x7fff);
506
+ const alignRate = options.alignRate ?? 4;
507
+ expectSafeInteger(alignRate, "alignRate", 2, 16);
508
+ const barsPerLine = options.barsPerLine ?? 0;
509
+ if (!Number.isSafeInteger(barsPerLine))
510
+ throw new RangeError("barsPerLine must be an integer");
511
+ const pitchMode = options.pitchMode ?? "absolute";
512
+ if (pitchMode !== "relative" && pitchMode !== "absolute") {
513
+ throw new TypeError("pitchMode must be relative or absolute");
514
+ }
515
+ const title = options.title ?? input.header.name;
516
+ if (typeof title !== "string")
517
+ throw new TypeError("title must be a string");
518
+ // 第一阶段:校验 note,并从最短时值求出全曲需要的二进制精度
519
+ const sourceTracks = [];
520
+ let rawNoteEnd = 0;
521
+ let globalDivisions = 1;
522
+ // 逐轨校验并复制会被后续阶段标记的 note,跳过尚未建模的打击乐通道
523
+ for (const [trackIndex, track] of input.tracks.entries()) {
524
+ if (!track || typeof track !== "object" || typeof track.name !== "string") {
525
+ throw new TypeError(`tracks[${trackIndex}] must contain a string name`);
526
+ }
527
+ expectSafeInteger(track.channel, `tracks[${trackIndex}].channel`, 0, 15);
528
+ if (track.channel === 9)
529
+ continue;
530
+ expectArray(track.notes, `tracks[${trackIndex}].notes`);
531
+ expectArray(track.instruments, `tracks[${trackIndex}].instruments`);
532
+ // program 事件保留原始 tick,等统一时间尺度确定后再换算
533
+ const programs = track.instruments.map((item, index) => {
534
+ expectSafeInteger(item.ticks, `tracks[${trackIndex}].instruments[${index}].ticks`);
535
+ expectSafeInteger(item.number, `tracks[${trackIndex}].instruments[${index}].number`, 0, 127);
536
+ return { ...item };
537
+ });
538
+ // 每个时值独立决定所需精度,全曲采用其中最高精度
539
+ const notes = track.notes.map((note, index) => {
540
+ expectSafeInteger(note.ticks, `tracks[${trackIndex}].notes[${index}].ticks`);
541
+ expectSafeInteger(note.durationTicks, `tracks[${trackIndex}].notes[${index}].durationTicks`, 1);
542
+ expectSafeInteger(note.midi, `tracks[${trackIndex}].notes[${index}].midi`, 0, 127);
543
+ rawNoteEnd = Math.max(rawNoteEnd, note.ticks + note.durationTicks);
544
+ const divisions = durationDivisions(note.durationTicks, ticksPerQuarter, alignRate);
545
+ globalDivisions = Math.max(globalDivisions, divisions);
546
+ return { ...note, divisions };
547
+ });
548
+ if (notes.length > 0)
549
+ sourceTracks.push({ source: track, notes, programs });
550
+ }
551
+ // 第二阶段:在原始 tick 域规范化全谱拍号和速度
552
+ // 默认拍号先参与同刻覆盖,保证结果始终从 tick 0 开始
553
+ const rawMeters = normalizeMeterTicks([
554
+ { ticks: 0, timeSignature: DEFAULT_TIME_SIGNATURE },
555
+ ...input.header.timeSignatures,
556
+ ].filter(item => item.ticks === 0 || item.ticks < rawNoteEnd).map((item, index) => {
557
+ expectSafeInteger(item.ticks, `header.timeSignatures[${index}].ticks`);
558
+ const [numerator, denominator] = item.timeSignature;
559
+ expectSafeInteger(numerator, `header.timeSignatures[${index}].numerator`, 1, 0xff);
560
+ expectSafeInteger(denominator, `header.timeSignatures[${index}].denominator`, 1, 0x8000);
561
+ const denominatorPower = Math.log2(denominator);
562
+ if (!Number.isInteger(denominatorPower))
563
+ throw new RangeError("MIDI time-signature denominator must be a power of two");
564
+ globalDivisions = Math.max(globalDivisions, denominatorPower - 2);
565
+ return { ticks: item.ticks, numerator, denominator };
566
+ }).sort((left, right) => left.ticks - right.ticks), ticksPerQuarter);
567
+ // 速度只保留尾音之前的点,同刻点稍后按后写覆盖
568
+ const rawTempos = [
569
+ { ticks: 0, bpm: DEFAULT_BPM },
570
+ ...input.header.tempos.map((item, index) => {
571
+ expectSafeInteger(item.ticks, `header.tempos[${index}].ticks`);
572
+ if (!Number.isFinite(item.bpm) || item.bpm <= 0) {
573
+ throw new RangeError(`header.tempos[${index}].bpm must be positive and finite`);
574
+ }
575
+ return item;
576
+ }),
577
+ ].filter(item => item.ticks === 0 || item.ticks < rawNoteEnd)
578
+ .sort((left, right) => left.ticks - right.ticks);
579
+ // 第三阶段:先识别三连音。命中时把内部时间轴乘 3,使三分槽也能用整数表示
580
+ const rhythmScale = 2 ** globalDivisions;
581
+ // 状态变化和小节边界都是三连音识别不可跨越的 blocker
582
+ const timeFactor = identifyTriplets(sourceTracks, ticksPerQuarter, [
583
+ ...rawMeters.slice(1).map(item => item.ticks),
584
+ ...rawTempos.slice(1).map(item => item.ticks),
585
+ ...sourceTracks.flatMap(track => track.programs.map(item => item.ticks)),
586
+ ...measureBoundaries(rawMeters, rawNoteEnd, ticksPerQuarter),
587
+ ]) ? 3 : 1;
588
+ const scale = rhythmScale * timeFactor;
589
+ // rawUnits 保留三分槽精度,binaryUnitAt 强制回到二进制网格
590
+ const rawUnits = (ticks) => {
591
+ if (!Number.isSafeInteger(ticks * scale))
592
+ throw new RangeError("MIDI timeline is too large to quantize exactly");
593
+ return ticks * scale / ticksPerQuarter;
594
+ };
595
+ const binaryUnitAt = (ticks) => {
596
+ if (!Number.isSafeInteger(ticks * rhythmScale))
597
+ throw new RangeError("MIDI timeline is too large to quantize exactly");
598
+ return Math.round(ticks * rhythmScale / ticksPerQuarter) * timeFactor;
599
+ };
600
+ const meters = rawMeters.map(item => ({
601
+ at: binaryUnitAt(item.ticks),
602
+ numerator: item.numerator,
603
+ denominator: item.denominator,
604
+ }));
605
+ // 第四阶段:量化音符;同一原始 tick 共用最高精度,防止和弦成员起点错开
606
+ const convertedTracks = [];
607
+ const startDivisions = new Map();
608
+ // 同一 onset 的所有和弦成员共享其中最细的起点网格
609
+ for (const track of sourceTracks) {
610
+ for (const note of track.notes) {
611
+ startDivisions.set(note.ticks, Math.max(startDivisions.get(note.ticks) ?? 1, note.divisions));
612
+ }
613
+ }
614
+ let lastNoteEnd = 0;
615
+ // 每轨依次量化、合并和弦、折叠三连音并划分局部重叠区域
616
+ for (const track of sourceTracks) {
617
+ const notes = track.notes.map(note => {
618
+ const tripletUnit = note.triplet
619
+ ? Math.round(rawUnits(note.triplet.spanTicks) / 3)
620
+ : 0;
621
+ const start = note.triplet
622
+ ? Math.round(rawUnits(note.triplet.startTicks)) + note.triplet.slot * tripletUnit
623
+ : quantizeTime(rawUnits(note.ticks), startDivisions.get(note.ticks), meters, scale);
624
+ let end = note.triplet
625
+ ? start + tripletUnit
626
+ : quantizeTime(rawUnits(note.ticks + note.durationTicks), note.divisions, meters, scale);
627
+ const step = scale / 2 ** note.divisions;
628
+ if (end <= start)
629
+ end = start + step;
630
+ lastNoteEnd = Math.max(lastNoteEnd, end);
631
+ return { ...note, start, end };
632
+ });
633
+ const programs = coalesceSorted(track.programs
634
+ .filter(item => item.ticks === 0 || item.ticks < rawNoteEnd)
635
+ .map(item => ({ at: binaryUnitAt(item.ticks), program: item.number })));
636
+ convertedTracks.push({
637
+ source: track.source,
638
+ regions: splitRegions(groupTriplets(combineChords(notes))),
639
+ programs: new Map(programs.map(item => [item.at, item.program])),
640
+ });
641
+ }
642
+ // 乐谱末尾补齐到当前拍号的完整小节边界
643
+ const activeMeter = pointAt(meters, lastNoteEnd);
644
+ const finalMeasureLength = meterDuration(activeMeter, scale);
645
+ const scoreEnd = lastNoteEnd === 0
646
+ ? 0
647
+ : activeMeter.at + Math.ceil((lastNoteEnd - activeMeter.at) / finalMeasureLength) * finalMeasureLength;
648
+ const tempoPoints = coalesceSorted(rawTempos.map(item => ({
649
+ at: binaryUnitAt(item.ticks),
650
+ bpm: item.bpm,
651
+ }))).filter(item => item.at === 0 || item.at < lastNoteEnd);
652
+ const relevantMeters = meters.filter(item => item.at === 0 || item.at < lastNoteEnd);
653
+ // 第五阶段:建立最终小节线和正文中的 tempo/meter 调整
654
+ const bars = new Set();
655
+ // 每段拍号各自产生规则小节线,拍号变化点本身也是边界
656
+ for (let index = 0; index < relevantMeters.length; index++) {
657
+ const meter = relevantMeters[index];
658
+ const next = relevantMeters[index + 1]?.at ?? scoreEnd;
659
+ if (meter.at > 0)
660
+ bars.add(meter.at);
661
+ const duration = meterDuration(meter, scale);
662
+ for (let at = meter.at + duration; at <= next && at <= scoreEnd; at += duration)
663
+ bars.add(at);
664
+ }
665
+ if (scoreEnd > 0)
666
+ bars.add(scoreEnd);
667
+ const orderedBars = [...bars].sort((left, right) => left - right);
668
+ const scoreAdjustments = new Map();
669
+ // 同一时刻的多个全谱状态按写入顺序叠到最高 lane
670
+ const addAdjustment = (at, source) => {
671
+ const sources = scoreAdjustments.get(at) ?? [];
672
+ sources.push(source);
673
+ scoreAdjustments.set(at, sources);
674
+ };
675
+ for (const meter of relevantMeters.slice(1)) {
676
+ addAdjustment(meter.at, `@meter(${meter.numerator}, ${meter.denominator})`);
677
+ }
678
+ for (const tempo of tempoPoints.slice(1))
679
+ addAdjustment(tempo.at, `@tempo(${tempo.bpm})`);
680
+ const initialMeter = relevantMeters[0];
681
+ const head = renderHead({
682
+ title,
683
+ key: "C4",
684
+ meter: [initialMeter.numerator, initialMeter.denominator],
685
+ tempo: tempoPoints[0].bpm,
686
+ });
687
+ if (convertedTracks.length === 0)
688
+ return head;
689
+ // 第六阶段:先生成单行候选做自然宽度测量,再用选出的断点生成最终源码
690
+ const renderScore = (lineBreaks) => {
691
+ let tieIndex = 0;
692
+ // 每次渲染重新编号 tie,单行测量与最终源码因此保持相同标签结构
693
+ const tracks = convertedTracks.map((track, trackIndex) => renderTrack(track, scoreEnd, bars, lineBreaks, (region, lane) => renderLane(lane, region.start, region.end, rhythmScale, timeFactor, pitchMode, bars, lineBreaks, trackIndex === 0 && lane === region.lanes.at(-1) ? scoreAdjustments : undefined, track.programs, () => `mt${tieIndex++}`), convertedTracks.length > 1));
694
+ return `${head}\n\n${renderSystems(tracks)}`;
695
+ };
696
+ const lineBreaks = barsPerLine <= 0
697
+ ? automaticLineBreaks(renderScore(new Set()), orderedBars, scale, layoutCapability)
698
+ : new Set(orderedBars.filter((at, index) => (index + 1) % barsPerLine === 0 && at < scoreEnd));
699
+ return renderScore(lineBreaks);
700
+ }