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